-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathfactory.go
608 lines (515 loc) · 18.4 KB
/
factory.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
package tx
import (
"context"
apitxsigning "cosmossdk.io/api/cosmos/tx/signing/v1beta1"
"cosmossdk.io/client/v2/autocli/keyring"
"cosmossdk.io/client/v2/internal/tx"
"cosmossdk.io/client/v2/offchain"
"cosmossdk.io/math"
//"cosmossdk.io/x/tx/signing"
cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring"
"errors"
"fmt"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/client/flags"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/go-bip39"
"github.com/spf13/pflag"
"math/big"
"os"
"strings"
)
// Factory defines a client transaction factory that facilitates generating and
// signing an application-specific transaction.
type Factory struct {
keybase cryptokeyring.Keyring
accountRetriever AccountRetriever
txConfig TxConfig
txParams TxParameters
}
func NewFactoryCLI(clientCtx tx.Context, flagSet *pflag.FlagSet) (Factory, error) {
if clientCtx.Viper == nil {
clientCtx = clientCtx.WithViper("")
}
if err := clientCtx.Viper.BindPFlags(flagSet); err != nil {
return Factory{}, fmt.Errorf("failed to bind flags to viper: %w", err)
}
var accNum, accSeq uint64
if clientCtx.Offline {
if flagSet.Changed(flags.FlagAccountNumber) && flagSet.Changed(flags.FlagSequence) {
accNum = clientCtx.Viper.GetUint64(flags.FlagAccountNumber)
accSeq = clientCtx.Viper.GetUint64(flags.FlagSequence)
} else {
return Factory{}, fmt.Errorf("account-number and sequence must be set in offline mode")
}
}
if clientCtx.Offline && clientCtx.GenerateOnly {
if clientCtx.ChainID != "" {
return Factory{}, errors.New("chain ID cannot be used when offline and generate-only flags are set")
}
} else if clientCtx.ChainID == "" {
return Factory{}, errors.New("chain ID required but not specified")
}
signMode := flags.ParseSignModeStr(clientCtx.SignModeStr)
memo := clientCtx.Viper.GetString(flags.FlagNote)
timeoutHeight := clientCtx.Viper.GetUint64(flags.FlagTimeoutHeight)
unordered := clientCtx.Viper.GetBool(flags.FlagUnordered)
gasAdj := clientCtx.Viper.GetFloat64(flags.FlagGasAdjustment)
gasStr := clientCtx.Viper.GetString(flags.FlagGas)
gasSetting, _ := flags.ParseGasSetting(gasStr)
gasPricesStr := clientCtx.Viper.GetString(flags.FlagGasPrices)
feesStr := clientCtx.Viper.GetString(flags.FlagFees)
f := Factory{
accountRetriever: clientCtx.AccountRetriever,
keybase: clientCtx.Keyring,
txParams: TxParameters{
timeoutHeight: timeoutHeight,
memo: memo,
chainID: clientCtx.ChainID,
signMode: signMode,
AccountConfig: AccountConfig{
accountNumber: accNum,
sequence: accSeq,
fromName: clientCtx.FromName,
fromAddress: sdk.MustAccAddressFromBech32(clientCtx.FromAddress),
},
GasConfig: GasConfig{
gas: gasSetting.Gas,
gasAdjustment: gasAdj,
},
FeeConfig: FeeConfig{
feeGranter: sdk.MustAccAddressFromBech32(clientCtx.FeeGranter),
feePayer: sdk.MustAccAddressFromBech32(clientCtx.FeePayer),
},
ExecutionOptions: ExecutionOptions{
unordered: unordered,
offline: clientCtx.Offline,
generateOnly: clientCtx.GenerateOnly,
simulateAndExecute: gasSetting.Simulate,
preprocessTxHook: clientCtx.PreprocessTxHook,
},
},
}
// Properties that need special parsing
f = f.WithFees(feesStr).WithGasPrices(gasPricesStr)
return f, nil
}
// Prepare ensures the account defined by ctx.GetFromAddress() exists and
// if the account number and/or the account sequence number are zero (not set),
// they will be queried for and set on the provided Factory.
// A new Factory with the updated fields will be returned.
// Note: When in offline mode, the Prepare does nothing and returns the original factory.
func (f Factory) Prepare(clientCtx tx.Context) (Factory, error) {
if f.txParams.ExecutionOptions.offline {
return f, nil
}
if f.txParams.fromAddress.Empty() {
return f, errors.New("missing 'from address' field")
}
if err := f.accountRetriever.EnsureExists(clientCtx, f.txParams.fromAddress); err != nil {
return f, err
}
if f.txParams.accountNumber == 0 || f.txParams.sequence == 0 {
fc := f
num, seq, err := fc.accountRetriever.GetAccountNumberSequence(clientCtx, f.txParams.fromAddress)
if err != nil {
return f, err
}
if f.txParams.accountNumber == 0 {
fc = fc.WithAccountNumber(num)
}
if f.txParams.sequence == 0 {
fc = fc.WithSequence(seq)
}
return fc, nil
}
return f, nil
}
// BuildUnsignedTx builds a transaction to be signed given a set of messages.
// Once created, the fee, memo, and messages are set.
func (f Factory) BuildUnsignedTx(msgs ...sdk.Msg) (TxBuilder, error) {
if f.txParams.offline && f.txParams.generateOnly {
if f.txParams.chainID != "" {
return nil, errors.New("chain ID cannot be used when offline and generate-only flags are set")
}
} else if f.txParams.chainID == "" {
return nil, errors.New("chain ID required but not specified")
}
fees := f.txParams.fees
if !f.txParams.gasPrices.IsZero() {
if !fees.IsZero() {
return nil, errors.New("cannot provide both fees and gas prices")
}
// f.gas is a uint64 and we should convert to LegacyDec
// without the risk of under/overflow via uint64->int64.
glDec := math.LegacyNewDecFromBigInt(new(big.Int).SetUint64(f.txParams.gas))
// Derive the fees based on the provided gas prices, where
// fee = ceil(gasPrice * gasLimit).
fees = make([]sdk.Coin, len(f.txParams.gasPrices))
for i, gp := range f.txParams.gasPrices {
fee := gp.Amount.Mul(glDec)
fees[i] = sdk.Coin{Denom: gp.Denom, Amount: fee.Ceil().RoundInt()}
}
}
if err := ValidateMemo(f.txParams.memo); err != nil {
return nil, err
}
txBuilder := f.txConfig.NewTxBuilder()
if err := txBuilder.SetMsgs(msgs...); err != nil {
return nil, err
}
txBuilder.SetMemo(f.txParams.memo)
txBuilder.SetFeeAmount(fees)
txBuilder.SetGasLimit(f.txParams.gas)
txBuilder.SetFeeGranter(f.txParams.feeGranter.String())
txBuilder.SetFeePayer(f.txParams.feePayer.String())
txBuilder.SetTimeoutHeight(f.txParams.timeoutHeight)
if etx, ok := txBuilder.(ExtendedTxBuilder); ok {
etx.SetExtensionOptions(f.txParams.ExtOptions...)
}
return txBuilder, nil
}
// PrintUnsignedTx will generate an unsigned transaction and print it to the writer
// specified by ctx.Output. If simulation was requested, the gas will be
// simulated and also printed to the same writer before the transaction is
// printed.
func (f Factory) PrintUnsignedTx(clientCtx tx.Context, msgs ...sdk.Msg) error {
if f.SimulateAndExecute() {
if clientCtx.Offline {
return errors.New("cannot estimate gas in offline mode")
}
// Prepare TxFactory with acc & seq numbers as CalculateGas requires
// account and sequence numbers to be set
preparedTxf, err := f.Prepare(clientCtx)
if err != nil {
return err
}
_, adjusted, err := CalculateGas(clientCtx, preparedTxf, msgs...)
if err != nil {
return err
}
f.WithGas(adjusted)
_, _ = fmt.Fprintf(os.Stderr, "%s\n", GasEstimateResponse{GasEstimate: f.Gas()})
}
unsignedTx, err := f.BuildUnsignedTx(msgs...)
if err != nil {
return err
}
encoder := f.txConfig.TxJSONEncoder()
if encoder == nil {
return errors.New("cannot print unsigned tx: tx json encoder is nil")
}
json, err := encoder(unsignedTx.GetTx())
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%s\n", json))
}
// 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 (f Factory) BuildSimTx(msgs ...sdk.Msg) ([]byte, error) {
txb, err := f.BuildUnsignedTx(msgs...)
if err != nil {
return nil, err
}
pk, err := f.getSimPK()
if err != nil {
return nil, err
}
// Create an empty signature literal as the ante handler will populate with a
// sentinel pubkey.
sig := offchain.OffchainSignature{
PubKey: pk,
Data: f.getSimSignatureData(pk),
Sequence: f.Sequence(),
}
if err := txb.SetSignatures(sig); err != nil {
return nil, err
}
encoder := f.txConfig.TxEncoder()
if encoder == nil {
return nil, fmt.Errorf("cannot simulate tx: tx encoder is nil")
}
return encoder(txb.GetTx())
}
// Sign signs a given tx with a named key. The bytes signed over are canonical.
// The resulting signature will be added to the transaction builder overwriting the previous
// ones if overwrite=true (otherwise, the signature will be appended).
// Signing a transaction with multiple signers in the DIRECT mode is not supported and will
// return an error.
// An error is returned upon failure.
func (f Factory) Sign(ctx context.Context, name string, txBuilder TxBuilder, overwriteSig bool) error {
if f.keybase == nil {
return errors.New("keybase must be set prior to signing a transaction")
}
var err error
signMode := f.txParams.signMode
if signMode == apitxsigning.SignMode_SIGN_MODE_UNSPECIFIED {
signMode = f.txConfig.SignModeHandler().DefaultMode()
}
pubKey, err := f.keybase.GetPubKey(name)
if err != nil {
return err
}
signerData := offchain.SignerData{
ChainID: f.txParams.chainID,
AccountNumber: f.txParams.accountNumber,
Sequence: f.txParams.sequence,
PubKey: pubKey,
Address: sdk.AccAddress(pubKey.Address()).String(),
}
tx := txBuilder.GetTx()
txWrap := TxWrapper{Tx: &tx}
// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on
// TxBuilder under the hood, and SignerInfos is needed to be generated the
// sign bytes. This is the reason for setting SetSignatures here, with a
// nil signature.
//
// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it
// also doesn't affect its generated sign bytes, so for code's simplicity
// sake, we put it here.
sigData := offchain.SingleSignatureData{
SignMode: signMode,
Signature: nil,
}
sig := offchain.OffchainSignature{
PubKey: pubKey,
Data: &sigData,
Sequence: f.txParams.sequence,
}
var prevSignatures []offchain.OffchainSignature
if !overwriteSig {
prevSignatures, err = txWrap.GetSignatures()
if err != nil {
return err
}
}
// Overwrite or append signer infos.
var sigs []offchain.OffchainSignature
if overwriteSig {
sigs = []offchain.OffchainSignature{sig}
} else {
sigs = append(sigs, prevSignatures...)
sigs = append(sigs, sig)
}
if err := txBuilder.SetSignatures(sigs...); err != nil {
return err
}
if err := checkMultipleSigners(txWrap); err != nil {
return err
}
bytesToSign, err := f.GetSignBytesAdapter(ctx, signerData, txBuilder)
if err != nil {
return err
}
// Sign those bytes
sigBytes, err := f.keybase.Sign(name, bytesToSign, signMode)
if err != nil {
return err
}
// Construct the SignatureV2 struct
sigData = offchain.SingleSignatureData{
SignMode: signMode,
Signature: sigBytes,
}
sig = offchain.OffchainSignature{
PubKey: pubKey,
Data: &sigData,
Sequence: f.txParams.sequence,
}
if overwriteSig {
err = txBuilder.SetSignatures(sig)
} else {
prevSignatures = append(prevSignatures, sig)
err = txBuilder.SetSignatures(prevSignatures...)
}
if err != nil {
return fmt.Errorf("unable to set signatures on payload: %w", err)
}
// Run optional preprocessing if specified. By default, this is unset
// and will return nil.
return f.PreprocessTx(name, txBuilder)
}
// GetSignBytesAdapter returns the sign bytes for a given transaction and sign mode.
func (f Factory) GetSignBytesAdapter(ctx context.Context, signerData offchain.SignerData, builder TxBuilder) ([]byte, error) {
txSignerData := offchain.SignerData{
ChainID: signerData.ChainID,
AccountNumber: signerData.AccountNumber,
Sequence: signerData.Sequence,
Address: signerData.Address,
PubKey: signerData.PubKey,
}
// Generate the bytes to be signed.
return f.txConfig.SignModeHandler().GetSignBytes(ctx, f.SignMode(), txSignerData, builder.GetSigningTxData())
}
func ValidateMemo(memo string) error {
// Prevent simple inclusion of a valid mnemonic in the memo field
if memo != "" && bip39.IsMnemonicValid(strings.ToLower(memo)) {
return errors.New("cannot provide a valid mnemonic seed in the memo field")
}
return nil
}
// WithAccountRetriever returns a copy of the Factory with an updated AccountRetriever.
func (f Factory) WithAccountRetriever(ar AccountRetriever) Factory {
f.accountRetriever = ar
return f
}
// WithChainID returns a copy of the Factory with an updated chainID.
func (f Factory) WithChainID(chainID string) Factory {
f.txParams.chainID = chainID
return f
}
// WithGas returns a copy of the Factory with an updated gas value.
func (f Factory) WithGas(gas uint64) Factory {
f.txParams.gas = gas
return f
}
// WithFees returns a copy of the Factory with an updated fee.
func (f Factory) WithFees(fees string) Factory {
parsedFees, err := sdk.ParseCoinsNormalized(fees)
if err != nil {
panic(err)
}
f.txParams.fees = parsedFees
return f
}
// WithGasPrices returns a copy of the Factory with updated gas prices.
func (f Factory) WithGasPrices(gasPrices string) Factory {
parsedGasPrices, err := sdk.ParseDecCoins(gasPrices)
if err != nil {
panic(err)
}
f.txParams.gasPrices = parsedGasPrices
return f
}
// WithKeybase returns a copy of the Factory with updated Keybase.
func (f Factory) WithKeybase(keybase keyring.Keyring) Factory {
f.keybase = keybase
return f
}
// WithFromName returns a copy of the Factory with updated fromName
// fromName will be use for building a simulation tx.
func (f Factory) WithFromName(fromName string) Factory {
f.txParams.fromName = fromName
return f
}
// WithSequence returns a copy of the Factory with an updated sequence number.
func (f Factory) WithSequence(sequence uint64) Factory {
f.txParams.sequence = sequence
return f
}
// WithMemo returns a copy of the Factory with an updated memo.
func (f Factory) WithMemo(memo string) Factory {
f.txParams.memo = memo
return f
}
// WithAccountNumber returns a copy of the Factory with an updated account number.
func (f Factory) WithAccountNumber(accnum uint64) Factory {
f.txParams.accountNumber = accnum
return f
}
// WithGasAdjustment returns a copy of the Factory with an updated gas adjustment.
func (f Factory) WithGasAdjustment(gasAdj float64) Factory {
f.txParams.gasAdjustment = gasAdj
return f
}
// WithSimulateAndExecute returns a copy of the Factory with an updated gas
// simulation value.
func (f Factory) WithSimulateAndExecute(sim bool) Factory {
f.txParams.simulateAndExecute = sim
return f
}
// WithSignMode returns a copy of the Factory with an updated sign mode value.
func (f Factory) WithSignMode(mode apitxsigning.SignMode) Factory {
f.txParams.signMode = mode
return f
}
// WithTimeoutHeight returns a copy of the Factory with an updated timeout height.
func (f Factory) WithTimeoutHeight(height uint64) Factory {
f.txParams.timeoutHeight = height
return f
}
// WithFeeGranter returns a copy of the Factory with an updated fee granter.
func (f Factory) WithFeeGranter(fg sdk.AccAddress) Factory {
f.txParams.feeGranter = fg
return f
}
// WithFeePayer returns a copy of the Factory with an updated fee granter.
func (f Factory) WithFeePayer(fp sdk.AccAddress) Factory {
f.txParams.feePayer = fp
return f
}
// WithPreprocessTxHook returns a copy of the Factory with an updated preprocess tx function,
// allows for preprocessing of transaction data using the TxBuilder.
func (f Factory) WithPreprocessTxHook(preprocessFn tx.PreprocessTxFn) Factory {
f.txParams.preprocessTxHook = preprocessFn
return f
}
func (f Factory) WithExtensionOptions(extOpts ...*codectypes.Any) Factory {
f.txParams.ExtOptions = extOpts
return f
}
// PreprocessTx calls the preprocessing hook with the factory parameters and
// returns the result.
func (f Factory) PreprocessTx(keyname string, builder TxBuilder) error {
if f.txParams.preprocessTxHook == nil {
// Allow pass-through
return nil
}
key, err := f.Keybase().Key(keyname)
if err != nil {
return fmt.Errorf("error retrieving key from keyring: %w", err)
}
return f.txParams.preprocessTxHook(f.txParams.chainID, cryptokeyring.KeyType(f.Keybase().GetRecordType(key)), builder)
}
func (f Factory) AccountNumber() uint64 { return f.txParams.accountNumber }
func (f Factory) Sequence() uint64 { return f.txParams.sequence }
func (f Factory) Gas() uint64 { return f.txParams.gas }
func (f Factory) GasAdjustment() float64 { return f.txParams.gasAdjustment }
func (f Factory) Keybase() keyring.Keyring { return f.keybase }
func (f Factory) ChainID() string { return f.txParams.chainID }
func (f Factory) Memo() string { return f.txParams.memo }
func (f Factory) Fees() sdk.Coins { return f.txParams.fees }
func (f Factory) GasPrices() sdk.DecCoins { return f.txParams.gasPrices }
func (f Factory) AccountRetriever() AccountRetriever { return f.accountRetriever }
func (f Factory) TimeoutHeight() uint64 { return f.txParams.timeoutHeight }
func (f Factory) FromName() string { return f.txParams.fromName }
func (f Factory) SimulateAndExecute() bool { return f.txParams.simulateAndExecute }
func (f Factory) SignMode() apitxsigning.SignMode { return f.txParams.signMode }
// getSimPK gets the public key to use for building a simulation tx.
// Note, we should only check for keys in the keybase if we are in simulate and execute mode,
// e.g. when using --gas=auto.
// When using --dry-run, we are is simulation mode only and should not check the keybase.
// Ref: https://github.com/cosmos/cosmos-sdk/issues/11283
func (f Factory) getSimPK() (cryptotypes.PubKey, error) {
var (
err error
pk cryptotypes.PubKey = cryptotypes.EmptyPubKey{}
)
if f.txParams.simulateAndExecute && f.keybase != nil {
pk, err = f.keybase.GetPubKey(f.txParams.fromName)
if err != nil {
return nil, err
}
}
return pk, nil
}
// getSimSignatureData based on the pubKey type gets the correct SignatureData type
// to use for building a simulation tx.
func (f Factory) getSimSignatureData(pk cryptotypes.PubKey) offchain.SignatureData {
multisigPubKey, ok := pk.(*cryptotypes.DummyMultiSig)
if !ok {
return &offchain.SingleSignatureData{SignMode: f.txParams.signMode}
}
multiSignatureData := make([]offchain.SignatureData, 0, multisigPubKey.Threshold)
for i := uint32(0); i < multisigPubKey.Threshold; i++ {
multiSignatureData = append(multiSignatureData, &offchain.SingleSignatureData{
SignMode: f.SignMode(),
})
}
return &offchain.MultiSignatureData{
Signatures: multiSignatureData,
}
}