github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/sdk/auth/ante_test.go (about)

     1  package auth
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"reflect"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/gnolang/gno/tm2/pkg/amino"
    13  	abci "github.com/gnolang/gno/tm2/pkg/bft/abci/types"
    14  	bft "github.com/gnolang/gno/tm2/pkg/bft/types"
    15  	"github.com/gnolang/gno/tm2/pkg/crypto"
    16  	"github.com/gnolang/gno/tm2/pkg/crypto/ed25519"
    17  	"github.com/gnolang/gno/tm2/pkg/crypto/multisig"
    18  	"github.com/gnolang/gno/tm2/pkg/crypto/secp256k1"
    19  	"github.com/gnolang/gno/tm2/pkg/sdk"
    20  	tu "github.com/gnolang/gno/tm2/pkg/sdk/testutils"
    21  	"github.com/gnolang/gno/tm2/pkg/std"
    22  	"github.com/gnolang/gno/tm2/pkg/store"
    23  )
    24  
    25  // run the tx through the anteHandler and ensure its valid
    26  func checkValidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx std.Tx, simulate bool) {
    27  	t.Helper()
    28  
    29  	_, result, abort := anteHandler(ctx, tx, simulate)
    30  	require.Equal(t, "", result.Log)
    31  	require.False(t, abort)
    32  	require.Nil(t, result.Error)
    33  	require.True(t, result.IsOK())
    34  }
    35  
    36  // run the tx through the anteHandler and ensure it fails with the given code
    37  func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx std.Tx, simulate bool, err abci.Error) {
    38  	t.Helper()
    39  
    40  	newCtx, result, abort := anteHandler(ctx, tx, simulate)
    41  	require.True(t, abort)
    42  
    43  	require.Equal(t, reflect.TypeOf(err), reflect.TypeOf(sdk.ABCIError(result.Error)), fmt.Sprintf("Expected %v, got %v", err, result))
    44  
    45  	if reflect.TypeOf(err) == reflect.TypeOf(std.OutOfGasError{}) {
    46  		// GasWanted set correctly
    47  		require.Equal(t, tx.Fee.GasWanted, result.GasWanted, "Gas wanted not set correctly")
    48  		require.True(t, result.GasUsed > result.GasWanted, "GasUsed not greated than GasWanted")
    49  		// Check that context is set correctly
    50  		require.Equal(t, result.GasUsed, newCtx.GasMeter().GasConsumed(), "Context not updated correctly")
    51  	}
    52  }
    53  
    54  func defaultAnteOptions() AnteOptions {
    55  	return AnteOptions{
    56  		VerifyGenesisSignatures: true,
    57  	}
    58  }
    59  
    60  // Test various error cases in the AnteHandler control flow.
    61  func TestAnteHandlerSigErrors(t *testing.T) {
    62  	t.Parallel()
    63  
    64  	// setup
    65  	env := setupTestEnv()
    66  	ctx := env.ctx
    67  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
    68  
    69  	// keys and addresses
    70  	priv1, _, addr1 := tu.KeyTestPubAddr()
    71  	priv2, _, addr2 := tu.KeyTestPubAddr()
    72  	priv3, _, addr3 := tu.KeyTestPubAddr()
    73  
    74  	// msg and signatures
    75  	var tx std.Tx
    76  	msg1 := tu.NewTestMsg(addr1, addr2)
    77  	msg2 := tu.NewTestMsg(addr1, addr3)
    78  	fee := tu.NewTestFee()
    79  
    80  	msgs := []std.Msg{msg1, msg2}
    81  
    82  	// test no signatures
    83  	privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{}
    84  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accNums, seqs, fee)
    85  
    86  	// tx.GetSigners returns addresses in correct order: addr1, addr2, addr3
    87  	expectedSigners := []crypto.Address{addr1, addr2, addr3}
    88  	require.Equal(t, expectedSigners, tx.GetSigners())
    89  
    90  	// Check no signatures fails
    91  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.NoSignaturesError{})
    92  
    93  	// test num sigs dont match GetSigners
    94  	privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
    95  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accNums, seqs, fee)
    96  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
    97  
    98  	// test an unrecognized account
    99  	privs, accNums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}
   100  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accNums, seqs, fee)
   101  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnknownAddressError{})
   102  
   103  	// save the first account, but second is still unrecognized
   104  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   105  	acc1.SetCoins(std.Coins{fee.GasFee})
   106  	env.acck.SetAccount(ctx, acc1)
   107  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnknownAddressError{})
   108  }
   109  
   110  // Test logic around account number checking with one signer and many signers.
   111  func TestAnteHandlerAccountNumbers(t *testing.T) {
   112  	t.Parallel()
   113  
   114  	// setup
   115  	env := setupTestEnv()
   116  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   117  	ctx := env.ctx
   118  
   119  	// keys and addresses
   120  	priv1, _, addr1 := tu.KeyTestPubAddr()
   121  	priv2, _, addr2 := tu.KeyTestPubAddr()
   122  
   123  	// set the accounts
   124  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   125  	acc1.SetCoins(tu.NewTestCoins())
   126  	require.NoError(t, acc1.SetAccountNumber(0))
   127  	env.acck.SetAccount(ctx, acc1)
   128  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   129  	acc2.SetCoins(tu.NewTestCoins())
   130  	require.NoError(t, acc2.SetAccountNumber(1))
   131  	env.acck.SetAccount(ctx, acc2)
   132  
   133  	// msg and signatures
   134  	var tx std.Tx
   135  	msg := tu.NewTestMsg(addr1)
   136  	fee := tu.NewTestFee()
   137  
   138  	msgs := []std.Msg{msg}
   139  
   140  	// test good tx from one signer
   141  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   142  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   143  	checkValidTx(t, anteHandler, ctx, tx, false)
   144  
   145  	// new tx from wrong account number
   146  	seqs = []uint64{1}
   147  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{1}, seqs, fee)
   148  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   149  
   150  	// from correct account number
   151  	seqs = []uint64{1}
   152  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{0}, seqs, fee)
   153  	checkValidTx(t, anteHandler, ctx, tx, false)
   154  
   155  	// new tx with another signer and incorrect account numbers
   156  	msg1 := tu.NewTestMsg(addr1, addr2)
   157  	msg2 := tu.NewTestMsg(addr2, addr1)
   158  	msgs = []std.Msg{msg1, msg2}
   159  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0}
   160  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   161  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   162  
   163  	// correct account numbers
   164  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{2, 0}
   165  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   166  	checkValidTx(t, anteHandler, ctx, tx, false)
   167  }
   168  
   169  // Test logic around account number checking with many signers when BlockHeight is 0.
   170  func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) {
   171  	t.Parallel()
   172  
   173  	// setup
   174  	env := setupTestEnv()
   175  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   176  	ctx := env.ctx
   177  	header := ctx.BlockHeader().(*bft.Header)
   178  	header.Height = 0
   179  	ctx = ctx.WithBlockHeader(header)
   180  
   181  	// keys and addresses
   182  	priv1, _, addr1 := tu.KeyTestPubAddr()
   183  	priv2, _, addr2 := tu.KeyTestPubAddr()
   184  
   185  	// set the accounts, we don't need the acc numbers as it is in the genesis block
   186  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   187  	acc1.SetCoins(tu.NewTestCoins())
   188  	env.acck.SetAccount(ctx, acc1)
   189  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   190  	acc2.SetCoins(tu.NewTestCoins())
   191  	require.NoError(t, acc2.SetAccountNumber(1))
   192  	env.acck.SetAccount(ctx, acc2)
   193  
   194  	// msg and signatures
   195  	var tx std.Tx
   196  	msg := tu.NewTestMsg(addr1)
   197  	fee := tu.NewTestFee()
   198  
   199  	msgs := []std.Msg{msg}
   200  
   201  	// test good tx from one signer
   202  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   203  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   204  	checkValidTx(t, anteHandler, ctx, tx, false)
   205  
   206  	// new tx from wrong account number
   207  	seqs = []uint64{1}
   208  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{1}, seqs, fee)
   209  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   210  
   211  	// from correct account number
   212  	seqs = []uint64{1}
   213  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{0}, seqs, fee)
   214  	checkValidTx(t, anteHandler, ctx, tx, false)
   215  
   216  	// new tx with another signer and incorrect account numbers
   217  	msg1 := tu.NewTestMsg(addr1, addr2)
   218  	msg2 := tu.NewTestMsg(addr2, addr1)
   219  	msgs = []std.Msg{msg1, msg2}
   220  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0}
   221  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   222  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   223  
   224  	// correct account numbers
   225  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 0}, []uint64{2, 0}
   226  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   227  	checkValidTx(t, anteHandler, ctx, tx, false)
   228  }
   229  
   230  // Test logic around sequence checking with one signer and many signers.
   231  func TestAnteHandlerSequences(t *testing.T) {
   232  	t.Parallel()
   233  
   234  	// setup
   235  	env := setupTestEnv()
   236  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   237  	ctx := env.ctx
   238  
   239  	// keys and addresses
   240  	priv1, _, addr1 := tu.KeyTestPubAddr()
   241  	priv2, _, addr2 := tu.KeyTestPubAddr()
   242  	priv3, _, addr3 := tu.KeyTestPubAddr()
   243  
   244  	// set the accounts
   245  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   246  	acc1.SetCoins(tu.NewTestCoins())
   247  	require.NoError(t, acc1.SetAccountNumber(0))
   248  	env.acck.SetAccount(ctx, acc1)
   249  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   250  	acc2.SetCoins(tu.NewTestCoins())
   251  	require.NoError(t, acc2.SetAccountNumber(1))
   252  	env.acck.SetAccount(ctx, acc2)
   253  	acc3 := env.acck.NewAccountWithAddress(ctx, addr3)
   254  	acc3.SetCoins(tu.NewTestCoins())
   255  	require.NoError(t, acc3.SetAccountNumber(2))
   256  	env.acck.SetAccount(ctx, acc3)
   257  
   258  	// msg and signatures
   259  	var tx std.Tx
   260  	msg := tu.NewTestMsg(addr1)
   261  	fee := tu.NewTestFee()
   262  
   263  	msgs := []std.Msg{msg}
   264  
   265  	// test good tx from one signer
   266  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   267  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   268  	checkValidTx(t, anteHandler, ctx, tx, false)
   269  
   270  	// test sending it again fails (replay protection)
   271  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   272  
   273  	// fix sequence, should pass
   274  	seqs = []uint64{1}
   275  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   276  	checkValidTx(t, anteHandler, ctx, tx, false)
   277  
   278  	// new tx with another signer and correct sequences
   279  	msg1 := tu.NewTestMsg(addr1, addr2)
   280  	msg2 := tu.NewTestMsg(addr3, addr1)
   281  	msgs = []std.Msg{msg1, msg2}
   282  
   283  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{2, 0, 0}
   284  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   285  	checkValidTx(t, anteHandler, ctx, tx, false)
   286  
   287  	// replay fails
   288  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   289  
   290  	// tx from just second signer with incorrect sequence fails
   291  	msg = tu.NewTestMsg(addr2)
   292  	msgs = []std.Msg{msg}
   293  	privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0}
   294  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   295  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   296  
   297  	// fix the sequence and it passes
   298  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee)
   299  	checkValidTx(t, anteHandler, ctx, tx, false)
   300  
   301  	// another tx from both of them that passes
   302  	msg = tu.NewTestMsg(addr1, addr2)
   303  	msgs = []std.Msg{msg}
   304  	privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{3, 2}
   305  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   306  	checkValidTx(t, anteHandler, ctx, tx, false)
   307  }
   308  
   309  // Test logic around fee deduction.
   310  func TestAnteHandlerFees(t *testing.T) {
   311  	t.Parallel()
   312  
   313  	// setup
   314  	env := setupTestEnv()
   315  	ctx := env.ctx
   316  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   317  
   318  	// keys and addresses
   319  	priv1, _, addr1 := tu.KeyTestPubAddr()
   320  
   321  	// set the accounts
   322  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   323  	env.acck.SetAccount(ctx, acc1)
   324  
   325  	// msg and signatures
   326  	var tx std.Tx
   327  	msg := tu.NewTestMsg(addr1)
   328  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   329  	fee := tu.NewTestFee()
   330  	msgs := []std.Msg{msg}
   331  
   332  	// signer does not have enough funds to pay the fee
   333  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   334  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InsufficientFundsError{})
   335  
   336  	acc1.SetCoins(std.NewCoins(std.NewCoin("atom", 149)))
   337  	env.acck.SetAccount(ctx, acc1)
   338  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InsufficientFundsError{})
   339  
   340  	collector := env.bank.(DummyBankKeeper).acck.GetAccount(ctx, FeeCollectorAddress())
   341  	require.Nil(t, collector)
   342  	require.Equal(t, env.acck.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), int64(149))
   343  
   344  	acc1.SetCoins(std.NewCoins(std.NewCoin("atom", 150)))
   345  	env.acck.SetAccount(ctx, acc1)
   346  	checkValidTx(t, anteHandler, ctx, tx, false)
   347  
   348  	require.Equal(t, env.bank.(DummyBankKeeper).acck.GetAccount(ctx, FeeCollectorAddress()).GetCoins().AmountOf("atom"), int64(150))
   349  	require.Equal(t, env.acck.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), int64(0))
   350  }
   351  
   352  // Test logic around memo gas consumption.
   353  func TestAnteHandlerMemoGas(t *testing.T) {
   354  	t.Parallel()
   355  
   356  	// setup
   357  	env := setupTestEnv()
   358  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   359  	ctx := env.ctx
   360  
   361  	// keys and addresses
   362  	priv1, _, addr1 := tu.KeyTestPubAddr()
   363  
   364  	// set the accounts
   365  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   366  	require.NoError(t, acc1.SetAccountNumber(0))
   367  	env.acck.SetAccount(ctx, acc1)
   368  
   369  	// msg and signatures
   370  	var tx std.Tx
   371  	msg := tu.NewTestMsg(addr1)
   372  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   373  	fee := std.NewFee(0, std.NewCoin("atom", 0))
   374  
   375  	// tx does not have enough gas
   376  	tx = tu.NewTestTx(t, ctx.ChainID(), []std.Msg{msg}, privs, accnums, seqs, fee)
   377  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.OutOfGasError{})
   378  
   379  	// tx with memo doesn't have enough gas
   380  	fee = std.NewFee(801, std.NewCoin("atom", 0))
   381  	tx = tu.NewTestTxWithMemo(t, ctx.ChainID(), []std.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd")
   382  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.OutOfGasError{})
   383  
   384  	// memo too large
   385  	fee = std.NewFee(9000, std.NewCoin("atom", 0))
   386  	tx = tu.NewTestTxWithMemo(t, ctx.ChainID(), []std.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 99000))
   387  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.MemoTooLargeError{})
   388  
   389  	// tx with memo has enough gas
   390  	fee = std.NewFee(9000, std.NewCoin("atom", 0))
   391  	tx = tu.NewTestTxWithMemo(t, ctx.ChainID(), []std.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10))
   392  	checkValidTx(t, anteHandler, ctx, tx, false)
   393  }
   394  
   395  func TestAnteHandlerMultiSigner(t *testing.T) {
   396  	t.Parallel()
   397  
   398  	// setup
   399  	env := setupTestEnv()
   400  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   401  	ctx := env.ctx
   402  
   403  	// keys and addresses
   404  	priv1, _, addr1 := tu.KeyTestPubAddr()
   405  	priv2, _, addr2 := tu.KeyTestPubAddr()
   406  	priv3, _, addr3 := tu.KeyTestPubAddr()
   407  
   408  	// set the accounts
   409  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   410  	acc1.SetCoins(tu.NewTestCoins())
   411  	require.NoError(t, acc1.SetAccountNumber(0))
   412  	env.acck.SetAccount(ctx, acc1)
   413  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   414  	acc2.SetCoins(tu.NewTestCoins())
   415  	require.NoError(t, acc2.SetAccountNumber(1))
   416  	env.acck.SetAccount(ctx, acc2)
   417  	acc3 := env.acck.NewAccountWithAddress(ctx, addr3)
   418  	acc3.SetCoins(tu.NewTestCoins())
   419  	require.NoError(t, acc3.SetAccountNumber(2))
   420  	env.acck.SetAccount(ctx, acc3)
   421  
   422  	// set up msgs and fee
   423  	var tx std.Tx
   424  	msg1 := tu.NewTestMsg(addr1, addr2)
   425  	msg2 := tu.NewTestMsg(addr3, addr1)
   426  	msg3 := tu.NewTestMsg(addr2, addr3)
   427  	msgs := []std.Msg{msg1, msg2, msg3}
   428  	fee := tu.NewTestFee()
   429  
   430  	// signers in order
   431  	privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}
   432  	tx = tu.NewTestTxWithMemo(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works")
   433  
   434  	checkValidTx(t, anteHandler, ctx, tx, false)
   435  
   436  	// change sequence numbers
   437  	tx = tu.NewTestTx(t, ctx.ChainID(), []std.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee)
   438  	checkValidTx(t, anteHandler, ctx, tx, false)
   439  	tx = tu.NewTestTx(t, ctx.ChainID(), []std.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee)
   440  	checkValidTx(t, anteHandler, ctx, tx, false)
   441  
   442  	// expected seqs = [3, 2, 2]
   443  	tx = tu.NewTestTxWithMemo(t, ctx.ChainID(), msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works")
   444  	checkValidTx(t, anteHandler, ctx, tx, false)
   445  }
   446  
   447  func TestAnteHandlerBadSignBytes(t *testing.T) {
   448  	t.Parallel()
   449  
   450  	// setup
   451  	env := setupTestEnv()
   452  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   453  	ctx := env.ctx
   454  
   455  	// keys and addresses
   456  	priv1, _, addr1 := tu.KeyTestPubAddr()
   457  	priv2, _, addr2 := tu.KeyTestPubAddr()
   458  
   459  	// set the accounts
   460  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   461  	acc1.SetCoins(tu.NewTestCoins())
   462  	require.NoError(t, acc1.SetAccountNumber(0))
   463  	env.acck.SetAccount(ctx, acc1)
   464  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   465  	acc2.SetCoins(tu.NewTestCoins())
   466  	require.NoError(t, acc2.SetAccountNumber(1))
   467  	env.acck.SetAccount(ctx, acc2)
   468  
   469  	var tx std.Tx
   470  	msg := tu.NewTestMsg(addr1)
   471  	msgs := []std.Msg{msg}
   472  	fee := tu.NewTestFee()
   473  	fee2 := tu.NewTestFee()
   474  	fee2.GasWanted += 100
   475  	fee3 := tu.NewTestFee()
   476  	fee3.GasFee.Amount += 100
   477  
   478  	// test good tx and signBytes
   479  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   480  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   481  	checkValidTx(t, anteHandler, ctx, tx, false)
   482  
   483  	chainID := ctx.ChainID()
   484  	chainID2 := chainID + "somemorestuff"
   485  	unauthErr := std.UnauthorizedError{}
   486  
   487  	cases := []struct {
   488  		chainID string
   489  		accnum  uint64
   490  		seq     uint64
   491  		fee     std.Fee
   492  		msgs    []std.Msg
   493  		err     abci.Error
   494  	}{
   495  		{chainID2, 0, 1, fee, msgs, unauthErr},                           // test wrong chain_id
   496  		{chainID, 0, 2, fee, msgs, unauthErr},                            // test wrong seqs
   497  		{chainID, 1, 1, fee, msgs, unauthErr},                            // test wrong accnum
   498  		{chainID, 0, 1, fee, []std.Msg{tu.NewTestMsg(addr2)}, unauthErr}, // test wrong msg
   499  		{chainID, 0, 1, fee2, msgs, unauthErr},                           // test wrong fee
   500  		{chainID, 0, 1, fee3, msgs, unauthErr},                           // test wrong fee
   501  	}
   502  
   503  	privs, seqs = []crypto.PrivKey{priv1}, []uint64{1}
   504  	for _, cs := range cases {
   505  		signPayload, err := std.GetSignaturePayload(std.SignDoc{
   506  			ChainID:       cs.chainID,
   507  			AccountNumber: cs.accnum,
   508  			Sequence:      cs.seq,
   509  			Fee:           cs.fee,
   510  			Msgs:          cs.msgs,
   511  		})
   512  		require.NoError(t, err)
   513  
   514  		tx := tu.NewTestTxWithSignBytes(
   515  			msgs, privs, fee,
   516  			signPayload,
   517  			"",
   518  		)
   519  		checkInvalidTx(t, anteHandler, ctx, tx, false, cs.err)
   520  	}
   521  
   522  	// test wrong signer if public key exist
   523  	privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{0}, []uint64{1}
   524  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   525  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.UnauthorizedError{})
   526  
   527  	// test wrong signer if public doesn't exist
   528  	msg = tu.NewTestMsg(addr2)
   529  	msgs = []std.Msg{msg}
   530  	privs, accnums, seqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0}
   531  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   532  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InvalidPubKeyError{})
   533  }
   534  
   535  func TestAnteHandlerSetPubKey(t *testing.T) {
   536  	t.Parallel()
   537  
   538  	// setup
   539  	env := setupTestEnv()
   540  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   541  	ctx := env.ctx
   542  
   543  	// keys and addresses
   544  	priv1, _, addr1 := tu.KeyTestPubAddr()
   545  	_, _, addr2 := tu.KeyTestPubAddr()
   546  
   547  	// set the accounts
   548  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   549  	acc1.SetCoins(tu.NewTestCoins())
   550  	require.NoError(t, acc1.SetAccountNumber(0))
   551  	env.acck.SetAccount(ctx, acc1)
   552  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   553  	acc2.SetCoins(tu.NewTestCoins())
   554  	require.NoError(t, acc2.SetAccountNumber(1))
   555  	env.acck.SetAccount(ctx, acc2)
   556  
   557  	var tx std.Tx
   558  
   559  	// test good tx and set public key
   560  	msg := tu.NewTestMsg(addr1)
   561  	msgs := []std.Msg{msg}
   562  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   563  	fee := tu.NewTestFee()
   564  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   565  	checkValidTx(t, anteHandler, ctx, tx, false)
   566  
   567  	acc1 = env.acck.GetAccount(ctx, addr1)
   568  	require.Equal(t, acc1.GetPubKey(), priv1.PubKey())
   569  
   570  	// test public key not found
   571  	msg = tu.NewTestMsg(addr2)
   572  	msgs = []std.Msg{msg}
   573  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{1}, seqs, fee)
   574  	sigs := tx.GetSignatures()
   575  	sigs[0].PubKey = nil
   576  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InvalidPubKeyError{})
   577  
   578  	acc2 = env.acck.GetAccount(ctx, addr2)
   579  	require.Nil(t, acc2.GetPubKey())
   580  
   581  	// test invalid signature and public key
   582  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, []uint64{1}, seqs, fee)
   583  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InvalidPubKeyError{})
   584  
   585  	acc2 = env.acck.GetAccount(ctx, addr2)
   586  	require.Nil(t, acc2.GetPubKey())
   587  }
   588  
   589  func TestProcessPubKey(t *testing.T) {
   590  	t.Parallel()
   591  
   592  	env := setupTestEnv()
   593  	ctx := env.ctx
   594  
   595  	// keys
   596  	_, _, addr1 := tu.KeyTestPubAddr()
   597  	priv2, _, addr2 := tu.KeyTestPubAddr()
   598  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   599  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   600  
   601  	acc2.SetPubKey(priv2.PubKey())
   602  
   603  	type args struct {
   604  		acc      std.Account
   605  		sig      std.Signature
   606  		simulate bool
   607  	}
   608  	tests := []struct {
   609  		name    string
   610  		args    args
   611  		wantErr bool
   612  	}{
   613  		{"no sigs, simulate off", args{acc1, std.Signature{}, false}, true},
   614  		{"no sigs, simulate on", args{acc1, std.Signature{}, true}, false},
   615  		{"no sigs, account with pub, simulate on", args{acc2, std.Signature{}, true}, false},
   616  		{"pubkey doesn't match addr, simulate off", args{acc1, std.Signature{PubKey: priv2.PubKey()}, false}, true},
   617  		{"pubkey doesn't match addr, simulate on", args{acc1, std.Signature{PubKey: priv2.PubKey()}, true}, false},
   618  	}
   619  	for _, tt := range tests {
   620  		tt := tt
   621  		t.Run(tt.name, func(t *testing.T) {
   622  			t.Parallel()
   623  
   624  			_, err := ProcessPubKey(tt.args.acc, tt.args.sig, tt.args.simulate)
   625  			require.Equal(t, tt.wantErr, !err.IsOK())
   626  		})
   627  	}
   628  }
   629  
   630  func TestConsumeSignatureVerificationGas(t *testing.T) {
   631  	t.Parallel()
   632  
   633  	params := DefaultParams()
   634  	msg := []byte{1, 2, 3, 4}
   635  
   636  	pkSet1, sigSet1 := generatePubKeysAndSignatures(5, msg, false)
   637  	multisigKey1 := multisig.NewPubKeyMultisigThreshold(2, pkSet1)
   638  	multisignature1 := multisig.NewMultisig(len(pkSet1))
   639  	expectedCost1 := expectedGasCostByKeys(pkSet1)
   640  	for i := 0; i < len(pkSet1); i++ {
   641  		multisignature1.AddSignatureFromPubKey(sigSet1[i], pkSet1[i], pkSet1)
   642  	}
   643  
   644  	type args struct {
   645  		meter  store.GasMeter
   646  		sig    []byte
   647  		pubkey crypto.PubKey
   648  		params Params
   649  	}
   650  	tests := []struct {
   651  		name        string
   652  		args        args
   653  		gasConsumed int64
   654  		shouldErr   bool
   655  	}{
   656  		{"PubKeyEd25519", args{store.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, DefaultSigVerifyCostED25519, true},
   657  		{"PubKeySecp256k1", args{store.NewInfiniteGasMeter(), nil, secp256k1.GenPrivKey().PubKey(), params}, DefaultSigVerifyCostSecp256k1, false},
   658  		{"Multisig", args{store.NewInfiniteGasMeter(), amino.MustMarshal(multisignature1), multisigKey1, params}, expectedCost1, false},
   659  		{"unknown key", args{store.NewInfiniteGasMeter(), nil, nil, params}, 0, true},
   660  	}
   661  	for _, tt := range tests {
   662  		tt := tt
   663  		t.Run(tt.name, func(t *testing.T) {
   664  			t.Parallel()
   665  
   666  			res := DefaultSigVerificationGasConsumer(tt.args.meter, tt.args.sig, tt.args.pubkey, tt.args.params)
   667  
   668  			if tt.shouldErr {
   669  				require.False(t, res.IsOK())
   670  			} else {
   671  				require.True(t, res.IsOK())
   672  				require.Equal(t, tt.gasConsumed, tt.args.meter.GasConsumed(), fmt.Sprintf("%d != %d", tt.gasConsumed, tt.args.meter.GasConsumed()))
   673  			}
   674  		})
   675  	}
   676  }
   677  
   678  func generatePubKeysAndSignatures(n int, msg []byte, keyTypeed25519 bool) (pubkeys []crypto.PubKey, signatures [][]byte) {
   679  	pubkeys = make([]crypto.PubKey, n)
   680  	signatures = make([][]byte, n)
   681  	for i := 0; i < n; i++ {
   682  		var privkey crypto.PrivKey
   683  		if rand.Int63()%2 == 0 {
   684  			privkey = ed25519.GenPrivKey()
   685  		} else {
   686  			privkey = secp256k1.GenPrivKey()
   687  		}
   688  		pubkeys[i] = privkey.PubKey()
   689  		signatures[i], _ = privkey.Sign(msg)
   690  	}
   691  	return
   692  }
   693  
   694  func expectedGasCostByKeys(pubkeys []crypto.PubKey) int64 {
   695  	cost := int64(0)
   696  	for _, pubkey := range pubkeys {
   697  		pubkeyType := strings.ToLower(fmt.Sprintf("%T", pubkey))
   698  		switch {
   699  		case strings.Contains(pubkeyType, "ed25519"):
   700  			cost += DefaultParams().SigVerifyCostED25519
   701  		case strings.Contains(pubkeyType, "secp256k1"):
   702  			cost += DefaultParams().SigVerifyCostSecp256k1
   703  		default:
   704  			panic("unexpected key type")
   705  		}
   706  	}
   707  	return cost
   708  }
   709  
   710  func TestCountSubkeys(t *testing.T) {
   711  	t.Parallel()
   712  
   713  	genPubKeys := func(n int) []crypto.PubKey {
   714  		var ret []crypto.PubKey
   715  		for i := 0; i < n; i++ {
   716  			ret = append(ret, secp256k1.GenPrivKey().PubKey())
   717  		}
   718  		return ret
   719  	}
   720  	singleKey := secp256k1.GenPrivKey().PubKey()
   721  	singleLevelMultiKey := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5))
   722  	multiLevelSubKey1 := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5))
   723  	multiLevelSubKey2 := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5))
   724  	multiLevelMultiKey := multisig.NewPubKeyMultisigThreshold(2, []crypto.PubKey{
   725  		multiLevelSubKey1, multiLevelSubKey2, secp256k1.GenPrivKey().PubKey(),
   726  	})
   727  	type args struct {
   728  		pub crypto.PubKey
   729  	}
   730  	tests := []struct {
   731  		name string
   732  		args args
   733  		want int
   734  	}{
   735  		{"single key", args{singleKey}, 1},
   736  		{"single level multikey", args{singleLevelMultiKey}, 5},
   737  		{"multi level multikey", args{multiLevelMultiKey}, 11},
   738  	}
   739  	for _, tt := range tests {
   740  		tt := tt
   741  		t.Run(tt.name, func(t *testing.T) {
   742  			t.Parallel()
   743  
   744  			require.Equal(t, tt.want, std.CountSubKeys(tt.args.pub))
   745  		})
   746  	}
   747  }
   748  
   749  func TestAnteHandlerSigLimitExceeded(t *testing.T) {
   750  	t.Parallel()
   751  
   752  	// setup
   753  	env := setupTestEnv()
   754  	anteHandler := NewAnteHandler(env.acck, env.bank, DefaultSigVerificationGasConsumer, defaultAnteOptions())
   755  	ctx := env.ctx
   756  
   757  	// keys and addresses
   758  	priv1, _, addr1 := tu.KeyTestPubAddr()
   759  	priv2, _, addr2 := tu.KeyTestPubAddr()
   760  	priv3, _, addr3 := tu.KeyTestPubAddr()
   761  	priv4, _, addr4 := tu.KeyTestPubAddr()
   762  	priv5, _, addr5 := tu.KeyTestPubAddr()
   763  	priv6, _, addr6 := tu.KeyTestPubAddr()
   764  	priv7, _, addr7 := tu.KeyTestPubAddr()
   765  	priv8, _, addr8 := tu.KeyTestPubAddr()
   766  
   767  	// set the accounts
   768  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   769  	acc1.SetCoins(tu.NewTestCoins())
   770  	env.acck.SetAccount(ctx, acc1)
   771  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   772  	acc2.SetCoins(tu.NewTestCoins())
   773  	require.NoError(t, acc2.SetAccountNumber(1))
   774  	env.acck.SetAccount(ctx, acc2)
   775  
   776  	var tx std.Tx
   777  	msg := tu.NewTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8)
   778  	msgs := []std.Msg{msg}
   779  	fee := tu.NewTestFee()
   780  
   781  	// test rejection logic
   782  	privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3, priv4, priv5, priv6, priv7, priv8},
   783  		[]uint64{0, 0, 0, 0, 0, 0, 0, 0}, []uint64{0, 0, 0, 0, 0, 0, 0, 0}
   784  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   785  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.TooManySignaturesError{})
   786  }
   787  
   788  func TestEnsureSufficientMempoolFees(t *testing.T) {
   789  	t.Parallel()
   790  
   791  	// setup
   792  	env := setupTestEnv()
   793  	ctx := env.ctx.WithMinGasPrices(
   794  		[]std.GasPrice{
   795  			{Gas: 100000, Price: std.Coin{Denom: "photino", Amount: 5}},
   796  			{Gas: 100000, Price: std.Coin{Denom: "stake", Amount: 1}},
   797  		},
   798  	)
   799  
   800  	testCases := []struct {
   801  		input      std.Fee
   802  		expectedOK bool
   803  	}{
   804  		{std.NewFee(200000, std.Coin{}), false},
   805  		{std.NewFee(200000, std.NewCoin("photino", 5)), false},
   806  		{std.NewFee(200000, std.NewCoin("stake", 1)), false},
   807  		{std.NewFee(200000, std.NewCoin("stake", 2)), true},
   808  		{std.NewFee(200000, std.NewCoin("photino", 10)), true},
   809  		{std.NewFee(200000, std.NewCoin("stake", 2)), true},
   810  		{std.NewFee(200000, std.NewCoin("atom", 5)), false},
   811  	}
   812  
   813  	for i, tc := range testCases {
   814  		res := EnsureSufficientMempoolFees(ctx, tc.input)
   815  		require.Equal(
   816  			t, tc.expectedOK, res.IsOK(),
   817  			"unexpected result; tc #%d, input: %v, log: %v", i, tc.input, res.Log,
   818  		)
   819  	}
   820  }
   821  
   822  // Test custom SignatureVerificationGasConsumer
   823  func TestCustomSignatureVerificationGasConsumer(t *testing.T) {
   824  	t.Parallel()
   825  
   826  	// setup
   827  	env := setupTestEnv()
   828  	// setup an ante handler that only accepts PubKeyEd25519
   829  	anteHandler := NewAnteHandler(env.acck, env.bank, func(meter store.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result {
   830  		switch pubkey := pubkey.(type) {
   831  		case ed25519.PubKeyEd25519:
   832  			meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519")
   833  			return sdk.Result{}
   834  		default:
   835  			return abciResult(std.ErrInvalidPubKey(fmt.Sprintf("unrecognized public key type: %T", pubkey)))
   836  		}
   837  	}, defaultAnteOptions())
   838  	ctx := env.ctx
   839  
   840  	// verify that an secp256k1 account gets rejected
   841  	priv1, _, addr1 := tu.KeyTestPubAddr()
   842  	acc1 := env.acck.NewAccountWithAddress(ctx, addr1)
   843  	_ = acc1.SetCoins(std.NewCoins(std.NewCoin("atom", 150)))
   844  	env.acck.SetAccount(ctx, acc1)
   845  
   846  	var tx std.Tx
   847  	msg := tu.NewTestMsg(addr1)
   848  	privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0}
   849  	fee := tu.NewTestFee()
   850  	msgs := []std.Msg{msg}
   851  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   852  	checkInvalidTx(t, anteHandler, ctx, tx, false, std.InvalidPubKeyError{})
   853  
   854  	// verify that an ed25519 account gets accepted
   855  	priv2 := ed25519.GenPrivKey()
   856  	pub2 := priv2.PubKey()
   857  	addr2 := pub2.Address()
   858  	acc2 := env.acck.NewAccountWithAddress(ctx, addr2)
   859  	require.NoError(t, acc2.SetCoins(std.NewCoins(std.NewCoin("atom", 150))))
   860  	require.NoError(t, acc2.SetAccountNumber(1))
   861  	env.acck.SetAccount(ctx, acc2)
   862  	msg = tu.NewTestMsg(addr2)
   863  	privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0}
   864  	fee = tu.NewTestFee()
   865  	msgs = []std.Msg{msg}
   866  	tx = tu.NewTestTx(t, ctx.ChainID(), msgs, privs, accnums, seqs, fee)
   867  	checkValidTx(t, anteHandler, ctx, tx, false)
   868  }