forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
99 lines (83 loc) · 2.49 KB
/
util.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
package rest
import (
"io/ioutil"
"net/http"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
"github.com/pkg/errors"
)
type baseReq struct {
Name string `json:"name"`
Password string `json:"password"`
ChainID string `json:"chain_id"`
AccountNumber int64 `json:"account_number"`
Sequence int64 `json:"sequence"`
Gas int64 `json:"gas"`
}
func buildReq(w http.ResponseWriter, r *http.Request, cdc *wire.Codec, req interface{}) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
writeErr(&w, http.StatusBadRequest, err.Error())
return err
}
err = cdc.UnmarshalJSON(body, req)
if err != nil {
writeErr(&w, http.StatusBadRequest, err.Error())
return err
}
return nil
}
func (req baseReq) baseReqValidate(w http.ResponseWriter) bool {
if len(req.Name) == 0 {
writeErr(&w, http.StatusUnauthorized, "Name required but not specified")
return false
}
if len(req.Password) == 0 {
writeErr(&w, http.StatusUnauthorized, "Password required but not specified")
return false
}
if len(req.ChainID) == 0 {
writeErr(&w, http.StatusUnauthorized, "ChainID required but not specified")
return false
}
if req.AccountNumber < 0 {
writeErr(&w, http.StatusUnauthorized, "Account Number required but not specified")
return false
}
if req.Sequence < 0 {
writeErr(&w, http.StatusUnauthorized, "Sequence required but not specified")
return false
}
return true
}
func writeErr(w *http.ResponseWriter, status int, msg string) {
(*w).WriteHeader(status)
err := errors.New(msg)
(*w).Write([]byte(err.Error()))
}
// TODO: Build this function out into a more generic base-request (probably should live in client/lcd)
func signAndBuild(w http.ResponseWriter, ctx context.CoreContext, baseReq baseReq, msg sdk.Msg, cdc *wire.Codec) {
ctx = ctx.WithAccountNumber(baseReq.AccountNumber)
ctx = ctx.WithSequence(baseReq.Sequence)
ctx = ctx.WithChainID(baseReq.ChainID)
// add gas to context
ctx = ctx.WithGas(baseReq.Gas)
txBytes, err := ctx.SignAndBuild(baseReq.Name, baseReq.Password, []sdk.Msg{msg}, cdc)
if err != nil {
writeErr(&w, http.StatusUnauthorized, err.Error())
return
}
// send
res, err := ctx.BroadcastTx(txBytes)
if err != nil {
writeErr(&w, http.StatusInternalServerError, err.Error())
return
}
output, err := wire.MarshalJSONIndent(cdc, res)
if err != nil {
writeErr(&w, http.StatusInternalServerError, err.Error())
return
}
w.Write(output)
}