ante: AnteHandler changes from state transition refactor (#56)

* ante: cherry-pick changes from state transition refactor

* ante: test setup

* ante: fixes

* ante: test (wip)

* ante: finish unit tests

* ante: intrinsic gas test

* ante: chaindecorators test (wip)

* update tests

* ante: cleanup tests

* ante: add test consuption test
This commit is contained in:
Federico Kunze
2021-05-31 05:05:32 -04:00
committed by GitHub
parent 4de0835b49
commit 9a5654f70d
22 changed files with 906 additions and 952 deletions
+10 -61
View File
@@ -1,14 +1,10 @@
package ante
import (
"fmt"
"runtime/debug"
log "github.com/xlab/suplog"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
@@ -20,9 +16,6 @@ import (
)
const (
// TODO: Use this cost per byte through parameter or overriding NewConsumeGasForTxSizeDecorator
// which currently defaults at 10, if intended
// memoCostPerByte sdk.Gas = 3
secp256k1VerifyCost uint64 = 21000
)
@@ -30,8 +23,7 @@ const (
type AccountKeeper interface {
authante.AccountKeeper
NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI
GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI
SetAccount(ctx sdk.Context, account authtypes.AccountI)
GetSequence(sdk.Context, sdk.AccAddress) (uint64, error)
}
// BankKeeper defines an expected keeper interface for the bank module's Keeper
@@ -67,43 +59,20 @@ func NewAnteHandler(
// handle as *evmtypes.MsgEthereumTx
anteHandler = sdk.ChainAnteDecorators(
NewEthSetupContextDecorator(evmKeeper), // outermost AnteDecorator. EthSetUpContext must be called first
NewEthMempoolFeeDecorator(evmKeeper),
NewEthValidateBasicDecorator(),
authante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
authante.NewMempoolFeeDecorator(),
authante.NewValidateBasicDecorator(),
authante.TxTimeoutHeightDecorator{},
NewEthSigVerificationDecorator(evmKeeper),
NewEthAccountSetupDecorator(ak),
NewEthAccountVerificationDecorator(ak, bankKeeper, evmKeeper),
NewEthNonceVerificationDecorator(ak),
NewEthGasConsumeDecorator(ak, bankKeeper, evmKeeper),
NewEthIncrementSenderSequenceDecorator(ak), // innermost AnteDecorator.
)
case "/ethermint.evm.v1alpha1.ExtensionOptionsWeb3Tx":
// handle as normal Cosmos SDK tx, except signature is checked for EIP712 representation
switch tx.(type) {
case sdk.Tx:
anteHandler = sdk.ChainAnteDecorators(
authante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
authante.NewMempoolFeeDecorator(),
authante.NewValidateBasicDecorator(),
authante.TxTimeoutHeightDecorator{},
authante.NewValidateMemoDecorator(ak),
authante.NewConsumeGasForTxSizeDecorator(ak),
authante.NewSetPubKeyDecorator(ak), // SetPubKeyDecorator must be called before all signature verification decorators
authante.NewValidateSigCountDecorator(ak),
authante.NewDeductFeeDecorator(ak, bankKeeper),
authante.NewSigGasConsumeDecorator(ak, DefaultSigVerificationGasConsumer),
authante.NewIncrementSequenceDecorator(ak), // innermost AnteDecorator
)
default:
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", tx)
}
default:
log.WithField("type_url", typeURL).Errorln("rejecting tx with unsupported extension option")
return ctx, sdkerrors.ErrUnknownExtensionOptions
return ctx, sdkerrors.Wrap(sdkerrors.ErrUnknownExtensionOptions, typeURL)
}
return anteHandler(ctx, tx, sim)
@@ -122,6 +91,7 @@ func NewAnteHandler(
authante.TxTimeoutHeightDecorator{},
authante.NewValidateMemoDecorator(ak),
authante.NewConsumeGasForTxSizeDecorator(ak),
authante.NewRejectFeeGranterDecorator(),
authante.NewSetPubKeyDecorator(ak), // SetPubKeyDecorator must be called before all signature verification decorators
authante.NewValidateSigCountDecorator(ak),
authante.NewDeductFeeDecorator(ak, bankKeeper),
@@ -158,33 +128,12 @@ var _ authante.SignatureVerificationGasConsumer = DefaultSigVerificationGasConsu
func DefaultSigVerificationGasConsumer(
meter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params,
) error {
pubkey := sig.PubKey
switch pubkey := pubkey.(type) {
case *ed25519.PubKey:
meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519")
return nil
case *secp256k1.PubKey:
meter.ConsumeGas(params.SigVerifyCostSecp256k1, "ante verify: secp256k1")
return nil
// support for ethereum ECDSA secp256k1 keys
case *ethsecp256k1.PubKey:
_, ok := sig.PubKey.(*ethsecp256k1.PubKey)
if ok {
meter.ConsumeGas(secp256k1VerifyCost, "ante verify: eth_secp256k1")
return nil
case multisig.PubKey:
multisignature, ok := sig.Data.(*signing.MultiSignatureData)
if !ok {
return fmt.Errorf("expected %T, got, %T", &signing.MultiSignatureData{}, sig.Data)
}
err := authante.ConsumeMultisignatureVerificationGas(meter, multisignature, pubkey, params, sig.Sequence)
if err != nil {
return err
}
return nil
default:
return sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey, "unrecognized public key type: %T", pubkey)
}
return authante.DefaultSigVerificationGasConsumer(meter, sig, params)
}
+48 -290
View File
@@ -2,310 +2,68 @@ package ante_test
import (
"math/big"
"testing"
"time"
"github.com/stretchr/testify/require"
ethcmn "github.com/ethereum/go-ethereum/common"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/params"
"github.com/cosmos/ethermint/app"
"github.com/cosmos/ethermint/app/ante"
"github.com/cosmos/ethermint/types"
evmtypes "github.com/cosmos/ethermint/x/evm/types"
)
func requireValidTx(
t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx sdk.Tx, sim bool,
) {
_, err := anteHandler(ctx, tx, sim)
require.NoError(t, err)
}
func (suite AnteTestSuite) TestAnteHandler() {
addr, privKey := newTestAddrKey()
to, _ := newTestAddrKey()
func requireInvalidTx(
t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context,
tx sdk.Tx, sim bool,
) {
_, err := anteHandler(ctx, tx, sim)
require.Error(t, err)
}
signedContractTx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 100000, big.NewInt(1), nil, nil)
signedContractTx.From = addr.Hex()
func (suite *AnteTestSuite) TestValidEthTx() {
suite.ctx = suite.ctx.WithBlockHeight(1)
signedTx := evmtypes.NewMsgEthereumTx(suite.app.EvmKeeper.ChainID(), 2, &to, big.NewInt(10), 100000, big.NewInt(1), nil, nil)
signedTx.From = addr.Hex()
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
txContract := suite.CreateTestTx(signedContractTx, privKey, 1)
acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc1)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc1.GetAddress(), newTestCoins())
suite.Require().NoError(err)
suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder()
tx := suite.CreateTestTx(signedTx, privKey, 1)
acc2 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr2)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc2)
err = suite.app.BankKeeper.SetBalances(suite.ctx, acc2.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
requireValidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestValidTx() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
addr2, priv2 := newTestAddrKey()
acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc1)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc1.GetAddress(), newTestCoins())
suite.Require().NoError(err)
acc2 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr2)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc2)
err = suite.app.BankKeeper.SetBalances(suite.ctx, acc2.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid SDK tx to pass
fee := newTestStdFee()
msg1 := newTestMsg(addr1, addr2)
msgs := []sdk.Msg{msg1}
privKeys := []cryptotypes.PrivKey{priv1, priv2}
accNums := []uint64{acc1.GetAccountNumber(), acc2.GetAccountNumber()}
accSeqs := []uint64{acc1.GetSequence(), acc2.GetSequence()}
tx := newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireValidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestSDKInvalidSigs() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
addr2, priv2 := newTestAddrKey()
addr3, priv3 := newTestAddrKey()
acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc1)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc1.GetAddress(), newTestCoins())
suite.Require().NoError(err)
acc2 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr2)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc2)
err = suite.app.BankKeeper.SetBalances(suite.ctx, acc2.GetAddress(), newTestCoins())
suite.Require().NoError(err)
fee := newTestStdFee()
msg1 := newTestMsg(addr1, addr2)
// require validation failure with no signers
msgs := []sdk.Msg{msg1}
privKeys := []cryptotypes.PrivKey{}
accNums := []uint64{acc1.GetAccountNumber(), acc2.GetAccountNumber()}
accSeqs := []uint64{acc1.GetSequence(), acc2.GetSequence()}
tx := newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
// require validation failure with invalid number of signers
msgs = []sdk.Msg{msg1}
privKeys = []cryptotypes.PrivKey{priv1}
accNums = []uint64{acc1.GetAccountNumber(), acc2.GetAccountNumber()}
accSeqs = []uint64{acc1.GetSequence(), acc2.GetSequence()}
tx = newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
// require validation failure with an invalid signer
msg2 := newTestMsg(addr1, addr3)
msgs = []sdk.Msg{msg1, msg2}
privKeys = []cryptotypes.PrivKey{priv1, priv2, priv3}
accNums = []uint64{acc1.GetAccountNumber(), acc2.GetAccountNumber(), 0}
accSeqs = []uint64{acc1.GetSequence(), acc2.GetSequence(), 0}
tx = newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestSDKInvalidAcc() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc1)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc1.GetAddress(), newTestCoins())
suite.Require().NoError(err)
fee := newTestStdFee()
msg1 := newTestMsg(addr1)
msgs := []sdk.Msg{msg1}
privKeys := []cryptotypes.PrivKey{priv1}
// require validation failure with invalid account number
accNums := []uint64{1}
accSeqs := []uint64{acc1.GetSequence()}
tx := newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
// require validation failure with invalid sequence (nonce)
accNums = []uint64{acc1.GetAccountNumber()}
accSeqs = []uint64{1}
tx = newTestSDKTx(suite.ctx, msgs, privKeys, accNums, accSeqs, fee)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestEthInvalidSig() {
suite.ctx = suite.ctx.WithBlockHeight(1)
_, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
ctx := suite.ctx.WithChainID("ethermint-4")
requireInvalidTx(suite.T(), suite.anteHandler, ctx, tx, false)
}
func (suite *AnteTestSuite) TestEthInvalidNonce() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
err := acc.SetSequence(10)
suite.Require().NoError(err)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err = suite.app.BankKeeper.SetBalances(suite.ctx, acc.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestEthInsufficientBalance() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.Require().NoError(acc.SetSequence(1))
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(10000000000)))
suite.Require().NoError(err)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestEthInvalidIntrinsicGas() {
suite.ctx = suite.ctx.WithBlockHeight(1)
testCases := []struct {
name string
tx sdk.Tx
checkTx bool
reCheckTx bool
expPass bool
}{
{"success - DeliverTx (contract)", txContract, false, false, true},
{"success - CheckTx (contract)", txContract, true, false, true},
{"success - ReCheckTx (contract)", txContract, false, true, true},
{"success - DeliverTx", tx, false, false, true},
{"success - CheckTx", tx, true, false, true},
{"success - ReCheckTx", tx, false, true, true},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
suite.ctx = suite.ctx.WithIsCheckTx(tc.reCheckTx).WithIsReCheckTx(tc.reCheckTx)
expConsumed := params.TxGasContractCreation + params.TxGas
_, err := suite.anteHandler(suite.ctx, tc.tx, false)
// suite.Require().Equal(consumed, ctx.GasMeter().GasConsumed())
if tc.expPass {
suite.Require().NoError(err)
suite.Require().Equal(int(expConsumed), int(suite.ctx.GasMeter().GasConsumed()))
} else {
suite.Require().Error(err)
}
})
}
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
gasLimit := uint64(1000)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, gasLimit, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx.WithIsCheckTx(true), tx, false)
}
func (suite *AnteTestSuite) TestEthInvalidMempoolFees() {
// setup app with checkTx = true
suite.app = app.Setup(true)
suite.ctx = suite.app.BaseApp.NewContext(true, tmproto.Header{Height: 1, ChainID: "ethermint-3", Time: time.Now().UTC()})
suite.app.EvmKeeper.SetParams(suite.ctx, evmtypes.DefaultParams())
suite.anteHandler = ante.NewAnteHandler(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.EvmKeeper, suite.encodingConfig.TxConfig.SignModeHandler())
suite.ctx = suite.ctx.WithMinGasPrices(sdk.NewDecCoins(types.NewPhotonDecCoin(sdk.NewInt(500000))))
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("payload"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
requireInvalidTx(suite.T(), suite.anteHandler, suite.ctx, tx, false)
}
func (suite *AnteTestSuite) TestEthInvalidChainID() {
suite.ctx = suite.ctx.WithBlockHeight(1)
addr1, priv1 := newTestAddrKey()
addr2, _ := newTestAddrKey()
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalances(suite.ctx, acc.GetAddress(), newTestCoins())
suite.Require().NoError(err)
// require a valid Ethereum tx to pass
to := ethcmn.BytesToAddress(addr2.Bytes())
amt := big.NewInt(32)
gas := big.NewInt(20)
ethMsg := evmtypes.NewMsgEthereumTx(suite.chainID, 0, &to, amt, 22000, gas, []byte("test"), nil)
tx, err := suite.newTestEthTx(ethMsg, priv1)
suite.Require().NoError(err)
ctx := suite.ctx.WithChainID("bad-chain-id")
requireInvalidTx(suite.T(), suite.anteHandler, ctx, tx, false)
}
+152 -351
View File
@@ -1,16 +1,12 @@
package ante
import (
"fmt"
"math/big"
log "github.com/xlab/suplog"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
ethermint "github.com/cosmos/ethermint/types"
evmtypes "github.com/cosmos/ethermint/x/evm/types"
"github.com/ethereum/go-ethereum/common"
@@ -20,158 +16,13 @@ import (
// EVMKeeper defines the expected keeper interface used on the Eth AnteHandler
type EVMKeeper interface {
ChainID() *big.Int
GetParams(ctx sdk.Context) evmtypes.Params
GetChainConfig(ctx sdk.Context) (evmtypes.ChainConfig, bool)
WithContext(ctx sdk.Context)
ResetRefundTransient(ctx sdk.Context)
}
// EthSetupContextDecorator sets the infinite GasMeter in the Context and wraps
// the next AnteHandler with a defer clause to recover from any downstream
// OutOfGas panics in the AnteHandler chain to return an error with information
// on gas provided and gas used.
// CONTRACT: Must be first decorator in the chain
// CONTRACT: Tx must implement GasTx interface
type EthSetupContextDecorator struct {
evmKeeper EVMKeeper
}
// NewEthSetupContextDecorator creates a new EthSetupContextDecorator
func NewEthSetupContextDecorator(ek EVMKeeper) EthSetupContextDecorator {
return EthSetupContextDecorator{
evmKeeper: ek,
}
}
// AnteHandle sets the infinite gas meter to done to ignore costs in AnteHandler checks.
// This is undone at the EthGasConsumeDecorator, where the context is set with the
// ethereum tx GasLimit.
func (escd EthSetupContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
// reset the refund gas value for the current transaction
escd.evmKeeper.ResetRefundTransient(ctx)
// all transactions must implement GasTx
gasTx, ok := tx.(authante.GasTx)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be GasTx")
}
// Decorator will catch an OutOfGasPanic caused in the next antehandler
// AnteHandlers must have their own defer/recover in order for the BaseApp
// to know how much gas was used! This is because the GasMeter is created in
// the AnteHandler, but if it panics the context won't be set properly in
// runTx's recover call.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf(
"out of gas in location: %v; gasLimit: %d, gasUsed: %d",
rType.Descriptor, gasTx.GetGas(), ctx.GasMeter().GasConsumed(),
)
err = sdkerrors.Wrap(sdkerrors.ErrOutOfGas, log)
default:
log.Errorln(r)
panic(r)
}
}
}()
return next(ctx, tx, simulate)
}
// EthMempoolFeeDecorator validates that sufficient fees have been provided that
// meet a minimum threshold defined by the proposer (for mempool purposes during CheckTx).
type EthMempoolFeeDecorator struct {
evmKeeper EVMKeeper
}
// NewEthMempoolFeeDecorator creates a new EthMempoolFeeDecorator
func NewEthMempoolFeeDecorator(ek EVMKeeper) EthMempoolFeeDecorator {
return EthMempoolFeeDecorator{
evmKeeper: ek,
}
}
// AnteHandle verifies that enough fees have been provided by the
// Ethereum transaction that meet the minimum threshold set by the block
// proposer.
//
// NOTE: This should only be run during a CheckTx mode.
func (emfd EthMempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
if !ctx.IsCheckTx() {
return next(ctx, tx, simulate)
}
msgEthTx, ok := tx.(sdk.FeeTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type, not implements sdk.FeeTx: %T", tx)
}
evmDenom := emfd.evmKeeper.GetParams(ctx).EvmDenom
txFee := msgEthTx.GetFee().AmountOf(evmDenom).Int64()
if txFee < 0 {
return ctx, sdkerrors.Wrap(
sdkerrors.ErrInsufficientFee,
"negative fee not allowed",
)
}
// txFee = GP * GL
fee := sdk.NewInt64DecCoin(evmDenom, txFee)
minGasPrices := ctx.MinGasPrices()
// check that fee provided is greater than the minimum
// NOTE: we only check if injs are present in min gas prices. It is up to the
// sender if they want to send additional fees in other denominations.
var hasEnoughFees bool
if fee.Amount.GTE(minGasPrices.AmountOf(evmDenom)) {
hasEnoughFees = true
}
// reject transaction if minimum gas price is positive and the transaction does not
// meet the minimum fee
if !ctx.MinGasPrices().IsZero() && !hasEnoughFees {
return ctx, sdkerrors.Wrap(
sdkerrors.ErrInsufficientFee,
fmt.Sprintf("insufficient fee, got: %q required: %q", fee, ctx.MinGasPrices()),
)
}
return next(ctx, tx, simulate)
}
// EthValidateBasicDecorator will call tx.ValidateBasic and return any non-nil error.
// If ValidateBasic passes, decorator calls next AnteHandler in chain. Note,
// EthValidateBasicDecorator decorator will not get executed on ReCheckTx since it
// is not dependent on application state.
type EthValidateBasicDecorator struct{}
func NewEthValidateBasicDecorator() EthValidateBasicDecorator {
return EthValidateBasicDecorator{}
}
func (vbd EthValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
// no need to validate basic on recheck tx, call next antehandler
if ctx.IsReCheckTx() {
return next(ctx, tx, simulate)
}
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
}
if err := msgEthTx.ValidateBasic(); err != nil {
return ctx, err
}
return next(ctx, tx, simulate)
}
// EthSigVerificationDecorator validates an ethereum signature
type EthSigVerificationDecorator struct {
evmKeeper EVMKeeper
@@ -184,67 +35,43 @@ func NewEthSigVerificationDecorator(ek EVMKeeper) EthSigVerificationDecorator {
}
}
// AnteHandle validates the signature and returns sender address
// AnteHandle validates checks that the registered chain id is the same as the one on the message, and
// that the signer address matches the one defined on the message.
func (esvd EthSigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
if simulate {
// when simulating, no signatures required and the from address is explicitly set
// no need to verify signatures on recheck tx
if ctx.IsReCheckTx() {
return next(ctx, tx, simulate)
}
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
}
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
infCtx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
// parse the chainID from a string to a base-10 integer
chainIDEpoch, err := ethermint.ParseChainID(ctx.ChainID())
if err != nil {
return ctx, err
}
chainID := esvd.evmKeeper.ChainID()
config, found := esvd.evmKeeper.GetChainConfig(ctx)
config, found := esvd.evmKeeper.GetChainConfig(infCtx)
if !found {
return ctx, evmtypes.ErrChainConfigNotFound
}
ethCfg := config.EthereumConfig(chainIDEpoch)
ethCfg := config.EthereumConfig(chainID)
blockNum := big.NewInt(ctx.BlockHeight())
signer := ethtypes.MakeSigner(ethCfg, blockNum)
chainID := signer.ChainID()
if chainIDEpoch.Cmp(chainID) != 0 {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrInvalidChainID,
"EVM chain ID doesn't match the one derived from the signer (%s ≠ %s)",
chainIDEpoch.String(), chainID.String(),
)
for _, msg := range tx.GetMsgs() {
msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type %T, expected %T", tx, &evmtypes.MsgEthereumTx{})
}
if _, err := signer.Sender(msgEthTx.AsTransaction()); err != nil {
return ctx, sdkerrors.Wrap(sdkerrors.ErrorInvalidSigner, err.Error())
}
}
sender, err := signer.Sender(msgEthTx.AsTransaction())
if err != nil {
return ctx, sdkerrors.Wrap(sdkerrors.ErrorInvalidSigner, err.Error())
}
// set the sender
msgEthTx.From = sender.String()
// NOTE: when signature verification succeeds, a non-empty signer address can be
// retrieved from the transaction on the next AnteDecorators.
return next(ctx, tx, simulate)
}
type noMessages struct{}
func getTxMsg(tx sdk.Tx) interface{} {
msgs := tx.GetMsgs()
if len(msgs) == 0 {
return &noMessages{}
}
return msgs[0]
}
// EthAccountVerificationDecorator validates an account balance checks
type EthAccountVerificationDecorator struct {
ak AccountKeeper
@@ -267,40 +94,37 @@ func (avd EthAccountVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx
return next(ctx, tx, simulate)
}
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
}
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
infCtx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
// sender address should be in the tx cache from the previous AnteHandle call
address := msgEthTx.GetFrom()
if address.Empty() {
log.Panicln("sender address cannot be empty")
}
evmDenom := avd.evmKeeper.GetParams(infCtx).EvmDenom
acc := avd.ak.GetAccount(ctx, address)
if acc == nil {
acc = avd.ak.NewAccountWithAddress(ctx, address)
avd.ak.SetAccount(ctx, acc)
}
for _, msg := range tx.GetMsgs() {
msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type %T, expected %T", tx, &evmtypes.MsgEthereumTx{})
}
// on InitChain make sure account number == 0
if ctx.BlockHeight() == 0 && acc.GetAccountNumber() != 0 {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrInvalidSequence,
"invalid account number for height zero (got %d)", acc.GetAccountNumber(),
)
}
// sender address should be in the tx cache from the previous AnteHandle call
from := msgEthTx.GetFrom()
if from.Empty() {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "from address cannot be empty")
}
evmDenom := avd.evmKeeper.GetParams(ctx).EvmDenom
acc := avd.ak.GetAccount(infCtx, from)
if acc == nil {
_ = avd.ak.NewAccountWithAddress(infCtx, from)
}
// validate sender has enough funds to pay for gas cost
balance := avd.bankKeeper.GetBalance(ctx, address, evmDenom)
if balance.Amount.BigInt().Cmp(msgEthTx.Cost()) < 0 {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds,
"sender balance < tx gas cost (%s < %s%s)", balance.String(), msgEthTx.Cost().String(), evmDenom,
)
// validate sender has enough funds to pay for gas cost
balance := avd.bankKeeper.GetBalance(infCtx, from, evmDenom)
if balance.Amount.BigInt().Cmp(msgEthTx.Cost()) < 0 {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds,
"sender balance < tx gas cost (%s < %s%s)", balance.String(), msgEthTx.Cost().String(), evmDenom,
)
}
}
return next(ctx, tx, simulate)
@@ -322,34 +146,36 @@ func NewEthNonceVerificationDecorator(ak AccountKeeper) EthNonceVerificationDeco
// AnteHandle validates that the transaction nonce is valid (equivalent to the sender accounts
// current nonce).
func (nvd EthNonceVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
// no need to check the nonce on ReCheckTx
if ctx.IsReCheckTx() {
return next(ctx, tx, simulate)
}
// sender address should be in the tx cache from the previous AnteHandle call
address := msgEthTx.GetFrom()
if address.Empty() {
log.Panicln("sender address cannot be empty")
}
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
infCtx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
acc := nvd.ak.GetAccount(ctx, address)
if acc == nil {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrUnknownAddress,
"account %s (%s) is nil", common.BytesToAddress(address.Bytes()), address,
)
}
for _, msg := range tx.GetMsgs() {
msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type %T, expected %T", tx, &evmtypes.MsgEthereumTx{})
}
seq := acc.GetSequence()
// if multiple transactions are submitted in succession with increasing nonces,
// all will be rejected except the first, since the first needs to be included in a block
// before the sequence increments
if msgEthTx.Data.Nonce != seq {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrInvalidSequence,
"invalid nonce; got %d, expected %d", msgEthTx.Data.Nonce, seq,
)
// sender address should be in the tx cache from the previous AnteHandle call
seq, err := nvd.ak.GetSequence(infCtx, msgEthTx.GetFrom())
if err != nil {
return ctx, err
}
// if multiple transactions are submitted in succession with increasing nonces,
// all will be rejected except the first, since the first needs to be included in a block
// before the sequence increments
if msgEthTx.Data.Nonce != seq {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrInvalidSequence,
"invalid nonce; got %d, expected %d", msgEthTx.Data.Nonce, seq,
)
}
}
return next(ctx, tx, simulate)
@@ -380,69 +206,84 @@ func NewEthGasConsumeDecorator(ak AccountKeeper, bankKeeper BankKeeper, ek EVMKe
// constant value of 21000 plus any cost inccured by additional bytes of data
// supplied with the transaction.
func (egcd EthGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
infCtx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
if len(tx.GetMsgs()) != 1 {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "only 1 ethereum msg supported per tx, got %d", len(tx.GetMsgs()))
}
// sender address should be in the tx cache from the previous AnteHandle call
address := msgEthTx.GetFrom()
if address.Empty() {
log.Panicln("sender address cannot be empty")
// reset the refund gas value for the current transaction
egcd.evmKeeper.ResetRefundTransient(infCtx)
config, found := egcd.evmKeeper.GetChainConfig(infCtx)
if !found {
return ctx, evmtypes.ErrChainConfigNotFound
}
// fetch sender account from signature
senderAcc, err := authante.GetSignerAcc(ctx, egcd.ak, address)
if err != nil {
return ctx, err
}
ethCfg := config.EthereumConfig(egcd.evmKeeper.ChainID())
if senderAcc == nil {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrUnknownAddress,
"sender account %s (%s) is nil", common.BytesToAddress(address.Bytes()), address,
)
}
blockHeight := big.NewInt(ctx.BlockHeight())
homestead := ethCfg.IsHomestead(blockHeight)
istanbul := ethCfg.IsIstanbul(blockHeight)
gasLimit := msgEthTx.GetGas()
for _, msg := range tx.GetMsgs() {
msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type %T, expected %T", tx, &evmtypes.MsgEthereumTx{})
}
var accessList ethtypes.AccessList
if msgEthTx.Data.Accesses != nil {
accessList = *msgEthTx.Data.Accesses.ToEthAccessList()
}
isContractCreation := msgEthTx.To() == nil
gas, err := core.IntrinsicGas(msgEthTx.Data.Input, accessList, msgEthTx.To() == nil, true, false)
if err != nil {
return ctx, sdkerrors.Wrap(err, "failed to compute intrinsic gas cost")
}
// intrinsic gas verification during CheckTx
if ctx.IsCheckTx() && gasLimit < gas {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrOutOfGas, "intrinsic gas too low: %d < %d", gasLimit, gas)
}
// Charge sender for gas up to limit
if gasLimit != 0 {
// Cost calculates the fees paid to validators based on gas limit and price
cost := new(big.Int).Mul(new(big.Int).SetBytes(msgEthTx.Data.GasPrice), new(big.Int).SetUint64(gasLimit))
evmDenom := egcd.evmKeeper.GetParams(ctx).EvmDenom
feeAmt := sdk.NewCoins(
sdk.NewCoin(evmDenom, sdk.NewIntFromBigInt(cost)),
)
err = authante.DeductFees(egcd.bankKeeper, ctx, senderAcc, feeAmt)
// fetch sender account from signature
signerAcc, err := authante.GetSignerAcc(infCtx, egcd.ak, msgEthTx.GetFrom())
if err != nil {
return ctx, err
}
gasLimit := msgEthTx.GetGas()
var accessList ethtypes.AccessList
if msgEthTx.Data.Accesses != nil {
accessList = *msgEthTx.Data.Accesses.ToEthAccessList()
}
intrinsicGas, err := core.IntrinsicGas(msgEthTx.Data.Input, accessList, isContractCreation, homestead, istanbul)
if err != nil {
return ctx, sdkerrors.Wrap(err, "failed to compute intrinsic gas cost")
}
// intrinsic gas verification during CheckTx
if ctx.IsCheckTx() && gasLimit < intrinsicGas {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrOutOfGas, "gas limit too low: %d (gas limit) < %d (intrinsic gas)", gasLimit, intrinsicGas)
}
// Cost calculates the fees paid to validators based on gas limit and price
cost := msgEthTx.Fee() // fee = gas limit * gas price
evmDenom := egcd.evmKeeper.GetParams(infCtx).EvmDenom
feeAmt := sdk.Coins{sdk.NewCoin(evmDenom, sdk.NewIntFromBigInt(cost))}
// deduct the full gas cost from the user balance
if err := authante.DeductFees(egcd.bankKeeper, infCtx, signerAcc, feeAmt); err != nil {
return ctx, err
}
// consume intrinsic gas for the current transaction. After runTx is executed on Baseapp, the
// application will consume gas from the block gas pool.
ctx.GasMeter().ConsumeGas(intrinsicGas, "intrinsic gas")
}
// Set gas meter after ante handler to ignore gaskv costs
newCtx = authante.SetGasMeter(simulate, ctx, gasLimit)
egcd.evmKeeper.WithContext(newCtx)
// generate a copy of the gas pool (i.e block gas meter) to see if we've run out of gas for this block
// if current gas consumed is greater than the limit, this funcion panics and the error is recovered on the Baseapp
gasPool := sdk.NewGasMeter(ctx.BlockGasMeter().Limit())
gasPool.ConsumeGas(ctx.GasMeter().GasConsumedToLimit(), "gas pool check")
return next(newCtx, tx, simulate)
// we know that we have enough gas on the pool to cover the intrinsic gas
// set up the updated context to the evm Keeper
egcd.evmKeeper.WithContext(ctx)
return next(ctx, tx, simulate)
}
// EthIncrementSenderSequenceDecorator increments the sequence of the signers. The
@@ -465,67 +306,27 @@ func NewEthIncrementSenderSequenceDecorator(ak AccountKeeper) EthIncrementSender
func (issd EthIncrementSenderSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
gasMeter := ctx.GasMeter()
ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
infCtx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
ctx = ctx.WithGasMeter(gasMeter)
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
}
for _, msg := range tx.GetMsgs() {
// increment sequence of all signers
for _, addr := range msg.GetSigners() {
acc := issd.ak.GetAccount(infCtx, addr)
if acc == nil {
return ctx, sdkerrors.Wrapf(
sdkerrors.ErrUnknownAddress,
"account %s (%s) is nil", common.BytesToAddress(addr.Bytes()), addr,
)
}
// increment sequence of all signers
for _, addr := range msgEthTx.GetSigners() {
acc := issd.ak.GetAccount(ctx, addr)
if err := acc.SetSequence(acc.GetSequence() + 1); err != nil {
log.WithError(err).Panicln("failed to set acc sequence")
if err := acc.SetSequence(acc.GetSequence() + 1); err != nil {
return ctx, err
}
issd.ak.SetAccount(infCtx, acc)
}
issd.ak.SetAccount(ctx, acc)
}
// set the original gas meter
ctx = ctx.WithGasMeter(gasMeter)
return next(ctx, tx, simulate)
}
// EthAccountSetupDecorator sets an account to state if it's not stored already. This only applies for MsgEthermint.
type EthAccountSetupDecorator struct {
ak AccountKeeper
}
// NewEthAccountSetupDecorator creates a new EthAccountSetupDecorator instance
func NewEthAccountSetupDecorator(ak AccountKeeper) EthAccountSetupDecorator {
return EthAccountSetupDecorator{
ak: ak,
}
}
// AnteHandle sets an account for MsgEthereumTx (evm) if the sender is registered.
func (asd EthAccountSetupDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
// get and set account must be called with an infinite gas meter in order to prevent
// additional gas from being deducted.
gasMeter := ctx.GasMeter()
ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
msgEthTx, ok := getTxMsg(tx).(*evmtypes.MsgEthereumTx)
if !ok {
ctx = ctx.WithGasMeter(gasMeter)
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", getTxMsg(tx))
}
setupAccount(asd.ak, ctx, msgEthTx.GetFrom())
// set the original gas meter
ctx = ctx.WithGasMeter(gasMeter)
return next(ctx, tx, simulate)
}
func setupAccount(ak AccountKeeper, ctx sdk.Context, addr sdk.AccAddress) {
acc := ak.GetAccount(ctx, addr)
if acc != nil {
return
}
acc = ak.NewAccountWithAddress(ctx, addr)
ak.SetAccount(ctx, acc)
}
+371
View File
@@ -0,0 +1,371 @@
package ante_test
import (
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ethermint/app/ante"
"github.com/cosmos/ethermint/tests"
evmtypes "github.com/cosmos/ethermint/x/evm/types"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
func nextFn(ctx sdk.Context, _ sdk.Tx, _ bool) (sdk.Context, error) {
return ctx, nil
}
func (suite AnteTestSuite) TestEthSigVerificationDecorator() {
dec := ante.NewEthSigVerificationDecorator(suite.app.EvmKeeper)
addr, privKey := newTestAddrKey()
signedTx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil)
signedTx.From = addr.Hex()
err := signedTx.Sign(suite.app.EvmKeeper.ChainID(), tests.NewSigner(privKey))
suite.Require().NoError(err)
testCases := []struct {
name string
tx sdk.Tx
reCheckTx bool
expPass bool
}{
{"ReCheckTx", nil, true, true},
{"invalid transaction type", &invalidTx{}, false, false},
{
"invalid sender",
evmtypes.NewMsgEthereumTx(suite.app.EvmKeeper.ChainID(), 1, &addr, big.NewInt(10), 1000, big.NewInt(1), nil, nil),
false,
false,
},
{"successful signature verification", signedTx, false, true},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
consumed := suite.ctx.GasMeter().GasConsumed()
ctx, err := dec.AnteHandle(suite.ctx.WithIsReCheckTx(tc.reCheckTx), tc.tx, false, nextFn)
suite.Require().Equal(consumed, ctx.GasMeter().GasConsumed())
if tc.expPass {
suite.Require().NoError(err)
} else {
suite.Require().Error(err)
}
})
}
}
func (suite AnteTestSuite) TestNewEthAccountVerificationDecorator() {
dec := ante.NewEthAccountVerificationDecorator(
suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.EvmKeeper,
)
addr, _ := newTestAddrKey()
tx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil)
tx.From = addr.Hex()
testCases := []struct {
name string
tx sdk.Tx
malleate func()
checkTx bool
expPass bool
}{
{"not CheckTx", nil, func() {}, false, true},
{"invalid transaction type", &invalidTx{}, func() {}, true, false},
{
"sender not set to msg",
evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil),
func() {},
true,
false,
},
{
"not enough balance to cover tx cost",
tx,
func() {},
true,
false,
},
{
"success new account",
tx,
func() {
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(1000000)))
suite.Require().NoError(err)
},
true,
true,
},
{
"success existing account",
tx,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(1000000)))
suite.Require().NoError(err)
},
true,
true,
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
tc.malleate()
consumed := suite.ctx.GasMeter().GasConsumed()
ctx, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(tc.checkTx), tc.tx, false, nextFn)
suite.Require().Equal(consumed, ctx.GasMeter().GasConsumed())
if tc.expPass {
suite.Require().NoError(err)
} else {
suite.Require().Error(err)
}
})
}
}
func (suite AnteTestSuite) TestEthNonceVerificationDecorator() {
dec := ante.NewEthNonceVerificationDecorator(suite.app.AccountKeeper)
addr, _ := newTestAddrKey()
tx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil)
tx.From = addr.Hex()
testCases := []struct {
name string
tx sdk.Tx
malleate func()
reCheckTx bool
expPass bool
}{
{"ReCheckTx", nil, func() {}, true, true},
{"invalid transaction type", &invalidTx{}, func() {}, false, false},
{"sender account not found", tx, func() {}, false, false},
{
"sender nonce missmatch",
tx,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
},
false,
false,
},
{
"success",
tx,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.Require().NoError(acc.SetSequence(1))
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
},
false,
true,
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
tc.malleate()
consumed := suite.ctx.GasMeter().GasConsumed()
ctx, err := dec.AnteHandle(suite.ctx.WithIsReCheckTx(tc.reCheckTx), tc.tx, false, nextFn)
suite.Require().Equal(consumed, ctx.GasMeter().GasConsumed())
if tc.expPass {
suite.Require().NoError(err)
} else {
suite.Require().Error(err)
}
})
}
}
func (suite AnteTestSuite) TestEthGasConsumeDecorator() {
dec := ante.NewEthGasConsumeDecorator(
suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.EvmKeeper,
)
addr, _ := newTestAddrKey()
tx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil)
tx.From = addr.Hex()
tx2 := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000000, big.NewInt(1), nil, &ethtypes.AccessList{{Address: addr, StorageKeys: nil}})
tx2.From = addr.Hex()
testCases := []struct {
name string
tx sdk.Tx
malleate func()
expPass bool
expPanic bool
}{
{"invalid transaction type", &invalidTx{}, func() {}, false, false},
{
"sender not found",
evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil),
func() {},
false, false,
},
{
"gas limit too low",
tx,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
},
false, false,
},
{
"not enough balance for fees",
tx2,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
},
false, false,
},
{
"not enough tx gas",
tx2,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(10000000000)))
suite.Require().NoError(err)
},
false, true,
},
{
"not enough block gas",
tx2,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(10000000000)))
suite.Require().NoError(err)
suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(1))
},
false, true,
},
{
"success",
tx2,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := suite.app.BankKeeper.SetBalance(suite.ctx, addr.Bytes(), sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(10000000000)))
suite.Require().NoError(err)
suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(10000000000000000000))
},
true, false,
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
tc.malleate()
if tc.expPanic {
suite.Require().Panics(func() {
_, _ = dec.AnteHandle(suite.ctx.WithIsCheckTx(true).WithGasMeter(sdk.NewGasMeter(1)), tc.tx, false, nextFn)
})
return
}
consumed := suite.ctx.GasMeter().GasConsumed()
ctx, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true), tc.tx, false, nextFn)
if tc.expPass {
suite.Require().NoError(err)
suite.Require().Equal(int(params.TxGasContractCreation+params.TxAccessListAddressGas), int(ctx.GasMeter().GasConsumed()-consumed))
} else {
suite.Require().Error(err)
}
})
}
}
func (suite AnteTestSuite) TestEthIncrementSenderSequenceDecorator() {
dec := ante.NewEthIncrementSenderSequenceDecorator(suite.app.AccountKeeper)
addr, privKey := newTestAddrKey()
signedTx := evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil)
signedTx.From = addr.Hex()
err := signedTx.Sign(suite.app.EvmKeeper.ChainID(), tests.NewSigner(privKey))
suite.Require().NoError(err)
testCases := []struct {
name string
tx sdk.Tx
malleate func()
expPass bool
expPanic bool
}{
{
"no signers",
evmtypes.NewMsgEthereumTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil),
func() {},
false, true,
},
{
"account not set to store",
signedTx,
func() {},
false, false,
},
{
"success",
signedTx,
func() {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr.Bytes())
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
},
true, false,
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
tc.malleate()
consumed := suite.ctx.GasMeter().GasConsumed()
if tc.expPanic {
suite.Require().Panics(func() {
_, _ = dec.AnteHandle(suite.ctx, tc.tx, false, nextFn)
})
return
}
ctx, err := dec.AnteHandle(suite.ctx, tc.tx, false, nextFn)
suite.Require().Equal(consumed, ctx.GasMeter().GasConsumed())
if tc.expPass {
suite.Require().NoError(err)
} else {
suite.Require().Error(err)
}
})
}
}
+90 -67
View File
@@ -1,115 +1,138 @@
package ante_test
import (
"math/big"
"testing"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"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/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/ethermint/app"
ante "github.com/cosmos/ethermint/app/ante"
"github.com/cosmos/ethermint/crypto/ethsecp256k1"
"github.com/cosmos/ethermint/tests"
ethermint "github.com/cosmos/ethermint/types"
evmtypes "github.com/cosmos/ethermint/x/evm/types"
"github.com/ethereum/go-ethereum/common"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
type AnteTestSuite struct {
suite.Suite
ctx sdk.Context
app *app.EthermintApp
encodingConfig params.EncodingConfig
anteHandler sdk.AnteHandler
chainID *big.Int
ctx sdk.Context
app *app.EthermintApp
clientCtx client.Context
txBuilder client.TxBuilder
anteHandler sdk.AnteHandler
}
func (suite *AnteTestSuite) SetupTest() {
checkTx := false
suite.app = app.Setup(checkTx)
suite.ctx = suite.app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 2, ChainID: "ethermint-1", Time: time.Now().UTC()})
suite.ctx = suite.ctx.WithMinGasPrices(sdk.NewDecCoins(sdk.NewDecCoin(evmtypes.DefaultEVMDenom, sdk.OneInt())))
suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(1000000000000000000))
suite.app.EvmKeeper.WithChainID(suite.ctx)
suite.ctx = suite.app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 2, ChainID: "ethermint-888", Time: time.Now().UTC()})
suite.app.AccountKeeper.SetParams(suite.ctx, authtypes.DefaultParams())
suite.app.EvmKeeper.SetParams(suite.ctx, evmtypes.DefaultParams())
infCtx := suite.ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
suite.app.AccountKeeper.SetParams(infCtx, authtypes.DefaultParams())
suite.app.EvmKeeper.SetParams(infCtx, evmtypes.DefaultParams())
suite.encodingConfig = app.MakeEncodingConfig()
encodingConfig := app.MakeEncodingConfig()
// We're using TestMsg amino encoding in some tests, so register it here.
suite.encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil)
encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil)
suite.anteHandler = ante.NewAnteHandler(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.EvmKeeper, suite.encodingConfig.TxConfig.SignModeHandler())
suite.chainID = big.NewInt(888)
suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig)
suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder()
suite.anteHandler = ante.NewAnteHandler(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.EvmKeeper, encodingConfig.TxConfig.SignModeHandler())
}
func TestAnteTestSuite(t *testing.T) {
suite.Run(t, new(AnteTestSuite))
}
func newTestMsg(addrs ...sdk.AccAddress) *testdata.TestMsg {
return testdata.NewTestMsg(addrs...)
// CreateTestTx is a helper function to create a tx given multiple inputs.
func (suite *AnteTestSuite) CreateTestTx(
msg *evmtypes.MsgEthereumTx, priv cryptotypes.PrivKey, accNum uint64,
) authsigning.Tx {
option, err := codectypes.NewAnyWithValue(&evmtypes.ExtensionOptionsEthereumTx{})
suite.Require().NoError(err)
builder, ok := suite.txBuilder.(authtx.ExtensionOptionsTxBuilder)
suite.Require().True(ok)
builder.SetExtensionOptions(option)
err = msg.Sign(suite.app.EvmKeeper.ChainID(), tests.NewSigner(priv))
suite.Require().NoError(err)
err = builder.SetMsgs(msg)
fees := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewIntFromBigInt(msg.Fee())))
builder.SetFeeAmount(fees)
builder.SetGasLimit(msg.GetGas())
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: msg.Data.Nonce,
}
sigsV2 := []signing.SignatureV2{sigV2}
err = suite.txBuilder.SetSignatures(sigsV2...)
suite.Require().NoError(err)
// Second round: all signer infos are set, so each signer can sign.
signerData := authsigning.SignerData{
ChainID: suite.ctx.ChainID(),
AccountNumber: accNum,
Sequence: msg.Data.Nonce,
}
sigV2, err = tx.SignWithPrivKey(
suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData,
suite.txBuilder, priv, suite.clientCtx.TxConfig, msg.Data.Nonce,
)
suite.Require().NoError(err)
sigsV2 = []signing.SignatureV2{sigV2}
err = suite.txBuilder.SetSignatures(sigsV2...)
suite.Require().NoError(err)
return suite.txBuilder.GetTx()
}
func newTestCoins() sdk.Coins {
return sdk.NewCoins(ethermint.NewPhotonCoinInt64(500000000))
}
func newTestStdFee() legacytx.StdFee {
return legacytx.NewStdFee(220000, sdk.NewCoins(ethermint.NewPhotonCoinInt64(150)))
}
// GenerateAddress generates an Ethereum address.
func newTestAddrKey() (sdk.AccAddress, cryptotypes.PrivKey) {
func newTestAddrKey() (common.Address, cryptotypes.PrivKey) {
privkey, _ := ethsecp256k1.GenerateKey()
addr := ethcrypto.PubkeyToAddress(privkey.ToECDSA().PublicKey)
addr := crypto.PubkeyToAddress(privkey.ToECDSA().PublicKey)
return sdk.AccAddress(addr.Bytes()), privkey
return addr, privkey
}
func newTestSDKTx(
ctx sdk.Context, msgs []sdk.Msg, privs []cryptotypes.PrivKey,
accNums []uint64, seqs []uint64, fee legacytx.StdFee,
) sdk.Tx {
var _ sdk.Tx = &invalidTx{}
sigs := make([]legacytx.StdSignature, len(privs))
for i, priv := range privs {
signBytes := legacytx.StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], 0, fee, msgs, "")
type invalidTx struct{}
sig, err := priv.Sign(signBytes)
if err != nil {
panic(err)
}
sigs[i] = legacytx.StdSignature{
PubKey: priv.PubKey(),
Signature: sig,
}
}
return legacytx.NewStdTx(msgs, fee, sigs, "")
}
func (suite *AnteTestSuite) newTestEthTx(msg *evmtypes.MsgEthereumTx, priv cryptotypes.PrivKey) (sdk.Tx, error) {
privkey := &ethsecp256k1.PrivKey{Key: priv.Bytes()}
signer := tests.NewSigner(privkey)
msg.From = common.BytesToAddress(privkey.PubKey().Address().Bytes()).String()
if err := msg.Sign(suite.chainID, signer); err != nil {
return nil, err
}
return msg, nil
}
func (invalidTx) GetMsgs() []sdk.Msg { return []sdk.Msg{nil} }
func (invalidTx) ValidateBasic() error { return nil }
+1
View File
@@ -25,6 +25,7 @@ func TestEthermintAppExport(t *testing.T) {
// Initialize the chain
app.InitChain(
abci.RequestInitChain{
ChainId: "ethermint-1",
Validators: []abci.ValidatorUpdate{},
AppStateBytes: stateBytes,
},
+1
View File
@@ -47,6 +47,7 @@ func Setup(isCheckTx bool) *EthermintApp {
// Initialize the chain
app.InitChain(
abci.RequestInitChain{
ChainId: "ethermint-1",
Validators: []abci.ValidatorUpdate{},
ConsensusParams: DefaultConsensusParams,
AppStateBytes: stateBytes,