This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
tx.go
272 lines (233 loc) · 8.33 KB
/
tx.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
package client
import (
"context"
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/client"
tx "github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
abci "github.com/tendermint/tendermint/abci/types"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// TxFactory returns a new transaction factory based on the chain client's configuration
// and the provided message.
func (cc *ChainClient) TxFactory() tx.Factory {
return tx.Factory{}.
WithAccountRetriever(cc).
WithChainID(cc.Config.ChainID).
WithTxConfig(cc.Codec.TxConfig).
WithGasAdjustment(cc.Config.GasAdjustment).
WithGasPrices(cc.Config.GasPrices).
WithKeybase(cc.Keybase).
WithSignMode(cc.Config.SignMode())
}
// SignMode returns the sign mode for the chain client
func (ccc *ChainClientConfig) SignMode() signing.SignMode {
signMode := signing.SignMode_SIGN_MODE_UNSPECIFIED
switch ccc.SignModeStr {
case "direct":
signMode = signing.SignMode_SIGN_MODE_DIRECT
case "amino-json":
signMode = signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON
}
return signMode
}
// SendMsg wraps the msg in a StdTx, signs and sends it. An error is returned if there
// was an issue sending the transaction. A successfully sent, but failed transaction will
// not return an error. If a transaction is successfully sent, the result of the execution
// of that transaction will be logged. A boolean indicating if a transaction was successfully
// sent and executed successfully is returned.
func (cc *ChainClient) SendMsg(ctx context.Context, msg sdk.Msg) (*sdk.TxResponse, bool, error) {
return cc.SendMsgs(ctx, []sdk.Msg{msg})
}
// SendMsgs wraps the msgs in a StdTx, signs and sends it. An error is returned if there
// was an issue sending the transaction. A successfully sent, but failed transaction will
// not return an error. If a transaction is successfully sent, the result of the execution
// of that transaction will be logged. A boolean indicating if a transaction was successfully
// sent and executed successfully is returned.
func (cc *ChainClient) SendMsgs(ctx context.Context, msgs []sdk.Msg) (*sdk.TxResponse, bool, error) {
txf, err := cc.PrepareFactory(cc.TxFactory())
if err != nil {
return nil, false, err
}
// TODO: Make this work with new CalculateGas method
// TODO: This is related to GRPC client stuff?
// https://github.com/cosmos/cosmos-sdk/blob/5725659684fc93790a63981c653feee33ecf3225/client/tx/tx.go#L297
_, adjusted, err := cc.CalculateGas(txf, msgs...)
if err != nil {
return nil, false, err
}
// Set the gas amount on the transaction factory
txf = txf.WithGas(adjusted)
// Build the transaction builder
txb, err := tx.BuildUnsignedTx(txf, msgs...)
if err != nil {
return nil, false, err
}
// Attach the signature to the transaction
// c.LogFailedTx(nil, err, msgs)
// Force encoding in the chain specific address
for _, msg := range msgs {
cc.Codec.Marshaler.MustMarshalJSON(msg)
}
err = tx.Sign(txf, cc.Config.Key, txb, false)
if err != nil {
return nil, false, err
}
// Generate the transaction bytes
txBytes, err := cc.Codec.TxConfig.TxEncoder()(txb.GetTx())
if err != nil {
return nil, false, err
}
// Broadcast those bytes
res, err := cc.BroadcastTx(ctx, txBytes)
if err != nil {
return nil, false, err
}
// transaction was executed, log the success or failure using the tx response code
// NOTE: error is nil, logic should use the returned error to determine if the
// transaction was successfully executed.
if res.Code != 0 {
return res, false, nil
}
return res, true, nil
}
// PrepareFactory returns a new transaction factory based on the chain client's configuration
// and the provided transaction factory.
func (cc *ChainClient) PrepareFactory(txf tx.Factory) (tx.Factory, error) {
from, err := cc.GetKeyAddress()
if err != nil {
return tx.Factory{}, err
}
cliCtx := client.Context{}.WithClient(cc.RPCClient).
WithInterfaceRegistry(cc.Codec.InterfaceRegistry).
WithChainID(cc.Config.ChainID).
WithCodec(cc.Codec.Marshaler)
// Set the account number and sequence on the transaction factory
if err := txf.AccountRetriever().EnsureExists(cliCtx, from); err != nil {
return txf, err
}
// TODO: why this code? this may potentially require another query when we don't want one
initNum, initSeq := txf.AccountNumber(), txf.Sequence()
if initNum == 0 || initSeq == 0 {
num, seq, err := txf.AccountRetriever().GetAccountNumberSequence(cliCtx, from)
if err != nil {
return txf, err
}
if initNum == 0 {
txf = txf.WithAccountNumber(num)
}
if initSeq == 0 {
txf = txf.WithSequence(seq)
}
}
return txf, nil
}
// CalculateGas estimates the gas for a transaction based on TxFactory and msgs.
func (cc *ChainClient) CalculateGas(txf tx.Factory, msgs ...sdk.Msg) (txtypes.SimulateResponse, uint64, error) {
txBytes, err := BuildSimTx(txf, msgs...)
if err != nil {
return txtypes.SimulateResponse{}, 0, err
}
simQuery := abci.RequestQuery{
Path: "/cosmos.tx.v1beta1.Service/Simulate",
Data: txBytes,
}
res, err := cc.QueryABCI(simQuery)
if err != nil {
return txtypes.SimulateResponse{}, 0, err
}
var simRes txtypes.SimulateResponse
if err := simRes.Unmarshal(res.Value); err != nil {
return txtypes.SimulateResponse{}, 0, err
}
return simRes, uint64(txf.GasAdjustment() * float64(simRes.GasInfo.GasUsed)), nil
}
// QueryABCI queries the ABCI server with the provided request. An error is returned
// if the query returns a non-zero code and the ABCI server returns a non-nil error.
func (cc *ChainClient) QueryABCI(req abci.RequestQuery) (abci.ResponseQuery, error) {
opts := rpcclient.ABCIQueryOptions{
Height: req.Height,
Prove: req.Prove,
}
result, err := cc.RPCClient.ABCIQueryWithOptions(context.Background(), req.Path, req.Data, opts)
if err != nil {
return abci.ResponseQuery{}, err
}
if !result.Response.IsOK() {
return abci.ResponseQuery{}, sdkErrorToGRPCError(result.Response)
}
// data from trusted node or subspace query doesn't need verification
if !opts.Prove || !isQueryStoreWithProof(req.Path) {
return result.Response, nil
}
return result.Response, nil
}
// sdkErrorToGRPCError converts an sdk error to a grpc error.
func sdkErrorToGRPCError(resp abci.ResponseQuery) error {
switch resp.Code {
case sdkerrors.ErrInvalidRequest.ABCICode():
return status.Error(codes.InvalidArgument, resp.Log)
case sdkerrors.ErrUnauthorized.ABCICode():
return status.Error(codes.Unauthenticated, resp.Log)
case sdkerrors.ErrKeyNotFound.ABCICode():
return status.Error(codes.NotFound, resp.Log)
default:
return status.Error(codes.Unknown, resp.Log)
}
}
// isQueryStoreWithProof expects a format like /<queryType>/<storeName>/<subpath>
// queryType must be "store" and subpath must be "key" to require a proof.
func isQueryStoreWithProof(path string) bool {
if !strings.HasPrefix(path, "/") {
return false
}
paths := strings.SplitN(path[1:], "/", 3)
switch {
case len(paths) != 3:
return false
case paths[0] != "store":
return false
case rootmulti.RequireProof("/" + paths[2]):
return true
}
return false
}
// protoTxProvider is a type which can provide a proto transaction. It is a
// workaround to get access to the wrapper TxBuilder's method GetProtoTx().
type protoTxProvider interface {
GetProtoTx() *txtypes.Tx
}
// BuildSimTx creates an unsigned tx with an empty single signature and returns
// the encoded transaction or an error if the unsigned transaction cannot be built.
func BuildSimTx(txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) {
txb, err := tx.BuildUnsignedTx(txf, msgs...)
if err != nil {
return nil, err
}
// Create an empty signature literal as the ante handler will populate with a
// sentinel pubkey.
sig := signing.SignatureV2{
PubKey: &secp256k1.PubKey{},
Data: &signing.SingleSignatureData{
SignMode: txf.SignMode(),
},
Sequence: txf.Sequence(),
}
if err := txb.SetSignatures(sig); err != nil {
return nil, err
}
protoProvider, ok := txb.(protoTxProvider)
if !ok {
return nil, fmt.Errorf("cannot simulate amino tx")
}
simReq := txtypes.SimulateRequest{Tx: protoProvider.GetProtoTx()}
return simReq.Marshal()
}