From 5c0e3b4de5b808765b1ec4793cfdba30401e023e Mon Sep 17 00:00:00 2001 From: Amaury Martiny Date: Mon, 20 Jul 2020 14:30:12 +0200 Subject: [PATCH] x/auth/ante: Migrate tests to use the new client.TxConfig (#6661) * WIP: using encoding config * Make it compile, test fails * test should be okay * Make tests pass * Add comments * Convert more tests * Make TestAnteHandlerSigErrors work * Make first 2 tests pass * TestAnteHandlerAccountNumbers * Use table tests * Remove print * Use test table * TestAnteHandlerSigErrors * TestAnteHandlerAccountNumbers * TestAnteHandlerAccountNumbers * Refactor TestAccount * Refactor getSignBytes * TestAnteHandlerAccountNumbersAtBlockHeightZero * TestAnteHandlerSequences * TestAnteHandlerFees * TestAnteHandlerMultiSigner * TestAnteHandlerBadSignBytes * TestAnteHandlerSetPubKey * TestAnteHandlerSigLimitExceeded * TestCustomSignatureVerificationGasConsumer * TestAnteHandlerReCheck * Make all tests pass * Refactor a little bit more * Fee test * SetupTest * All tests pass * Refactor to RunTestCase * Don't use StdFee * Revert some little stuff * Finish up last couple of test cases * Less verbose * s/TxGenerator/TxConfig * Add comments * Indent * Move KeyTestPubAddr to testdata * Move testdata to /testutil * Revert to use signature: nil step in signing * Add comments Co-authored-by: Alexander Bezobchuk --- baseapp/baseapp_test.go | 2 +- baseapp/grpcrouter_test.go | 2 +- client/context.go | 8 +- client/context_test.go | 2 +- client/testutil/suite.go | 65 +- client/tx/factory.go | 10 +- client/tx/tx.go | 133 +- client/tx/tx_test.go | 14 +- client/tx_generator.go | 4 +- codec/amino_codec_test.go | 2 +- codec/any_test.go | 2 +- codec/hybrid_codec_test.go | 2 +- codec/proto_codec_test.go | 2 +- codec/testdata/test_msg.go | 26 - codec/types/compat_test.go | 2 +- codec/types/types_test.go | 2 +- scripts/protocgen.sh | 2 +- simapp/app.go | 2 +- simapp/helpers/test_helpers.go | 2 +- simapp/params/amino.go | 2 +- simapp/params/encoding.go | 2 +- simapp/simd/cmd/root.go | 2 +- simapp/test_helpers.go | 4 +- tests/cli/grpc_query_test.go | 2 +- testutil/network/network.go | 6 +- {codec => testutil}/testdata/animal.go | 0 {codec => testutil}/testdata/proto.pb.go | 0 {codec => testutil}/testdata/proto.proto | 2 +- {codec => testutil}/testdata/test_helper.go | 0 {codec => testutil}/testdata/test_service.go | 0 testutil/testdata/test_tx.go | 47 + types/tx_msg_test.go | 2 +- x/auth/ante/ante_test.go | 1488 +++++++++++------- x/auth/ante/basic_test.go | 151 +- x/auth/ante/fee_test.go | 95 +- x/auth/ante/setup_test.go | 75 +- x/auth/ante/sigverify.go | 2 +- x/auth/ante/sigverify_test.go | 220 +-- x/auth/ante/testutil_test.go | 120 ++ x/auth/client/cli/broadcast.go | 2 +- x/auth/client/cli/cli_test.go | 4 +- x/auth/client/cli/decode.go | 2 +- x/auth/client/cli/encode.go | 2 +- x/auth/client/cli/encode_test.go | 12 +- x/auth/client/tx.go | 2 +- x/auth/client/tx_test.go | 10 +- x/auth/keeper/grpc_query_test.go | 3 +- x/auth/keeper/querier_test.go | 3 +- x/auth/signing/direct/direct_test.go | 7 +- x/auth/signing/verify_test.go | 6 +- x/auth/tx/builder_test.go | 23 +- x/auth/tx/generator.go | 4 +- x/auth/tx/generator_test.go | 4 +- x/auth/tx/sigs_test.go | 2 +- x/auth/types/account_test.go | 9 +- x/auth/types/client_tx.go | 22 +- x/auth/types/client_tx_test.go | 8 +- x/auth/types/stdtx_test.go | 39 +- x/auth/types/test_utils.go | 77 - x/auth/types/txbuilder_test.go | 2 +- x/auth/vesting/types/test_common.go | 2 +- x/auth/vesting/types/vesting_account_test.go | 31 +- x/bank/app_test.go | 12 +- x/bank/bench_test.go | 4 +- x/bank/handler_test.go | 2 +- x/bank/keeper/grpc_query_test.go | 6 +- x/bank/keeper/querier_test.go | 6 +- x/bank/simulation/operations.go | 4 +- x/crisis/handler_test.go | 2 +- x/distribution/client/cli/tx_test.go | 2 +- x/distribution/simulation/operations.go | 8 +- x/gov/handler_test.go | 2 +- x/gov/simulation/operations.go | 6 +- x/ibc/testing/chain.go | 8 +- x/slashing/app_test.go | 2 +- x/slashing/handler_test.go | 2 +- x/slashing/simulation/operations.go | 2 +- x/staking/app_test.go | 2 +- x/staking/client/cli/tx.go | 2 +- x/staking/handler_test.go | 2 +- x/staking/simulation/operations.go | 10 +- x/upgrade/client/rest/tx.go | 6 +- 82 files changed, 1686 insertions(+), 1184 deletions(-) delete mode 100644 codec/testdata/test_msg.go rename {codec => testutil}/testdata/animal.go (100%) rename {codec => testutil}/testdata/proto.pb.go (100%) rename {codec => testutil}/testdata/proto.proto (94%) rename {codec => testutil}/testdata/test_helper.go (100%) rename {codec => testutil}/testdata/test_service.go (100%) create mode 100644 testutil/testdata/test_tx.go create mode 100644 x/auth/ante/testutil_test.go delete mode 100644 x/auth/types/test_utils.go diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 056a51ddc9..3dcef1600b 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -10,7 +10,7 @@ import ( "sync" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/gogo/protobuf/jsonpb" "github.com/stretchr/testify/assert" diff --git a/baseapp/grpcrouter_test.go b/baseapp/grpcrouter_test.go index 5e4c905163..13e839a231 100644 --- a/baseapp/grpcrouter_test.go +++ b/baseapp/grpcrouter_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/client/context.go b/client/context.go index 2d74aa2776..40a7c7c163 100644 --- a/client/context.go +++ b/client/context.go @@ -47,7 +47,7 @@ type Context struct { GenerateOnly bool Offline bool SkipConfirm bool - TxGenerator TxGenerator + TxConfig TxConfig AccountRetriever AccountRetriever NodeURI string Verifier tmlite.Verifier @@ -319,9 +319,9 @@ func (ctx Context) WithSkipConfirmation(skip bool) Context { return ctx } -// WithTxGenerator returns the context with an updated TxGenerator -func (ctx Context) WithTxGenerator(generator TxGenerator) Context { - ctx.TxGenerator = generator +// WithTxConfig returns the context with an updated TxConfig +func (ctx Context) WithTxConfig(generator TxConfig) Context { + ctx.TxConfig = generator return ctx } diff --git a/client/context_test.go b/client/context_test.go index 3276d73f37..0027bcd0e7 100644 --- a/client/context_test.go +++ b/client/context_test.go @@ -6,8 +6,8 @@ import ( "testing" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/client/testutil/suite.go b/client/testutil/suite.go index c85dcf51b3..c6d35c181f 100644 --- a/client/testutil/suite.go +++ b/client/testutil/suite.go @@ -3,10 +3,9 @@ package testutil import ( "bytes" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/x/auth/signing" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/suite" "github.com/tendermint/tendermint/crypto" @@ -17,27 +16,27 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// TxGeneratorTestSuite provides a test suite that can be used to test that a TxGenerator implementation is correct -//nolint:golint // type name will be used as tx.TxGeneratorTestSuite by other packages, and that stutters; consider calling this GeneratorTestSuite -type TxGeneratorTestSuite struct { +// TxConfigTestSuite provides a test suite that can be used to test that a TxConfig implementation is correct +//nolint:golint // type name will be used as tx.TxConfigTestSuite by other packages, and that stutters; consider calling this GeneratorTestSuite +type TxConfigTestSuite struct { suite.Suite - TxGenerator client.TxGenerator + TxConfig client.TxConfig } -// NewTxGeneratorTestSuite returns a new TxGeneratorTestSuite with the provided TxGenerator implementation -func NewTxGeneratorTestSuite(txGenerator client.TxGenerator) *TxGeneratorTestSuite { - return &TxGeneratorTestSuite{TxGenerator: txGenerator} +// NewTxConfigTestSuite returns a new TxConfigTestSuite with the provided TxConfig implementation +func NewTxConfigTestSuite(txConfig client.TxConfig) *TxConfigTestSuite { + return &TxConfigTestSuite{TxConfig: txConfig} } -func (s *TxGeneratorTestSuite) TestTxBuilderGetTx() { - txBuilder := s.TxGenerator.NewTxBuilder() +func (s *TxConfigTestSuite) TestTxBuilderGetTx() { + txBuilder := s.TxConfig.NewTxBuilder() tx := txBuilder.GetTx() s.Require().NotNil(tx) s.Require().Equal(len(tx.GetMsgs()), 0) } -func (s *TxGeneratorTestSuite) TestTxBuilderSetFeeAmount() { - txBuilder := s.TxGenerator.NewTxBuilder() +func (s *TxConfigTestSuite) TestTxBuilderSetFeeAmount() { + txBuilder := s.TxConfig.NewTxBuilder() feeAmount := sdk.Coins{ sdk.NewInt64Coin("atom", 20000000), } @@ -46,30 +45,30 @@ func (s *TxGeneratorTestSuite) TestTxBuilderSetFeeAmount() { s.Require().Equal(feeAmount, feeTx.GetFee()) } -func (s *TxGeneratorTestSuite) TestTxBuilderSetGasLimit() { +func (s *TxConfigTestSuite) TestTxBuilderSetGasLimit() { const newGas uint64 = 300000 - txBuilder := s.TxGenerator.NewTxBuilder() + txBuilder := s.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(newGas) feeTx := txBuilder.GetTx() s.Require().Equal(newGas, feeTx.GetGas()) } -func (s *TxGeneratorTestSuite) TestTxBuilderSetMemo() { +func (s *TxConfigTestSuite) TestTxBuilderSetMemo() { const newMemo string = "newfoomemo" - txBuilder := s.TxGenerator.NewTxBuilder() + txBuilder := s.TxConfig.NewTxBuilder() txBuilder.SetMemo(newMemo) txWithMemo := txBuilder.GetTx() s.Require().Equal(txWithMemo.GetMemo(), newMemo) } -func (s *TxGeneratorTestSuite) TestTxBuilderSetMsgs() { - _, _, addr1 := authtypes.KeyTestPubAddr() - _, _, addr2 := authtypes.KeyTestPubAddr() +func (s *TxConfigTestSuite) TestTxBuilderSetMsgs() { + _, _, addr1 := testdata.KeyTestPubAddr() + _, _, addr2 := testdata.KeyTestPubAddr() msg1 := testdata.NewTestMsg(addr1) msg2 := testdata.NewTestMsg(addr2) msgs := []sdk.Msg{msg1, msg2} - txBuilder := s.TxGenerator.NewTxBuilder() + txBuilder := s.TxConfig.NewTxBuilder() err := txBuilder.SetMsgs(msgs...) s.Require().NoError(err) @@ -80,12 +79,12 @@ func (s *TxGeneratorTestSuite) TestTxBuilderSetMsgs() { s.Require().Error(tx.ValidateBasic()) // should fail because of no signatures } -func (s *TxGeneratorTestSuite) TestTxBuilderSetSignatures() { - privKey, pubkey, addr := authtypes.KeyTestPubAddr() - privKey2, pubkey2, _ := authtypes.KeyTestPubAddr() +func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { + privKey, pubkey, addr := testdata.KeyTestPubAddr() + privKey2, pubkey2, _ := testdata.KeyTestPubAddr() multisigPk := multisig.NewPubKeyMultisigThreshold(2, []crypto.PubKey{pubkey, pubkey2}) - txBuilder := s.TxGenerator.NewTxBuilder() + txBuilder := s.TxConfig.NewTxBuilder() // set test msg msg := testdata.NewTestMsg(addr) @@ -97,7 +96,7 @@ func (s *TxGeneratorTestSuite) TestTxBuilderSetSignatures() { // check that validation fails s.Require().Error(txBuilder.GetTx().ValidateBasic()) - signModeHandler := s.TxGenerator.SignModeHandler() + signModeHandler := s.TxConfig.SignModeHandler() s.Require().Contains(signModeHandler.Modes(), signModeHandler.DefaultMode()) // set SignatureV2 without actual signature bytes @@ -227,8 +226,8 @@ func sigDataEquals(data1, data2 signingtypes.SignatureData) bool { } } -func (s *TxGeneratorTestSuite) TestTxEncodeDecode() { - _, pubkey, addr := authtypes.KeyTestPubAddr() +func (s *TxConfigTestSuite) TestTxEncodeDecode() { + _, pubkey, addr := testdata.KeyTestPubAddr() feeAmount := sdk.Coins{sdk.NewInt64Coin("atom", 150)} gasLimit := uint64(50000) memo := "foomemo" @@ -242,7 +241,7 @@ func (s *TxGeneratorTestSuite) TestTxEncodeDecode() { }, } - txBuilder := s.TxGenerator.NewTxBuilder() + txBuilder := s.TxConfig.NewTxBuilder() txBuilder.SetFeeAmount(feeAmount) txBuilder.SetGasLimit(gasLimit) txBuilder.SetMemo(memo) @@ -253,12 +252,12 @@ func (s *TxGeneratorTestSuite) TestTxEncodeDecode() { tx := txBuilder.GetTx() s.T().Log("encode transaction") - txBytes, err := s.TxGenerator.TxEncoder()(tx) + txBytes, err := s.TxConfig.TxEncoder()(tx) s.Require().NoError(err) s.Require().NotNil(txBytes) s.T().Log("decode transaction") - tx2, err := s.TxGenerator.TxDecoder()(txBytes) + tx2, err := s.TxConfig.TxDecoder()(txBytes) s.Require().NoError(err) tx3, ok := tx2.(signing.SigFeeMemoTx) s.Require().True(ok) @@ -270,12 +269,12 @@ func (s *TxGeneratorTestSuite) TestTxEncodeDecode() { s.Require().Equal([]crypto.PubKey{pubkey}, tx3.GetPubKeys()) s.T().Log("JSON encode transaction") - jsonTxBytes, err := s.TxGenerator.TxJSONEncoder()(tx) + jsonTxBytes, err := s.TxConfig.TxJSONEncoder()(tx) s.Require().NoError(err) s.Require().NotNil(jsonTxBytes) s.T().Log("JSON decode transaction") - tx2, err = s.TxGenerator.TxJSONDecoder()(jsonTxBytes) + tx2, err = s.TxConfig.TxJSONDecoder()(jsonTxBytes) s.Require().NoError(err) tx3, ok = tx2.(signing.SigFeeMemoTx) s.Require().True(ok) diff --git a/client/tx/factory.go b/client/tx/factory.go index 97884b5b47..44f73034af 100644 --- a/client/tx/factory.go +++ b/client/tx/factory.go @@ -17,7 +17,7 @@ import ( // signing an application-specific transaction. type Factory struct { keybase keyring.Keyring - txGenerator client.TxGenerator + txConfig client.TxConfig accountRetriever client.AccountRetriever accountNumber uint64 sequence uint64 @@ -56,7 +56,7 @@ func NewFactoryCLI(clientCtx client.Context, flagSet *pflag.FlagSet) Factory { gasSetting, _ := flags.ParseGasSetting(gasStr) f := Factory{ - txGenerator: clientCtx.TxGenerator, + txConfig: clientCtx.TxConfig, accountRetriever: clientCtx.AccountRetriever, keybase: clientCtx.Keyring, chainID: clientCtx.ChainID, @@ -134,9 +134,9 @@ func (f Factory) AccountRetriever() client.AccountRetriever { return f.accountRe // using the gas from the simulation results func (f Factory) SimulateAndExecute() bool { return f.simulateAndExecute } -// WithTxGenerator returns a copy of the Factory with an updated TxGenerator. -func (f Factory) WithTxGenerator(g client.TxGenerator) Factory { - f.txGenerator = g +// WithTxConfig returns a copy of the Factory with an updated TxConfig. +func (f Factory) WithTxConfig(g client.TxConfig) Factory { + f.txConfig = g return f } diff --git a/client/tx/tx.go b/client/tx/tx.go index cb64ac1b4b..18de4eadac 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -10,6 +10,7 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/spf13/pflag" + "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -33,7 +34,7 @@ func GenerateOrBroadcastTxCLI(clientCtx client.Context, flagSet *pflag.FlagSet, // // TODO: Remove in favor of GenerateOrBroadcastTxCLI func GenerateOrBroadcastTx(clientCtx client.Context, msgs ...sdk.Msg) error { - txf := NewFactoryFromDeprecated(clientCtx.Input).WithTxGenerator(clientCtx.TxGenerator).WithAccountRetriever(clientCtx.AccountRetriever) + txf := NewFactoryFromDeprecated(clientCtx.Input).WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) return GenerateOrBroadcastTxWithFactory(clientCtx, txf, msgs...) } @@ -124,7 +125,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { return err } - txBytes, err := clientCtx.TxGenerator.TxEncoder()(tx.GetTx()) + txBytes, err := clientCtx.TxConfig.TxEncoder()(tx.GetTx()) if err != nil { return err } @@ -162,7 +163,7 @@ func WriteGeneratedTxResponse( WithMemo(br.Memo). WithChainID(br.ChainID). WithSimulateAndExecute(br.Simulate). - WithTxGenerator(ctx.TxGenerator) + WithTxConfig(ctx.TxConfig) if br.Simulate || gasSetting.Simulate { if gasAdj < 0 { @@ -225,7 +226,7 @@ func BuildUnsignedTx(txf Factory, msgs ...sdk.Msg) (client.TxBuilder, error) { } } - tx := txf.txGenerator.NewTxBuilder() + tx := txf.txConfig.NewTxBuilder() if err := tx.SetMsgs(msgs...); err != nil { return nil, err @@ -254,7 +255,7 @@ func BuildSimTx(txf Factory, msgs ...sdk.Msg) ([]byte, error) { return nil, err } - return txf.txGenerator.TxEncoder()(tx.GetTx()) + return txf.txConfig.TxEncoder()(tx.GetTx()) } // CalculateGas simulates the execution of a transaction and returns the @@ -310,6 +311,83 @@ func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { return txf, nil } +// Helper function to retrieve sign bytes. +func getSignBytes( + signMode signing.SignMode, + signerData authsigning.SignerData, + txBuilder client.TxBuilder, + pubKey crypto.PubKey, + txConfig client.TxConfig, +) ([]byte, error) { + sigData := signing.SingleSignatureData{ + SignMode: signMode, + Signature: nil, + } + sig := signing.SignatureV2{ + PubKey: pubKey, + Data: &sigData, + } + // For SIGN_MODE_DIRECT, calling SetSignatures calls SetSignerInfos on + // TxBuilder under the hood, and SignerInfos is needed to 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, along with this comment. + err := txBuilder.SetSignatures(sig) + if err != nil { + return nil, err + } + + // Generate the bytes to be signed + signBytes, err := txConfig.SignModeHandler().GetSignBytes( + signMode, + signerData, + txBuilder.GetTx(), + ) + if err != nil { + return nil, err + } + + return signBytes, nil +} + +// SignWithPrivKey signs a given tx with the given private key, and returns the +// corresponding SignatureV2 if the signing is successful. +func SignWithPrivKey( + signMode signing.SignMode, + signerData authsigning.SignerData, + txBuilder client.TxBuilder, + priv crypto.PrivKey, + txConfig client.TxConfig, +) (signing.SignatureV2, error) { + var sigV2 signing.SignatureV2 + + // Generate the bytes to be signed + signBytes, err := getSignBytes(signMode, signerData, txBuilder, priv.PubKey(), txConfig) + if err != nil { + return sigV2, err + } + + // Sign those bytes + signature, err := priv.Sign(signBytes) + if err != nil { + return sigV2, err + } + + // Construct the SignatureV2 struct + sigData := signing.SingleSignatureData{ + SignMode: signMode, + Signature: signature, + } + sigV2 = signing.SignatureV2{ + PubKey: priv.PubKey(), + Data: &sigData, + } + + return sigV2, nil +} + // Sign signs a given tx with the provided name and passphrase. If the Factory's // Keybase is not set, a new one will be created based on the client's backend. // The bytes signed over are canconical. The resulting signature will be set on @@ -318,7 +396,7 @@ func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { // // Note, It is assumed the Factory has the necessary fields set that are required // by the CanonicalSignBytes call. -func Sign(txf Factory, name string, tx client.TxBuilder) error { +func Sign(txf Factory, name string, txBuilder client.TxBuilder) error { if txf.keybase == nil { return errors.New("keybase must be set prior to signing a transaction") } @@ -326,7 +404,7 @@ func Sign(txf Factory, name string, tx client.TxBuilder) error { signMode := txf.signMode if signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED { // use the SignModeHandler's default mode if unspecified - signMode = txf.txGenerator.SignModeHandler().DefaultMode() + signMode = txf.txConfig.SignModeHandler().DefaultMode() } key, err := txf.keybase.Key(name) @@ -335,43 +413,36 @@ func Sign(txf Factory, name string, tx client.TxBuilder) error { } pubKey := key.GetPubKey() - sigData := &signing.SingleSignatureData{ - SignMode: signMode, - Signature: nil, + signerData := authsigning.SignerData{ + ChainID: txf.chainID, + AccountNumber: txf.accountNumber, + AccountSequence: txf.sequence, } - sig := signing.SignatureV2{ - PubKey: pubKey, - Data: sigData, - } - err = tx.SetSignatures(sig) - if err != nil { - return err - } - - signBytes, err := txf.txGenerator.SignModeHandler().GetSignBytes( - signMode, - authsigning.SignerData{ - ChainID: txf.chainID, - AccountNumber: txf.accountNumber, - AccountSequence: txf.sequence, - }, tx.GetTx(), - ) + + // Generate the bytes to be signed + signBytes, err := getSignBytes(signMode, signerData, txBuilder, pubKey, txf.txConfig) if err != nil { return err } + // Sign those bytes sigBytes, _, err := txf.keybase.Sign(name, signBytes) if err != nil { return err } - sigData.Signature = sigBytes - sig = signing.SignatureV2{ + // Construct the SignatureV2 struct + sigData := signing.SingleSignatureData{ + SignMode: signMode, + Signature: sigBytes, + } + sig := signing.SignatureV2{ PubKey: pubKey, - Data: sigData, + Data: &sigData, } - return tx.SetSignatures(sig) + // And here the tx is populated with the signature + return txBuilder.SetSignatures(sig) } // GasEstimateResponse defines a response definition for tx gas estimation. diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index b129e61879..fb3f36c578 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -21,9 +21,9 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) -func NewTestTxGenerator() client.TxGenerator { +func NewTestTxConfig() client.TxConfig { _, cdc := simapp.MakeCodecs() - return types.StdTxGenerator{Cdc: cdc} + return types.StdTxConfig{Cdc: cdc} } func TestCalculateGas(t *testing.T) { @@ -65,7 +65,7 @@ func TestCalculateGas(t *testing.T) { for _, tc := range testCases { stc := tc - txf := tx.Factory{}.WithChainID("test-chain").WithTxGenerator(NewTestTxGenerator()) + txf := tx.Factory{}.WithChainID("test-chain").WithTxConfig(NewTestTxConfig()) t.Run(stc.name, func(t *testing.T) { queryFunc := makeQueryFunc(stc.args.queryFuncGasUsed, stc.args.queryFuncWantErr) @@ -85,7 +85,7 @@ func TestCalculateGas(t *testing.T) { func TestBuildSimTx(t *testing.T) { txf := tx.Factory{}. - WithTxGenerator(NewTestTxGenerator()). + WithTxConfig(NewTestTxConfig()). WithAccountNumber(50). WithSequence(23). WithFees("50stake"). @@ -100,7 +100,7 @@ func TestBuildSimTx(t *testing.T) { func TestBuildUnsignedTx(t *testing.T) { txf := tx.Factory{}. - WithTxGenerator(NewTestTxGenerator()). + WithTxConfig(NewTestTxConfig()). WithAccountNumber(50). WithSequence(23). WithFees("50stake"). @@ -132,7 +132,7 @@ func TestSign(t *testing.T) { require.NoError(t, err) txf := tx.Factory{}. - WithTxGenerator(NewTestTxGenerator()). + WithTxConfig(NewTestTxConfig()). WithAccountNumber(50). WithSequence(23). WithFees("50stake"). @@ -149,7 +149,7 @@ func TestSign(t *testing.T) { txf = tx.Factory{}. WithKeybase(kr). - WithTxGenerator(NewTestTxGenerator()). + WithTxConfig(NewTestTxConfig()). WithAccountNumber(50). WithSequence(23). WithFees("50stake"). diff --git a/client/tx_generator.go b/client/tx_generator.go index 6718a603de..c5aecb1f46 100644 --- a/client/tx_generator.go +++ b/client/tx_generator.go @@ -7,10 +7,10 @@ import ( ) type ( - // TxGenerator defines an interface a client can utilize to generate an + // TxConfig defines an interface a client can utilize to generate an // application-defined concrete transaction type. The type returned must // implement TxBuilder. - TxGenerator interface { + TxConfig interface { NewTxBuilder() TxBuilder SignModeHandler() signing.SignModeHandler diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index 0df2071db4..937d2799ff 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func createTestCodec() *codec.Codec { diff --git a/codec/any_test.go b/codec/any_test.go index 19ac26d81f..fff902c3d9 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func NewTestInterfaceRegistry() types.InterfaceRegistry { diff --git a/codec/hybrid_codec_test.go b/codec/hybrid_codec_test.go index 2718807bd4..bb02c17d83 100644 --- a/codec/hybrid_codec_test.go +++ b/codec/hybrid_codec_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func TestHybridCodec(t *testing.T) { diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 6c6c3c2038..def016a6cf 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func createTestInterfaceRegistry() types.InterfaceRegistry { diff --git a/codec/testdata/test_msg.go b/codec/testdata/test_msg.go deleted file mode 100644 index 9ae3088e9b..0000000000 --- a/codec/testdata/test_msg.go +++ /dev/null @@ -1,26 +0,0 @@ -package testdata - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func NewTestMsg(addrs ...sdk.AccAddress) *TestMsg { - return &TestMsg{ - Signers: addrs, - } -} - -var _ sdk.Msg = (*TestMsg)(nil) - -func (msg *TestMsg) Route() string { return "TestMsg" } -func (msg *TestMsg) Type() string { return "Test message" } -func (msg *TestMsg) GetSignBytes() []byte { - bz, err := json.Marshal(msg.Signers) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(bz) -} -func (msg *TestMsg) ValidateBasic() error { return nil } diff --git a/codec/types/compat_test.go b/codec/types/compat_test.go index 31f53d27a1..56cb32e82c 100644 --- a/codec/types/compat_test.go +++ b/codec/types/compat_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/suite" amino "github.com/tendermint/go-amino" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) type TypeWithInterface struct { diff --git a/codec/types/types_test.go b/codec/types/types_test.go index e547ca7a00..0a14ed3e61 100644 --- a/codec/types/types_test.go +++ b/codec/types/types_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func TestPackUnpack(t *testing.T) { diff --git a/scripts/protocgen.sh b/scripts/protocgen.sh index 71d0b70a9e..c99a4c007c 100755 --- a/scripts/protocgen.sh +++ b/scripts/protocgen.sh @@ -13,7 +13,7 @@ Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. \ done # generate codec/testdata proto code -protoc -I "proto" -I "third_party/proto" -I "codec/testdata" --gocosmos_out=plugins=interfacetype+grpc,\ +protoc -I "proto" -I "third_party/proto" -I "testutil/testdata" --gocosmos_out=plugins=interfacetype+grpc,\ Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. ./codec/testdata/proto.proto # move proto files to the right places diff --git a/simapp/app.go b/simapp/app.go index dc619a8574..b7ca02d91e 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -14,9 +14,9 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/std" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 5f71e24a8c..c567bbb483 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -20,7 +20,7 @@ const ( ) // GenTx generates a signed mock transaction. -func GenTx(gen client.TxGenerator, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) (sdk.Tx, error) { +func GenTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) (sdk.Tx, error) { sigs := make([]signing.SignatureV2, len(priv)) // create a random length memo diff --git a/simapp/params/amino.go b/simapp/params/amino.go index f16dda4c67..6cb8a4de63 100644 --- a/simapp/params/amino.go +++ b/simapp/params/amino.go @@ -17,7 +17,7 @@ func MakeEncodingConfig() EncodingConfig { return EncodingConfig{ InterfaceRegistry: interfaceRegistry, Marshaler: marshaler, - TxGenerator: authtypes.StdTxGenerator{Cdc: cdc}, + TxConfig: authtypes.StdTxConfig{Cdc: cdc}, Amino: cdc, } } diff --git a/simapp/params/encoding.go b/simapp/params/encoding.go index bb63e60022..a5fe0eaea8 100644 --- a/simapp/params/encoding.go +++ b/simapp/params/encoding.go @@ -11,6 +11,6 @@ import ( type EncodingConfig struct { InterfaceRegistry types.InterfaceRegistry Marshaler codec.Marshaler - TxGenerator client.TxGenerator + TxConfig client.TxConfig Amino *codec.Codec } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index fdec53aa1b..983cfd9997 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -46,7 +46,7 @@ var ( encodingConfig = simapp.MakeEncodingConfig() initClientCtx = client.Context{}. WithJSONMarshaler(encodingConfig.Marshaler). - WithTxGenerator(encodingConfig.TxGenerator). + WithTxConfig(encodingConfig.TxConfig). WithCodec(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)). diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 758b84d4b6..4be41810d7 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -313,7 +313,7 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.C // the parameter 'expPass' against the result. A corresponding result is // returned. func SignCheckDeliver( - t *testing.T, txGen client.TxGenerator, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, + t *testing.T, txGen client.TxConfig, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { @@ -363,7 +363,7 @@ func SignCheckDeliver( // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. -func GenSequenceOfTxs(txGen client.TxGenerator, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) ([]sdk.Tx, error) { +func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) ([]sdk.Tx, error) { txs := make([]sdk.Tx, numToGenerate) var err error for i := 0; i < numToGenerate; i++ { diff --git a/tests/cli/grpc_query_test.go b/tests/cli/grpc_query_test.go index a6286d6781..63c192d1bd 100644 --- a/tests/cli/grpc_query_test.go +++ b/tests/cli/grpc_query_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func TestCliQueryConn(t *testing.T) { diff --git a/testutil/network/network.go b/testutil/network/network.go index d682e9c742..46e27bf081 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -59,7 +59,7 @@ func NewSimApp(val Validator) server.Application { // in-process local testing network. type Config struct { Codec codec.Marshaler - TxGenerator client.TxGenerator + TxConfig client.TxConfig AccountRetriever client.AccountRetriever AppConstructor AppConstructor // the ABCI application constructor GenesisState map[string]json.RawMessage // custom gensis state to provide @@ -84,7 +84,7 @@ func DefaultConfig() Config { return Config{ Codec: encCfg.Marshaler, - TxGenerator: encCfg.TxGenerator, + TxConfig: encCfg.TxConfig, AccountRetriever: authtypes.NewAccountRetriever(encCfg.Marshaler), AppConstructor: NewSimApp, GenesisState: simapp.ModuleBasics.DefaultGenesis(encCfg.Marshaler), @@ -298,7 +298,7 @@ func New(t *testing.T, cfg Config) *Network { WithHomeDir(tmCfg.RootDir). WithChainID(cfg.ChainID). WithJSONMarshaler(cfg.Codec). - WithTxGenerator(cfg.TxGenerator). + WithTxConfig(cfg.TxConfig). WithAccountRetriever(cfg.AccountRetriever) network.Validators[i] = &Validator{ diff --git a/codec/testdata/animal.go b/testutil/testdata/animal.go similarity index 100% rename from codec/testdata/animal.go rename to testutil/testdata/animal.go diff --git a/codec/testdata/proto.pb.go b/testutil/testdata/proto.pb.go similarity index 100% rename from codec/testdata/proto.pb.go rename to testutil/testdata/proto.pb.go diff --git a/codec/testdata/proto.proto b/testutil/testdata/proto.proto similarity index 94% rename from codec/testdata/proto.proto rename to testutil/testdata/proto.proto index 5767bbd3b6..682f9733fb 100644 --- a/codec/testdata/proto.proto +++ b/testutil/testdata/proto.proto @@ -4,7 +4,7 @@ package testdata; import "google/protobuf/any.proto"; import "gogoproto/gogo.proto"; -option go_package = "github.com/cosmos/cosmos-sdk/codec/testdata"; +option go_package = "github.com/cosmos/cosmos-sdk/testutil/testdata"; message Dog { string size = 1; diff --git a/codec/testdata/test_helper.go b/testutil/testdata/test_helper.go similarity index 100% rename from codec/testdata/test_helper.go rename to testutil/testdata/test_helper.go diff --git a/codec/testdata/test_service.go b/testutil/testdata/test_service.go similarity index 100% rename from codec/testdata/test_service.go rename to testutil/testdata/test_service.go diff --git a/testutil/testdata/test_tx.go b/testutil/testdata/test_tx.go new file mode 100644 index 0000000000..4ba9b6066a --- /dev/null +++ b/testutil/testdata/test_tx.go @@ -0,0 +1,47 @@ +package testdata + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/secp256k1" +) + +// KeyTestPubAddr generates a new secp256k1 keypair. +func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { + key := secp256k1.GenPrivKey() + pub := key.PubKey() + addr := sdk.AccAddress(pub.Address()) + return key, pub, addr +} + +// NewTestFeeAmount is a test fee amount. +func NewTestFeeAmount() sdk.Coins { + return sdk.NewCoins(sdk.NewInt64Coin("atom", 150)) +} + +// NewTestGasLimit is a test fee gas limit. +func NewTestGasLimit() uint64 { + return 100000 +} + +// NewTestMsg creates a message for testing with the given signers. +func NewTestMsg(addrs ...sdk.AccAddress) *TestMsg { + return &TestMsg{ + Signers: addrs, + } +} + +var _ sdk.Msg = (*TestMsg)(nil) + +func (msg *TestMsg) Route() string { return "TestMsg" } +func (msg *TestMsg) Type() string { return "Test message" } +func (msg *TestMsg) GetSignBytes() []byte { + bz, err := json.Marshal(msg.Signers) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(bz) +} +func (msg *TestMsg) ValidateBasic() error { return nil } diff --git a/types/tx_msg_test.go b/types/tx_msg_test.go index 9f7d0a26de..70a21bcad3 100644 --- a/types/tx_msg_test.go +++ b/types/tx_msg_test.go @@ -3,7 +3,7 @@ package types_test import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 44366659d7..0f22285155 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -7,592 +7,865 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" - - "github.com/cosmos/cosmos-sdk/types/tx/signing" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/auth/types" ) -// run the tx through the anteHandler and ensure its valid -func checkValidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx sdk.Tx, simulate bool) { - _, err := anteHandler(ctx, tx, simulate) - require.Nil(t, err) -} - -// run the tx through the anteHandler and ensure it fails with the given code -func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx sdk.Tx, simulate bool, expErr error) { - _, err := anteHandler(ctx, tx, simulate) - require.NotNil(t, err) - require.True(t, errors.Is(expErr, err)) -} - // Test that simulate transaction accurately estimates gas cost -func TestSimulateGasCost(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestSimulateGasCost() { + suite.SetupTest(true) // reset - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(3) + msgs := []sdk.Msg{ + testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()), + testdata.NewTestMsg(accounts[2].acc.GetAddress(), accounts[0].acc.GetAddress()), + testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[2].acc.GetAddress()), + } + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + accSeqs := []uint64{0, 0, 0} + privs := []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv} + accNums := []uint64{0, 1, 2} - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - err := app.BankKeeper.SetBalances(ctx, acc1.GetAddress(), types.NewTestCoins()) - require.NoError(t, err) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - err = app.BankKeeper.SetBalances(ctx, acc2.GetAddress(), types.NewTestCoins()) - require.NoError(t, err) - acc3 := app.AccountKeeper.NewAccountWithAddress(ctx, addr3) - require.NoError(t, acc3.SetAccountNumber(2)) - app.AccountKeeper.SetAccount(ctx, acc3) - err = app.BankKeeper.SetBalances(ctx, acc3.GetAddress(), types.NewTestCoins()) - require.NoError(t, err) + testCases := []TestCase{ + { + "tx with 150atom fee", + func() { + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) + }, + true, + true, + nil, + }, + { + "with previously estimated gas", + func() { + simulatedGas := suite.ctx.GasMeter().GasConsumed() - // set up msgs and fee - var tx sdk.Tx - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr3, addr1) - msg3 := testdata.NewTestMsg(addr2, addr3) - msgs := []sdk.Msg{msg1, msg2, msg3} - fee := types.NewTestStdFee() + accSeqs = []uint64{1, 1, 1} + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(simulatedGas) + }, + false, + true, + nil, + }, + } - // signers in order. accnums are all 0 because it is in genesis block - privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - cc, _ := ctx.CacheContext() - newCtx, err := anteHandler(cc, tx, true) - require.Nil(t, err, "transaction failed on simulate mode") - - simulatedGas := newCtx.GasMeter().GasConsumed() - fee.Gas = simulatedGas - - // update tx with simulated gas estimate - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - _, err = anteHandler(ctx, tx, false) - - require.Nil(t, err, "transaction failed with gas estimate") + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test various error cases in the AnteHandler control flow. -func TestAnteHandlerSigErrors(t *testing.T) { - // setup - app, ctx := createTestApp(true) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { + suite.SetupTest(true) // reset - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() + // Same data for every test cases + priv0, _, addr0 := testdata.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() + priv2, _, addr2 := testdata.KeyTestPubAddr() + msgs := []sdk.Msg{ + testdata.NewTestMsg(addr0, addr1), + testdata.NewTestMsg(addr0, addr2), + } + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // msg and signatures - var tx sdk.Tx - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr1, addr3) - fee := types.NewTestStdFee() + // Variable data per test case + var ( + privs []crypto.PrivKey + accNums []uint64 + accSeqs []uint64 + ) - msgs := []sdk.Msg{msg1, msg2} + testCases := []TestCase{ + { + "check no signatures fails", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{}, []uint64{}, []uint64{} - // test no signatures - privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - tx = types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + // Create tx manually to test the tx's signers + suite.txBuilder.SetMsgs(msgs...) + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) + // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 + expectedSigners := []sdk.AccAddress{addr0, addr1, addr2} + suite.Require().Equal(expectedSigners, tx.GetSigners()) + }, + false, + false, + sdkerrors.ErrNoSignatures, + }, + { + "num sigs dont match GetSigners", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{priv0}, []uint64{0}, []uint64{0} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "unrecognized account", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{priv0, priv1, priv2}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + }, + false, + false, + sdkerrors.ErrUnknownAddress, + }, + { + "save the first account, but second is still unrecognized", + func() { + acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr0) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc1) + err := suite.app.BankKeeper.SetBalances(suite.ctx, addr0, feeAmount) + suite.Require().NoError(err) + }, + false, + false, + sdkerrors.ErrUnknownAddress, + }, + } - // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 - expectedSigners := []sdk.AccAddress{addr1, addr2, addr3} - stdTx := tx.(types.StdTx) - require.Equal(t, expectedSigners, stdTx.GetSigners()) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // Check no signatures fails - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrNoSignatures) - - // test num sigs dont match GetSigners - privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // test an unrecognized account - privs, accNums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnknownAddress) - - // save the first account, but second is still unrecognized - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - app.AccountKeeper.SetAccount(ctx, acc1) - err := app.BankKeeper.SetBalances(ctx, addr1, fee.Amount) - require.NoError(t, err) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnknownAddress) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test logic around account number checking with one signer and many signers. -func TestAnteHandlerAccountNumbers(t *testing.T) { - // setup - app, ctx := createTestApp(false) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { + suite.SetupTest(false) // reset - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(2) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - err := app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - require.NoError(t, err) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - err = app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) - require.NoError(t, err) + // Variable data per test case + var ( + accNums []uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - // msg and signatures - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + testCases := []TestCase{ + { + "good tx from one signer", + func() { + msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg} - msgs := []sdk.Msg{msg} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + true, + nil, + }, + { + "new tx from wrong account number", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "new tx from correct account number", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + }, + false, + true, + nil, + }, + { + "new tx with another signer and incorrect account numbers", + func() { + msg1 := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) + msg2 := testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg1, msg2} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "new tx with correct account numbers", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{2, 0} + }, + false, + true, + nil, + }, + } - // test good tx from one signer - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // new tx from wrong account number - seqs = []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // from correct account number - seqs = []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - // new tx with another signer and incorrect account numbers - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr2, addr1) - msgs = []sdk.Msg{msg1, msg2} - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // correct account numbers - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{2, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test logic around account number checking with many signers when BlockHeight is 0. -func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { - // setup - app, ctx := createTestApp(false) - ctx = ctx.WithBlockHeight(0) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { + suite.SetupTest(false) // setup + suite.ctx = suite.ctx.WithBlockHeight(0) - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(2) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // set the accounts, we don't need the acc numbers as it is in the genesis block - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - app.AccountKeeper.SetAccount(ctx, acc1) - err := app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - require.NoError(t, err) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - err = app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) - require.NoError(t, err) + // Variable data per test case + var ( + accNums []uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - // msg and signatures - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + testCases := []TestCase{ + { + "good tx from one signer", + func() { + msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg} - msgs := []sdk.Msg{msg} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + true, + nil, + }, + { + "new tx from wrong account number", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "new tx from correct account number", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + }, + false, + true, + nil, + }, + { + "new tx with another signer and incorrect account numbers", + func() { + msg1 := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) + msg2 := testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg1, msg2} - // test good tx from one signer - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "new tx with another signer and correct account numbers", + func() { + // Note that accNums is [0,0] at block 0. + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 0}, []uint64{2, 0} + }, + false, + true, + nil, + }, + } - // new tx from wrong account number - seqs = []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // from correct account number - seqs = []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - // new tx with another signer and incorrect account numbers - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr2, addr1) - msgs = []sdk.Msg{msg1, msg2} - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // correct account numbers - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 0}, []uint64{2, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test logic around sequence checking with one signer and many signers. -func TestAnteHandlerSequences(t *testing.T) { - // setup - app, ctx := createTestApp(false) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerSequences() { + suite.SetupTest(false) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(3) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) - acc3 := app.AccountKeeper.NewAccountWithAddress(ctx, addr3) - require.NoError(t, acc3.SetAccountNumber(2)) - app.AccountKeeper.SetAccount(ctx, acc3) - app.BankKeeper.SetBalances(ctx, addr3, types.NewTestCoins()) + // Variable data per test case + var ( + accNums []uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - // msg and signatures - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + testCases := []TestCase{ + { + "good tx from one signer", + func() { + msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg} - msgs := []sdk.Msg{msg} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + true, + nil, + }, + { + "test sending it again fails (replay protection)", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "fix sequence, should pass", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + }, + false, + true, + nil, + }, + { + "new tx with another signer and correct sequences", + func() { + msg1 := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) + msg2 := testdata.NewTestMsg(accounts[2].acc.GetAddress(), accounts[0].acc.GetAddress()) + msgs = []sdk.Msg{msg1, msg2} - // test good tx from one signer - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{2, 0, 0} + }, + false, + true, + nil, + }, + { + "replay fails", + func() {}, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "tx from just second signer with incorrect sequence fails", + func() { + msg := testdata.NewTestMsg(accounts[1].acc.GetAddress()) + msgs = []sdk.Msg{msg} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "fix the sequence and it passes", + func() { + accSeqs = []uint64{1} + }, + false, + true, + nil, + }, + { + "fix the sequence and it passes", + func() { + msg := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) + msgs = []sdk.Msg{msg} - // test sending it again fails (replay protection) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{3, 2} + }, + false, + true, + nil, + }, + } - // fix sequence, should pass - seqs = []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // new tx with another signer and correct sequences - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr3, addr1) - msgs = []sdk.Msg{msg1, msg2} - - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{2, 0, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - // replay fails - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // tx from just second signer with incorrect sequence fails - msg = testdata.NewTestMsg(addr2) - msgs = []sdk.Msg{msg} - privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrUnauthorized) - - // fix the sequence and it passes - tx = types.NewTestTx(ctx, msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - // another tx from both of them that passes - msg = testdata.NewTestMsg(addr1, addr2) - msgs = []sdk.Msg{msg} - privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{3, 2} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test logic around fee deduction. -func TestAnteHandlerFees(t *testing.T) { - // setup - app, ctx := createTestApp(true) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerFees() { + suite.SetupTest(true) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + // Same data for every test cases + priv0, _, addr0 := testdata.KeyTestPubAddr() - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - app.AccountKeeper.SetAccount(ctx, acc1) + acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr0) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc1) + msgs := []sdk.Msg{testdata.NewTestMsg(addr0)} + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + privs, accNums, accSeqs := []crypto.PrivKey{priv0}, []uint64{0}, []uint64{0} - // msg and signatures - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := types.NewTestStdFee() - msgs := []sdk.Msg{msg} + testCases := []struct { + desc string + malleate func() + simulate bool + expPass bool + expErr error + }{ + { + "signer has no funds", + func() { + accSeqs = []uint64{0} + }, + false, + false, + sdkerrors.ErrInsufficientFunds, + }, + { + "signer does not have enough funds to pay the fee", + func() { + suite.app.BankKeeper.SetBalances(suite.ctx, addr0, sdk.NewCoins(sdk.NewInt64Coin("atom", 149))) + }, + false, + false, + sdkerrors.ErrInsufficientFunds, + }, + { + "signer as enough funds, should pass", + func() { + modAcc := suite.app.AccountKeeper.GetModuleAccount(suite.ctx, types.FeeCollectorName) - // signer does not have enough funds to pay the fee - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInsufficientFunds) + suite.Require().True(suite.app.BankKeeper.GetAllBalances(suite.ctx, modAcc.GetAddress()).Empty()) + require.True(sdk.IntEq(suite.T(), suite.app.BankKeeper.GetAllBalances(suite.ctx, addr0).AmountOf("atom"), sdk.NewInt(149))) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("atom", 149))) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInsufficientFunds) + suite.app.BankKeeper.SetBalances(suite.ctx, addr0, sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) + }, + false, + true, + nil, + }, + { + "signer doesn't have any more funds", + func() { + modAcc := suite.app.AccountKeeper.GetModuleAccount(suite.ctx, types.FeeCollectorName) - modAcc := app.AccountKeeper.GetModuleAccount(ctx, types.FeeCollectorName) + require.True(sdk.IntEq(suite.T(), suite.app.BankKeeper.GetAllBalances(suite.ctx, modAcc.GetAddress()).AmountOf("atom"), sdk.NewInt(150))) + require.True(sdk.IntEq(suite.T(), suite.app.BankKeeper.GetAllBalances(suite.ctx, addr0).AmountOf("atom"), sdk.NewInt(0))) + }, + false, + false, + sdkerrors.ErrInsufficientFunds, + }, + } - require.True(t, app.BankKeeper.GetAllBalances(ctx, modAcc.GetAddress()).Empty()) - require.True(sdk.IntEq(t, app.BankKeeper.GetAllBalances(ctx, addr1).AmountOf("atom"), sdk.NewInt(149))) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) - checkValidTx(t, anteHandler, ctx, tx, false) - - require.True(sdk.IntEq(t, app.BankKeeper.GetAllBalances(ctx, modAcc.GetAddress()).AmountOf("atom"), sdk.NewInt(150))) - require.True(sdk.IntEq(t, app.BankKeeper.GetAllBalances(ctx, addr1).AmountOf("atom"), sdk.NewInt(0))) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test logic around memo gas consumption. -func TestAnteHandlerMemoGas(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerMemoGas() { + suite.SetupTest(false) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(1) + msgs := []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} + privs, accNums, accSeqs := []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) + // Variable data per test case + var ( + feeAmount sdk.Coins + gasLimit uint64 + ) - // msg and signatures - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := types.NewStdFee(0, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) + testCases := []TestCase{ + { + "tx does not have enough gas", + func() { + feeAmount = sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) + gasLimit = 0 + }, + false, + false, + sdkerrors.ErrOutOfGas, + }, + { + "tx with memo doesn't have enough gas", + func() { + feeAmount = sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) + gasLimit = 801 + suite.txBuilder.SetMemo("abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") + }, + false, + false, + sdkerrors.ErrOutOfGas, + }, + { + "memo too large", + func() { + feeAmount = sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) + gasLimit = 50000 + suite.txBuilder.SetMemo(strings.Repeat("01234567890", 500)) + }, + false, + false, + sdkerrors.ErrMemoTooLarge, + }, + { + "tx with memo has enough gas", + func() { + feeAmount = sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) + gasLimit = 50000 + suite.txBuilder.SetMemo(strings.Repeat("0123456789", 10)) + }, + false, + true, + nil, + }, + } - // tx does not have enough gas - tx = types.NewTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrOutOfGas) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // tx with memo doesn't have enough gas - fee = types.NewStdFee(801, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrOutOfGas) - - // memo too large - fee = types.NewStdFee(50000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrMemoTooLarge) - - // tx with memo has enough gas - fee = types.NewStdFee(50000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) - checkValidTx(t, anteHandler, ctx, tx, false) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } -func TestAnteHandlerMultiSigner(t *testing.T) { - // setup - app, ctx := createTestApp(false) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { + suite.SetupTest(false) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(3) + msg1 := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) + msg2 := testdata.NewTestMsg(accounts[2].acc.GetAddress(), accounts[0].acc.GetAddress()) + msg3 := testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[2].acc.GetAddress()) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) - acc3 := app.AccountKeeper.NewAccountWithAddress(ctx, addr3) - require.NoError(t, acc3.SetAccountNumber(2)) - app.AccountKeeper.SetAccount(ctx, acc3) - app.BankKeeper.SetBalances(ctx, addr3, types.NewTestCoins()) - - // set up msgs and fee - var tx sdk.Tx - msg1 := testdata.NewTestMsg(addr1, addr2) - msg2 := testdata.NewTestMsg(addr3, addr1) - msg3 := testdata.NewTestMsg(addr2, addr3) - msgs := []sdk.Msg{msg1, msg2, msg3} - fee := types.NewTestStdFee() - - // signers in order - privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = types.NewTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works") - - checkValidTx(t, anteHandler, ctx, tx, false) - - // change sequence numbers - tx = types.NewTestTx(ctx, []sdk.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - tx = types.NewTestTx(ctx, []sdk.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - // expected seqs = [3, 2, 2] - tx = types.NewTestTxWithMemo(ctx, msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works") - checkValidTx(t, anteHandler, ctx, tx, false) -} - -func TestAnteHandlerBadSignBytes(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) - - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) - - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - msgs := []sdk.Msg{msg} - fee := types.NewTestStdFee() - fee2 := types.NewTestStdFee() - fee2.Gas += 100 - fee3 := types.NewTestStdFee() - fee3.Amount[0].Amount = fee3.Amount[0].Amount.AddRaw(100) - - // test good tx and signBytes - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) - - chainID := ctx.ChainID() - chainID2 := chainID + "somemorestuff" - errUnauth := sdkerrors.ErrUnauthorized - - cases := []struct { - chainID string - accnum uint64 - seq uint64 - fee types.StdFee + // Variable data per test case + var ( + accNums []uint64 msgs []sdk.Msg - err error - }{ - {chainID2, 0, 1, fee, msgs, errUnauth}, // test wrong chain_id - {chainID, 0, 2, fee, msgs, errUnauth}, // test wrong seqs - {chainID, 1, 1, fee, msgs, errUnauth}, // test wrong accnum - {chainID, 0, 1, fee, []sdk.Msg{testdata.NewTestMsg(addr2)}, errUnauth}, // test wrong msg - {chainID, 0, 1, fee2, msgs, errUnauth}, // test wrong fee - {chainID, 0, 1, fee3, msgs, errUnauth}, // test wrong fee + privs []crypto.PrivKey + accSeqs []uint64 + ) + + testCases := []TestCase{ + { + "signers in order", + func() { + msgs = []sdk.Msg{msg1, msg2, msg3} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + suite.txBuilder.SetMemo("Check signers are in expected order and different account numbers works") + }, + false, + true, + nil, + }, + { + "change sequence numbers (only accounts 0 and 1 sign)", + func() { + msgs = []sdk.Msg{msg1} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{1, 1} + }, + false, + true, + nil, + }, + { + "change sequence numbers (only accounts 1 and 2 sign)", + func() { + msgs = []sdk.Msg{msg2} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[2].priv, accounts[0].priv}, []uint64{2, 0}, []uint64{1, 2} + }, + false, + true, + nil, + }, + { + "everyone signs again", + func() { + msgs = []sdk.Msg{msg1, msg2, msg3} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{3, 2, 2} + }, + false, + true, + nil, + }, } - privs, seqs = []crypto.PrivKey{priv1}, []uint64{1} - for _, cs := range cases { - tx := types.NewTestTxWithSignBytes( - msgs, privs, accnums, seqs, fee, - types.StdSignBytes(cs.chainID, cs.accnum, cs.seq, cs.fee, cs.msgs, ""), - "", - ) - checkInvalidTx(t, anteHandler, ctx, tx, false, cs.err) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() + + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) } - - // test wrong signer if public key exist - privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{0}, []uint64{1} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInvalidPubKey) - - // test wrong signer if public doesn't exist - msg = testdata.NewTestMsg(addr2) - msgs = []sdk.Msg{msg} - privs, accnums, seqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInvalidPubKey) } -func TestAnteHandlerSetPubKey(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerBadSignBytes() { + suite.SetupTest(false) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - _, _, addr2 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(2) + msg0 := testdata.NewTestMsg(accounts[0].acc.GetAddress()) - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - app.BankKeeper.SetBalances(ctx, addr2, types.NewTestCoins()) + // Variable data per test case + var ( + accNums []uint64 + chainID string + feeAmount sdk.Coins + gasLimit uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - var tx sdk.Tx + testCases := []TestCase{ + { + "test good tx and signBytes", + func() { + chainID = suite.ctx.ChainID() + feeAmount = testdata.NewTestFeeAmount() + gasLimit = testdata.NewTestGasLimit() + msgs = []sdk.Msg{msg0} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + true, + nil, + }, + { + "test wrong chainID", + func() { + accSeqs = []uint64{1} // Back to correct accSeqs + chainID = "chain-foo" + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test wrong accSeqs", + func() { + chainID = suite.ctx.ChainID() // Back to correct chainID + accSeqs = []uint64{2} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test wrong accNums", + func() { + accSeqs = []uint64{1} // Back to correct accSeqs + accNums = []uint64{1} + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test wrong msg", + func() { + msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + { + "test wrong fee gas", + func() { + msgs = []sdk.Msg{msg0} // Back to correct msgs + feeAmount = testdata.NewTestFeeAmount() + gasLimit = testdata.NewTestGasLimit() + 100 + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test wrong fee amount", + func() { + feeAmount = testdata.NewTestFeeAmount() + feeAmount[0].Amount = feeAmount[0].Amount.AddRaw(100) + gasLimit = testdata.NewTestGasLimit() + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test wrong signer if public key exist", + func() { + feeAmount = testdata.NewTestFeeAmount() + gasLimit = testdata.NewTestGasLimit() + privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{0}, []uint64{1} + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + { + "test wrong signer if public doesn't exist", + func() { + msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{0} + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + } - // test good tx and set public key - msg := testdata.NewTestMsg(addr1) - msgs := []sdk.Msg{msg} - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := types.NewTestStdFee() - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - acc1 = app.AccountKeeper.GetAccount(ctx, addr1) - require.Equal(t, acc1.GetPubKey(), priv1.PubKey()) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, chainID, tc) + }) + } +} - // test public key not found - msg = testdata.NewTestMsg(addr2) - msgs = []sdk.Msg{msg} - tx = types.NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - sigs := tx.(types.StdTx).Signatures - sigs[0].PubKey = nil - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInvalidPubKey) +func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { + suite.SetupTest(false) // setup - acc2 = app.AccountKeeper.GetAccount(ctx, addr2) - require.Nil(t, acc2.GetPubKey()) + // Same data for every test cases + accounts := suite.CreateTestAccounts(2) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - // test invalid signature and public key - tx = types.NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInvalidPubKey) + // Variable data per test case + var ( + accNums []uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - acc2 = app.AccountKeeper.GetAccount(ctx, addr2) - require.Nil(t, acc2.GetPubKey()) + testCases := []TestCase{ + { + "test good tx", + func() { + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + msgs = []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} + }, + false, + true, + nil, + }, + { + "make sure public key has been set (tx itself should fail because of replay protection)", + func() { + acc0 := suite.app.AccountKeeper.GetAccount(suite.ctx, accounts[0].acc.GetAddress()) + suite.Require().Equal(acc0.GetPubKey(), accounts[0].priv.PubKey()) + }, + false, + false, + sdkerrors.ErrUnauthorized, + }, + { + "test public key not found", + func() { + accNums = []uint64{1} + msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} + + // Manually create tx, and remove signature + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) + sigs := tx.(types.StdTx).Signatures + sigs[0].PubKey = nil + _, err := suite.anteHandler(suite.ctx, tx, false) + suite.Require().Error(err) + suite.Require().Equal(err.Error(), "wrong number of signers; expected 0, got 1: unauthorized") + suite.Require().True(errors.Is(err, sdkerrors.ErrUnauthorized)) + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + { + "make sure previous public key has NOT been set, test invalid signature and public key", + func() { + acc1 := suite.app.AccountKeeper.GetAccount(suite.ctx, accounts[1].acc.GetAddress()) + suite.Require().Nil(acc1.GetPubKey()) + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + { + "make sure previous public key has NOT been set", + func() { + acc1 := suite.app.AccountKeeper.GetAccount(suite.ctx, accounts[1].acc.GetAddress()) + suite.Require().Nil(acc1.GetPubKey()) + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() + + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []crypto.PubKey, signatures [][]byte) { @@ -650,7 +923,7 @@ func TestCountSubkeys(t *testing.T) { type args struct { pub crypto.PubKey } - tests := []struct { + testCases := []struct { name string args args want int @@ -659,60 +932,55 @@ func TestCountSubkeys(t *testing.T) { {"single level multikey", args{singleLevelMultiKey}, 5}, {"multi level multikey", args{multiLevelMultiKey}, 11}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(T *testing.T) { - require.Equal(t, tt.want, types.CountSubKeys(tt.args.pub)) + for _, tc := range testCases { + t.Run(tc.name, func(T *testing.T) { + require.Equal(t, tc.want, types.CountSubKeys(tc.args.pub)) }) } } -func TestAnteHandlerSigLimitExceeded(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) +func (suite *AnteTestSuite) TestAnteHandlerSigLimitExceeded() { + suite.SetupTest(true) // setup - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() - priv4, _, addr4 := types.KeyTestPubAddr() - priv5, _, addr5 := types.KeyTestPubAddr() - priv6, _, addr6 := types.KeyTestPubAddr() - priv7, _, addr7 := types.KeyTestPubAddr() - priv8, _, addr8 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(8) + var addrs []sdk.AccAddress + var privs []crypto.PrivKey + for i := 0; i < 8; i++ { + addrs = append(addrs, accounts[i].acc.GetAddress()) + privs = append(privs, accounts[i].priv) + } + msgs := []sdk.Msg{testdata.NewTestMsg(addrs...)} + accNums, accSeqs := []uint64{0, 1, 2, 3, 4, 5, 6, 7}, []uint64{0, 0, 0, 0, 0, 0, 0, 0} + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - addrs := []sdk.AccAddress{addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8} - - // set the accounts - for i, addr := range addrs { - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - err := acc.SetAccountNumber(uint64(i)) - require.NoError(t, err) - app.AccountKeeper.SetAccount(ctx, acc) - app.BankKeeper.SetBalances(ctx, addr, types.NewTestCoins()) + testCases := []TestCase{ + { + "test rejection logic", + func() {}, + false, + false, + sdkerrors.ErrTooManySignatures, + }, } - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) - msgs := []sdk.Msg{msg} - fee := types.NewTestStdFee() + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() - // test rejection logic - privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3, priv4, priv5, priv6, priv7, priv8}, - []uint64{0, 1, 2, 3, 4, 5, 6, 7}, []uint64{0, 0, 0, 0, 0, 0, 0, 0} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrTooManySignatures) + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } // Test custom SignatureVerificationGasConsumer -func TestCustomSignatureVerificationGasConsumer(t *testing.T) { - // setup - app, ctx := createTestApp(true) - ctx = ctx.WithBlockHeight(1) +func (suite *AnteTestSuite) TestCustomSignatureVerificationGasConsumer() { + suite.SetupTest(true) // setup + // setup an ante handler that only accepts PubKeyEd25519 - anteHandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error { + suite.anteHandler = ante.NewAnteHandler(suite.app.AccountKeeper, suite.app.BankKeeper, *suite.app.IBCKeeper, func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error { switch pubkey := sig.PubKey.(type) { case ed25519.PubKeyEd25519: meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519") @@ -722,77 +990,97 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { } }, types.LegacyAminoJSONHandler{}) - // verify that an secp256k1 account gets rejected - priv1, _, addr1 := types.KeyTestPubAddr() - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) + // Same data for every test cases + accounts := suite.CreateTestAccounts(1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - var tx sdk.Tx - msg := testdata.NewTestMsg(addr1) - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := types.NewTestStdFee() - msgs := []sdk.Msg{msg} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkInvalidTx(t, anteHandler, ctx, tx, false, sdkerrors.ErrInvalidPubKey) + // Variable data per test case + var ( + accNums []uint64 + msgs []sdk.Msg + privs []crypto.PrivKey + accSeqs []uint64 + ) - // verify that an ed25519 account gets accepted - priv2 := ed25519.GenPrivKey() - pub2 := priv2.PubKey() - addr2 := sdk.AccAddress(pub2.Address()) - acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) + testCases := []TestCase{ + { + "verify that an secp256k1 account gets rejected", + func() { + msgs = []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} + privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + }, + false, + false, + sdkerrors.ErrInvalidPubKey, + }, + { + "verify that an ed25519 account gets accepted", + func() { + priv1 := ed25519.GenPrivKey() + pub1 := priv1.PubKey() + addr1 := sdk.AccAddress(pub1.Address()) + acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1) - require.NoError(t, app.BankKeeper.SetBalances(ctx, addr2, sdk.NewCoins(sdk.NewInt64Coin("atom", 150)))) - require.NoError(t, acc2.SetAccountNumber(1)) - app.AccountKeeper.SetAccount(ctx, acc2) - msg = testdata.NewTestMsg(addr2) - privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - fee = types.NewTestStdFee() - msgs = []sdk.Msg{msg} - tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) - checkValidTx(t, anteHandler, ctx, tx, false) + suite.Require().NoError(suite.app.BankKeeper.SetBalances(suite.ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("atom", 150)))) + suite.Require().NoError(acc1.SetAccountNumber(1)) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc1) + msg := testdata.NewTestMsg(addr1) + privs, accNums, accSeqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0} + msgs = []sdk.Msg{msg} + }, + false, + true, + nil, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + tc.malleate() + + suite.RunTestCase(privs, msgs, feeAmount, gasLimit, accNums, accSeqs, suite.ctx.ChainID(), tc) + }) + } } -func TestAnteHandlerReCheck(t *testing.T) { - // setup - app, ctx := createTestApp(true) - // set blockheight and recheck=true - ctx = ctx.WithBlockHeight(1) - ctx = ctx.WithIsReCheckTx(true) +func (suite *AnteTestSuite) TestAnteHandlerReCheck() { + suite.SetupTest(true) // setup + // Set recheck=true + suite.ctx = suite.ctx.WithIsReCheckTx(true) + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() - // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - // priv2, _, addr2 := types.KeyTestPubAddr() + // Same data for every test cases + accounts := suite.CreateTestAccounts(1) - // set the accounts - acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - require.NoError(t, acc1.SetAccountNumber(0)) - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, types.NewTestCoins()) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - antehandler := ante.NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) + msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) + msgs := []sdk.Msg{msg} + suite.txBuilder.SetMsgs(msgs...) + + suite.txBuilder.SetMemo("thisisatestmemo") // test that operations skipped on recheck do not run - - msg := testdata.NewTestMsg(addr1) - msgs := []sdk.Msg{msg} - fee := types.NewTestStdFee() - - privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "thisisatestmemo") + privs, accNums, accSeqs := []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) // make signature array empty which would normally cause ValidateBasicDecorator and SigVerificationDecorator fail // since these decorators don't run on recheck, the tx should pass the antehandler stdTx := tx.(types.StdTx) stdTx.Signatures = []types.StdSignature{} - _, err := antehandler(ctx, stdTx, false) - require.Nil(t, err, "AnteHandler errored on recheck unexpectedly: %v", err) + _, err := suite.anteHandler(suite.ctx, stdTx, false) + suite.Require().Nil(err, "AnteHandler errored on recheck unexpectedly: %v", err) - tx = types.NewTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "thisisatestmemo") + tx = suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) txBytes, err := json.Marshal(tx) - require.Nil(t, err, "Error marshalling tx: %v", err) - ctx = ctx.WithTxBytes(txBytes) + suite.Require().Nil(err, "Error marshalling tx: %v", err) + suite.ctx = suite.ctx.WithTxBytes(txBytes) // require that state machine param-dependent checking is still run on recheck since parameters can change between check and recheck testCases := []struct { @@ -805,31 +1093,35 @@ func TestAnteHandlerReCheck(t *testing.T) { } for _, tc := range testCases { // set testcase parameters - app.AccountKeeper.SetParams(ctx, tc.params) + suite.app.AccountKeeper.SetParams(suite.ctx, tc.params) - _, err := antehandler(ctx, tx, false) + _, err := suite.anteHandler(suite.ctx, tx, false) - require.NotNil(t, err, "tx does not fail on recheck with updated params in test case: %s", tc.name) + suite.Require().NotNil(err, "tx does not fail on recheck with updated params in test case: %s", tc.name) // reset parameters to default values - app.AccountKeeper.SetParams(ctx, types.DefaultParams()) + suite.app.AccountKeeper.SetParams(suite.ctx, types.DefaultParams()) } // require that local mempool fee check is still run on recheck since validator may change minFee between check and recheck // create new minimum gas price so antehandler fails on recheck - ctx = ctx.WithMinGasPrices([]sdk.DecCoin{{ + suite.ctx = suite.ctx.WithMinGasPrices([]sdk.DecCoin{{ Denom: "dnecoin", // fee does not have this denom Amount: sdk.NewDec(5), }}) - _, err = antehandler(ctx, tx, false) - require.NotNil(t, err, "antehandler on recheck did not fail when mingasPrice was changed") + _, err = suite.anteHandler(suite.ctx, tx, false) + suite.Require().NotNil(err, "antehandler on recheck did not fail when mingasPrice was changed") // reset min gasprice - ctx = ctx.WithMinGasPrices(sdk.DecCoins{}) + suite.ctx = suite.ctx.WithMinGasPrices(sdk.DecCoins{}) // remove funds for account so antehandler fails on recheck - app.AccountKeeper.SetAccount(ctx, acc1) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins()) + suite.app.AccountKeeper.SetAccount(suite.ctx, accounts[0].acc) + suite.app.BankKeeper.SetBalances(suite.ctx, accounts[0].acc.GetAddress(), sdk.NewCoins()) - _, err = antehandler(ctx, tx, false) - require.NotNil(t, err, "antehandler on recheck did not fail once feePayer no longer has sufficient funds") + _, err = suite.anteHandler(suite.ctx, tx, false) + suite.Require().NotNil(err, "antehandler on recheck did not fail once feePayer no longer has sufficient funds") +} + +func TestAnteTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) } diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index ce97bc43e2..b29066198a 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -5,9 +5,9 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/stretchr/testify/suite" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,133 +15,146 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func TestValidateBasic(t *testing.T) { - // setup - _, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestValidateBasic() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - invalidTx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{}, []uint64{}, []uint64{} + invalidTx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) vbd := ante.NewValidateBasicDecorator() antehandler := sdk.ChainAnteDecorators(vbd) - _, err := antehandler(ctx, invalidTx, false) + _, err := antehandler(suite.ctx, invalidTx, false) - require.NotNil(t, err, "Did not error on invalid tx") + suite.Require().NotNil(err, "Did not error on invalid tx") - privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - validTx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + validTx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) - _, err = antehandler(ctx, validTx, false) - require.Nil(t, err, "ValidateBasicDecorator returned error on valid tx. err: %v", err) + _, err = antehandler(suite.ctx, validTx, false) + suite.Require().Nil(err, "ValidateBasicDecorator returned error on valid tx. err: %v", err) // test decorator skips on recheck - ctx = ctx.WithIsReCheckTx(true) + suite.ctx = suite.ctx.WithIsReCheckTx(true) // decorator should skip processing invalidTx on recheck and thus return nil-error - _, err = antehandler(ctx, invalidTx, false) + _, err = antehandler(suite.ctx, invalidTx, false) - require.Nil(t, err, "ValidateBasicDecorator ran on ReCheck") + suite.Require().Nil(err, "ValidateBasicDecorator ran on ReCheck") } -func TestValidateMemo(t *testing.T) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestValidateMemo() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - invalidTx := types.NewTestTxWithMemo(ctx, msgs, privs, accNums, seqs, fee, strings.Repeat("01234567890", 500)) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + suite.txBuilder.SetMemo(strings.Repeat("01234567890", 500)) + invalidTx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) // require that long memos get rejected - vmd := ante.NewValidateMemoDecorator(app.AccountKeeper) + vmd := ante.NewValidateMemoDecorator(suite.app.AccountKeeper) antehandler := sdk.ChainAnteDecorators(vmd) - _, err := antehandler(ctx, invalidTx, false) + _, err := antehandler(suite.ctx, invalidTx, false) - require.NotNil(t, err, "Did not error on tx with high memo") + suite.Require().NotNil(err, "Did not error on tx with high memo") - validTx := types.NewTestTxWithMemo(ctx, msgs, privs, accNums, seqs, fee, strings.Repeat("01234567890", 10)) + suite.txBuilder.SetMemo(strings.Repeat("01234567890", 10)) + validTx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) // require small memos pass ValidateMemo Decorator - _, err = antehandler(ctx, validTx, false) - require.Nil(t, err, "ValidateBasicDecorator returned error on valid tx. err: %v", err) + _, err = antehandler(suite.ctx, validTx, false) + suite.Require().Nil(err, "ValidateBasicDecorator returned error on valid tx. err: %v", err) } -func TestConsumeGasForTxSize(t *testing.T) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestConsumeGasForTxSize() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) + suite.txBuilder.SetMemo(strings.Repeat("01234567890", 10)) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTxWithMemo(ctx, msgs, privs, accNums, seqs, fee, strings.Repeat("01234567890", 10)) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) txBytes, err := json.Marshal(tx) - require.Nil(t, err, "Cannot marshal tx: %v", err) + suite.Require().Nil(err, "Cannot marshal tx: %v", err) - cgtsd := ante.NewConsumeGasForTxSizeDecorator(app.AccountKeeper) + cgtsd := ante.NewConsumeGasForTxSizeDecorator(suite.app.AccountKeeper) antehandler := sdk.ChainAnteDecorators(cgtsd) - params := app.AccountKeeper.GetParams(ctx) + params := suite.app.AccountKeeper.GetParams(suite.ctx) expectedGas := sdk.Gas(len(txBytes)) * params.TxSizeCostPerByte - // Set ctx with TxBytes manually - ctx = ctx.WithTxBytes(txBytes) + // Set suite.ctx with TxBytes manually + suite.ctx = suite.ctx.WithTxBytes(txBytes) // track how much gas is necessary to retrieve parameters - beforeGas := ctx.GasMeter().GasConsumed() - app.AccountKeeper.GetParams(ctx) - afterGas := ctx.GasMeter().GasConsumed() + beforeGas := suite.ctx.GasMeter().GasConsumed() + suite.app.AccountKeeper.GetParams(suite.ctx) + afterGas := suite.ctx.GasMeter().GasConsumed() expectedGas += afterGas - beforeGas - beforeGas = ctx.GasMeter().GasConsumed() - ctx, err = antehandler(ctx, tx, false) - require.Nil(t, err, "ConsumeTxSizeGasDecorator returned error: %v", err) + beforeGas = suite.ctx.GasMeter().GasConsumed() + suite.ctx, err = antehandler(suite.ctx, tx, false) + suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) // require that decorator consumes expected amount of gas - consumedGas := ctx.GasMeter().GasConsumed() - beforeGas - require.Equal(t, expectedGas, consumedGas, "Decorator did not consume the correct amount of gas") + consumedGas := suite.ctx.GasMeter().GasConsumed() - beforeGas + suite.Require().Equal(expectedGas, consumedGas, "Decorator did not consume the correct amount of gas") // simulation must not underestimate gas of this decorator even with nil signatures sigTx := tx.(types.StdTx) sigTx.Signatures = []types.StdSignature{{}} simTxBytes, err := json.Marshal(sigTx) - require.Nil(t, err) + suite.Require().Nil(err) // require that simulated tx is smaller than tx with signatures - require.True(t, len(simTxBytes) < len(txBytes), "simulated tx still has signatures") + suite.Require().True(len(simTxBytes) < len(txBytes), "simulated tx still has signatures") - // Set ctx with smaller simulated TxBytes manually - ctx = ctx.WithTxBytes(txBytes) + // Set suite.ctx with smaller simulated TxBytes manually + suite.ctx = suite.ctx.WithTxBytes(txBytes) - beforeSimGas := ctx.GasMeter().GasConsumed() + beforeSimGas := suite.ctx.GasMeter().GasConsumed() // run antehandler with simulate=true - ctx, err = antehandler(ctx, sigTx, true) - consumedSimGas := ctx.GasMeter().GasConsumed() - beforeSimGas + suite.ctx, err = antehandler(suite.ctx, sigTx, true) + consumedSimGas := suite.ctx.GasMeter().GasConsumed() - beforeSimGas // require that antehandler passes and does not underestimate decorator cost - require.Nil(t, err, "ConsumeTxSizeGasDecorator returned error: %v", err) - require.True(t, consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) + suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) + suite.Require().True(consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) +} + +func TestAnteBasicTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) } diff --git a/x/auth/ante/fee_test.go b/x/auth/ante/fee_test.go index c56ca7219d..b8b4d59710 100644 --- a/x/auth/ante/fee_test.go +++ b/x/auth/ante/fee_test.go @@ -3,98 +3,105 @@ package ante_test import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/stretchr/testify/suite" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/ante" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func TestEnsureMempoolFees(t *testing.T) { - // setup - _, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestEnsureMempoolFees() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() mfd := ante.NewMempoolFeeDecorator() antehandler := sdk.ChainAnteDecorators(mfd) // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) // Set high gas price so standard test fee fails atomPrice := sdk.NewDecCoinFromDec("atom", sdk.NewDec(200).Quo(sdk.NewDec(100000))) highGasPrice := []sdk.DecCoin{atomPrice} - ctx = ctx.WithMinGasPrices(highGasPrice) + suite.ctx = suite.ctx.WithMinGasPrices(highGasPrice) // Set IsCheckTx to true - ctx = ctx.WithIsCheckTx(true) + suite.ctx = suite.ctx.WithIsCheckTx(true) // antehandler errors with insufficient fees - _, err := antehandler(ctx, tx, false) - require.NotNil(t, err, "Decorator should have errored on too low fee for local gasPrice") + _, err := antehandler(suite.ctx, tx, false) + suite.Require().NotNil(err, "Decorator should have errored on too low fee for local gasPrice") // Set IsCheckTx to false - ctx = ctx.WithIsCheckTx(false) + suite.ctx = suite.ctx.WithIsCheckTx(false) // antehandler should not error since we do not check minGasPrice in DeliverTx - _, err = antehandler(ctx, tx, false) - require.Nil(t, err, "MempoolFeeDecorator returned error in DeliverTx") + _, err = antehandler(suite.ctx, tx, false) + suite.Require().Nil(err, "MempoolFeeDecorator returned error in DeliverTx") // Set IsCheckTx back to true for testing sufficient mempool fee - ctx = ctx.WithIsCheckTx(true) + suite.ctx = suite.ctx.WithIsCheckTx(true) atomPrice = sdk.NewDecCoinFromDec("atom", sdk.NewDec(0).Quo(sdk.NewDec(100000))) lowGasPrice := []sdk.DecCoin{atomPrice} - ctx = ctx.WithMinGasPrices(lowGasPrice) + suite.ctx = suite.ctx.WithMinGasPrices(lowGasPrice) - _, err = antehandler(ctx, tx, false) - require.Nil(t, err, "Decorator should not have errored on fee higher than local gasPrice") + _, err = antehandler(suite.ctx, tx, false) + suite.Require().Nil(err, "Decorator should not have errored on fee higher than local gasPrice") } -func TestDeductFees(t *testing.T) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestDeductFees() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) // Set account with insufficient funds - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) - app.AccountKeeper.SetAccount(ctx, acc) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(10)))) + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + suite.app.BankKeeper.SetBalances(suite.ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(10)))) - dfd := ante.NewDeductFeeDecorator(app.AccountKeeper, app.BankKeeper) + dfd := ante.NewDeductFeeDecorator(suite.app.AccountKeeper, suite.app.BankKeeper) antehandler := sdk.ChainAnteDecorators(dfd) - _, err := antehandler(ctx, tx, false) + _, err := antehandler(suite.ctx, tx, false) - require.NotNil(t, err, "Tx did not error when fee payer had insufficient funds") + suite.Require().NotNil(err, "Tx did not error when fee payer had insufficient funds") // Set account with sufficient funds - app.AccountKeeper.SetAccount(ctx, acc) - app.BankKeeper.SetBalances(ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(200)))) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + suite.app.BankKeeper.SetBalances(suite.ctx, addr1, sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(200)))) - _, err = antehandler(ctx, tx, false) + _, err = antehandler(suite.ctx, tx, false) - require.Nil(t, err, "Tx errored after account has been set with sufficient funds") + suite.Require().Nil(err, "Tx errored after account has been set with sufficient funds") +} + +func TestAnteFeeTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) } diff --git a/x/auth/ante/setup_test.go b/x/auth/ante/setup_test.go index ad1346760c..b78585ed31 100644 --- a/x/auth/ante/setup_test.go +++ b/x/auth/ante/setup_test.go @@ -3,80 +3,83 @@ package ante_test import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/stretchr/testify/suite" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/ante" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func TestSetup(t *testing.T) { - // setup - _, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestSetup() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) sud := ante.NewSetUpContextDecorator() antehandler := sdk.ChainAnteDecorators(sud) // Set height to non-zero value for GasMeter to be set - ctx = ctx.WithBlockHeight(1) + suite.ctx = suite.ctx.WithBlockHeight(1) // Context GasMeter Limit not set - require.Equal(t, uint64(0), ctx.GasMeter().Limit(), "GasMeter set with limit before setup") + suite.Require().Equal(uint64(0), suite.ctx.GasMeter().Limit(), "GasMeter set with limit before setup") - newCtx, err := antehandler(ctx, tx, false) - require.Nil(t, err, "SetUpContextDecorator returned error") + newCtx, err := antehandler(suite.ctx, tx, false) + suite.Require().Nil(err, "SetUpContextDecorator returned error") // Context GasMeter Limit should be set after SetUpContextDecorator runs - require.Equal(t, fee.Gas, newCtx.GasMeter().Limit(), "GasMeter not set correctly") + suite.Require().Equal(gasLimit, newCtx.GasMeter().Limit(), "GasMeter not set correctly") } -func TestRecoverPanic(t *testing.T) { - // setup - _, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestRecoverPanic() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg1 := testdata.NewTestMsg(addr1) - fee := types.NewTestStdFee() + msg := testdata.NewTestMsg(addr1) + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetMsgs(msg) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - msgs := []sdk.Msg{msg1} - - privs, accNums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) sud := ante.NewSetUpContextDecorator() antehandler := sdk.ChainAnteDecorators(sud, OutOfGasDecorator{}) // Set height to non-zero value for GasMeter to be set - ctx = ctx.WithBlockHeight(1) + suite.ctx = suite.ctx.WithBlockHeight(1) - newCtx, err := antehandler(ctx, tx, false) + newCtx, err := antehandler(suite.ctx, tx, false) - require.NotNil(t, err, "Did not return error on OutOfGas panic") + suite.Require().NotNil(err, "Did not return error on OutOfGas panic") - require.True(t, sdkerrors.ErrOutOfGas.Is(err), "Returned error is not an out of gas error") - require.Equal(t, fee.Gas, newCtx.GasMeter().Limit()) + suite.Require().True(sdkerrors.ErrOutOfGas.Is(err), "Returned error is not an out of gas error") + suite.Require().Equal(gasLimit, newCtx.GasMeter().Limit()) antehandler = sdk.ChainAnteDecorators(sud, PanicDecorator{}) - require.Panics(t, func() { antehandler(ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") // nolint:errcheck + suite.Require().Panics(func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") // nolint:errcheck } type OutOfGasDecorator struct{} @@ -97,3 +100,7 @@ type PanicDecorator struct{} func (pd PanicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { panic("random error") } + +func TestAnteSetupTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) +} diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c04217b58d..a33d5fb0fc 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -230,7 +230,7 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul if err != nil { return ctx, sdkerrors.Wrapf( sdkerrors.ErrUnauthorized, - "signature verification failed; verify correct account sequence (%d) and chain-id (%s)", signerAccs[i].GetSequence(), ctx.ChainID()) + "signature verification failed; verify correct account number (%d), account sequence (%d), and chain-id (%s)", signerAccs[i].GetAccountNumber(), signerAccs[i].GetSequence(), ctx.ChainID()) } } } diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index cdbd88888d..f9ac32ec67 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -2,14 +2,15 @@ package ante_test import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec/testdata" "testing" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" @@ -20,14 +21,14 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func TestSetPubKey(t *testing.T) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestSetPubKey() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // keys and addresses - priv1, pub1, addr1 := types.KeyTestPubAddr() - priv2, pub2, addr2 := types.KeyTestPubAddr() - priv3, pub3, addr3 := types.KeyTestPubAddr() + priv1, pub1, addr1 := testdata.KeyTestPubAddr() + priv2, pub2, addr2 := testdata.KeyTestPubAddr() + priv3, pub3, addr3 := testdata.KeyTestPubAddr() addrs := []sdk.AccAddress{addr1, addr2, addr3} pubs := []crypto.PubKey{pub1, pub2, pub3} @@ -35,32 +36,36 @@ func TestSetPubKey(t *testing.T) { msgs := make([]sdk.Msg, len(addrs)) // set accounts and create msg for each address for i, addr := range addrs { - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - require.NoError(t, acc.SetAccountNumber(uint64(i))) - app.AccountKeeper.SetAccount(ctx, acc) + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) + suite.Require().NoError(acc.SetAccountNumber(uint64(i))) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) msgs[i] = testdata.NewTestMsg(addr) } + suite.txBuilder.SetMsgs(msgs...) - fee := types.NewTestStdFee() + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + privs, accNums, accSeqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) - spkd := ante.NewSetPubKeyDecorator(app.AccountKeeper) + spkd := ante.NewSetPubKeyDecorator(suite.app.AccountKeeper) antehandler := sdk.ChainAnteDecorators(spkd) - ctx, err := antehandler(ctx, tx, false) - require.Nil(t, err) + ctx, err := antehandler(suite.ctx, tx, false) + suite.Require().Nil(err) // Require that all accounts have pubkey set after Decorator runs for i, addr := range addrs { - pk, err := app.AccountKeeper.GetPubKey(ctx, addr) - require.Nil(t, err, "Error on retrieving pubkey from account") - require.Equal(t, pubs[i], pk, "Pubkey retrieved from account is unexpected") + pk, err := suite.app.AccountKeeper.GetPubKey(ctx, addr) + suite.Require().Nil(err, "Error on retrieving pubkey from account") + suite.Require().Equal(pubs[i], pk, "Pubkey retrieved from account is unexpected") } } -func TestConsumeSignatureVerificationGas(t *testing.T) { +func (suite *AnteTestSuite) TestConsumeSignatureVerificationGas() { params := types.DefaultParams() msg := []byte{1, 2, 3, 4} _, cdc := simapp.MakeCodecs() @@ -72,9 +77,9 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { for i := 0; i < len(pkSet1); i++ { stdSig := types.StdSignature{PubKey: pkSet1[i].Bytes(), Signature: sigSet1[i]} sigV2, err := types.StdSignatureToSignatureV2(cdc, stdSig) - require.NoError(t, err) + suite.Require().NoError(err) err = multisig.AddSignatureV2(multisignature1, sigV2, pkSet1) - require.NoError(t, err) + suite.Require().NoError(err) } type args struct { @@ -95,57 +100,56 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { {"unknown key", args{sdk.NewInfiniteGasMeter(), nil, nil, params}, 0, true}, } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - sigV2 := signing.SignatureV2{ - PubKey: tt.args.pubkey, - Data: tt.args.sig, - } - err := ante.DefaultSigVerificationGasConsumer(tt.args.meter, sigV2, tt.args.params) + sigV2 := signing.SignatureV2{ + PubKey: tt.args.pubkey, + Data: tt.args.sig, + } + err := ante.DefaultSigVerificationGasConsumer(tt.args.meter, sigV2, tt.args.params) - if tt.shouldErr { - require.NotNil(t, err) - } else { - require.Nil(t, err) - require.Equal(t, tt.gasConsumed, tt.args.meter.GasConsumed(), fmt.Sprintf("%d != %d", tt.gasConsumed, tt.args.meter.GasConsumed())) - } - }) + if tt.shouldErr { + suite.Require().NotNil(err) + } else { + suite.Require().Nil(err) + suite.Require().Equal(tt.gasConsumed, tt.args.meter.GasConsumed(), fmt.Sprintf("%d != %d", tt.gasConsumed, tt.args.meter.GasConsumed())) + } } } -func TestSigVerification(t *testing.T) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestSigVerification() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + // make block height non-zero to ensure account numbers part of signBytes - ctx = ctx.WithBlockHeight(1) + suite.ctx = suite.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := types.KeyTestPubAddr() - priv2, _, addr2 := types.KeyTestPubAddr() - priv3, _, addr3 := types.KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() + priv2, _, addr2 := testdata.KeyTestPubAddr() + priv3, _, addr3 := testdata.KeyTestPubAddr() addrs := []sdk.AccAddress{addr1, addr2, addr3} msgs := make([]sdk.Msg, len(addrs)) // set accounts and create msg for each address for i, addr := range addrs { - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - require.NoError(t, acc.SetAccountNumber(uint64(i))) - app.AccountKeeper.SetAccount(ctx, acc) + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) + suite.Require().NoError(acc.SetAccountNumber(uint64(i))) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) msgs[i] = testdata.NewTestMsg(addr) } - fee := types.NewTestStdFee() + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() - spkd := ante.NewSetPubKeyDecorator(app.AccountKeeper) - svd := ante.NewSigVerificationDecorator(app.AccountKeeper, types.LegacyAminoJSONHandler{}) + spkd := ante.NewSetPubKeyDecorator(suite.app.AccountKeeper) + svd := ante.NewSigVerificationDecorator(suite.app.AccountKeeper, types.LegacyAminoJSONHandler{}) antehandler := sdk.ChainAnteDecorators(spkd, svd) type testCase struct { name string privs []crypto.PrivKey accNums []uint64 - seqs []uint64 + accSeqs []uint64 recheck bool shouldErr bool } @@ -159,89 +163,105 @@ func TestSigVerification(t *testing.T) { {"no err on recheck", []crypto.PrivKey{}, []uint64{}, []uint64{}, true, false}, } for i, tc := range testCases { - ctx = ctx.WithIsReCheckTx(tc.recheck) + suite.ctx = suite.ctx.WithIsReCheckTx(tc.recheck) + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() // Create new txBuilder for each test - tx := types.NewTestTx(ctx, msgs, tc.privs, tc.accNums, tc.seqs, fee) + suite.txBuilder.SetMsgs(msgs...) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - _, err := antehandler(ctx, tx, false) + tx := suite.CreateTestTx(tc.privs, tc.accNums, tc.accSeqs, suite.ctx.ChainID()) + + _, err := antehandler(suite.ctx, tx, false) if tc.shouldErr { - require.NotNil(t, err, "TestCase %d: %s did not error as expected", i, tc.name) + suite.Require().NotNil(err, "TestCase %d: %s did not error as expected", i, tc.name) } else { - require.Nil(t, err, "TestCase %d: %s errored unexpectedly. Err: %v", i, tc.name, err) + suite.Require().Nil(err, "TestCase %d: %s errored unexpectedly. Err: %v", i, tc.name, err) } } } -func TestSigIntegration(t *testing.T) { +func (suite *AnteTestSuite) TestSigIntegration() { // generate private keys privs := []crypto.PrivKey{secp256k1.GenPrivKey(), secp256k1.GenPrivKey(), secp256k1.GenPrivKey()} params := types.DefaultParams() initialSigCost := params.SigVerifyCostSecp256k1 - initialCost, err := runSigDecorators(t, params, false, privs...) - require.Nil(t, err) + initialCost, err := suite.runSigDecorators(params, false, privs...) + suite.Require().Nil(err) params.SigVerifyCostSecp256k1 *= 2 - doubleCost, err := runSigDecorators(t, params, false, privs...) - require.Nil(t, err) + doubleCost, err := suite.runSigDecorators(params, false, privs...) + suite.Require().Nil(err) - require.Equal(t, initialSigCost*uint64(len(privs)), doubleCost-initialCost) + suite.Require().Equal(initialSigCost*uint64(len(privs)), doubleCost-initialCost) } -func runSigDecorators(t *testing.T, params types.Params, _ bool, privs ...crypto.PrivKey) (sdk.Gas, error) { - // setup - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) runSigDecorators(params types.Params, _ bool, privs ...crypto.PrivKey) (sdk.Gas, error) { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() + // Make block-height non-zero to include accNum in SignBytes - ctx = ctx.WithBlockHeight(1) - app.AccountKeeper.SetParams(ctx, params) + suite.ctx = suite.ctx.WithBlockHeight(1) + suite.app.AccountKeeper.SetParams(suite.ctx, params) msgs := make([]sdk.Msg, len(privs)) accNums := make([]uint64, len(privs)) - seqs := make([]uint64, len(privs)) + accSeqs := make([]uint64, len(privs)) // set accounts and create msg for each address for i, priv := range privs { addr := sdk.AccAddress(priv.PubKey().Address()) - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - require.NoError(t, acc.SetAccountNumber(uint64(i))) - app.AccountKeeper.SetAccount(ctx, acc) + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) + suite.Require().NoError(acc.SetAccountNumber(uint64(i))) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) msgs[i] = testdata.NewTestMsg(addr) accNums[i] = uint64(i) - seqs[i] = uint64(0) + accSeqs[i] = uint64(0) } + suite.txBuilder.SetMsgs(msgs...) - fee := types.NewTestStdFee() + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - tx := types.NewTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) - spkd := ante.NewSetPubKeyDecorator(app.AccountKeeper) - svgc := ante.NewSigGasConsumeDecorator(app.AccountKeeper, ante.DefaultSigVerificationGasConsumer) - svd := ante.NewSigVerificationDecorator(app.AccountKeeper, types.LegacyAminoJSONHandler{}) + spkd := ante.NewSetPubKeyDecorator(suite.app.AccountKeeper) + svgc := ante.NewSigGasConsumeDecorator(suite.app.AccountKeeper, ante.DefaultSigVerificationGasConsumer) + svd := ante.NewSigVerificationDecorator(suite.app.AccountKeeper, types.LegacyAminoJSONHandler{}) antehandler := sdk.ChainAnteDecorators(spkd, svgc, svd) // Determine gas consumption of antehandler with default params - before := ctx.GasMeter().GasConsumed() - ctx, err := antehandler(ctx, tx, false) + before := suite.ctx.GasMeter().GasConsumed() + ctx, err := antehandler(suite.ctx, tx, false) after := ctx.GasMeter().GasConsumed() return after - before, err } -func TestIncrementSequenceDecorator(t *testing.T) { - app, ctx := createTestApp(true) +func (suite *AnteTestSuite) TestIncrementSequenceDecorator() { + suite.SetupTest(true) // setup + suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() - priv, _, addr := types.KeyTestPubAddr() - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - require.NoError(t, acc.SetAccountNumber(uint64(50))) - app.AccountKeeper.SetAccount(ctx, acc) + priv, _, addr := testdata.KeyTestPubAddr() + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) + suite.Require().NoError(acc.SetAccountNumber(uint64(50))) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) msgs := []sdk.Msg{testdata.NewTestMsg(addr)} - privKeys := []crypto.PrivKey{priv} - accNums := []uint64{app.AccountKeeper.GetAccount(ctx, addr).GetAccountNumber()} - accSeqs := []uint64{app.AccountKeeper.GetAccount(ctx, addr).GetSequence()} - fee := types.NewTestStdFee() - tx := types.NewTestTx(ctx, msgs, privKeys, accNums, accSeqs, fee) + suite.txBuilder.SetMsgs(msgs...) + privs := []crypto.PrivKey{priv} + accNums := []uint64{suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetAccountNumber()} + accSeqs := []uint64{suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetSequence()} + feeAmount := testdata.NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) - isd := ante.NewIncrementSequenceDecorator(app.AccountKeeper) + tx := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) + + isd := ante.NewIncrementSequenceDecorator(suite.app.AccountKeeper) antehandler := sdk.ChainAnteDecorators(isd) testCases := []struct { @@ -249,16 +269,20 @@ func TestIncrementSequenceDecorator(t *testing.T) { simulate bool expectedSeq uint64 }{ - {ctx.WithIsReCheckTx(true), false, 1}, - {ctx.WithIsCheckTx(true).WithIsReCheckTx(false), false, 2}, - {ctx.WithIsReCheckTx(true), false, 3}, - {ctx.WithIsReCheckTx(true), false, 4}, - {ctx.WithIsReCheckTx(true), true, 5}, + {suite.ctx.WithIsReCheckTx(true), false, 1}, + {suite.ctx.WithIsCheckTx(true).WithIsReCheckTx(false), false, 2}, + {suite.ctx.WithIsReCheckTx(true), false, 3}, + {suite.ctx.WithIsReCheckTx(true), false, 4}, + {suite.ctx.WithIsReCheckTx(true), true, 5}, } for i, tc := range testCases { _, err := antehandler(tc.ctx, tx, tc.simulate) - require.NoError(t, err, "unexpected error; tc #%d, %v", i, tc) - require.Equal(t, tc.expectedSeq, app.AccountKeeper.GetAccount(ctx, addr).GetSequence()) + suite.Require().NoError(err, "unexpected error; tc #%d, %v", i, tc) + suite.Require().Equal(tc.expectedSeq, suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetSequence()) } } + +func TestAnteSigverifyTestSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) +} diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go new file mode 100644 index 0000000000..0df768ad80 --- /dev/null +++ b/x/auth/ante/testutil_test.go @@ -0,0 +1,120 @@ +package ante_test + +import ( + "errors" + "fmt" + + "github.com/stretchr/testify/suite" + "github.com/tendermint/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/simapp" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// TestAccount represents an account used in the tests in x/auth/ante. +type TestAccount struct { + acc types.AccountI + priv crypto.PrivKey +} + +// AnteTestSuite is a test suite to be used with ante handler tests. +type AnteTestSuite struct { + suite.Suite + + app *simapp.SimApp + anteHandler sdk.AnteHandler + ctx sdk.Context + clientCtx client.Context + txBuilder client.TxBuilder +} + +// SetupTest setups a new test, with new app, context, and anteHandler. +func (suite *AnteTestSuite) SetupTest(isCheckTx bool) { + suite.app, suite.ctx = createTestApp(isCheckTx) + suite.ctx = suite.ctx.WithBlockHeight(1) + suite.anteHandler = ante.NewAnteHandler(suite.app.AccountKeeper, suite.app.BankKeeper, *suite.app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, types.LegacyAminoJSONHandler{}) + + // set up the TxBuilder + encodingConfig := simappparams.MakeEncodingConfig() + suite.clientCtx = client.Context{}. + WithTxConfig(encodingConfig.TxConfig) +} + +// CreateTestAccounts creates `numAccs` accounts, and return all relevant +// information about them including their private keys. +func (suite *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { + var accounts []TestAccount + + for i := 0; i < numAccs; i++ { + priv, _, addr := testdata.KeyTestPubAddr() + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) + err := acc.SetAccountNumber(uint64(i)) + suite.Require().NoError(err) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + suite.app.BankKeeper.SetBalances(suite.ctx, addr, sdk.Coins{ + sdk.NewInt64Coin("atom", 10000000), + }) + + accounts = append(accounts, TestAccount{acc, priv}) + } + + return accounts +} + +// CreateTestTx is a helper function to create a tx given multiple inputs. +func (suite *AnteTestSuite) CreateTestTx(privs []crypto.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) xauthsigning.SigFeeMemoTx { + var sigsV2 []signing.SignatureV2 + for i, priv := range privs { + signerData := xauthsigning.SignerData{ + ChainID: chainID, + AccountNumber: accNums[i], + AccountSequence: accSeqs[i], + } + sigV2, err := tx.SignWithPrivKey(suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData, suite.txBuilder, priv, suite.clientCtx.TxConfig) + suite.Require().NoError(err) + + sigsV2 = append(sigsV2, sigV2) + } + suite.txBuilder.SetSignatures(sigsV2...) + + return suite.txBuilder.GetTx() +} + +// TestCase represents a test case used in test tables. +type TestCase struct { + desc string + malleate func() + simulate bool + expPass bool + expErr error +} + +// CreateTestTx is a helper function to create a tx given multiple inputs. +func (suite *AnteTestSuite) RunTestCase(privs []crypto.PrivKey, msgs []sdk.Msg, feeAmount sdk.Coins, gasLimit uint64, accNums, accSeqs []uint64, chainID string, tc TestCase) { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + suite.txBuilder.SetMsgs(msgs...) + suite.txBuilder.SetFeeAmount(feeAmount) + suite.txBuilder.SetGasLimit(gasLimit) + + tx := suite.CreateTestTx(privs, accNums, accSeqs, chainID) + newCtx, err := suite.anteHandler(suite.ctx, tx, tc.simulate) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().NotNil(newCtx) + + suite.ctx = newCtx + } else { + suite.Require().Error(err) + suite.Require().True(errors.Is(err, tc.expErr)) + } + }) +} diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index 89c902febc..5f09d4ca7c 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -36,7 +36,7 @@ $ tx broadcast ./mytxn.json return err } - txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) + txBytes, err := clientCtx.TxConfig.TxEncoder()(stdTx) if err != nil { return err } diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 750df016df..714050dfdd 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -624,7 +624,7 @@ func (s *IntegrationTestSuite) TestCLIMultisign() { func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { clientCtx := client.Context{}.WithOffline(true) - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + clientCtx = clientCtx.WithTxConfig(simappparams.MakeEncodingConfig().TxConfig) cmd := cli2.GetBroadcastCommand() _ = testutil.ApplyMockIODiscardOutErr(cmd) @@ -635,7 +635,7 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + clientCtx = clientCtx.WithTxConfig(simappparams.MakeEncodingConfig().TxConfig) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) diff --git a/x/auth/client/cli/decode.go b/x/auth/client/cli/decode.go index 8d11e8805a..513b23d45e 100644 --- a/x/auth/client/cli/decode.go +++ b/x/auth/client/cli/decode.go @@ -32,7 +32,7 @@ func GetDecodeCommand() *cobra.Command { return err } - tx, err := clientCtx.TxGenerator.TxDecoder()(txBytes) + tx, err := clientCtx.TxConfig.TxDecoder()(txBytes) if err != nil { return err } diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index d73e6aa788..73fcfb450a 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -36,7 +36,7 @@ If you supply a dash (-) argument in place of an input filename, the command rea } // re-encode it - txBytes, err := clientCtx.TxGenerator.TxEncoder()(tx) + txBytes, err := clientCtx.TxConfig.TxEncoder()(tx) if err != nil { return err } diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index cbb5b0a182..2458b55321 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -23,7 +23,7 @@ func TestGetCommandEncode(t *testing.T) { authtypes.RegisterCodec(encodingConfig.Amino) sdk.RegisterCodec(encodingConfig.Amino) - txGen := encodingConfig.TxGenerator + txGen := encodingConfig.TxConfig // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) @@ -37,7 +37,7 @@ func TestGetCommandEncode(t *testing.T) { ctx := context.Background() clientCtx := client.Context{}. - WithTxGenerator(encodingConfig.TxGenerator). + WithTxConfig(encodingConfig.TxConfig). WithJSONMarshaler(encodingConfig.Marshaler) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) @@ -50,7 +50,7 @@ func TestGetCommandDecode(t *testing.T) { encodingConfig := simappparams.MakeEncodingConfig() clientCtx := client.Context{}. - WithTxGenerator(encodingConfig.TxGenerator). + WithTxConfig(encodingConfig.TxConfig). WithJSONMarshaler(encodingConfig.Marshaler) cmd := GetDecodeCommand() @@ -58,15 +58,15 @@ func TestGetCommandDecode(t *testing.T) { sdk.RegisterCodec(encodingConfig.Amino) - txGen := encodingConfig.TxGenerator - clientCtx = clientCtx.WithTxGenerator(txGen) + txGen := encodingConfig.TxConfig + clientCtx = clientCtx.WithTxConfig(txGen) // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") // Encode transaction - txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) + txBytes, err := clientCtx.TxConfig.TxEncoder()(stdTx) require.NoError(t, err) // Convert the transaction into base64 encoded string diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 14f9146550..c8b3464ad8 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -232,7 +232,7 @@ func ReadTxFromFile(ctx client.Context, filename string) (tx sdk.Tx, err error) return } - return ctx.TxGenerator.TxJSONDecoder()(bytes) + return ctx.TxConfig.TxJSONDecoder()(bytes) } // NewBatchScanner returns a new BatchScanner to read newline-delimited StdTx transactions from r. diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index e5d7fd3088..cb51696253 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/testdata" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" @@ -127,9 +127,9 @@ func TestReadStdTxFromFile(t *testing.T) { encodingConfig := simappparams.MakeEncodingConfig() sdk.RegisterCodec(encodingConfig.Amino) - txGen := encodingConfig.TxGenerator + txGen := encodingConfig.TxConfig clientCtx := client.Context{} - clientCtx = clientCtx.WithTxGenerator(txGen) + clientCtx = clientCtx.WithTxConfig(txGen) // Build a test transaction fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) @@ -218,10 +218,10 @@ func TestPrepareTxBuilder(t *testing.T) { var accNum uint64 = 10 var accSeq uint64 = 17 - txGen := encodingConfig.TxGenerator + txGen := encodingConfig.TxConfig clientCtx := client.Context{} clientCtx = clientCtx. - WithTxGenerator(txGen). + WithTxConfig(txGen). WithJSONMarshaler(encodingConfig.Marshaler). WithAccountRetriever(client.TestAccountRetriever{Accounts: map[string]struct { Address sdk.AccAddress diff --git a/x/auth/keeper/grpc_query_test.go b/x/auth/keeper/grpc_query_test.go index 6f2da165d9..465a839374 100644 --- a/x/auth/keeper/grpc_query_test.go +++ b/x/auth/keeper/grpc_query_test.go @@ -3,6 +3,7 @@ package keeper_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -11,7 +12,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryAccount() { var ( req *types.QueryAccountRequest ) - _, _, addr := types.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() testCases := []struct { msg string diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go index 56a0b1b619..60a762eefc 100644 --- a/x/auth/keeper/querier_test.go +++ b/x/auth/keeper/querier_test.go @@ -8,6 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" keep "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -41,7 +42,7 @@ func TestQueryAccount(t *testing.T) { require.Error(t, err) require.Nil(t, res) - _, _, addr := types.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() req.Data = cdc.MustMarshalJSON(types.NewQueryAccountRequest(addr)) res, err = querier(ctx, path, req) require.Error(t, err) diff --git a/x/auth/signing/direct/direct_test.go b/x/auth/signing/direct/direct_test.go index 5dc60f9068..7af0c16244 100644 --- a/x/auth/signing/direct/direct_test.go +++ b/x/auth/signing/direct/direct_test.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/signing/direct" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/codec" @@ -21,17 +21,16 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/x/auth/signing" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) func TestDirectModeHandler(t *testing.T) { - privKey, pubkey, addr := authtypes.KeyTestPubAddr() + privKey, pubkey, addr := testdata.KeyTestPubAddr() interfaceRegistry := codectypes.NewInterfaceRegistry() interfaceRegistry.RegisterImplementations((*sdk.Msg)(nil), &testdata.TestMsg{}) marshaler := codec.NewProtoCodec(interfaceRegistry) pubKeyCdc := std.DefaultPublicKeyCodec{} - txGen := tx.NewTxGenerator(marshaler, pubKeyCdc, tx.DefaultSignModeHandler()) + txGen := tx.NewTxConfig(marshaler, pubKeyCdc, tx.DefaultSignModeHandler()) txBuilder := txGen.NewTxBuilder() memo := "sometestmemo" diff --git a/x/auth/signing/verify_test.go b/x/auth/signing/verify_test.go index 98b820478a..30f53013a0 100644 --- a/x/auth/signing/verify_test.go +++ b/x/auth/signing/verify_test.go @@ -3,7 +3,7 @@ package signing_test import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -19,8 +19,8 @@ import ( ) func TestVerifySignature(t *testing.T) { - priv, pubKey, addr := types.KeyTestPubAddr() - priv1, pubKey1, addr1 := types.KeyTestPubAddr() + priv, pubKey, addr := testdata.KeyTestPubAddr() + priv1, pubKey1, addr1 := testdata.KeyTestPubAddr() const ( memo = "testmemo" diff --git a/x/auth/tx/builder_test.go b/x/auth/tx/builder_test.go index 64040c953f..136078fa76 100644 --- a/x/auth/tx/builder_test.go +++ b/x/auth/tx/builder_test.go @@ -3,7 +3,7 @@ package tx import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" tx2 "github.com/cosmos/cosmos-sdk/types/tx" @@ -12,8 +12,6 @@ import ( "github.com/stretchr/testify/require" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/std" @@ -21,7 +19,7 @@ import ( ) func TestTxBuilder(t *testing.T) { - _, pubkey, addr := authtypes.KeyTestPubAddr() + _, pubkey, addr := testdata.KeyTestPubAddr() marshaler := codec.NewHybridCodec(codec.New(), codectypes.NewInterfaceRegistry()) tx := newBuilder(marshaler, std.DefaultPublicKeyCodec{}) @@ -116,18 +114,17 @@ func TestTxBuilder(t *testing.T) { func TestBuilderValidateBasic(t *testing.T) { // keys and addresses - _, pubKey1, addr1 := authtypes.KeyTestPubAddr() - _, pubKey2, addr2 := authtypes.KeyTestPubAddr() + _, pubKey1, addr1 := testdata.KeyTestPubAddr() + _, pubKey2, addr2 := testdata.KeyTestPubAddr() // msg and signatures msg1 := testdata.NewTestMsg(addr1, addr2) - fee := authtypes.NewTestStdFee() - + feeAmount := testdata.NewTestFeeAmount() msgs := []sdk.Msg{msg1} // require to fail validation upon invalid fee - badFee := authtypes.NewTestStdFee() - badFee.Amount[0].Amount = sdk.NewInt(-5) + badFeeAmount := testdata.NewTestFeeAmount() + badFeeAmount[0].Amount = sdk.NewInt(-5) marshaler := codec.NewHybridCodec(codec.New(), codectypes.NewInterfaceRegistry()) bldr := newBuilder(marshaler, std.DefaultPublicKeyCodec{}) @@ -153,7 +150,7 @@ func TestBuilderValidateBasic(t *testing.T) { bldr.SetGasLimit(200000) err = bldr.SetSignatures(sig1, sig2) require.NoError(t, err) - bldr.SetFeeAmount(badFee.Amount) + bldr.SetFeeAmount(badFeeAmount) err = bldr.ValidateBasic() require.Error(t, err) _, code, _ := sdkerrors.ABCIInfo(err, false) @@ -162,7 +159,7 @@ func TestBuilderValidateBasic(t *testing.T) { // require to fail validation when no signatures exist err = bldr.SetSignatures() require.NoError(t, err) - bldr.SetFeeAmount(fee.Amount) + bldr.SetFeeAmount(feeAmount) err = bldr.ValidateBasic() require.Error(t, err) _, code, _ = sdkerrors.ABCIInfo(err, false) @@ -184,7 +181,7 @@ func TestBuilderValidateBasic(t *testing.T) { require.Equal(t, sdkerrors.ErrUnauthorized.ABCICode(), code) require.Error(t, err) - bldr.SetFeeAmount(fee.Amount) + bldr.SetFeeAmount(feeAmount) err = bldr.SetSignatures(sig1, sig2) require.NoError(t, err) err = bldr.ValidateBasic() diff --git a/x/auth/tx/generator.go b/x/auth/tx/generator.go index de54b017b9..3d6bb529ee 100644 --- a/x/auth/tx/generator.go +++ b/x/auth/tx/generator.go @@ -18,8 +18,8 @@ type generator struct { jsonEncoder sdk.TxEncoder } -// NewTxGenerator returns a new protobuf TxGenerator using the provided Marshaler, PublicKeyCodec and SignModeHandler. -func NewTxGenerator(marshaler codec.Marshaler, pubkeyCodec types.PublicKeyCodec, signModeHandler signing.SignModeHandler) client.TxGenerator { +// NewTxConfig returns a new protobuf TxConfig using the provided Marshaler, PublicKeyCodec and SignModeHandler. +func NewTxConfig(marshaler codec.Marshaler, pubkeyCodec types.PublicKeyCodec, signModeHandler signing.SignModeHandler) client.TxConfig { return &generator{ marshaler: marshaler, pubkeyCodec: pubkeyCodec, diff --git a/x/auth/tx/generator_test.go b/x/auth/tx/generator_test.go index ca63ecfc1f..21fc057dce 100644 --- a/x/auth/tx/generator_test.go +++ b/x/auth/tx/generator_test.go @@ -3,7 +3,7 @@ package tx import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -21,5 +21,5 @@ func TestGenerator(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) pubKeyCodec := std.DefaultPublicKeyCodec{} signModeHandler := DefaultSignModeHandler() - suite.Run(t, testutil.NewTxGeneratorTestSuite(NewTxGenerator(marshaler, pubKeyCodec, signModeHandler))) + suite.Run(t, testutil.NewTxConfigTestSuite(NewTxConfig(marshaler, pubKeyCodec, signModeHandler))) } diff --git a/x/auth/tx/sigs_test.go b/x/auth/tx/sigs_test.go index 7280188d0f..ab868db1cd 100644 --- a/x/auth/tx/sigs_test.go +++ b/x/auth/tx/sigs_test.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" ) func TestDecodeMultisignatures(t *testing.T) { diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index 69a3d2e918..aab4893fc5 100644 --- a/x/auth/types/account_test.go +++ b/x/auth/types/account_test.go @@ -10,13 +10,14 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" yaml "gopkg.in/yaml.v2" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) func TestBaseAddressPubKey(t *testing.T) { - _, pub1, addr1 := types.KeyTestPubAddr() - _, pub2, addr2 := types.KeyTestPubAddr() + _, pub1, addr1 := testdata.KeyTestPubAddr() + _, pub2, addr2 := testdata.KeyTestPubAddr() acc := types.NewBaseAccountWithAddress(addr1) // check the address (set) and pubkey (not set) @@ -48,7 +49,7 @@ func TestBaseAddressPubKey(t *testing.T) { } func TestBaseAccountSequence(t *testing.T) { - _, _, addr := types.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() acc := types.NewBaseAccountWithAddress(addr) seq := uint64(7) @@ -58,7 +59,7 @@ func TestBaseAccountSequence(t *testing.T) { } func TestBaseAccountMarshal(t *testing.T) { - _, pub, addr := types.KeyTestPubAddr() + _, pub, addr := testdata.KeyTestPubAddr() acc := types.NewBaseAccountWithAddress(addr) seq := uint64(7) diff --git a/x/auth/types/client_tx.go b/x/auth/types/client_tx.go index 3175cc89cf..da03ab2fa3 100644 --- a/x/auth/types/client_tx.go +++ b/x/auth/types/client_tx.go @@ -71,40 +71,40 @@ func (s *StdTxBuilder) SetMemo(memo string) { s.Memo = memo } -// StdTxGenerator is a context.TxGenerator for StdTx -type StdTxGenerator struct { +// StdTxConfig is a context.TxConfig for StdTx +type StdTxConfig struct { Cdc *codec.Codec } -var _ client.TxGenerator = StdTxGenerator{} +var _ client.TxConfig = StdTxConfig{} -// NewTxBuilder implements TxGenerator.NewTxBuilder -func (s StdTxGenerator) NewTxBuilder() client.TxBuilder { +// NewTxBuilder implements TxConfig.NewTxBuilder +func (s StdTxConfig) NewTxBuilder() client.TxBuilder { return &StdTxBuilder{ StdTx: StdTx{}, cdc: s.Cdc, } } -// MarshalTx implements TxGenerator.MarshalTx -func (s StdTxGenerator) TxEncoder() sdk.TxEncoder { +// MarshalTx implements TxConfig.MarshalTx +func (s StdTxConfig) TxEncoder() sdk.TxEncoder { return DefaultTxEncoder(s.Cdc) } -func (s StdTxGenerator) TxDecoder() sdk.TxDecoder { +func (s StdTxConfig) TxDecoder() sdk.TxDecoder { return DefaultTxDecoder(s.Cdc) } -func (s StdTxGenerator) TxJSONEncoder() sdk.TxEncoder { +func (s StdTxConfig) TxJSONEncoder() sdk.TxEncoder { return func(tx sdk.Tx) ([]byte, error) { return s.Cdc.MarshalJSON(tx) } } -func (s StdTxGenerator) TxJSONDecoder() sdk.TxDecoder { +func (s StdTxConfig) TxJSONDecoder() sdk.TxDecoder { return DefaultJSONTxDecoder(s.Cdc) } -func (s StdTxGenerator) SignModeHandler() authsigning.SignModeHandler { +func (s StdTxConfig) SignModeHandler() authsigning.SignModeHandler { return LegacyAminoJSONHandler{} } diff --git a/x/auth/types/client_tx_test.go b/x/auth/types/client_tx_test.go index 600a20af32..2be71b74ca 100644 --- a/x/auth/types/client_tx_test.go +++ b/x/auth/types/client_tx_test.go @@ -3,7 +3,7 @@ package types_test import ( "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/client/testutil" @@ -21,8 +21,8 @@ func testCodec() *codec.Codec { return cdc } -func TestStdTxGenerator(t *testing.T) { +func TestStdTxConfig(t *testing.T) { cdc := testCodec() - txGen := types.StdTxGenerator{Cdc: cdc} - suite.Run(t, testutil.NewTxGeneratorTestSuite(txGen)) + txGen := types.StdTxConfig{Cdc: cdc} + suite.Run(t, testutil.NewTxConfigTestSuite(txGen)) } diff --git a/x/auth/types/stdtx_test.go b/x/auth/types/stdtx_test.go index 15d3f89eb5..70d0ff2f74 100644 --- a/x/auth/types/stdtx_test.go +++ b/x/auth/types/stdtx_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" @@ -28,6 +28,31 @@ var ( addr = sdk.AccAddress(priv.PubKey().Address()) ) +// Deprecated, use fee amount and gas limit separately on TxBuilder. +func NewTestStdFee() StdFee { + return NewStdFee(100000, + sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), + ) +} + +// Deprecated, use TxBuilder. +func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { + sigs := make([]StdSignature, len(privs)) + for i, priv := range privs { + signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") + + sig, err := priv.Sign(signBytes) + if err != nil { + panic(err) + } + + sigs[i] = StdSignature{PubKey: priv.PubKey().Bytes(), Signature: sig} + } + + tx := NewStdTx(msgs, fee, sigs, "") + return tx +} + func TestStdTx(t *testing.T) { msgs := []sdk.Msg{testdata.NewTestMsg(addr)} fee := NewTestStdFee() @@ -70,8 +95,8 @@ func TestTxValidateBasic(t *testing.T) { ctx := sdk.NewContext(nil, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) // keys and addresses - priv1, _, addr1 := KeyTestPubAddr() - priv2, _, addr2 := KeyTestPubAddr() + priv1, _, addr1 := testdata.KeyTestPubAddr() + priv2, _, addr2 := testdata.KeyTestPubAddr() // msg and signatures msg1 := testdata.NewTestMsg(addr1, addr2) @@ -148,7 +173,7 @@ func TestDefaultTxEncoder(t *testing.T) { } func TestStdSignatureMarshalYAML(t *testing.T) { - _, pubKey, _ := KeyTestPubAddr() + _, pubKey, _ := testdata.KeyTestPubAddr() testCases := []struct { sig StdSignature @@ -176,7 +201,7 @@ func TestStdSignatureMarshalYAML(t *testing.T) { } func TestSignatureV2Conversions(t *testing.T) { - _, pubKey, _ := KeyTestPubAddr() + _, pubKey, _ := testdata.KeyTestPubAddr() cdc := codec.New() sdk.RegisterCodec(cdc) RegisterCodec(cdc) @@ -196,7 +221,7 @@ func TestSignatureV2Conversions(t *testing.T) { require.Equal(t, dummy, sigBz) // multisigs - _, pubKey2, _ := KeyTestPubAddr() + _, pubKey2, _ := testdata.KeyTestPubAddr() multiPK := multisig.NewPubKeyMultisigThreshold(1, []crypto.PubKey{ pubKey, pubKey2, }) @@ -231,7 +256,7 @@ func TestSignatureV2Conversions(t *testing.T) { } func TestGetSignaturesV2(t *testing.T) { - _, pubKey, _ := KeyTestPubAddr() + _, pubKey, _ := testdata.KeyTestPubAddr() dummy := []byte("dummySig") cdc := codec.New() diff --git a/x/auth/types/test_utils.go b/x/auth/types/test_utils.go deleted file mode 100644 index c25f8d89c6..0000000000 --- a/x/auth/types/test_utils.go +++ /dev/null @@ -1,77 +0,0 @@ -package types - -import ( - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/secp256k1" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func NewTestStdFee() StdFee { - return NewStdFee(100000, - sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), - ) -} - -// coins to more than cover the fee -func NewTestCoins() sdk.Coins { - return sdk.Coins{ - sdk.NewInt64Coin("atom", 10000000), - } -} - -func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { - key := secp256k1.GenPrivKey() - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return key, pub, addr -} - -func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") - - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey().Bytes(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, "") - return tx -} - -func NewTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, memo) - - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey().Bytes(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, memo) - return tx -} - -func NewTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey().Bytes(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, memo) - return tx -} diff --git a/x/auth/types/txbuilder_test.go b/x/auth/types/txbuilder_test.go index 19d4e101b2..fc007eb679 100644 --- a/x/auth/types/txbuilder_test.go +++ b/x/auth/types/txbuilder_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" diff --git a/x/auth/vesting/types/test_common.go b/x/auth/vesting/types/test_common.go index 0ccb5e62f3..948e506b3c 100644 --- a/x/auth/vesting/types/test_common.go +++ b/x/auth/vesting/types/test_common.go @@ -4,7 +4,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 5f6d8a31cd..d5652bef45 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -9,6 +9,7 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmtime "github.com/tendermint/tendermint/types/time" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" @@ -23,7 +24,7 @@ func TestGetVestedCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix()) @@ -49,7 +50,7 @@ func TestGetVestingCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix()) @@ -71,7 +72,7 @@ func TestSpendableCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -99,7 +100,7 @@ func TestTrackDelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -138,7 +139,7 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -186,7 +187,7 @@ func TestGetVestedCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -204,7 +205,7 @@ func TestGetVestingCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -222,7 +223,7 @@ func TestSpendableCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -259,7 +260,7 @@ func TestTrackDelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -296,7 +297,7 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -349,7 +350,7 @@ func TestGetVestedCoinsPeriodicVestingAcc(t *testing.T) { types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}}, } - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods) @@ -394,7 +395,7 @@ func TestGetVestingCoinsPeriodicVestingAcc(t *testing.T) { types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}}, } - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{ sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -434,7 +435,7 @@ func TestSpendableCoinsPeriodicVestingAcc(t *testing.T) { types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}}, } - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{ sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -469,7 +470,7 @@ func TestTrackDelegationPeriodicVestingAcc(t *testing.T) { types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}}, } - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) @@ -527,7 +528,7 @@ func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) { types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}}, } - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := authtypes.NewBaseAccountWithAddress(addr) diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 0516baee5d..d99539e034 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -110,7 +110,7 @@ func TestSendNotEnoughBalance(t *testing.T) { sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{sendMsg}, []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) require.Error(t, err) @@ -178,7 +178,7 @@ func TestSendToModuleAcc(t *testing.T) { origSeq := res1.GetSequence() header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{test.msg}, []uint64{origAccNum}, []uint64{origSeq}, test.expSimPass, test.expPass, priv1) if test.expPass { require.NoError(t, err) @@ -249,7 +249,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) if tc.expPass { require.NoError(t, err) @@ -301,7 +301,7 @@ func TestMsgMultiSendMultipleOut(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) @@ -356,7 +356,7 @@ func TestMsgMultiSendMultipleInOut(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) @@ -409,7 +409,7 @@ func TestMsgMultiSendDependent(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index f82384ad47..67750d6b24 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -32,7 +32,7 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) { require.NoError(b, err) benchmarkApp.Commit() - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig // Precompute all txs txs, err := simapp.GenSequenceOfTxs(txGen, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) @@ -74,7 +74,7 @@ func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) { require.NoError(b, err) benchmarkApp.Commit() - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig // Precompute all txs txs, err := simapp.GenSequenceOfTxs(txGen, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) diff --git a/x/bank/handler_test.go b/x/bank/handler_test.go index ab6338d1d4..ef870e4213 100644 --- a/x/bank/handler_test.go +++ b/x/bank/handler_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 5715aa84cf..1612ac55df 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -6,14 +6,14 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/bank/types" ) func (suite *IntegrationTestSuite) TestQueryBalance() { app, ctx := suite.app, suite.ctx - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry()) types.RegisterQueryServer(queryHelper, app.BankKeeper) @@ -45,7 +45,7 @@ func (suite *IntegrationTestSuite) TestQueryBalance() { func (suite *IntegrationTestSuite) TestQueryAllBalances() { app, ctx := suite.app, suite.ctx - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry()) types.RegisterQueryServer(queryHelper, app.BankKeeper) diff --git a/x/bank/keeper/querier_test.go b/x/bank/keeper/querier_test.go index 1c52079cad..df7c6f79c0 100644 --- a/x/bank/keeper/querier_test.go +++ b/x/bank/keeper/querier_test.go @@ -5,15 +5,15 @@ import ( abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/x/bank/types" ) func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() { app, ctx := suite.app, suite.ctx - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() req := abci.RequestQuery{ Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryBalance), Data: []byte{}, @@ -49,7 +49,7 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() { func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() { app, ctx := suite.app, suite.ctx - _, _, addr := authtypes.KeyTestPubAddr() + _, _, addr := testdata.KeyTestPubAddr() req := abci.RequestQuery{ Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryAllBalances), Data: []byte{}, diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 92bf6db75a..7cd73e2342 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -103,7 +103,7 @@ func sendMsgSend( return err } } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -251,7 +251,7 @@ func sendMsgMultiSend( } } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, diff --git a/x/crisis/handler_test.go b/x/crisis/handler_test.go index b4aa14e701..bd2752704e 100644 --- a/x/crisis/handler_test.go +++ b/x/crisis/handler_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 06ec46db9b..bc40c15105 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -5,8 +5,8 @@ import ( "github.com/spf13/pflag" - "github.com/cosmos/cosmos-sdk/codec/testdata" "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 8d90c01bbb..f33329b5f3 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -100,7 +100,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -152,7 +152,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -207,7 +207,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -262,7 +262,7 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k } msg := types.NewMsgFundCommunityPool(fundAmount, funder.Address) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, diff --git a/x/gov/handler_test.go b/x/gov/handler_test.go index 96728accda..57dde01958 100644 --- a/x/gov/handler_test.go +++ b/x/gov/handler_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 6bfaf47b6b..93f8af8a9e 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -142,7 +142,7 @@ func SimulateMsgSubmitProposal( } } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -229,7 +229,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke } } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -291,7 +291,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to generate fees"), nil, err } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, diff --git a/x/ibc/testing/chain.go b/x/ibc/testing/chain.go index 78d71e47e1..b7df7cf826 100644 --- a/x/ibc/testing/chain.go +++ b/x/ibc/testing/chain.go @@ -69,7 +69,7 @@ type TestChain struct { CurrentHeader abci.Header // header for current block height Querier sdk.Querier // TODO: deprecate once clients are migrated to gRPC QueryServer types.QueryServer - TxGenerator client.TxGenerator + TxConfig client.TxConfig Vals *tmtypes.ValidatorSet Signers []tmtypes.PrivValidator @@ -117,7 +117,7 @@ func NewTestChain(t *testing.T, chainID string) *TestChain { Time: globalStartTime, } - txGenerator := simapp.MakeEncodingConfig().TxGenerator + txConfig := simapp.MakeEncodingConfig().TxConfig // create an account to send transactions from chain := &TestChain{ @@ -127,7 +127,7 @@ func NewTestChain(t *testing.T, chainID string) *TestChain { CurrentHeader: header, Querier: keeper.NewQuerier(*app.IBCKeeper), QueryServer: app.IBCKeeper, - TxGenerator: txGenerator, + TxConfig: txConfig, Vals: valSet, Signers: signers, senderPrivKey: senderPrivKey, @@ -209,7 +209,7 @@ func (chain *TestChain) NextBlock() { func (chain *TestChain) SendMsg(msg sdk.Msg) error { _, _, err := simapp.SignCheckDeliver( chain.t, - chain.TxGenerator, + chain.TxConfig, chain.App.BaseApp, chain.GetContext().BlockHeader(), []sdk.Msg{msg}, diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 629bb621e8..bc8f6e03eb 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -63,7 +63,7 @@ func TestSlashingMsgs(t *testing.T) { ) header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 38a3014afe..d2ee849cea 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index cfcf5c2a41..f8ea2845a3 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -86,7 +86,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee msg := types.NewMsgUnjail(validator.GetOperator()) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, diff --git a/x/staking/app_test.go b/x/staking/app_test.go index bc1f41bda1..457003475e 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -69,7 +69,7 @@ func TestStakingMsgs(t *testing.T) { ) header := abci.Header{Height: app.LastBlockHeight() + 1} - txGen := simapp.MakeEncodingConfig().TxGenerator + txGen := simapp.MakeEncodingConfig().TxConfig _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index bdad214cbc..b56e66d924 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -55,7 +55,7 @@ func NewCreateValidatorCmd(clientCtx client.Context) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { clientCtx.WithInput(cmd.InOrStdin()) - txf := tx.NewFactoryCLI(clientCtx, cmd.Flags()).WithTxGenerator(clientCtx.TxGenerator).WithAccountRetriever(clientCtx.AccountRetriever) + txf := tx.NewFactoryCLI(clientCtx, cmd.Flags()).WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) txf, msg, err := NewBuildCreateValidatorMsg(clientCtx, txf, cmd.Flags()) if err != nil { diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 462ee92be1..488fa6b8b5 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/codec/testdata" + "github.com/cosmos/cosmos-sdk/testutil/testdata" gogotypes "github.com/gogo/protobuf/types" "github.com/stretchr/testify/assert" diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index fbd9e444d0..fe5e341aa5 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -151,7 +151,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k msg := types.NewMsgCreateValidator(address, simAccount.PubKey, selfDelegation, description, commission, sdk.OneInt()) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -222,7 +222,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -295,7 +295,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K msg := types.NewMsgDelegate(simAccount.Address, val.GetOperator(), bondAmt) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -385,7 +385,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to generate fees"), nil, err } - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, @@ -498,7 +498,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k sdk.NewCoin(k.BondDenom(ctx), redAmt), ) - txGen := simappparams.MakeEncodingConfig().TxGenerator + txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( txGen, []sdk.Msg{msg}, diff --git a/x/upgrade/client/rest/tx.go b/x/upgrade/client/rest/tx.go index bc4b0795fe..2a242c2417 100644 --- a/x/upgrade/client/rest/tx.go +++ b/x/upgrade/client/rest/tx.go @@ -21,7 +21,7 @@ import ( // nolint func newRegisterTxRoutes( clientCtx client.Context, - txg client.TxGenerator, + txg client.TxConfig, newMsgFn func() gov.MsgSubmitProposalI, r *mux.Router) { r.HandleFunc("/upgrade/plan", newPostPlanHandler(clientCtx, txg, newMsgFn)).Methods("POST") @@ -61,7 +61,7 @@ func ProposalRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { } // nolint -func newPostPlanHandler(clientCtx client.Context, txg client.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { +func newPostPlanHandler(clientCtx client.Context, txg client.TxConfig, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PlanRequest @@ -106,7 +106,7 @@ func newPostPlanHandler(clientCtx client.Context, txg client.TxGenerator, newMsg } // nolint -func newCancelPlanHandler(clientCtx client.Context, txg client.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { +func newCancelPlanHandler(clientCtx client.Context, txg client.TxConfig, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CancelRequest