Exemple #1
0
func (r *Remote) streamLedgerData(ledger interface{}, c chan data.LedgerEntrySlice) {
	defer close(c)
	cmd := newBinaryLedgerDataCommand(ledger, nil)
	for ; ; cmd = newBinaryLedgerDataCommand(ledger, cmd.Result.Marker) {
		r.outgoing <- cmd
		<-cmd.Ready
		if cmd.CommandError != nil {
			glog.Errorln(cmd.Error())
			return
		}
		les := make(data.LedgerEntrySlice, len(cmd.Result.State))
		for i, state := range cmd.Result.State {
			b, err := hex.DecodeString(state.Data + state.Index)
			if err != nil {
				glog.Errorln(cmd.Error())
				return
			}
			les[i], err = data.ReadLedgerEntry(bytes.NewReader(b), data.Hash256{})
			if err != nil {
				glog.Errorln(err.Error())
				return
			}
		}
		c <- les
		if cmd.Result.Marker == nil {
			return
		}
	}
}
Exemple #2
0
func (c *MainController) ApiDepositAmountPost() {
	glog.Infof("%#+v", c.Ctx.Request)
	upath := c.Ctx.Request.URL.Path
	buyIcc := false
	if strings.Contains(upath, "buyicc") {
		buyIcc = true
	}

	currency := "USD"
	if !buyIcc {
		s := c.GetString("currency")
		if s == "" {
			glog.Errorln("currency is nil")
			return
		}
		currency = getCurrencyID(s)
	}

	gba, err := getGba(currency)
	if err != nil {
		glog.Errorln(err)
		return
	}

	amount, err := c.GetFloat("amount")
	if err != nil {
		glog.Errorln(err)
		return
	}

	if buyIcc {
		amount *= models.Gconf.UsdRate
	}

	fees := models.Gconf.Fees

	min, max := fees.FeeMap[currency][0], fees.FeeMap[currency][1]
	fee := amount * fees.Rate
	if fee < min {
		fee = min
	}
	if fee > max {
		fee = max
	}

	amt := &AmountInfo{
		BankName: gba.BankName,
		BankId:   gba.BankId,
		Currency: currency,
		Amount:   amount,
		Fees:     fee,
		Total:    amount + fee,
	}
	c.SetSession("Amt", amt)
	currencys := models.Gconf.Currencies
	c.Data["Currencies"] = currencys
	c.Data["Amt"] = amt
	c.Data["BuyIcc"] = buyIcc
	c.TplNames = "deposit.html"
}
Exemple #3
0
func main() {
	glog.SetLogDirs(".")
	glog.SetLogToStderr(true)
	conf := controllers.Gconf
	beego.Get("/federation", func(ctx *context.Context) {
		federation(ctx, conf)
	})

	beego.Get("/ripple.txt", func(ctx *context.Context) {
		f, err := os.Open("ripple.txt")
		if err != nil {
			glog.Fatal(err)
		}
		io.Copy(ctx.ResponseWriter, f)
		f.Close()
	})

	beego.Get("/quote", func(ctx *context.Context) {
		u := "http://" + conf.Host + "/api/quote?" + ctx.Request.URL.RawQuery
		glog.Infoln(u)
		r, err := http.Get(u)
		if err != nil {
			glog.Errorln(err)
			return
		}
		io.Copy(ctx.ResponseWriter, r.Body)
		r.Body.Close()
	})

	beego.Run()
}
Exemple #4
0
func main() {
	flag.Parse()
	glog.SetLogToStderr(true)
	if *server == "" {
		usage()
		return
	}
	if *sender == "" || len(*sender) != 34 || (*sender)[0] != 'i' {
		usage()
		return
	}
	if *secret == "" || len(*secret) != 29 || (*secret)[0] != 's' {
		usage()
		return
	}
	if *recipient == "" || len(*recipient) != 34 || (*recipient)[0] != 'i' {
		usage()
		return
	}
	if *amount <= 0 {
		glog.Errorln(*amount, "发送金额必须>0")
		return
	}

	ws, err := websockets.NewRemote(*server)
	if err != nil {
		glog.Fatal(err)
	}

	issuer := "iN8sGowQCg1qptWcJG1WyTmymKX7y9cpmr"
	err = payment(ws, *secret, *sender, issuer, *recipient, *currency, "", *amount)
	if err != nil {
		glog.Fatal(err)
	}
}
Exemple #5
0
// readPump reads from the websocket and sends to inbound channel.
// Expects to receive PONGs at specified interval, or logs an error and returns.
func (r *Remote) readPump(inbound chan<- []byte) {
	r.ws.SetReadDeadline(time.Now().Add(pongWait))
	r.ws.SetPongHandler(func(string) error { r.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := r.ws.ReadMessage()
		if err != nil {
			glog.Errorln(err)
			return
		}
		glog.V(2).Infoln(dump(message))
		r.ws.SetReadDeadline(time.Now().Add(pongWait))
		inbound <- message
	}
}
Exemple #6
0
// Consumes from the outbound channel and sends them over the websocket.
// Also sends PING messages at the specified interval.
// Returns when outbound channel is closed, or an error is encountered.
func (r *Remote) writePump(outbound <-chan interface{}) {
	ticker := time.NewTicker(pingPeriod)
	defer ticker.Stop()

	for {
		select {

		// An outbound message is available to send
		case message, ok := <-outbound:
			if !ok {
				r.ws.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			b, err := json.Marshal(message)
			if err != nil {
				// Outbound message cannot be JSON serialized (log it and continue)
				glog.Errorln(err)
				continue
			}

			glog.V(2).Infoln(dump(b))
			if err := r.ws.WriteMessage(websocket.TextMessage, b); err != nil {
				glog.Errorln(err)
				return
			}

		// Time to send a ping
		case <-ticker.C:
			if err := r.ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				glog.Errorln(err)
				return
			}
		}
	}
}
Exemple #7
0
func (r *Remote) accountTx(account data.Account, c chan *data.TransactionWithMetaData, pageSize int) {
	defer close(c)
	cmd := newAccountTxCommand(account, pageSize, nil)
	for ; ; cmd = newAccountTxCommand(account, pageSize, cmd.Result.Marker) {
		r.outgoing <- cmd
		<-cmd.Ready
		if cmd.CommandError != nil {
			glog.Errorln(cmd.Error())
			return
		}
		for _, tx := range cmd.Result.Transactions {
			c <- tx
		}
		if cmd.Result.Marker == nil {
			return
		}
	}
}
Exemple #8
0
// run spawns the read/write pumps and then runs until Close() is called.
func (r *Remote) run() {
	outbound := make(chan interface{})
	inbound := make(chan []byte)
	pending := make(map[uint64]Syncer)

	defer func() {
		close(outbound) // Shuts down the writePump
		close(r.Incoming)

		// Cancel all pending commands with an error
		for _, c := range pending {
			c.Fail("Connection Closed")
		}

		// Drain the inbound channel and block until it is closed,
		// indicating that the readPump has returned.
		for _ = range inbound {
		}
	}()

	// Spawn read/write goroutines
	go func() {
		defer r.ws.Close()
		r.writePump(outbound)
	}()
	go func() {
		defer close(inbound)
		r.readPump(inbound)
	}()

	// Main run loop
	var response Command
	for {
		select {
		case command, ok := <-r.outgoing:
			if !ok {
				return
			}
			outbound <- command
			id := reflect.ValueOf(command).Elem().FieldByName("Id").Uint()
			pending[id] = command

		case in, ok := <-inbound:
			if !ok {
				glog.Errorln("Connection closed by server")
				return
			}

			if err := json.Unmarshal(in, &response); err != nil {
				glog.Errorln(err.Error())
				continue
			}
			// Stream message
			factory, ok := streamMessageFactory[response.Type]
			if ok {
				cmd := factory()
				if err := json.Unmarshal(in, &cmd); err != nil {
					glog.Errorln(err.Error(), string(in))
					continue
				}
				r.Incoming <- cmd
				continue
			}

			// Command response message
			cmd, ok := pending[response.Id]
			if !ok {
				glog.Errorf("Unexpected message: %+v", response)
				continue
			}
			delete(pending, response.Id)
			if err := json.Unmarshal(in, &cmd); err != nil {
				glog.Errorln(err.Error())
				continue
			}
			cmd.Done()
		}
	}
}
Exemple #9
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
}
Exemple #10
0
func (c *MainController) Deposit() {
	r := c.Ctx.Request
	u := *r.URL
	u.Scheme = "http"
	u.Host = Gconf.Host
	u.Path = "/api" + u.Path

	glog.Infoln(u)

	var resp *http.Response
	var err error
	if r.Method == "GET" {
		resp, err = http.Get(u.String())
	} else {
		contentType := r.Header.Get("Content-Type")
		var nr *http.Request
		if strings.Contains(contentType, "multipart/form-data") {
			buf := &bytes.Buffer{}
			writer := multipart.NewWriter(buf)
			i := strings.Index(contentType, "--")
			boundary := contentType[i:]
			err = writer.SetBoundary(boundary)
			if err != nil {
				glog.Infoln(err)
				return
			}

			for k, v := range r.MultipartForm.Value {
				writer.WriteField(k, v[0])
			}
			for k, v := range r.MultipartForm.File {
				w, err := writer.CreateFormFile(k, v[0].Filename)
				if err != nil {
					glog.Errorln(err)
					return
				}
				f, err := v[0].Open()
				if err != nil {
					glog.Errorln(err)
					return
				}
				io.Copy(w, f)
				f.Close()
			}
			writer.Close()
			nr, err = http.NewRequest(r.Method, u.String(), buf)
		} else {
			nr, err = http.NewRequest(r.Method, u.String(), strings.NewReader(r.Form.Encode()))
		}
		if err != nil {
			glog.Errorln(err)
			return
		}
		nr.Header.Set("Content-Type", contentType)
		resp, err = http.DefaultClient.Do(nr)
	}

	if err != nil {
		glog.Errorln(err)
		c.Redirect("/", 302)
		return
	}
	io.Copy(c.Ctx.ResponseWriter, resp.Body)
}