forked from onomyprotocol/onomy-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
90 lines (73 loc) · 2.56 KB
/
decode.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
package rest
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"github.com/puneetsingh166/onomy-sdk/client"
clienttx "github.com/puneetsingh166/onomy-sdk/client/tx"
sdkerrors "github.com/puneetsingh166/onomy-sdk/types/errors"
"github.com/puneetsingh166/onomy-sdk/types/rest"
"github.com/puneetsingh166/onomy-sdk/x/auth/legacy/legacytx"
"github.com/puneetsingh166/onomy-sdk/x/auth/signing"
)
type (
// DecodeReq defines a tx decoding request.
DecodeReq struct {
Tx string `json:"tx"`
}
// DecodeResp defines a tx decoding response.
DecodeResp legacytx.StdTx
)
// DecodeTxRequestHandlerFn returns the decode tx REST handler. In particular,
// it takes base64-decoded bytes, decodes it from the Amino wire protocol,
// and responds with a json-formatted transaction.
func DecodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req DecodeReq
body, err := ioutil.ReadAll(r.Body)
if rest.CheckBadRequestError(w, err) {
return
}
// NOTE: amino is used intentionally here, don't migrate it
err = clientCtx.LegacyAmino.UnmarshalJSON(body, &req)
if rest.CheckBadRequestError(w, err) {
return
}
txBytes, err := base64.StdEncoding.DecodeString(req.Tx)
if rest.CheckBadRequestError(w, err) {
return
}
stdTx, err := convertToStdTx(w, clientCtx, txBytes)
if err != nil {
// Error is already returned by convertToStdTx.
return
}
response := DecodeResp(stdTx)
err = checkAminoMarshalError(clientCtx, response, "/cosmos/tx/v1beta1/txs/decode")
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, clientCtx, response)
}
}
// convertToStdTx converts tx proto binary bytes retrieved from Tendermint into
// a StdTx. Returns the StdTx, as well as a flag denoting if the function
// successfully converted or not.
func convertToStdTx(w http.ResponseWriter, clientCtx client.Context, txBytes []byte) (legacytx.StdTx, error) {
txI, err := clientCtx.TxConfig.TxDecoder()(txBytes)
if rest.CheckBadRequestError(w, err) {
return legacytx.StdTx{}, err
}
tx, ok := txI.(signing.Tx)
if !ok {
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("%+v is not backwards compatible with %T", tx, legacytx.StdTx{}))
return legacytx.StdTx{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected %T, got %T", (signing.Tx)(nil), txI)
}
stdTx, err := clienttx.ConvertTxToStdTx(clientCtx.LegacyAmino, tx)
if rest.CheckBadRequestError(w, err) {
return legacytx.StdTx{}, err
}
return stdTx, nil
}