Пример #1
0
func (c *MainController) SigninPost() {
	uname := c.GetString("Name")
	upass := c.GetString("Password")
	token := c.GetString("Token")
	if t, ok := c.GetSession("Token").(string); !ok || token != t {
		c.Redirect("/signin", 302)
		return
	}
	r := &models.Role{Username: uname}
	err := models.Gorm.Read(r, "Username")
	if err != nil {
		glog.Error("Sign in error: " + uname + " is NOT in database")
		c.SetSession("ErrMsg", "name OR password error")
		c.Redirect("/signin", 302)
		return
	}
	if r.Password != models.PassHash(upass) {
		glog.Error("Sign in error: password error")
		c.SetSession("ErrMsg", "name OR password error")
		c.Redirect("/signin", 302)
		return
	}
	c.SetSession("Role", r)
	c.Redirect("/", 302)
}
Пример #2
0
func PassHash(password string) string {
	key, err := scrypt.Key([]byte(password), []byte("wangch"), 16384, 8, 1, 32)
	if err != nil {
		glog.Error(err)
		return ""
	}
	return string(base64.StdEncoding.EncodeToString(key))
}
Пример #3
0
func sendResp(resp interface{}, ctx *context.Context) error {
	b, err := json.Marshal(resp)
	if err != nil {
		glog.Error(err)
		return err
	}
	glog.Info(string(b))
	ctx.ResponseWriter.Write(b)
	return nil
}
Пример #4
0
func getInvoiceId(r *Request) string {
	s := fmt.Sprintf("%s%s%s%s%s%s%s%s%f%f%d", r.CTime.String(), r.UName, r.UWallet, r.UBankName, r.UBankId, r.UContact, r.Currency, r.Amount, r.Fees, r.Type)
	hash := sha256.Sum256([]byte(s))
	h, err := data.NewHash256(hash[:])
	if err != nil {
		glog.Error(err)
		return ""
	}
	return h.String()
}
Пример #5
0
func (c *MainController) queryTable() error {
	r := c.getRole()
	if r == nil {
		return PDErr
	}
	sst := c.GetString("stime")
	set := c.GetString("etime")

	st, err := time.Parse("2006-01-02", sst)
	if err != nil {
		glog.Error(err)
		return err
	}
	et, err := time.Parse("2006-01-02", set)
	if err != nil {
		glog.Error(err)
		return err
	}
	c.SetSession("StartDate", &st)
	c.SetSession("EndDate", &et)
	c.SetSession("Status", c.GetString("status"))
	return nil
}
Пример #6
0
// secret is sender's secret
func payment(ws *websockets.Remote, secret, sender, issuer, recipient, currency, invoiceID string, amount float64) error {
	glog.Info("payment:", secret, sender, recipient, currency, amount, issuer, invoiceID)
	sam := ""
	if currency == "ICC" {
		sam = fmt.Sprintf("%d/ICC", uint64(amount))
	} else {
		sam = fmt.Sprintf("%f/%s/%s", amount, currency, issuer)
	}
	a, err := data.NewAmount(sam)
	if err != nil {
		err = errors.New("NewAmount error: " + sam + err.Error())
		glog.Error(err)
		return err
	}

	ptx := &websockets.PaymentTx{
		TransactionType: "Payment",
		Account:         sender,
		Destination:     recipient,
		Amount:          a,
		InvoiceID:       invoiceID,
	}

	// glog.Infof("payment: %+v", ptx)

	r, err := ws.SubmitWithSign(ptx, secret)
	if err != nil {
		glog.Error(err)
		return err
	}
	glog.Infof("pament result: %+v", r)
	if !r.EngineResult.Success() {
		return errors.New(r.EngineResultMessage)
	}
	return nil
}
Пример #7
0
// TODO: 获取Gconf中每个Hotwallet的每种货币的余额, 选择最多的那个作为sender
func Payment(r *Request, sender string) error {
	secret := ""
	for _, x := range Gconf.HoltWallet {
		if sender == x.AccountId {
			secret = x.Secret
			break
		}
	}
	if secret == "" {
		errMsg := fmt.Sprintf("Payment error: the Sender %s is NOT in config hotwallets", sender)
		err := errors.New(errMsg)
		glog.Error(err)
		return err
	}
	return payment(gws, secret, sender, Gconf.ColdWallet, r.UWallet, r.Currency, r.InvoiceId, r.Amount)
}
Пример #8
0
// https://ripplecn.com/bridge?type=quote&amount=1%2FCNY&destination=z&address=ra5tSyQ2cvJUHfAvEdmC89HKSKZTn7xXMw&alipay_account=aa&full_name=bb&contact_info=cc
func (c *MainController) ApiQuote() {
	sa := c.Ctx.Request.URL.Query().Get("amount")
	address := c.Ctx.Request.URL.Query().Get("address")
	bank_name := c.Ctx.Request.URL.Query().Get("bank_name")
	card_number := c.Ctx.Request.URL.Query().Get("card_number")
	full_name := c.Ctx.Request.URL.Query().Get("full_name")
	contact_info := c.Ctx.Request.URL.Query().Get("contact_info")

	a, err := data.NewAmount(sa)
	if err != nil {
		glog.Error(err)
		resp := quoteErrorResp("the query amount err")
		sendResp(resp, c.Ctx)
		return
	}
	glog.Info("ApiQuote:", address, bank_name, card_number, full_name, contact_info, a, a.IsNative())
	sv := a.Value.String()
	am, err := strconv.ParseFloat(sv, 64)
	if err != nil {
		glog.Error(err)
		resp := quoteErrorResp("the query amount err2")
		sendResp(resp, c.Ctx)
		return
	}

	if a.IsNative() {
		pv, _ := data.NewNativeValue(1e6)
		a.Value, _ = a.Value.Divide(*pv)
	}

	currency := a.Currency.String()
	fee := am * models.Gconf.Fees.Rate
	min := models.Gconf.Fees.FeeMap[currency][0]
	max := models.Gconf.Fees.FeeMap[currency][1]
	if fee < min {
		fee = min
	}
	if fee > max {
		fee = max
	}
	acc, err := data.NewAccountFromAddress(models.Gconf.ColdWallet)
	if err != nil {
		glog.Fatal(err)
	}
	a.Issuer = *acc

	u := &models.User{
		UName:     full_name,
		UWallet:   address,
		UBankName: bank_name,
		UBankId:   card_number,
		UContact:  contact_info,
	}

	t := models.Withdrawal
	if a.IsNative() {
		t = models.Redeem
	}
	req, err := models.AddReq("", models.Gconf.ColdWallet, t, u, a.Currency.String(), am/1e6, fee)
	if err != nil {
		// glog.Error(err)
		return
	}

	fv, err := data.NewValue(fmt.Sprintf("%f", fee), a.IsNative())
	if err != nil {
		glog.Fatal(err)
	}

	a.Value, err = a.Value.Add(*fv)
	if err != nil {
		glog.Fatal(err)
	}

	if a.IsNative() {
		pv, _ := data.NewNativeValue(1e6)
		a.Value, _ = a.Value.Divide(*pv)
		a.Currency, _ = data.NewCurrency("ICC")
	}

	quote := &Quote{
		Address:        models.Gconf.ColdWallet,
		DestinationTag: 2147483647,
		Send:           []data.Amount{*a},
		InvoiceID:      req.InvoiceId,
	}
	resp := &QuoteResp{
		Result:    "success",
		QuoteJson: quote,
	}
	glog.Info("Quote:", address, full_name, "OK")
	sendResp(resp, c.Ctx)
}
Пример #9
0
func monitor(serverAddr string, wallets []string) error {
	for {
		ws, err := websockets.NewRemote(serverAddr)
		gws = ws
		if err != nil {
			glog.Error(err)
			time.Sleep(time.Second * 1)
			continue
		}

		_, err = ws.Subscribe(false, false, false, false, wallets)
		if err != nil {
			glog.Error(err)
			time.Sleep(time.Second * 1)
			continue
		}

		for {
			msg, ok := <-ws.Incoming
			if !ok {
				glog.Warning("ws.Incoming chan closed.")
				break
			}

			switch msg := msg.(type) {
			case *websockets.TransactionStreamMsg:
				// the transaction must be validated
				// and only watch payments
				b, err := json.MarshalIndent(msg, "", "  ")
				if err != nil {
					glog.Error(err)
				}
				glog.Info(string(b))
				if !msg.EngineResult.Success() {
					glog.Warning("the transaction NOT success")
					break
				}

				if msg.Transaction.GetType() == "Payment" {
					paymentTx := msg.Transaction.Transaction.(*data.Payment)
					out := isOut(paymentTx.Account.String(), wallets)
					if paymentTx.InvoiceID == nil {
						glog.Warning("paymentTx.InvoiceID == nil")
						break
					}
					// query the paymen tx InvoiceId in database and update tx hash
					invid := paymentTx.InvoiceID.String()
					r := &Request{}
					Gorm.QueryTable("request").Filter("invoice_id", invid).RelatedSel().One(r)
					if r.R == nil {
						glog.Warning("the payment invoiceID " + invid + "is NOT in database")
						// must be cold wallet send to hotwallet
						break
					}

					r.R.TxHash = paymentTx.Hash.String()
					if out { // 存款 or 发行ICC
						r.R.Status = OKC
					} else { // 取款 or 回收ICC
						r.R.Status = C*K
					}
					_, err = Gorm.Update(r.R)
					if err != nil {
						// have error in database
						// must report the error msg on web
						glog.Error(err)
					}
				}
			}
		}
	}
}
Пример #10
0
func (c *MainController) addReq(t int) error {
	amt, ok := c.GetSession("Amt").(*AmountInfo)
	if !ok {
		c.Ctx.Request.ParseMultipartForm(1024 * 1024 * 10)
		glog.Infof("%#+v", c.Ctx.Request)
		gbankId := c.GetString("gbankId")
		currency := c.GetString("currency")
		fee, err := c.GetFloat("fees")
		if err != nil {
			glog.Errorln(err)
			return err
		}
		a, err := c.GetFloat("amount")
		if err != nil {
			glog.Errorln(err)
			return err
		}
		amt = &AmountInfo{
			BankId:   gbankId,
			Currency: currency,
			Amount:   a,
			Fees:     fee,
		}
	}
	uname := c.GetString("name")
	uwallet := c.GetString("iccWallet")
	ubankName := c.GetString("bankName")
	ubankId := c.GetString("bankId")
	ucontact := c.GetString("contact")

	rf, header, err := c.Ctx.Request.FormFile("certificate")
	if err != nil {
		glog.Error(err)
		return err
	}
	defer rf.Close()

	filePath := "./certificates/" + RandToken() + "-" + header.Filename

	wf, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		glog.Error(err)
		return err
	}
	io.Copy(wf, rf)
	wf.Close()

	u := &models.User{
		UName:        uname,
		UWallet:      uwallet,
		UBankName:    ubankName,
		UBankId:      ubankId,
		UContact:     ucontact,
		UCertificate: filePath[1:],
	}

	_, err = models.AddReq(amt.BankId, "", t, u, amt.Currency, amt.Amount, amt.Fees)
	if err != nil {
		glog.Errorln(err)
		return err
	}
	return nil
}
Пример #11
0
func (c *MainController) verify(isOut bool) error {
	r := c.getRole()
	if r == nil {
		return PDErr
	}
	sid := c.Ctx.Request.URL.Query().Get("id")
	id, err := strconv.Atoi(sid)
	if err != nil {
		return err
	}
	// rec := &models.Recoder{Id: int64(id)}
	var req models.Request
	err = models.Gorm.QueryTable("Request").Filter("R__id", id).RelatedSel().One(&req)
	if err != nil {
		return err
	}
	rec := req.R
	newStatus := canVerify(r.Type, rec.Status, 0 /*rec.R.Type*/)
	if newStatus == -1 {
		return PDErr
	}
	if r.Type == models.RoleF {
		if rec.GWallet == "" || rec.GBankId == "" {
			err = errors.New("HotWallet OR GateBandId config error")
			glog.Error(err)
			return err
		}
		rec.FId = r.Username
		rec.FTime = time.Now()
		rec.Status = models.FOK
	} else if r.Type == models.RoleM {
		rec.MId = r.Username
		rec.MTime = time.Now()
		rec.Status = models.MOK
	} else if r.Type == models.RoleA {
		rec.AId = r.Username
		rec.ATime = time.Now()
		// 会计审批, 直接发送
		if isOut {
			if rec.R == nil {
				return PDErr
			}
			sender := ""
			if strings.Contains(rec.GWallet, ":") {
				sender = strings.Split(rec.GWallet, ":")[1]
			}
			if sender == "" {
				return errors.New("HotWallet error")
			}
			rec.R.Currency = getCurrencyID(rec.R.Currency)
			err := models.Payment(rec.R, sender)
			if err != nil {
				return err
			}
			rec.Status = models.AOK
		} else { // 回收和取款
			rec.Status = models.OKC // 转账完成则整个记录完成
		}
	} else {
		glog.Fatal("can't go here")
	}
	_, err = models.Gorm.Update(rec)
	return err
}