-
Notifications
You must be signed in to change notification settings - Fork 5
/
rest.go
executable file
·500 lines (424 loc) · 14.1 KB
/
rest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package rest
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
mtypes "github.com/cbarraford/cosmos-multisig/x/multisig/types"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/gorilla/mux"
)
const (
walletAddress = "address"
transactionID = "transaction_id"
)
var (
ModuleCdc = mtypes.ModuleCdc
)
// RegisterRoutes - Central function to define routes that get registered by the main application
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) {
r.HandleFunc(fmt.Sprintf("/%s/wallet/{%s}", storeName, walletAddress), getWalletHandler(cliCtx, storeName)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/transaction/{%s}", storeName, transactionID), getTransactionHandler(cliCtx, storeName)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/wallets/{%s}", storeName, walletAddress), walletsHandler(cliCtx, storeName)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/transactions/{%s}", storeName, transactionID), transactionsHandler(cliCtx, storeName)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/wallet", storeName), createWalletHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/transaction", storeName), createTransactionHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/transaction/sign", storeName), signTransactionHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/transaction/complete", storeName), completeTransactionHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/tx", storeName), createUnsignedTransactionHandler(cliCtx)).Methods("PUT")
r.HandleFunc(fmt.Sprintf("/%s/sign/multi", storeName), multiSignHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/broadcast", storeName), broadcastTxRequest(cliCtx)).Methods("POST")
}
func getWalletHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
paramType := vars[walletAddress]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/getWallet/%s", storeName, paramType), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, res)
}
}
func getTransactionHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
paramType := vars[transactionID]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/getTransaction/%s", storeName, paramType), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, res)
}
}
func walletsHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
paramType := vars[walletAddress]
log.Printf("Param %+v", paramType)
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/listWallets/%s", storeName, paramType), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, res)
}
}
func transactionsHandler(cliCtx context.CLIContext, storeName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
paramType := vars[transactionID]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/listTransactions/%s", storeName, paramType), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, res)
}
}
type multiSign struct {
Signatures []string `json:"signatures"`
Slots string `json:"slots"`
}
func multiSignHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req multiSign
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
// Important: The input signature must be in order relative to their
// public key was in the list of public keys were used to create the
// multisig wallet.
signatures := make([]string, len(req.Signatures))
for i, siggy := range req.Signatures {
if i < (len(req.Signatures) - 1) {
sig := []byte(siggy)
// since we are not the last signature, make edits...
// remove the '==' at the end of the string
sig = sig[:len(sig)-2]
// increment the last character by 1
sig[len(sig)-1] += 1
signatures[i] = string(sig)
} else {
signatures[i] = siggy
}
}
var totalPrefix string
switch len(slots) {
case 2:
totalPrefix = "Ah"
slots = fmt.Printf("%s0", slots)
case 3:
totalPrefix = "Ax"
//case 4:
//totalPrefix = "BB"
default:
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Number of public keys (%d) in this wallet is not currently supported", len(slots)))
}
var sigPrefix string
switch slots {
case "001":
sigPrefix = "IB"
case "010":
sigPrefix = "QB"
case "011":
sigPrefix = "YB"
case "100":
sigPrefix = "qB"
case "101":
sigPrefix = "oB"
case "110":
sigPrefix = "wB"
case "111":
sigPrefix = "4B"
default:
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Number of public keys (%d) in this wallet is not currently supported", len(slots)))
}
prefix := fmt.Sprintf("CgUI%sIB%s", totalPrefix, sigPrefix)
signatures = append([]string{prefix}, signatures...)
multisignature := strings.Join(signatures[:], "JA")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
io.WriteString(w, fmt.Sprintf(`{"signature":"%s"}`, multisignature))
}
}
type createUnsignedTransaction struct {
From string `json:"from"`
To string `json:"to"`
Amount string `json:"amount"`
Memo string `json:"memo"`
}
type msg struct {
Type string `json:"type"`
Value value2 `json:"value"`
}
type value2 struct {
FromAddress string `json:"from_address"`
ToAddress string `json:"to_address"`
Amount sdk.Coins `json:"amount"`
}
type value1 struct {
Msgs []msg `json:"msg"`
Fee types.StdFee `json:"fee"`
Signatures []string `json:"signatures"`
Memo string `json:"memo"`
}
type unsignedTransaction struct {
Type string `json:"type"`
Value value1 `json:"value"`
}
func createUnsignedTransactionHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req createUnsignedTransaction
var err error
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
_, err = sdk.AccAddressFromBech32(req.From)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
_, err = sdk.AccAddressFromBech32(req.To)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
coins, err := sdk.ParseCoins(req.Amount)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
tx := unsignedTransaction{
Type: "auth/StdTx",
Value: value1{
Msgs: []msg{
{
Type: "cosmos-sdk/MsgSend",
Value: value2{
FromAddress: req.From,
ToAddress: req.To,
Amount: coins,
},
},
},
Fee: types.NewStdFee(flags.DefaultGasLimit, sdk.Coins{}),
Signatures: nil,
Memo: req.Memo,
},
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
j, _ := json.Marshal(tx)
io.WriteString(w, string(j))
}
}
type createTransaction struct {
BaseReq rest.BaseReq `json:"base_req"`
From sdk.AccAddress `json:"from"`
To sdk.AccAddress `json:"to"`
Amount sdk.Int `json:"amount"`
Denom string `json:"denom"`
Signers []string `json:"signers"`
}
func createTransactionHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req createTransaction
var err error
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
baseReq := req.BaseReq.Sanitize()
if !baseReq.ValidateBasic(w) {
return
}
signers := make([]sdk.AccAddress, len(req.Signers))
for i, _ := range req.Signers {
signers[i], err = sdk.AccAddressFromBech32(req.Signers[i])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
// create the message
msg := mtypes.NewMsgCreateTransaction(req.From, req.To, req.Amount, req.Denom, signers)
err = msg.ValidateBasic()
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg})
}
}
type signTransaction struct {
BaseReq rest.BaseReq `json:"base_req"`
UUID string `json:"uuid"`
Signature string `json:"signature"`
PubKey string `json:"pub_key"`
PubKeyBase64 string `json:"pub_key_base64"`
Signers []string `json:"signers"`
}
func signTransactionHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req signTransaction
var err error
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
baseReq := req.BaseReq.Sanitize()
if !baseReq.ValidateBasic(w) {
// TODO: is this needed?
// return
}
signers := make([]sdk.AccAddress, len(req.Signers))
for i, _ := range req.Signers {
signers[i], err = sdk.AccAddressFromBech32(req.Signers[i])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
// create the message
msg := mtypes.NewMsgSignTransaction(req.UUID, req.PubKey, req.PubKeyBase64, req.Signature, signers)
err = msg.ValidateBasic()
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg})
}
}
type completeTransaction struct {
BaseReq rest.BaseReq `json:"base_req"`
UUID string `json:"uuid"`
TxID string `json:"tx_id"`
Signers []string `json:"signers"`
}
func completeTransactionHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req completeTransaction
var err error
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
baseReq := req.BaseReq.Sanitize()
if !baseReq.ValidateBasic(w) {
// TODO: is this needed?
// return
}
signers := make([]sdk.AccAddress, len(req.Signers))
for i, _ := range req.Signers {
signers[i], err = sdk.AccAddressFromBech32(req.Signers[i])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
// create the message
msg := mtypes.NewMsgCompleteTransaction(req.UUID, req.TxID, signers)
err = msg.ValidateBasic()
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg})
}
}
type createWallet struct {
Name string `json:"name"`
BaseReq rest.BaseReq `json:"base_req"`
Address string `json:"address"`
MinSigTx int `json:"min_sig_tx"`
PubKeys []string `json:"pub_keys"`
Signers []string `json:"signers"`
}
func createWalletHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req createWallet
var err error
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
baseReq := req.BaseReq.Sanitize()
if !baseReq.ValidateBasic(w) {
return
}
signers := make([]sdk.AccAddress, len(req.Signers))
for i, _ := range req.Signers {
signers[i], err = sdk.AccAddressFromBech32(req.Signers[i])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
// create the message
msg := mtypes.NewMsgCreateWallet(req.Name, req.PubKeys, req.MinSigTx, signers)
err = msg.ValidateBasic()
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg})
}
}
func validateMultisigThreshold(k, nKeys int) error {
if k <= 0 {
return fmt.Errorf("threshold must be a positive integer")
}
if nKeys < k {
return fmt.Errorf(
"threshold k of n multisignature: %d < %d", nKeys, k)
}
return nil
}
// BroadcastReq defines a tx broadcasting request.
type BroadcastReq struct {
Tx types.StdTx `json:"tx"`
Mode string `json:"mode"`
}
// broadcastTxRequest implements a tx broadcasting handler that is responsible
// for broadcasting a valid and signed tx to a full node. The tx can be
// broadcasted via a sync|async|block mechanism.
func broadcastTxRequest(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req BroadcastReq
body, err := ioutil.ReadAll(r.Body)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
err = cliCtx.Codec.UnmarshalJSON(body, &req)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
txBytes, err := cliCtx.Codec.MarshalBinaryLengthPrefixed(req.Tx)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
cliCtx = cliCtx.WithBroadcastMode(req.Mode)
res, err := cliCtx.BroadcastTx(txBytes)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, res)
}
}