diff --git a/app/ante/ante.go b/app/ante/ante.go index f5c47d7e1a..afa1cec08a 100644 --- a/app/ante/ante.go +++ b/app/ante/ante.go @@ -19,9 +19,9 @@ import ( "fmt" "runtime/debug" - tmlog "github.com/cometbft/cometbft/libs/log" - errorsmod "cosmossdk.io/errors" + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" @@ -60,9 +60,6 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { case "/ethermint.evm.v1.ExtensionOptionsEthereumTx": // handle as *evmtypes.MsgEthereumTx anteHandler = newEthAnteHandler(options) - case "/ethermint.types.v1.ExtensionOptionsWeb3Tx": - // Deprecated: Handle as normal Cosmos SDK tx, except signature is checked for Legacy EIP712 representation - anteHandler = NewLegacyCosmosAnteHandlerEip712(options) case "/ethermint.types.v1.ExtensionOptionDynamicFeeTx": // cosmos-sdk tx with dynamic fee extension anteHandler = newCosmosAnteHandler(options) @@ -89,7 +86,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { }, nil } -func Recover(logger tmlog.Logger, err *error) { +func Recover(logger log.Logger, err *error) { if r := recover(); r != nil { *err = errorsmod.Wrapf(errortypes.ErrPanic, "%v", r) @@ -114,7 +111,7 @@ var _ authante.SignatureVerificationGasConsumer = DefaultSigVerificationGasConsu // for signature verification based upon the public key type. The cost is fetched from the given params and is matched // by the concrete type. func DefaultSigVerificationGasConsumer( - meter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params, + meter storetypes.GasMeter, sig signing.SignatureV2, params authtypes.Params, ) error { pubkey := sig.PubKey switch pubkey := pubkey.(type) { @@ -137,7 +134,7 @@ func DefaultSigVerificationGasConsumer( // ConsumeMultisignatureVerificationGas consumes gas from a GasMeter for verifying a multisig pubkey signature func ConsumeMultisignatureVerificationGas( - meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, + meter storetypes.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params authtypes.Params, accSeq uint64, ) error { size := sig.BitArray.Count() diff --git a/app/ante/ante_test.go b/app/ante/ante_test.go index 2de41e97e0..1bc68d6620 100644 --- a/app/ante/ante_test.go +++ b/app/ante/ante_test.go @@ -8,21 +8,22 @@ import ( "testing" "time" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" - kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" - "github.com/stretchr/testify/suite" - + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/authz" - - sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/stretchr/testify/suite" "github.com/ethereum/go-ethereum/core/types" ethparams "github.com/ethereum/go-ethereum/params" @@ -30,9 +31,6 @@ import ( "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/tests" evmtypes "github.com/evmos/ethermint/x/evm/types" - - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) func TestAnteTestSuite(t *testing.T) { @@ -363,7 +361,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 create validator", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MsgCreateValidator(from, privKey, "ethermint_9000-1", gas, amount) @@ -374,7 +372,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 create validator (with blank fields)", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MsgCreateValidator2(from, privKey, "ethermint_9000-1", gas, amount) @@ -385,7 +383,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgSubmitProposal", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) // reusing the gasAmount for deposit @@ -399,7 +397,7 @@ func (suite AnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := acc.GetAddress() grantee := sdk.AccAddress("_______grantee______") - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) blockTime := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC) @@ -416,7 +414,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgGrantAllowance", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712GrantAllowance(from, privKey, "ethermint_9000-1", gas, gasAmount) @@ -427,7 +425,7 @@ func (suite AnteTestSuite) TestAnteHandler() { // "success- DeliverTx EIP712 edit validator", // func() sdk.Tx { // from := acc.GetAddress() - // coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + // coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) // amount := sdk.NewCoins(coinAmount) // gas := uint64(200000) // txBuilder := suite.CreateTestEIP712MsgEditValidator(from, privKey, "ethermint_9000-1", gas, amount) @@ -438,7 +436,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 submit evidence", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MsgSubmitEvidence(from, privKey, "ethermint_9000-1", gas, amount) @@ -449,7 +447,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 submit proposal v1", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712SubmitProposalV1(from, privKey, "ethermint_9000-1", gas, amount) @@ -460,7 +458,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgExec", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MsgExec(from, privKey, "ethermint_9000-1", gas, amount) @@ -471,7 +469,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgVoteV1", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MsgVoteV1(from, privKey, "ethermint_9000-1", gas, amount) @@ -482,7 +480,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Multiple MsgSend", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MultipleMsgSend(from, privKey, "ethermint_9000-1", gas, amount) @@ -493,7 +491,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "fails - DeliverTx EIP712 Multiple Signers", func() sdk.Tx { from := acc.GetAddress() - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder := suite.CreateTestEIP712MultipleSignerMsgs(from, privKey, "ethermint_9000-1", gas, amount) @@ -604,7 +602,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -634,7 +632,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -664,7 +662,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -719,7 +717,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -749,7 +747,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -779,7 +777,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -809,7 +807,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -823,7 +821,7 @@ func (suite AnteTestSuite) TestAnteHandler() { "EIP-712", ) - msg.Amount[0].Amount = sdk.NewInt(5) + msg.Amount[0].Amount = math.NewInt(5) txBuilder.SetMsgs(msg) return txBuilder.GetTx() @@ -842,7 +840,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -871,7 +869,7 @@ func (suite AnteTestSuite) TestAnteHandler() { sdk.NewCoins( sdk.NewCoin( "photon", - sdk.NewInt(1), + math.NewInt(1), ), ), ) @@ -1368,7 +1366,7 @@ func (suite *AnteTestSuite) TestConsumeSignatureVerificationGas() { } type args struct { - meter sdk.GasMeter + meter storetypes.GasMeter sig signing.SignatureData pubkey cryptotypes.PubKey params authtypes.Params @@ -1379,11 +1377,11 @@ func (suite *AnteTestSuite) TestConsumeSignatureVerificationGas() { gasConsumed uint64 shouldErr bool }{ - {"PubKeyEd25519", args{sdk.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, p.SigVerifyCostED25519, true}, - {"PubKeyEthSecp256k1", args{sdk.NewInfiniteGasMeter(), nil, pkSet1[0], params}, 21_000, false}, - {"PubKeySecp256r1", args{sdk.NewInfiniteGasMeter(), nil, skR1.PubKey(), params}, p.SigVerifyCostSecp256r1(), false}, - {"Multisig", args{sdk.NewInfiniteGasMeter(), multisignature1, multisigKey1, params}, expectedCost1, false}, - {"unknown key", args{sdk.NewInfiniteGasMeter(), nil, nil, params}, 0, true}, + {"PubKeyEd25519", args{storetypes.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, p.SigVerifyCostED25519, true}, + {"PubKeyEthSecp256k1", args{storetypes.NewInfiniteGasMeter(), nil, pkSet1[0], params}, 21_000, false}, + {"PubKeySecp256r1", args{storetypes.NewInfiniteGasMeter(), nil, skR1.PubKey(), params}, p.SigVerifyCostSecp256r1(), false}, + {"Multisig", args{storetypes.NewInfiniteGasMeter(), multisignature1, multisigKey1, params}, expectedCost1, false}, + {"unknown key", args{storetypes.NewInfiniteGasMeter(), nil, nil, params}, 0, true}, } for _, tt := range tests { sigV2 := signing.SignatureV2{ diff --git a/app/ante/authz_test.go b/app/ante/authz_test.go index 64de145838..447067258f 100644 --- a/app/ante/authz_test.go +++ b/app/ante/authz_test.go @@ -5,6 +5,7 @@ import ( "math/big" "time" + "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -341,20 +342,30 @@ func (suite *AnteTestSuite) TestRejectDeliverMsgsInAuthz() { bz, err := txEncoder(tx) suite.Require().NoError(err) - resCheckTx := suite.app.CheckTx( - abci.RequestCheckTx{ + resCheckTx,err := suite.app.CheckTx( + &abci.RequestCheckTx{ Tx: bz, Type: abci.CheckTxType_New, }, ) + suite.Require().NoError(err) suite.Require().Equal(resCheckTx.Code, tc.expectedCode, resCheckTx.Log) - resDeliverTx := suite.app.DeliverTx( - abci.RequestDeliverTx{ - Tx: bz, + header := suite.ctx.BlockHeader() + blockRes, err := suite.app.FinalizeBlock( + &abci.RequestFinalizeBlock{ + Height: suite.ctx.BlockHeight() + 1, + Txs: [][]byte{bz}, + Hash: header.AppHash, + NextValidatorsHash: header.NextValidatorsHash, + ProposerAddress: header.ProposerAddress, + Time: header.Time.Add(time.Second), }, ) - suite.Require().Equal(resDeliverTx.Code, tc.expectedCode, resDeliverTx.Log) + suite.Require().NoError(err) + suite.Require().Len(blockRes.TxResults, 1) + txRes := blockRes.TxResults[0] + suite.Require().Equal(txRes.Code, tc.expectedCode, txRes.Log) }) } } @@ -439,7 +450,7 @@ func (suite *AnteTestSuite) createTx(priv cryptotypes.PrivKey, msgs ...sdk.Msg) } func (suite *AnteTestSuite) createEIP712Tx(priv cryptotypes.PrivKey, msgs ...sdk.Msg) (sdk.Tx, error) { - coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)) + coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, math.NewInt(20)) fees := sdk.NewCoins(coinAmount) cosmosTxArgs := utiltx.CosmosTxArgs{ TxCfg: suite.clientCtx.TxConfig, diff --git a/app/ante/eip712.go b/app/ante/eip712.go index d4e07bb92c..e92a620143 100644 --- a/app/ante/eip712.go +++ b/app/ante/eip712.go @@ -28,7 +28,6 @@ import ( authante "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - ibcante "github.com/cosmos/ibc-go/v8/modules/core/ante" ethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto/secp256k1" @@ -48,32 +47,6 @@ func init() { ethermintCodec = codec.NewProtoCodec(registry) } -// Deprecated: NewLegacyCosmosAnteHandlerEip712 creates an AnteHandler to process legacy EIP-712 -// transactions, as defined by the presence of an ExtensionOptionsWeb3Tx extension. -func NewLegacyCosmosAnteHandlerEip712(options HandlerOptions) sdk.AnteHandler { - return sdk.ChainAnteDecorators( - RejectMessagesDecorator{}, // reject MsgEthereumTxs - // disable the Msg types that cannot be included on an authz.MsgExec msgs field - NewAuthzLimiterDecorator(options.DisabledAuthzMsgs), - authante.NewSetUpContextDecorator(), - authante.NewValidateBasicDecorator(), - authante.NewTxTimeoutHeightDecorator(), - NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper), - authante.NewValidateMemoDecorator(options.AccountKeeper), - authante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - authante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), - // SetPubKeyDecorator must be called before all signature verification decorators - authante.NewSetPubKeyDecorator(options.AccountKeeper), - authante.NewValidateSigCountDecorator(options.AccountKeeper), - authante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), - // Note: signature verification uses EIP instead of the cosmos signature validator - NewLegacyEip712SigVerificationDecorator(options.AccountKeeper, options.SignModeHandler), - authante.NewIncrementSequenceDecorator(options.AccountKeeper), - ibcante.NewRedundantRelayDecorator(options.IBCKeeper), - NewGasWantedDecorator(options.EvmKeeper, options.FeeMarketKeeper), - ) -} - // Deprecated: LegacyEip712SigVerificationDecorator Verify all signatures for a tx and return an error if any are invalid. Note, // the LegacyEip712SigVerificationDecorator decorator will not get executed on ReCheck. // NOTE: As of v0.20.0, EIP-712 signature verification is handled by the ethsecp256k1 public key (see ethsecp256k1.go) @@ -125,7 +98,10 @@ func (svd LegacyEip712SigVerificationDecorator) AnteHandle(ctx sdk.Context, return ctx, err } - signerAddrs := sigTx.GetSigners() + signerAddrs, err := sigTx.GetSigners() + if err != nil { + return ctx, err + } // EIP712 allows just one signature if len(sigs) != 1 { @@ -228,7 +204,7 @@ func VerifySignature( Amount: tx.GetFee(), Gas: tx.GetGas(), }, - msgs, tx.GetMemo(), tx.GetTip(), + msgs, tx.GetMemo(), ) signerChainID, err := ethermint.ParseChainID(signerData.ChainID) diff --git a/app/ante/eth.go b/app/ante/eth.go index 3ddaafb129..274eab593d 100644 --- a/app/ante/eth.go +++ b/app/ante/eth.go @@ -96,7 +96,7 @@ func (avd EthAccountVerificationDecorator) AnteHandle( feePayerAddr, feePayerAcct.CodeHash) } - if err := keeper.CheckSenderBalance(sdk.NewIntFromBigInt(feePayerAcct.Balance), txData); err != nil { + if err := keeper.CheckSenderBalance(sdkmath.NewIntFromBigInt(feePayerAcct.Balance), txData); err != nil { return ctx, errorsmod.Wrap(err, "failed to check feePayer balance") } } else { @@ -332,7 +332,7 @@ func (ctd CanTransferDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate BaseFee: baseFee, } - stateDB := statedb.New(ctx, ctd.evmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash().Bytes()))) + stateDB := statedb.New(ctx, ctd.evmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash()))) evm := ctd.evmKeeper.NewEVM(ctx, coreMsg, cfg, evmtypes.NewNoOpTracer(), stateDB) // check that caller has enough balance to cover asset transfer for **topmost** call diff --git a/app/ante/eth_test.go b/app/ante/eth_test.go index 0fb9ea8b20..0f668325a0 100644 --- a/app/ante/eth_test.go +++ b/app/ante/eth_test.go @@ -4,11 +4,13 @@ import ( "math" "math/big" + storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/evmos/ethermint/app/ante" "github.com/evmos/ethermint/server/config" "github.com/evmos/ethermint/tests" + utiltx "github.com/evmos/ethermint/testutil/tx" ethermint "github.com/evmos/ethermint/types" "github.com/evmos/ethermint/x/evm/statedb" evmtypes "github.com/evmos/ethermint/x/evm/types" @@ -21,7 +23,7 @@ func (suite AnteTestSuite) TestNewEthAccountVerificationDecorator() { suite.app.AccountKeeper, suite.app.EvmKeeper, ) - addr := tests.GenerateAddress() + addr := utiltx.GenerateAddress() tx := evmtypes.NewTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil) tx.From = addr.Hex() @@ -108,7 +110,7 @@ func (suite AnteTestSuite) TestEthNonceVerificationDecorator() { suite.SetupTest() dec := ante.NewEthIncrementSenderSequenceDecorator(suite.app.AccountKeeper) - addr := tests.GenerateAddress() + addr := utiltx.GenerateAddress() tx := evmtypes.NewTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil) tx.From = addr.Hex() @@ -163,7 +165,7 @@ func (suite AnteTestSuite) TestEthNonceVerificationDecorator() { func (suite AnteTestSuite) TestEthGasConsumeDecorator() { dec := ante.NewEthGasConsumeDecorator(suite.app.EvmKeeper, config.DefaultMaxTxGasWanted) - addr := tests.GenerateAddress() + addr := utiltx.GenerateAddress() txGasLimit := uint64(1000) tx := evmtypes.NewTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), txGasLimit, big.NewInt(1), nil, nil, nil, nil) @@ -252,7 +254,7 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() { 0, func() { vmdb.AddBalance(addr, big.NewInt(1000000)) - suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(1)) + suite.ctx = suite.ctx.WithBlockGasMeter(storetypes.NewGasMeter(1)) }, false, true, 0, @@ -263,7 +265,7 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() { tx2GasLimit, // it's capped func() { vmdb.AddBalance(addr, big.NewInt(1001000000000000)) - suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(10000000000000000000)) + suite.ctx = suite.ctx.WithBlockGasMeter(storetypes.NewGasMeter(10000000000000000000)) }, true, false, tx2Priority, @@ -274,7 +276,7 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() { tx2GasLimit, // it's capped func() { vmdb.AddBalance(addr, big.NewInt(1001000000000000)) - suite.ctx = suite.ctx.WithBlockGasMeter(sdk.NewGasMeter(10000000000000000000)) + suite.ctx = suite.ctx.WithBlockGasMeter(storetypes.NewGasMeter(10000000000000000000)) }, true, false, dynamicFeeTxPriority, @@ -300,12 +302,12 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() { if tc.expPanic { suite.Require().Panics(func() { - _, _ = dec.AnteHandle(suite.ctx.WithIsCheckTx(true).WithGasMeter(sdk.NewGasMeter(1)), tc.tx, false, NextFn) + _, _ = dec.AnteHandle(suite.ctx.WithIsCheckTx(true).WithGasMeter(storetypes.NewGasMeter(1)), tc.tx, false, NextFn) }) return } - ctx, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true).WithGasMeter(sdk.NewInfiniteGasMeter()), tc.tx, false, NextFn) + ctx, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true).WithGasMeter(storetypes.NewInfiniteGasMeter()), tc.tx, false, NextFn) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(tc.expPriority, ctx.Priority()) @@ -320,7 +322,7 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() { func (suite AnteTestSuite) TestCanTransferDecorator() { dec := ante.NewCanTransferDecorator(suite.app.EvmKeeper) - addr, privKey := tests.NewAddrKey() + addr, privKey := utiltx.NewAddrKey() suite.app.FeeMarketKeeper.SetBaseFee(suite.ctx, big.NewInt(100)) @@ -349,7 +351,7 @@ func (suite AnteTestSuite) TestCanTransferDecorator() { tx.From = addr.Hex() - err := tx.Sign(suite.ethSigner, tests.NewSigner(privKey)) + err := tx.Sign(suite.ethSigner, utiltx.NewSigner(privKey)) suite.Require().NoError(err) var vmdb *statedb.StateDB @@ -403,22 +405,22 @@ func (suite AnteTestSuite) TestCanTransferDecorator() { func (suite AnteTestSuite) TestEthIncrementSenderSequenceDecorator() { dec := ante.NewEthIncrementSenderSequenceDecorator(suite.app.AccountKeeper) - addr, privKey := tests.NewAddrKey() + addr, privKey := utiltx.NewAddrKey() contract := evmtypes.NewTxContract(suite.app.EvmKeeper.ChainID(), 0, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil) contract.From = addr.Hex() - err := contract.Sign(suite.ethSigner, tests.NewSigner(privKey)) + err := contract.Sign(suite.ethSigner, utiltx.NewSigner(privKey)) suite.Require().NoError(err) to := tests.GenerateAddress() tx := evmtypes.NewTx(suite.app.EvmKeeper.ChainID(), 0, &to, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil) tx.From = addr.Hex() - err = tx.Sign(suite.ethSigner, tests.NewSigner(privKey)) + err = tx.Sign(suite.ethSigner, utiltx.NewSigner(privKey)) suite.Require().NoError(err) tx2 := evmtypes.NewTx(suite.app.EvmKeeper.ChainID(), 1, &to, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil) tx2.From = addr.Hex() - err = tx2.Sign(suite.ethSigner, tests.NewSigner(privKey)) + err = tx2.Sign(suite.ethSigner, utiltx.NewSigner(privKey)) suite.Require().NoError(err) testCases := []struct { diff --git a/app/ante/fee_checker_test.go b/app/ante/fee_checker_test.go index f823e69949..94c254f5f0 100644 --- a/app/ante/fee_checker_test.go +++ b/app/ante/fee_checker_test.go @@ -6,7 +6,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -55,7 +56,7 @@ func TestSDKTxFeeChecker(t *testing.T) { // without extension option // london hardfork enableness encodingConfig := encoding.MakeConfig(module.NewBasicManager()) - minGasPrices := sdk.NewDecCoins(sdk.NewDecCoin("aphoton", sdk.NewInt(10))) + minGasPrices := sdk.NewDecCoins(sdk.NewDecCoin("aphoton", math.NewInt(10))) genesisCtx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) checkTxCtx := sdk.NewContext(nil, tmproto.Header{Height: 1}, true, log.NewNopLogger()).WithMinGasPrices(minGasPrices) @@ -99,7 +100,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.Tx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(10)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", math.NewInt(10)))) return txBuilder.GetTx() }, "10aphoton", @@ -141,7 +142,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.Tx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(10)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", math.NewInt(10)))) return txBuilder.GetTx() }, "10aphoton", @@ -157,7 +158,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.Tx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(10).Mul(types.DefaultPriorityReduction).Add(sdk.NewInt(10))))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", math.NewInt(10).Mul(types.DefaultPriorityReduction).Add(math.NewInt(10))))) return txBuilder.GetTx() }, "10000010aphoton", @@ -173,7 +174,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.Tx { txBuilder := encodingConfig.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(10).Mul(types.DefaultPriorityReduction)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", math.NewInt(10).Mul(types.DefaultPriorityReduction)))) option, err := codectypes.NewAnyWithValue(ðermint.ExtensionOptionDynamicFeeTx{}) require.NoError(t, err) @@ -193,10 +194,10 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.Tx { txBuilder := encodingConfig.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(10).Mul(types.DefaultPriorityReduction).Add(sdk.NewInt(10))))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("aphoton", math.NewInt(10).Mul(types.DefaultPriorityReduction).Add(math.NewInt(10))))) option, err := codectypes.NewAnyWithValue(ðermint.ExtensionOptionDynamicFeeTx{ - MaxPriorityPrice: sdk.NewInt(5).Mul(types.DefaultPriorityReduction), + MaxPriorityPrice: math.NewInt(5).Mul(types.DefaultPriorityReduction), }) require.NoError(t, err) txBuilder.SetExtensionOptions(option) diff --git a/app/ante/feegrant.go b/app/ante/feegrant.go index 80dc9fe45f..2300b56361 100644 --- a/app/ante/feegrant.go +++ b/app/ante/feegrant.go @@ -3,6 +3,8 @@ package ante import ( "math/big" + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -30,12 +32,12 @@ func (ev EthFeeGrantValidator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b 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)(nil)) + return ctx, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type %T, expected %T", tx, (*evmtypes.MsgEthereumTx)(nil)) } ethTx := msgEthTx.AsTransaction() sender, err := signer.Sender(ethTx) if err != nil { - return ctx, sdkerrors.Wrapf( + return ctx, errorsmod.Wrapf( sdkerrors.ErrorInvalidSigner, "couldn't retrieve sender address ('%s') from the ethereum transaction: %s", msgEthTx.From, @@ -44,24 +46,24 @@ func (ev EthFeeGrantValidator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b } txData, err := evmtypes.UnpackTxData(msgEthTx.Data) if err != nil { - return ctx, sdkerrors.Wrap(err, "failed to unpack tx data") + return ctx, errorsmod.Wrap(err, "failed to unpack tx data") } feeGrantee := sender.Bytes() feeGranteeCosmosAddr := sdk.AccAddress(feeGrantee) feePayer := msgEthTx.GetFeePayer() feeAmt := txData.Fee() if feeAmt.Sign() == 0 { - return ctx, sdkerrors.Wrap(err, "failed to fee amount") + return ctx, errorsmod.Wrap(err, "failed to fee amount") } - fees := sdk.Coins{sdk.NewCoin(params.EvmDenom, sdk.NewIntFromBigInt(feeAmt))} + fees := sdk.Coins{sdk.NewCoin(params.EvmDenom, math.NewIntFromBigInt(feeAmt))} msgs := []sdk.Msg{msg} if feePayer != nil { err := ev.feegrantKeeper.UseGrantedFees(ctx, feePayer, feeGrantee, fees, msgs) if err != nil { - return ctx, sdkerrors.Wrapf(err, + return ctx, errorsmod.Wrapf(err, "%s(%s) not allowed to pay fees from %s", sender.Hex(), feeGranteeCosmosAddr, feePayer) } } diff --git a/app/ante/fees.go b/app/ante/fees.go index 8c207b7cbf..3bbfdc1866 100644 --- a/app/ante/fees.go +++ b/app/ante/fees.go @@ -19,6 +19,7 @@ import ( "math/big" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" @@ -104,7 +105,7 @@ func (mpd MinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate // Determine the required fees by multiplying each required minimum gas // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). - gasLimit := sdk.NewDecFromBigInt(new(big.Int).SetUint64(gas)) + gasLimit := math.LegacyNewDecFromBigInt(new(big.Int).SetUint64(gas)) for _, gp := range minGasPrices { fee := gp.Amount.Mul(gasLimit).Ceil().RoundInt() @@ -168,10 +169,10 @@ func (empd EthMinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul feeAmt = ethMsg.GetEffectiveFee(baseFee) } - gasLimit := sdk.NewDecFromBigInt(new(big.Int).SetUint64(ethMsg.GetGas())) + gasLimit := math.LegacyNewDecFromBigInt(new(big.Int).SetUint64(ethMsg.GetGas())) requiredFee := minGasPrice.Mul(gasLimit) - fee := sdk.NewDecFromBigInt(feeAmt) + fee := math.LegacyNewDecFromBigInt(feeAmt) if fee.LT(requiredFee) { return ctx, errorsmod.Wrapf( @@ -211,8 +212,8 @@ func (mfd EthMempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulat return ctx, errorsmod.Wrapf(errortypes.ErrUnknownRequest, "invalid message type %T, expected %T", msg, (*evmtypes.MsgEthereumTx)(nil)) } - fee := sdk.NewDecFromBigInt(ethMsg.GetFee()) - gasLimit := sdk.NewDecFromBigInt(new(big.Int).SetUint64(ethMsg.GetGas())) + fee := math.LegacyNewDecFromBigInt(ethMsg.GetFee()) + gasLimit := math.LegacyNewDecFromBigInt(new(big.Int).SetUint64(ethMsg.GetGas())) requiredFee := minGasPrice.Mul(gasLimit) if fee.LT(requiredFee) { diff --git a/app/ante/fees_test.go b/app/ante/fees_test.go index e8fb5d5d05..74d5eac16b 100644 --- a/app/ante/fees_test.go +++ b/app/ante/fees_test.go @@ -3,6 +3,7 @@ package ante_test import ( "math/big" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -49,7 +50,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() { "valid cosmos tx with MinGasPrices = 0, gasPrice = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(0), denom, &testMsg) @@ -63,7 +64,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() { "valid cosmos tx with MinGasPrices = 0, gasPrice > 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), denom, &testMsg) @@ -77,7 +78,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() { "valid cosmos tx with MinGasPrices = 10, gasPrice = 10", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), denom, &testMsg) @@ -91,7 +92,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() { "invalid cosmos tx with MinGasPrices = 10, gasPrice = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(0), denom, &testMsg) @@ -105,7 +106,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() { "invalid cosmos tx with wrong denom", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), "stake", &testMsg) @@ -152,7 +153,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "invalid tx type", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) return &invalidTx{} }, @@ -163,7 +164,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "wrong tx type", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) testMsg := banktypes.MsgSend{ FromAddress: "evmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp", @@ -180,7 +181,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid: invalid tx type with MinGasPrices = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) return &invalidTx{} }, @@ -191,7 +192,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid legacy tx with MinGasPrices = 0, gasPrice = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), big.NewInt(0), nil, nil, nil) @@ -204,7 +205,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid legacy tx with MinGasPrices = 0, gasPrice > 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), big.NewInt(10), nil, nil, nil) @@ -217,7 +218,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid legacy tx with MinGasPrices = 10, gasPrice = 10", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), big.NewInt(10), nil, nil, nil) @@ -230,7 +231,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "invalid legacy tx with MinGasPrices = 10, gasPrice = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), big.NewInt(0), nil, nil, nil) @@ -243,7 +244,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid dynamic tx with MinGasPrices = 0, EffectivePrice = 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(0), big.NewInt(0), &emptyAccessList) @@ -256,7 +257,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid dynamic tx with MinGasPrices = 0, EffectivePrice > 0", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.ZeroDec() + params.MinGasPrice = math.LegacyZeroDec() s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(100), big.NewInt(50), &emptyAccessList) @@ -269,7 +270,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid dynamic tx with MinGasPrices < EffectivePrice", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(100), big.NewInt(100), &emptyAccessList) @@ -282,7 +283,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "invalid dynamic tx with MinGasPrices > EffectivePrice", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(10) + params.MinGasPrice = math.LegacyNewDec(10) s.app.FeeMarketKeeper.SetParams(s.ctx, params) msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(0), big.NewInt(0), &emptyAccessList) @@ -295,7 +296,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "invalid dynamic tx with MinGasPrices > BaseFee, MinGasPrices > EffectivePrice", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(100) + params.MinGasPrice = math.LegacyNewDec(100) s.app.FeeMarketKeeper.SetParams(s.ctx, params) feemarketParams := s.app.FeeMarketKeeper.GetParams(s.ctx) @@ -312,7 +313,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() { "valid dynamic tx with MinGasPrices > BaseFee, MinGasPrices < EffectivePrice (big GasTipCap)", func() sdk.Tx { params := s.app.FeeMarketKeeper.GetParams(s.ctx) - params.MinGasPrice = sdk.NewDec(100) + params.MinGasPrice = math.LegacyNewDec(100) s.app.FeeMarketKeeper.SetParams(s.ctx, params) feemarketParams := s.app.FeeMarketKeeper.GetParams(s.ctx) diff --git a/app/ante/handler_options.go b/app/ante/handler_options.go index 8e84b30f95..90c1c259d0 100644 --- a/app/ante/handler_options.go +++ b/app/ante/handler_options.go @@ -17,11 +17,12 @@ package ante import ( errorsmod "cosmossdk.io/errors" + storetypes "cosmossdk.io/store/types" + txsigning "cosmossdk.io/x/tx/signing" sdk "github.com/cosmos/cosmos-sdk/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/ante" - authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ibcante "github.com/cosmos/ibc-go/v8/modules/core/ante" @@ -39,8 +40,8 @@ type HandlerOptions struct { FeeMarketKeeper FeeMarketKeeper EvmKeeper EVMKeeper FeegrantKeeper ante.FeegrantKeeper - SignModeHandler authsigning.SignModeHandler - SigGasConsumer func(meter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params) error + SignModeHandler *txsigning.HandlerMap + SigGasConsumer func(meter storetypes.GasMeter, sig signing.SignatureV2, params authtypes.Params) error MaxTxGasWanted uint64 ExtensionOptionChecker ante.ExtensionOptionChecker TxFeeChecker ante.TxFeeChecker diff --git a/app/ante/setup.go b/app/ante/setup.go index 6103fbb503..9c5ad2245f 100644 --- a/app/ante/setup.go +++ b/app/ante/setup.go @@ -49,7 +49,7 @@ func (esc EthSetupContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul } // We need to setup an empty gas config so that the gas is consistent with Ethereum. - newCtx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()). + newCtx = ctx.WithGasMeter(storetypes.NewInfiniteGasMeter()). WithKVGasConfig(storetypes.GasConfig{}). WithTransientKVGasConfig(storetypes.GasConfig{}) diff --git a/app/ante/utils_test.go b/app/ante/utils_test.go index d4ff0d6ab9..c166263d8d 100644 --- a/app/ante/utils_test.go +++ b/app/ante/utils_test.go @@ -1,6 +1,7 @@ package ante_test import ( + "context" "encoding/json" "fmt" "math" @@ -12,17 +13,17 @@ import ( sdkmath "cosmossdk.io/math" "cosmossdk.io/simapp" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/testutil" utiltx "github.com/evmos/ethermint/testutil/tx" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -77,7 +78,7 @@ type AnteTestSuite struct { const TestGasLimit uint64 = 100000 func (suite *AnteTestSuite) StateDB() *statedb.StateDB { - return statedb.New(suite.ctx, suite.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(suite.ctx.HeaderHash().Bytes()))) + return statedb.New(suite.ctx, suite.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(suite.ctx.HeaderHash()))) } func (suite *AnteTestSuite) SetupTest() { @@ -115,12 +116,12 @@ func (suite *AnteTestSuite) SetupTest() { return genesis }) - suite.ctx = suite.app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 2, ChainID: testutil.TestnetChainID + "-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.ctx = suite.app.BaseApp.NewContextLegacy(checkTx, tmproto.Header{Height: 2, ChainID: testutil.TestnetChainID + "-1", Time: time.Now().UTC()}) + suite.ctx = suite.ctx.WithMinGasPrices(sdk.NewDecCoins(sdk.NewDecCoin(evmtypes.DefaultEVMDenom, sdkmath.OneInt()))) + suite.ctx = suite.ctx.WithBlockGasMeter(storetypes.NewGasMeter(1000000000000000000)) suite.app.EvmKeeper.WithChainID(suite.ctx) - infCtx := suite.ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + infCtx := suite.ctx.WithGasMeter(storetypes.NewInfiniteGasMeter()) suite.app.AccountKeeper.SetParams(infCtx, authtypes.DefaultParams()) addr := sdk.AccAddress(priv.PubKey().Address().Bytes()) @@ -154,7 +155,7 @@ func (suite *AnteTestSuite) SetupTest() { suite.ethSigner = ethtypes.LatestSignerForChainID(suite.app.EvmKeeper.ChainID()) // fund signer acc to pay for tx fees - amt := sdk.NewInt(int64(math.Pow10(18) * 2)) + amt := sdkmath.NewInt(int64(math.Pow10(18) * 2)) err = testutil.FundAccount( suite.app.BankKeeper, suite.ctx, @@ -315,10 +316,10 @@ func (suite *AnteTestSuite) CreateTestEIP712MsgCreateValidator(from sdk.AccAddre msgCreate, err := ethermint.NewMsgCreateValidator( valAddr, privEd.PubKey(), - sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)), + sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)), stakingtypes.NewDescription("moniker", "indentity", "website", "security_contract", "details"), - stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), - sdk.NewInt(0), + stakingtypes.NewCommissionRates(sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec()), + sdkmath.NewInt(0), ) suite.Require().NoError(err) return suite.CreateTestEIP712SingleMessageTxBuilder(priv, chainId, gas, gasAmount, msgCreate) @@ -331,11 +332,11 @@ func (suite *AnteTestSuite) CreateTestEIP712MsgCreateValidator2(from sdk.AccAddr msgCreate, err := ethermint.NewMsgCreateValidator( valAddr, privEd.PubKey(), - sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)), + sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)), // Ensure optional fields can be left blank stakingtypes.NewDescription("moniker", "indentity", "", "", ""), - stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), - sdk.NewInt(0), + stakingtypes.NewCommissionRates(sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec()), + sdkmath.NewInt(0), ) suite.Require().NoError(err) return suite.CreateTestEIP712SingleMessageTxBuilder(priv, chainId, gas, gasAmount, msgCreate) @@ -481,7 +482,6 @@ func StdSignBytes(cdc *codec.LegacyAmino, chainID string, accnum uint64, sequenc Msgs: msgsBytes, Sequence: sequence, TimeoutHeight: timeout, - Tip: stdTip, }) if err != nil { panic(err) @@ -612,6 +612,7 @@ func (suite *AnteTestSuite) createSignerBytes(chainId string, signMode signing.S } signerBytes, err := suite.clientCtx.TxConfig.SignModeHandler().GetSignBytes( + context.Background(), signMode, signerInfo, txBuilder.GetTx(), @@ -627,7 +628,7 @@ func (suite *AnteTestSuite) createBaseTxBuilder(msg sdk.Msg, gas uint64) client. txBuilder.SetGasLimit(gas) txBuilder.SetFeeAmount(sdk.NewCoins( - sdk.NewCoin("aphoton", sdk.NewInt(10000)), + sdk.NewCoin("aphoton", sdkmath.NewInt(10000)), )) err := txBuilder.SetMsgs(msg) diff --git a/app/app.go b/app/app.go index 630c41590a..c9479fae2d 100644 --- a/app/app.go +++ b/app/app.go @@ -26,38 +26,42 @@ import ( "github.com/rakyll/statik/fs" "github.com/spf13/cast" - dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmos "github.com/cometbft/cometbft/libs/os" + "cosmossdk.io/log" "cosmossdk.io/simapp" simappparams "cosmossdk.io/simapp/params" - storetypes "cosmossdk.io/store/types" + "cosmossdk.io/x/evidence" + evidencekeeper "cosmossdk.io/x/evidence/keeper" + evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/feegrant" + feegrantkeeper "cosmossdk.io/x/feegrant/keeper" + feegrantmodule "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/upgrade" + upgradekeeper "cosmossdk.io/x/upgrade/keeper" + upgradetypes "cosmossdk.io/x/upgrade/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" "github.com/cosmos/cosmos-sdk/client/grpc/node" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" - - "cosmossdk.io/x/evidence" - evidencekeeper "cosmossdk.io/x/evidence/keeper" - evidencetypes "cosmossdk.io/x/evidence/types" - "cosmossdk.io/x/feegrant" - feegrantkeeper "cosmossdk.io/x/feegrant/keeper" - feegrantmodule "cosmossdk.io/x/feegrant/module" - "cosmossdk.io/x/upgrade" - upgradekeeper "cosmossdk.io/x/upgrade/keeper" - upgradetypes "cosmossdk.io/x/upgrade/types" "github.com/cosmos/cosmos-sdk/x/auth" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/posthandler" authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" @@ -102,6 +106,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/gogoproto/proto" "github.com/cosmos/ibc-go/modules/capability" capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" @@ -110,7 +115,6 @@ import ( ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibcclient "github.com/cosmos/ibc-go/v8/modules/core/02-client" porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" @@ -213,6 +217,7 @@ type EthermintApp struct { cdc *codec.LegacyAmino appCodec codec.Codec interfaceRegistry types.InterfaceRegistry + txConfig client.TxConfig invCheckPeriod uint @@ -250,6 +255,7 @@ type EthermintApp struct { // the module manager mm *module.Manager + BasicModuleManager module.BasicManager // the configurator configurator module.Configurator @@ -263,30 +269,54 @@ func NewEthermintApp( loadLatest bool, skipUpgradeHeights map[int64]bool, homePath string, - invCheckPeriod uint, - encodingConfig simappparams.EncodingConfig, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *EthermintApp { - appCodec := encodingConfig.Codec - cdc := encodingConfig.Amino - interfaceRegistry := encodingConfig.InterfaceRegistry + legacyAmino := codec.NewLegacyAmino() + interfaceRegistry, err := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ + ProtoFiles: proto.HybridResolver, + SigningOptions: signing.Options{ + AddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32AccountAddrPrefix(), + }, + ValidatorAddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), + }, + }, + }) + if err != nil { + panic(err) + } + appCodec := codec.NewProtoCodec(interfaceRegistry) + txConfig := authtx.NewTxConfig(appCodec, authtx.DefaultSignModes) + + std.RegisterLegacyAminoCodec(legacyAmino) + std.RegisterInterfaces(interfaceRegistry) + + skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) + invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) - eip712.SetEncodingConfig(encodingConfig) + eip712.SetEncodingConfig(simappparams.EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: appCodec, + TxConfig: txConfig, + Amino: legacyAmino, + }) // NOTE we use custom transaction decoder that supports the sdk.Tx interface instead of sdk.StdTx bApp := baseapp.NewBaseApp( appName, logger, db, - encodingConfig.TxConfig.TxDecoder(), + txConfig.TxDecoder(), baseAppOptions..., ) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) + bApp.SetTxEncoder(txConfig.TxEncoder()) - keys := sdk.NewKVStoreKeys( + keys := storetypes.NewKVStoreKeys( // SDK keys authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, @@ -300,8 +330,8 @@ func NewEthermintApp( ) // Add the EVM transient store key - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) + tkeys := storetypes.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) + memKeys := storetypes.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) // load state streaming if enabled // register streaming services @@ -311,20 +341,26 @@ func NewEthermintApp( app := &EthermintApp{ BaseApp: bApp, - cdc: cdc, + cdc: legacyAmino, appCodec: appCodec, interfaceRegistry: interfaceRegistry, invCheckPeriod: invCheckPeriod, + txConfig: txConfig, keys: keys, tkeys: tkeys, memKeys: memKeys, } // init params keeper and subspaces - app.ParamsKeeper = initParamsKeeper(appCodec, cdc, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey]) + app.ParamsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey]) // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) - bApp.SetParamStore(&app.ConsensusParamsKeeper) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + runtime.EventService{}, + ) + bApp.SetParamStore(app.ConsensusParamsKeeper.ParamsStore) // add capability keeper and ScopeToModule for ibc module app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey]) @@ -338,28 +374,34 @@ func NewEthermintApp( // use custom Ethermint account for contracts app.AccountKeeper = authkeeper.NewAccountKeeper( - appCodec, keys[authtypes.StoreKey], + appCodec, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), ethermint.ProtoAccount, maccPerms, + address.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()), sdk.GetConfig().GetBech32AccountAddrPrefix(), authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, - keys[banktypes.StoreKey], + runtime.NewKVStoreService(keys[banktypes.StoreKey]), app.AccountKeeper, app.BlockedAddrs(), authtypes.NewModuleAddress(govtypes.ModuleName).String(), + logger, ) app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, keys[stakingtypes.StoreKey], + appCodec, + runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()), + authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()), ) app.MintKeeper = mintkeeper.NewKeeper( appCodec, - keys[minttypes.StoreKey], + runtime.NewKVStoreService(keys[minttypes.StoreKey]), app.StakingKeeper, app.AccountKeeper, app.BankKeeper, @@ -368,7 +410,7 @@ func NewEthermintApp( ) app.DistrKeeper = distrkeeper.NewKeeper( appCodec, - keys[distrtypes.StoreKey], + runtime.NewKVStoreService(keys[distrtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, @@ -377,32 +419,35 @@ func NewEthermintApp( ) app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, - cdc, - keys[slashingtypes.StoreKey], + legacyAmino, + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.CrisisKeeper = crisiskeeper.NewKeeper( appCodec, - keys[crisistypes.StoreKey], + runtime.NewKVStoreService(keys[crisistypes.StoreKey]), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + app.AccountKeeper.AddressCodec(), ) app.FeeGrantKeeper = feegrantkeeper.NewKeeper( appCodec, - keys[feegrant.StoreKey], - app.AccountKeeper) + runtime.NewKVStoreService(keys[feegrant.StoreKey]), + app.AccountKeeper, + ) // set the governance module account as the authority for conducting upgrades app.UpgradeKeeper = upgradekeeper.NewKeeper( skipUpgradeHeights, - keys[upgradetypes.StoreKey], + runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, - authtypes.NewModuleAddress(govtypes.ModuleName).String()) + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks @@ -411,10 +456,11 @@ func NewEthermintApp( ) app.AuthzKeeper = authzkeeper.NewKeeper( - keys[authzkeeper.StoreKey], + runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), appCodec, app.MsgServiceRouter(), - app.AccountKeeper) + app.AccountKeeper, + ) tracer := cast.ToString(appOpts.Get(srvflags.EVMTracer)) @@ -428,30 +474,50 @@ func NewEthermintApp( // Set authority to x/gov module account to only expect the module account to update params evmSs := app.GetSubspace(evmtypes.ModuleName) app.EvmKeeper = evmkeeper.NewKeeper( - appCodec, keys[evmtypes.StoreKey], tkeys[evmtypes.TransientKey], authtypes.NewModuleAddress(govtypes.ModuleName), - app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.FeeMarketKeeper, - nil, geth.NewEVM, tracer, evmSs, + appCodec, + keys[evmtypes.StoreKey], + tkeys[evmtypes.TransientKey], + authtypes.NewModuleAddress(govtypes.ModuleName), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.FeeMarketKeeper, + nil, + geth.NewEVM, + tracer, + evmSs, ) // Create IBC Keeper app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibcexported.StoreKey], app.GetSubspace(ibcexported.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, + appCodec, + keys[ibcexported.StoreKey], + app.GetSubspace(ibcexported.ModuleName), + app.StakingKeeper, + app.UpgradeKeeper, + scopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // register the proposal types govRouter := govv1beta1.NewRouter() govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)). - AddRoute(ibcexported.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)) + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)) govConfig := govtypes.DefaultConfig() /* Example of setting gov params: govConfig.MaxMetadataLen = 10000 */ govKeeper := govkeeper.NewKeeper( - appCodec, keys[govtypes.StoreKey], app.AccountKeeper, app.BankKeeper, - app.StakingKeeper, app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, + runtime.NewKVStoreService(keys[govtypes.StoreKey]), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.DistrKeeper, + app.MsgServiceRouter(), + govConfig, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // Set legacy router for backwards compatibility with gov v1beta1 @@ -465,9 +531,16 @@ func NewEthermintApp( // Create Transfer Keepers app.TransferKeeper = ibctransferkeeper.NewKeeper( - appCodec, keys[ibctransfertypes.StoreKey], app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCKeeper.ChannelKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, - app.AccountKeeper, app.BankKeeper, scopedTransferKeeper, + appCodec, + keys[ibctransfertypes.StoreKey], + app.GetSubspace(ibctransfertypes.ModuleName), + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + scopedTransferKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) transferModule := transfer.NewAppModule(app.TransferKeeper) transferIBCModule := transfer.NewIBCModule(app.TransferKeeper) @@ -479,24 +552,27 @@ func NewEthermintApp( // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, keys[evidencetypes.StoreKey], app.StakingKeeper, app.SlashingKeeper, + appCodec, + runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), + app.StakingKeeper, + app.SlashingKeeper, + app.AccountKeeper.AddressCodec(), + runtime.ProvideCometInfoService(), ) // If evidence needs to be handled for the app, set routes in router here and seal app.EvidenceKeeper = *evidenceKeeper /**** Module Options ****/ - // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment - // we prefer to be more strict in what arguments the modules expect. - skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) - // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.mm = module.NewManager( // SDK app modules genutil.NewAppModule( - app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, - encodingConfig.TxConfig, + app.AccountKeeper, + app.StakingKeeper, + app, + txConfig, ), auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), @@ -506,10 +582,10 @@ func NewEthermintApp( feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(authtypes.ModuleName)), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(authtypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(authtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(authtypes.ModuleName),interfaceRegistry), distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(authtypes.ModuleName)), staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(authtypes.ModuleName)), - upgrade.NewAppModule(app.UpgradeKeeper), + upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.AddressCodec()), evidence.NewAppModule(app.EvidenceKeeper), params.NewAppModule(app.ParamsKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), @@ -522,6 +598,7 @@ func NewEthermintApp( feemarket.NewAppModule(app.FeeMarketKeeper, feeMarketSs), evm.NewAppModule(app.EvmKeeper, app.AccountKeeper, evmSs), ) + app.BasicModuleManager = newBasicManagerFromManager(app) // During begin block slashing happens after distr.BeginBlocker so that // there is nothing left over in the validator fee pool, so as to keep the @@ -634,11 +711,15 @@ func NewEthermintApp( app.MountTransientStores(tkeys) app.MountMemoryStores(memKeys) + // NOTE: upgrade module is required to be prioritized + app.mm.SetOrderPreBlockers( + upgradetypes.ModuleName, + ) // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.setAnteHandler(encodingConfig.TxConfig, cast.ToUint64(appOpts.Get(srvflags.EVMMaxTxGasWanted))) + app.setAnteHandler(txConfig, cast.ToUint64(appOpts.Get(srvflags.EVMMaxTxGasWanted))) // In v0.46, the SDK introduces _postHandlers_. PostHandlers are like // antehandlers, but are run _after_ the `runMsgs` execution. They are also // defined as a chain, and have the same signature as antehandlers. @@ -707,23 +788,28 @@ func (app *EthermintApp) setPostHandler() { func (app *EthermintApp) Name() string { return app.BaseApp.Name() } // BeginBlocker updates every begin block -func (app *EthermintApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.mm.BeginBlock(ctx, req) +func (app *EthermintApp) BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error) { + return app.mm.BeginBlock(ctx) } // EndBlocker updates every end block -func (app *EthermintApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.mm.EndBlock(ctx, req) +func (app *EthermintApp) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { + return app.mm.EndBlock(ctx) } // InitChainer updates at chain initialization -func (app *EthermintApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { +func (app *EthermintApp) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { var genesisState simapp.GenesisState if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { panic(err) } - app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) - return app.mm.InitGenesis(ctx, app.appCodec, genesisState) + + response, err := app.mm.InitGenesis(ctx, app.appCodec, genesisState) + if err != nil { + panic(err) + } + + return response, nil } // LoadHeight loads state at a particular height @@ -773,6 +859,11 @@ func (app *EthermintApp) InterfaceRegistry() types.InterfaceRegistry { return app.interfaceRegistry } +// TxConfig returns EthermintApp's TxConfig +func (app *EthermintApp) TxConfig() client.TxConfig { + return app.txConfig +} + // GetKey returns the KVStoreKey for the provided store key. // // NOTE: This is solely to be used for testing purposes. @@ -839,8 +930,8 @@ func (app *EthermintApp) RegisterTendermintService(clientCtx client.Context) { // RegisterNodeService registers the node gRPC service on the provided // application gRPC query router. -func (app *EthermintApp) RegisterNodeService(clientCtx client.Context) { - node.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) +func (app *EthermintApp) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + node.RegisterNodeService(clientCtx, app.GRPCQueryRouter(),cfg) } // RegisterSwaggerAPI registers swagger route with API Server @@ -883,3 +974,22 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(feemarkettypes.ModuleName).WithKeyTable(feemarkettypes.ParamKeyTable()) return paramsKeeper } + +// ModuleBasics defines the module BasicManager that is in charge of setting up basic, +// non-dependant module elements, such as codec registration +// and genesis verification. +func newBasicManagerFromManager(app *EthermintApp) module.BasicManager { + basicManager := module.NewBasicManagerFromManager( + app.mm, + map[string]module.AppModuleBasic{ + genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + govtypes.ModuleName: gov.NewAppModuleBasic( + []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + }, + ), + }) + basicManager.RegisterLegacyAminoCodec(app.cdc) + basicManager.RegisterInterfaces(app.interfaceRegistry) + return basicManager +} diff --git a/app/app_test.go b/app/app_test.go index c125ff4fe4..8608685f8d 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -1,17 +1,14 @@ package app import ( - "os" "testing" "github.com/stretchr/testify/require" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - - "github.com/evmos/ethermint/encoding" + "cosmossdk.io/log" + dbm "github.com/cosmos/cosmos-db" ) func TestEthermintAppExport(t *testing.T) { @@ -20,7 +17,8 @@ func TestEthermintAppExport(t *testing.T) { app.Commit() // Making a new app object with the db, so that initchain hasn't been called - app2 := NewEthermintApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encoding.MakeConfig(ModuleBasics), simtestutil.EmptyAppOptions{}) - _, err := app2.ExportAppStateAndValidators(false, []string{}) + app2 := NewEthermintApp( + log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome,simtestutil.EmptyAppOptions{}) + _, err := app2.ExportAppStateAndValidators(false, []string{}, []string{}) require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } diff --git a/app/benchmark_test.go b/app/benchmark_test.go index 8e5816acb0..399ba6be7f 100644 --- a/app/benchmark_test.go +++ b/app/benchmark_test.go @@ -2,21 +2,18 @@ package app import ( "encoding/json" - "io" "testing" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" - - "github.com/evmos/ethermint/encoding" + dbm "github.com/cosmos/cosmos-db" ) func BenchmarkEthermintApp_ExportAppStateAndValidators(b *testing.B) { db := dbm.NewMemDB() - app := NewEthermintApp(log.NewTMLogger(io.Discard), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encoding.MakeConfig(ModuleBasics), simtestutil.EmptyAppOptions{}) + app := NewEthermintApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, simtestutil.EmptyAppOptions{}) genesisState := NewTestGenesisState(app.AppCodec()) stateBytes, err := json.MarshalIndent(genesisState, "", " ") @@ -26,7 +23,7 @@ func BenchmarkEthermintApp_ExportAppStateAndValidators(b *testing.B) { // Initialize the chain app.InitChain( - abci.RequestInitChain{ + &abci.RequestInitChain{ ChainId: "ethermint_9000-1", Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes, @@ -38,8 +35,8 @@ func BenchmarkEthermintApp_ExportAppStateAndValidators(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { // Making a new app object with the db, so that initchain hasn't been called - app2 := NewEthermintApp(log.NewTMLogger(log.NewSyncWriter(io.Discard)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encoding.MakeConfig(ModuleBasics), simtestutil.EmptyAppOptions{}) - if _, err := app2.ExportAppStateAndValidators(false, []string{}); err != nil { + app2 := NewEthermintApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, simtestutil.EmptyAppOptions{}) + if _, err := app2.ExportAppStateAndValidators(false, []string{}, []string{}); err != nil { b.Fatal(err) } } diff --git a/app/export.go b/app/export.go index b74cf5322f..f019c267fa 100644 --- a/app/export.go +++ b/app/export.go @@ -17,11 +17,11 @@ package app import ( "encoding/json" - "fmt" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "cosmossdk.io/simapp" + storetypes "cosmossdk.io/store/types" servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -40,10 +40,12 @@ func NewDefaultGenesisState() simapp.GenesisState { // ExportAppStateAndValidators exports the state of the application for a genesis // file. func (app *EthermintApp) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs []string, + forZeroHeight bool, + jailAllowedAddrs []string, + modulesToExport []string, ) (servertypes.ExportedApp, error) { // Creates context with current height and checks txs for ctx to be usable by start of next block - ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + ctx := app.NewContextLegacy(true, tmproto.Header{Height: app.LastBlockHeight()}) // We export at last height + 1, because that's the height at which // Tendermint will start InitChain. @@ -56,7 +58,11 @@ func (app *EthermintApp) ExportAppStateAndValidators( } } - genState := app.mm.ExportGenesis(ctx, app.appCodec) + genState,err := app.mm.ExportGenesisForModules(ctx, app.appCodec,modulesToExport) + if err != nil { + return servertypes.ExportedApp{}, err + } + appState, err := json.MarshalIndent(genState, "", " ") if err != nil { return servertypes.ExportedApp{}, err @@ -103,12 +109,22 @@ func (app *EthermintApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAd // withdraw all validator commission app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + app.Logger().Error(err.Error(), "ValOperatorAddress", val.GetOperator()) + } + _, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddr) + if err != nil { + app.Logger().Error(err.Error(), "ValOperatorAddress", val.GetOperator()) + } return false }) // withdraw all delegator rewards - dels := app.StakingKeeper.GetAllDelegations(ctx) + dels,err := app.StakingKeeper.GetAllDelegations(ctx) + if err != nil { + panic(err) + } for _, delegation := range dels { valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { @@ -135,13 +151,25 @@ func (app *EthermintApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAd // reinitialize all validators app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - feePool := app.DistrKeeper.GetFeePool(ctx) + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err) + } + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valAddr) + if err != nil { + panic(err) + } + feePool, err := app.DistrKeeper.FeePool.Get(ctx) + if err != nil { + panic(err) + } feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.SetFeePool(ctx, feePool) - - if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { - return true + err = app.DistrKeeper.FeePool.Set(ctx, feePool) + if err != nil { + panic(err) + } + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valAddr); err != nil { + panic(err) } return false }) @@ -170,61 +198,79 @@ func (app *EthermintApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAd /* Handle staking state. */ // iterate through redelegations, reset creation height - app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + err = app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { for i := range red.Entries { red.Entries[i].CreationHeight = 0 } app.StakingKeeper.SetRedelegation(ctx, red) return false }) + if err != nil { + panic(err) + } // iterate through unbonding delegations, reset creation height - app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + err = app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) return false }) + if err != nil { + panic(err) + } // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) - iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) - - for ; iter.Valid(); iter.Next() { - addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, found := app.StakingKeeper.GetValidator(ctx, addr) - if !found { - return fmt.Errorf("expected validator %s not found", addr) - } - - validator.UnbondingHeight = 0 - if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { - validator.Jailed = true + iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) + + counter := int16(0) + + // Closure to ensure iterator doesn't leak. + func() { + defer iter.Close() + for ; iter.Valid(); iter.Next() { + addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) + validator, err := app.StakingKeeper.GetValidator(ctx, addr) + if err != nil { + panic("expected validator, not found") + } + + validator.UnbondingHeight = 0 + if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { + validator.Jailed = true + } + + if err = app.StakingKeeper.SetValidator(ctx, validator); err != nil { + panic(err) + } + + counter++ } + }() - app.StakingKeeper.SetValidator(ctx, validator) - } - - if err := iter.Close(); err != nil { - return err - } - - if _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx); err != nil { - return err + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + if err != nil { + panic(err) } /* Handle slashing state. */ // reset start height on signing infos - app.SlashingKeeper.IterateValidatorSigningInfos( + err = app.SlashingKeeper.IterateValidatorSigningInfos( ctx, func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + if err = app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info); err != nil { + panic(err) + } return false }, ) + if err != nil { + panic(err) + } return nil } diff --git a/app/upgrades.go b/app/upgrades.go index 9cc2ea33a9..c4f98d4f16 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -16,14 +16,19 @@ package app import ( + "context" + upgradetypes "cosmossdk.io/x/upgrade/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" ) +// RegisterUpgradeHandlers registers the upgrade handler for the +// "integration-test-upgrade" plan. It sets an upgrade handler that +// executes the migrations defined by the module manager using the +// provided configuration and version map. func (app *EthermintApp) RegisterUpgradeHandlers() { planName := "integration-test-upgrade" - app.UpgradeKeeper.SetUpgradeHandler(planName, func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + app.UpgradeKeeper.SetUpgradeHandler(planName, func(ctx context.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { return app.mm.RunMigrations(ctx, app.configurator, fromVM) }) } diff --git a/app/utils.go b/app/utils.go index 826d645e6b..939e149ecc 100644 --- a/app/utils.go +++ b/app/utils.go @@ -19,6 +19,7 @@ import ( "encoding/json" "time" + "cosmossdk.io/math" "cosmossdk.io/simapp" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" @@ -31,14 +32,13 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" types1 "github.com/cometbft/cometbft/proto/tendermint/types" tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/encoding" ) // DefaultConsensusParams defines the default Tendermint consensus params used in @@ -74,8 +74,6 @@ func SetupWithDB(isCheckTx bool, patchGenesis func(*EthermintApp, simapp.Genesis true, map[int64]bool{}, DefaultNodeHome, - 5, - encoding.MakeConfig(ModuleBasics), simtestutil.EmptyAppOptions{}, // NOTE: added as init examines the chain id baseapp.SetChainID("ethermint_9000-1")) @@ -93,7 +91,7 @@ func SetupWithDB(isCheckTx bool, patchGenesis func(*EthermintApp, simapp.Genesis // Initialize the chain app.InitChain( - abci.RequestInitChain{ + &abci.RequestInitChain{ ChainId: "ethermint_9000-1", Validators: []abci.ValidatorUpdate{}, ConsensusParams: DefaultConsensusParams, @@ -121,7 +119,7 @@ func NewTestGenesisState(codec codec.Codec) simapp.GenesisState { acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) balance := banktypes.Balance{ Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), + Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100000000000000))), } genesisState := NewDefaultGenesisState() @@ -156,15 +154,15 @@ func genesisStateWithValSet(codec codec.Codec, genesisState simapp.GenesisState, Jailed: false, Status: stakingtypes.Bonded, Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), + DelegatorShares: math.LegacyOneDec(), Description: stakingtypes.Description{}, UnbondingHeight: int64(0), UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), + Commission: stakingtypes.NewCommission(math.LegacyOneDec(), math.LegacyOneDec(), math.LegacyOneDec()), + MinSelfDelegation: math.ZeroInt(), } validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress().String(), val.Address.String(), math.LegacyOneDec())) } // set validators and delegations stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) diff --git a/client/keys/add.go b/client/keys/add.go index d644a20e43..d499b38718 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -270,9 +270,9 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemonic, outputFormat string) error { switch outputFormat { - case OutputFormatText: + case flags.OutputFormatText: cmd.PrintErrln() - if err := printKeyringRecord(cmd.OutOrStdout(), k, keyring.MkAccKeyOutput, outputFormat); err != nil { + if err := printKeyringRecord(cmd.OutOrStdout(), k, keys.MkAccKeyOutput, outputFormat); err != nil { return err } @@ -284,8 +284,8 @@ func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemo return fmt.Errorf("failed to print mnemonic: %v", err) } } - case OutputFormatJSON: - out, err := keyring.MkAccKeyOutput(k) + case flags.OutputFormatJSON: + out, err := keys.MkAccKeyOutput(k) if err != nil { return err } diff --git a/client/keys/utils.go b/client/keys/utils.go index fc36650224..d85c857ea4 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -22,16 +22,13 @@ import ( "sigs.k8s.io/yaml" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring" ) -// available output formats. -const ( - OutputFormatText = "text" - OutputFormatJSON = "json" -) -type bechKeyOutFn func(k *cryptokeyring.Record) (cryptokeyring.KeyOutput, error) +type bechKeyOutFn func(k *cryptokeyring.Record) (keys.KeyOutput, error) func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKeyOutFn, output string) error { ko, err := bechKeyOut(k) @@ -40,12 +37,12 @@ func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKey } switch output { - case OutputFormatText: - if err := printTextRecords(w, []cryptokeyring.KeyOutput{ko}); err != nil { + case flags.OutputFormatText: + if err := printTextRecords(w, []keys.KeyOutput{ko}); err != nil { return err } - case OutputFormatJSON: + case flags.OutputFormatJSON: out, err := json.Marshal(ko) if err != nil { return err @@ -59,7 +56,7 @@ func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKey return nil } -func printTextRecords(w io.Writer, kos []cryptokeyring.KeyOutput) error { +func printTextRecords(w io.Writer, kos []keys.KeyOutput) error { out, err := yaml.Marshal(&kos) if err != nil { return err diff --git a/client/testnet.go b/client/testnet.go index e788e432d3..bfcd14ddb1 100644 --- a/client/testnet.go +++ b/client/testnet.go @@ -19,12 +19,14 @@ package client import ( "bufio" + "context" "encoding/json" "fmt" "net" "os" "path/filepath" + "cosmossdk.io/math" "github.com/spf13/cobra" tmconfig "github.com/cometbft/cometbft/config" @@ -329,8 +331,8 @@ func initTestnetFiles( valPubKeys[i], sdk.NewCoin(ethermint.AttoPhoton, valTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), - stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), - sdk.ZeroInt(), + stakingtypes.NewCommissionRates(math.LegacyOneDec(), math.LegacyOneDec(), math.LegacyOneDec()), + math.ZeroInt(), ) if err != nil { return err @@ -350,7 +352,7 @@ func initTestnetFiles( WithKeybase(kb). WithTxConfig(clientCtx.TxConfig) - if err := tx.Sign(txFactory, nodeDirName, txBuilder, true); err != nil { + if err := tx.Sign(context.Background(),txFactory, nodeDirName, txBuilder, true); err != nil { return err } @@ -487,12 +489,17 @@ func collectGenFiles( nodeID, valPubKey := nodeIDs[i], valPubKeys[i] initCfg := genutiltypes.NewInitConfig(chainID, gentxsDir, nodeID, valPubKey) - genDoc, err := types.GenesisDocFromFile(nodeConfig.GenesisFile()) + appGenesis, err := genutiltypes.AppGenesisFromFile(nodeConfig.GenesisFile()) if err != nil { return err } - nodeAppState, err := genutil.GenAppStateFromConfig(clientCtx.Codec, clientCtx.TxConfig, nodeConfig, initCfg, *genDoc, genBalIterator, gtypes.DefaultMessageValidator) + nodeAppState, err := genutil.GenAppStateFromConfig( + clientCtx.Codec, clientCtx.TxConfig, + nodeConfig, initCfg, appGenesis, genBalIterator, + gtypes.DefaultMessageValidator, + clientCtx.TxConfig.SigningContext().ValidatorAddressCodec(), + ) if err != nil { return err } diff --git a/cmd/config/config.go b/cmd/config/config.go index 06f1623b3c..269ea45ed2 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -16,6 +16,7 @@ package config import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ethermint "github.com/evmos/ethermint/types" @@ -60,11 +61,11 @@ func SetBip44CoinType(config *sdk.Config) { // RegisterDenoms registers the base and display denominations to the SDK. func RegisterDenoms() { - if err := sdk.RegisterDenom(DisplayDenom, sdk.OneDec()); err != nil { + if err := sdk.RegisterDenom(DisplayDenom, math.LegacyOneDec()); err != nil { panic(err) } - if err := sdk.RegisterDenom(ethermint.AttoPhoton, sdk.NewDecWithPrec(1, ethermint.BaseDenomUnit)); err != nil { + if err := sdk.RegisterDenom(ethermint.AttoPhoton, math.LegacyNewDecWithPrec(1, ethermint.BaseDenomUnit)); err != nil { panic(err) } } diff --git a/cmd/ethermintd/genaccounts.go b/cmd/ethermintd/genaccounts.go index 046213b58d..0028a81e9b 100644 --- a/cmd/ethermintd/genaccounts.go +++ b/cmd/ethermintd/genaccounts.go @@ -111,7 +111,10 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa baseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0) if !vestingAmt.IsZero() { - baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) + baseVestingAccount, err := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) + if err != nil { + return err + } if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) || baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) { diff --git a/cmd/ethermintd/main.go b/cmd/ethermintd/main.go index fd9d7e8b21..c2fc9e43e0 100644 --- a/cmd/ethermintd/main.go +++ b/cmd/ethermintd/main.go @@ -18,7 +18,6 @@ package main import ( "os" - "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" sdk "github.com/cosmos/cosmos-sdk/types" @@ -33,13 +32,7 @@ func main() { rootCmd, _ := NewRootCmd() if err := svrcmd.Execute(rootCmd, EnvPrefix, app.DefaultNodeHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: - os.Exit(e.Code) - - default: - os.Exit(1) - } + os.Exit(1) } } diff --git a/cmd/ethermintd/root.go b/cmd/ethermintd/root.go index 5070156260..094d27ba75 100644 --- a/cmd/ethermintd/root.go +++ b/cmd/ethermintd/root.go @@ -17,22 +17,26 @@ package main import ( "errors" + "fmt" "io" "os" "path/filepath" "github.com/spf13/cast" "github.com/spf13/cobra" + "github.com/spf13/viper" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" + tmlog "cosmossdk.io/log" tmcfg "github.com/cometbft/cometbft/config" tmcli "github.com/cometbft/cometbft/libs/cli" - tmlog "github.com/cometbft/cometbft/libs/log" + dbm "github.com/cosmos/cosmos-db" "cosmossdk.io/simapp/params" "cosmossdk.io/store" "cosmossdk.io/store/snapshots" snapshottypes "cosmossdk.io/store/snapshots/types" + storetypes "cosmossdk.io/store/types" rosettacmd "cosmossdk.io/tools/rosetta/cmd" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -46,7 +50,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/genutil" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" @@ -54,8 +57,6 @@ import ( ethermintclient "github.com/evmos/ethermint/client" "github.com/evmos/ethermint/client/debug" "github.com/evmos/ethermint/crypto/hd" - "github.com/evmos/ethermint/encoding" - "github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/server" servercfg "github.com/evmos/ethermint/server/config" srvflags "github.com/evmos/ethermint/server/flags" @@ -67,12 +68,32 @@ const EnvPrefix = "ETHERMINT" // NewRootCmd creates a new root command for simd. It is called once in the // main function. func NewRootCmd() (*cobra.Command, params.EncodingConfig) { - encodingConfig := encoding.MakeConfig(app.ModuleBasics) + // we "pre"-instantiate the application for getting the injected/configured encoding configuration + initAppOptions := viper.New() + tempDir := tempDir() + initAppOptions.Set(flags.FlagHome, tempDir) + tempApplication := app.NewEthermintApp( + log.NewNopLogger(), + dbm.NewMemDB(), + nil, + true, + map[int64]bool{}, + tempDir, + initAppOptions, + ) + defer func() { + if err := tempApplication.Close(); err != nil { + panic(err) + } + if tempDir != app.DefaultNodeHome { + os.RemoveAll(tempDir) + } + }() initClientCtx := client.Context{}. - WithCodec(encodingConfig.Codec). - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithLegacyAmino(encodingConfig.Amino). + WithCodec(tempApplication.AppCodec()). + WithInterfaceRegistry(tempApplication.InterfaceRegistry()). + WithTxConfig(tempApplication.TxConfig()). + WithLegacyAmino(tempApplication.LegacyAmino()). WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithBroadcastMode(flags.BroadcastSync). @@ -80,8 +101,6 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithKeyringOptions(hd.EthSecp256k1Option()). WithViper(EnvPrefix) - eip712.SetEncodingConfig(encodingConfig) - rootCmd := &cobra.Command{ Use: "ethermintd", Short: "Ethermint Daemon", @@ -121,24 +140,35 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { ethermintclient.ValidateChainID( genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome), ), - genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome, - app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic).GenTxValidator), - genutilcli.MigrateGenesisCmd(), // TODO: shouldn't this include the local app version instead of the SDK? - genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), + genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, + app.DefaultNodeHome, + genutiltypes.DefaultMessageValidator, + tempApplication.TxConfig().SigningContext().ValidatorAddressCodec(), + ), + genutilcli.GenTxCmd( + tempApplication.BasicModuleManager, tempApplication.TxConfig(), + banktypes.GenesisBalancesIterator{}, + app.DefaultNodeHome, + tempApplication.TxConfig().SigningContext().ValidatorAddressCodec(), + ), genutilcli.ValidateGenesisCmd(app.ModuleBasics), AddGenesisAccountCmd(app.DefaultNodeHome), tmcli.NewCompletionCmd(rootCmd, true), ethermintclient.NewTestnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), - config.Cmd(), ) + encodingConfig := params.EncodingConfig{ + InterfaceRegistry: tempApplication.InterfaceRegistry(), + Codec: tempApplication.AppCodec(), + TxConfig: tempApplication.TxConfig(), + Amino: tempApplication.LegacyAmino(), + } a := appCreator{encodingConfig} server.AddCommands(rootCmd, server.NewDefaultStartOptions(a.newApp, app.DefaultNodeHome), a.appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( - rpc.StatusCommand(), queryCommand(), txCommand(), ethermintclient.KeyCommands(app.DefaultNodeHome), @@ -170,14 +200,14 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetAccountCmd(), + rpc.QueryEventForTxCmd(), rpc.ValidatorCommand(), - rpc.BlockCommand(), authcmd.QueryTxsByEventsCmd(), + sdkserver.QueryBlockCmd(), authcmd.QueryTxCmd(), + sdkserver.QueryBlockResultsCmd(), ) - app.ModuleBasics.AddQueryCommands(cmd) cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd @@ -201,7 +231,6 @@ func txCommand() *cobra.Command { authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), - authcmd.GetAuxToFeeCommand(), ) app.ModuleBasics.AddTxCommands(cmd) @@ -216,7 +245,7 @@ type appCreator struct { // newApp is an appCreator func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { - var cache sdk.MultiStorePersistentCache + var cache storetypes.MultiStorePersistentCache if cast.ToBool(appOpts.Get(sdkserver.FlagInterBlockCache)) { cache = store.NewCommitKVStoreCacheManager() @@ -254,8 +283,6 @@ func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer, ethermintApp := app.NewEthermintApp( logger, db, traceStore, true, skipUpgradeHeights, cast.ToString(appOpts.Get(flags.FlagHome)), - cast.ToUint(appOpts.Get(sdkserver.FlagInvCheckPeriod)), - a.encCfg, appOpts, baseapp.SetPruning(pruningOpts), baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(sdkserver.FlagMinGasPrices))), @@ -276,8 +303,14 @@ func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer, // appExport creates a new simapp (optionally at a given height) // and exports state. func (a appCreator) appExport( - logger tmlog.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, - appOpts servertypes.AppOptions, modulesToExport []string, + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + height int64, + forZeroHeight bool, + jailAllowedAddrs []string, + appOpts servertypes.AppOptions, + modulesToExport []string, ) (servertypes.ExportedApp, error) { var ethermintApp *app.EthermintApp homePath, ok := appOpts.Get(flags.FlagHome).(string) @@ -286,14 +319,24 @@ func (a appCreator) appExport( } if height != -1 { - ethermintApp = app.NewEthermintApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1), a.encCfg, appOpts) + ethermintApp = app.NewEthermintApp(logger, db, traceStore, false, map[int64]bool{}, "", appOpts) if err := ethermintApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } } else { - ethermintApp = app.NewEthermintApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), a.encCfg, appOpts) + ethermintApp = app.NewEthermintApp(logger, db, traceStore, true, map[int64]bool{}, "", appOpts) + } + + return ethermintApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) +} + +var tempDir = func() string { + dir, err := os.MkdirTemp("", ".ethermint") + if err != nil { + panic(fmt.Sprintf("failed creating temp directory: %s", err.Error())) } + defer os.RemoveAll(dir) - return ethermintApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) + return dir } diff --git a/docs/architecture/adr-002-evm-hooks.md b/docs/architecture/adr-002-evm-hooks.md index 2326f5820d..0514e345cf 100644 --- a/docs/architecture/adr-002-evm-hooks.md +++ b/docs/architecture/adr-002-evm-hooks.md @@ -157,7 +157,7 @@ func (h BankSendHook) PostTxProcessing(ctx sdk.Context, txHash common.Hash, logs } contract := sdk.AccAddress(log.Address.Bytes()) recipient := sdk.AccAddress(unpacked[0].(common.Address).Bytes()) - coins := sdk.NewCoins(sdk.NewCoin(unpacked[2].(string), sdk.NewIntFromBigInt(unpacked[1].(*big.Int)))) + coins := sdk.NewCoins(sdk.NewCoin(unpacked[2].(string), math.NewIntFromBigInt(unpacked[1].(*big.Int)))) err = h.bankKeeper.SendCoins(ctx, contract, recipient, coins) if err != nil { return err diff --git a/ethereum/eip712/eip712_legacy.go b/ethereum/eip712/eip712_legacy.go index d0f432c192..e093065ee2 100644 --- a/ethereum/eip712/eip712_legacy.go +++ b/ethereum/eip712/eip712_legacy.go @@ -382,7 +382,7 @@ var ( addressType = reflect.TypeOf(common.Address{}) bigIntType = reflect.TypeOf(big.Int{}) cosmIntType = reflect.TypeOf(sdkmath.Int{}) - cosmDecType = reflect.TypeOf(sdk.Dec{}) + cosmDecType = reflect.TypeOf(sdkmath.LegacyDec{}) timeType = reflect.TypeOf(time.Time{}) cosmosAnyType = reflect.TypeOf(&codectypes.Any{}) edType = reflect.TypeOf(ed25519.PubKey{}) diff --git a/ethereum/eip712/eip712_test.go b/ethereum/eip712/eip712_test.go index 33d9473644..cec485833c 100644 --- a/ethereum/eip712/eip712_test.go +++ b/ethereum/eip712/eip712_test.go @@ -164,8 +164,8 @@ func (suite *EIP712TestSuite) TestEIP712() { title: "Succeeds - Standard MsgDelegate", msgs: []sdk.Msg{ stakingtypes.NewMsgDelegate( - suite.createTestAddress(), - sdk.ValAddress(suite.createTestAddress()), + suite.createTestAddress().String(), + sdk.ValAddress(suite.createTestAddress()).String(), suite.makeCoins(suite.denom, math.NewInt(1))[0], ), }, @@ -175,8 +175,8 @@ func (suite *EIP712TestSuite) TestEIP712() { title: "Succeeds - Standard MsgWithdrawDelegationReward", msgs: []sdk.Msg{ distributiontypes.NewMsgWithdrawDelegatorReward( - suite.createTestAddress(), - sdk.ValAddress(suite.createTestAddress()), + suite.createTestAddress().String(), + sdk.ValAddress(suite.createTestAddress()).String(), ), }, expectSuccess: true, @@ -185,13 +185,13 @@ func (suite *EIP712TestSuite) TestEIP712() { title: "Succeeds - Two Single-Signer MsgDelegate", msgs: []sdk.Msg{ stakingtypes.NewMsgDelegate( - params.address, - sdk.ValAddress(suite.createTestAddress()), + params.address.String(), + sdk.ValAddress(suite.createTestAddress()).String(), suite.makeCoins(suite.denom, math.NewInt(1))[0], ), stakingtypes.NewMsgDelegate( - params.address, - sdk.ValAddress(suite.createTestAddress()), + params.address.String(), + sdk.ValAddress(suite.createTestAddress()).String(), suite.makeCoins(suite.denom, math.NewInt(5))[0], ), }, @@ -292,16 +292,10 @@ func (suite *EIP712TestSuite) TestEIP712() { title: "Fails - Single Message / Multi-Signer", msgs: []sdk.Msg{ banktypes.NewMsgMultiSend( - []banktypes.Input{ - banktypes.NewInput( - suite.createTestAddress(), - suite.makeCoins(suite.denom, math.NewInt(50)), - ), - banktypes.NewInput( - suite.createTestAddress(), - suite.makeCoins(suite.denom, math.NewInt(50)), - ), - }, + banktypes.NewInput( + suite.createTestAddress(), + suite.makeCoins(suite.denom, math.NewInt(50)), + ), []banktypes.Output{ banktypes.NewOutput( suite.createTestAddress(), @@ -364,7 +358,9 @@ func (suite *EIP712TestSuite) TestEIP712() { Address: sdk.MustBech32ifyAddressBytes(config.Bech32Prefix, pubKey.Bytes()), } - bz, err := suite.clientCtx.TxConfig.SignModeHandler().GetSignBytes( + bz, err := authsigning.GetSignBytesAdapter( + suite.clientCtx.CmdContext, + suite.clientCtx.TxConfig.SignModeHandler(), signMode, signerData, txBuilder.GetTx(), diff --git a/ethereum/eip712/encoding.go b/ethereum/eip712/encoding.go index 3d9a464366..e16b8085ce 100644 --- a/ethereum/eip712/encoding.go +++ b/ethereum/eip712/encoding.go @@ -190,8 +190,6 @@ func decodeProtobufSignDoc(signDocBytes []byte) (apitypes.TypedData, error) { Gas: authInfo.Fee.GasLimit, } - tip := authInfo.Tip - // WrapTxToTypedData expects the payload as an Amino Sign Doc signBytes := legacytx.StdSignBytes( signDoc.ChainId, @@ -201,7 +199,6 @@ func decodeProtobufSignDoc(signDocBytes []byte) (apitypes.TypedData, error) { *stdFee, msgs, body.Memo, - tip, ) typedData, err := WrapTxToTypedData( @@ -235,16 +232,20 @@ func validatePayloadMessages(msgs []sdk.Msg) error { var msgSigner sdk.AccAddress for i, m := range msgs { - if len(m.GetSigners()) != 1 { + signers, _, err := protoCodec.GetMsgV1Signers(m) + if err != nil { + return fmt.Errorf("error getting signers. %w", err) + } + if len(signers) != 1 { return errors.New("unable to build EIP-712 payload: expect exactly 1 signer") } if i == 0 { - msgSigner = m.GetSigners()[0] + msgSigner = signers[0] continue } - if !msgSigner.Equals(m.GetSigners()[0]) { + if !msgSigner.Equals(sdk.AccAddress(signers[0])) { return errors.New("unable to build EIP-712 payload: multiple signers detected") } } diff --git a/ethereum/eip712/encoding_legacy.go b/ethereum/eip712/encoding_legacy.go index f568b1f68d..a0ef1b00e5 100644 --- a/ethereum/eip712/encoding_legacy.go +++ b/ethereum/eip712/encoding_legacy.go @@ -103,7 +103,11 @@ func legacyDecodeAminoSignDoc(signDocBytes []byte) (apitypes.TypedData, error) { msg := msgs[0] // By convention, the fee payer is the first address in the list of signers. - feePayer := msg.GetSigners()[0] + signers, _, err := protoCodec.GetMsgV1Signers(msg) + if err != nil { + return apitypes.TypedData{}, err + } + feePayer := signers[0] feeDelegation := &FeeDelegationOptions{ FeePayer: feePayer, } @@ -188,13 +192,15 @@ func legacyDecodeProtobufSignDoc(signDocBytes []byte) (apitypes.TypedData, error Gas: authInfo.Fee.GasLimit, } - feePayer := msg.GetSigners()[0] + signers, _, err := protoCodec.GetMsgV1Signers(msg) + if err != nil { + return apitypes.TypedData{}, err + } + feePayer := signers[0] feeDelegation := &FeeDelegationOptions{ FeePayer: feePayer, } - tip := authInfo.Tip - // WrapTxToTypedData expects the payload as an Amino Sign Doc signBytes := legacytx.StdSignBytes( signDoc.ChainId, @@ -204,7 +210,6 @@ func legacyDecodeProtobufSignDoc(signDocBytes []byte) (apitypes.TypedData, error *stdFee, msgs, body.Memo, - tip, ) typedData, err := LegacyWrapTxToTypedData( @@ -237,13 +242,17 @@ func legacyValidatePayloadMessages(msgs []sdk.Msg) error { return err } - if len(m.GetSigners()) != 1 { + signers, _, err := protoCodec.GetMsgV1Signers(m) + if err != nil { + return err + } + if len(signers) != 1 { return errors.New("unable to build EIP-712 payload: expect exactly 1 signer") } if i == 0 { msgType = t - msgSigner = m.GetSigners()[0] + msgSigner = signers[0] continue } @@ -251,7 +260,7 @@ func legacyValidatePayloadMessages(msgs []sdk.Msg) error { return errors.New("unable to build EIP-712 payload: different types of messages detected") } - if !msgSigner.Equals(m.GetSigners()[0]) { + if !msgSigner.Equals(sdk.AccAddress(signers[0])) { return errors.New("unable to build EIP-712 payload: multiple signers detected") } } diff --git a/indexer/kv_indexer.go b/indexer/kv_indexer.go index 48df6cdd4f..cb0c5bab64 100644 --- a/indexer/kv_indexer.go +++ b/indexer/kv_indexer.go @@ -19,10 +19,10 @@ import ( "fmt" errorsmod "cosmossdk.io/errors" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -61,7 +61,7 @@ func NewKVIndexer(db dbm.DB, logger log.Logger, clientCtx client.Context) *KVInd // - Parses eth Tx infos from cosmos-sdk events for every TxResult // - Iterates over all the messages of the Tx // - Builds and stores a indexer.TxResult based on parsed events for every message -func (kv *KVIndexer) IndexBlock(block *tmtypes.Block, txResults []*abci.ResponseDeliverTx) error { +func (kv *KVIndexer) IndexBlock(block *tmtypes.Block, txResults []*abci.ExecTxResult) error { height := block.Header.Height batch := kv.db.NewBatch() diff --git a/indexer/kv_indexer_test.go b/indexer/kv_indexer_test.go index 0efd0c32bc..6977a9513d 100644 --- a/indexer/kv_indexer_test.go +++ b/indexer/kv_indexer_test.go @@ -4,11 +4,11 @@ import ( "math/big" "testing" + tmlog "cosmossdk.io/log" "cosmossdk.io/simapp/params" - dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" - tmlog "github.com/cometbft/cometbft/libs/log" tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/client" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -55,13 +55,13 @@ func TestKVIndexer(t *testing.T) { testCases := []struct { name string block *tmtypes.Block - blockResult []*abci.ResponseDeliverTx + blockResult []*abci.ExecTxResult expSuccess bool }{ { "success, format 1", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -81,7 +81,7 @@ func TestKVIndexer(t *testing.T) { { "success, format 2", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -103,7 +103,7 @@ func TestKVIndexer(t *testing.T) { { "success, exceed block gas limit", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 11, Log: "out of gas in location: block gas meter; gasWanted: 21000", @@ -115,7 +115,7 @@ func TestKVIndexer(t *testing.T) { { "fail, failed eth tx", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 15, Log: "nonce mismatch", @@ -127,7 +127,7 @@ func TestKVIndexer(t *testing.T) { { "fail, invalid events", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{}, @@ -138,7 +138,7 @@ func TestKVIndexer(t *testing.T) { { "fail, not eth tx", &tmtypes.Block{Header: tmtypes.Header{Height: 1}, Data: tmtypes.Data{Txs: []tmtypes.Tx{txBz2}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{}, diff --git a/rpc/backend/account_info.go b/rpc/backend/account_info.go index 21a483aa51..ea4c130179 100644 --- a/rpc/backend/account_info.go +++ b/rpc/backend/account_info.go @@ -22,6 +22,7 @@ import ( errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" + "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -110,7 +111,7 @@ func (b *Backend) GetProof(address common.Address, storageKeys []string, blockNr } // query account proofs - accountKey := authtypes.AddressStoreKey(sdk.AccAddress(address.Bytes())) + accountKey := bytes.HexBytes(append(authtypes.AddressStoreKeyPrefix, address.Bytes()...)) _, proof, err := b.queryClient.GetProof(clientCtx, authtypes.StoreKey, accountKey) if err != nil { return nil, err diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go index 52b29d0f45..989e710876 100644 --- a/rpc/backend/account_info_test.go +++ b/rpc/backend/account_info_test.go @@ -4,8 +4,8 @@ import ( "fmt" "math/big" + "github.com/cometbft/cometbft/libs/bytes" tmrpcclient "github.com/cometbft/cometbft/rpc/client" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" @@ -142,7 +142,7 @@ func (suite *BackendTestSuite) TestGetProof() { client, bn.Int64(), "store/acc/key", - authtypes.AddressStoreKey(sdk.AccAddress(address1.Bytes())), + bytes.HexBytes(append(authtypes.AddressStoreKeyPrefix, address1.Bytes()...)), tmrpcclient.ABCIQueryOptions{Height: iavlHeight, Prove: true}, ) }, diff --git a/rpc/backend/backend.go b/rpc/backend/backend.go index e73ce8634b..21a07dc8a8 100644 --- a/rpc/backend/backend.go +++ b/rpc/backend/backend.go @@ -20,7 +20,8 @@ import ( "math/big" "time" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + "cosmossdk.io/math" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -105,7 +106,7 @@ type EVMBackend interface { // Chain Info ChainID() (*hexutil.Big, error) ChainConfig() *params.ChainConfig - GlobalMinGasPrice() (sdk.Dec, error) + GlobalMinGasPrice() (math.LegacyDec, error) BaseFee(blockRes *tmrpctypes.ResultBlockResults) (*big.Int, error) CurrentHeader() *ethtypes.Header PendingTransactions() ([]*sdk.Tx, error) diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index a14b6254e0..9ab037cc0e 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -7,7 +7,7 @@ import ( "path/filepath" "testing" - dbm "github.com/cometbft/cometbft-db" + dbm "github.com/cosmos/cosmos-db" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cosmos/cosmos-sdk/client" diff --git a/rpc/backend/blocks.go b/rpc/backend/blocks.go index 1504fa222d..987edc8fcb 100644 --- a/rpc/backend/blocks.go +++ b/rpc/backend/blocks.go @@ -365,7 +365,7 @@ func (b *Backend) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) // BlockBloom query block bloom filter from block results func (b *Backend) BlockBloom(blockRes *tmrpctypes.ResultBlockResults) (ethtypes.Bloom, error) { - for _, event := range blockRes.EndBlockEvents { + for _, event := range blockRes.FinalizeBlockEvents { if event.Type != evmtypes.EventTypeBlockBloom { continue } diff --git a/rpc/backend/blocks_test.go b/rpc/backend/blocks_test.go index d2a7121ec9..7800b54848 100644 --- a/rpc/backend/blocks_test.go +++ b/rpc/backend/blocks_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" + "cosmossdk.io/math" "github.com/cometbft/cometbft/abci/types" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" tmtypes "github.com/cometbft/cometbft/types" @@ -93,7 +94,7 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { validator sdk.AccAddress tx *evmtypes.MsgEthereumTx txBz []byte - registerMock func(ethrpc.BlockNumber, sdk.Int, sdk.AccAddress, []byte) + registerMock func(ethrpc.BlockNumber, math.Int, sdk.AccAddress, []byte) expNoop bool expPass bool }{ @@ -101,11 +102,11 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { "pass - tendermint block not found", ethrpc.BlockNumber(1), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(blockNum ethrpc.BlockNumber, _ sdk.Int, _ sdk.AccAddress, _ []byte) { + func(blockNum ethrpc.BlockNumber, _ math.Int, _ sdk.AccAddress, _ []byte) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockError(client, height) @@ -117,11 +118,11 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { "pass - block not found (e.g. request block height that is greater than current one)", ethrpc.BlockNumber(1), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(blockNum ethrpc.BlockNumber, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlockNotFound(client, height) @@ -133,11 +134,11 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { "pass - block results error", ethrpc.BlockNumber(1), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(blockNum ethrpc.BlockNumber, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlock(client, height, txBz) @@ -150,11 +151,11 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { "pass - without tx", ethrpc.BlockNumber(1), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(blockNum ethrpc.BlockNumber, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlock(client, height, txBz) @@ -172,11 +173,11 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { "pass - with tx", ethrpc.BlockNumber(1), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), msgEthereumTx, bz, - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(blockNum ethrpc.BlockNumber, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlock(client, height, txBz) @@ -194,7 +195,7 @@ func (suite *BackendTestSuite) TestGetBlockByNumber() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(tc.blockNumber, sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) + tc.registerMock(tc.blockNumber, math.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) block, err := suite.backend.GetBlockByNumber(tc.blockNumber, tc.fullTx) @@ -238,7 +239,7 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { validator sdk.AccAddress tx *evmtypes.MsgEthereumTx txBz []byte - registerMock func(common.Hash, sdk.Int, sdk.AccAddress, []byte) + registerMock func(common.Hash, math.Int, sdk.AccAddress, []byte) expNoop bool expPass bool }{ @@ -246,11 +247,11 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { "fail - tendermint failed to get block", common.BytesToHash(block.Hash()), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(hash common.Hash, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(hash common.Hash, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockByHashError(client, hash, txBz) }, @@ -261,11 +262,11 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { "noop - tendermint blockres not found", common.BytesToHash(block.Hash()), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(hash common.Hash, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(hash common.Hash, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockByHashNotFound(client, hash, txBz) }, @@ -276,11 +277,11 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { "noop - tendermint failed to fetch block result", common.BytesToHash(block.Hash()), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(hash common.Hash, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(hash common.Hash, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlockByHash(client, hash, txBz) @@ -294,11 +295,11 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { "pass - without tx", common.BytesToHash(block.Hash()), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), nil, nil, - func(hash common.Hash, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(hash common.Hash, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlockByHash(client, hash, txBz) @@ -317,11 +318,11 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { "pass - with tx", common.BytesToHash(block.Hash()), true, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), msgEthereumTx, bz, - func(hash common.Hash, baseFee sdk.Int, validator sdk.AccAddress, txBz []byte) { + func(hash common.Hash, baseFee math.Int, validator sdk.AccAddress, txBz []byte) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) resBlock, _ = RegisterBlockByHash(client, hash, txBz) @@ -340,7 +341,7 @@ func (suite *BackendTestSuite) TestGetBlockByHash() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(tc.hash, sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) + tc.registerMock(tc.hash, math.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) block, err := suite.backend.GetBlockByHash(tc.hash, tc.fullTx) @@ -649,7 +650,7 @@ func (suite *BackendTestSuite) TestTendermintBlockResultByNumber() { expBlockRes = &tmrpctypes.ResultBlockResults{ Height: blockNum, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, } }, true, @@ -823,7 +824,7 @@ func (suite *BackendTestSuite) TestBlockBloom() { { "fail - non block bloom event type", &tmrpctypes.ResultBlockResults{ - EndBlockEvents: []types.Event{{Type: evmtypes.EventTypeEthereumTx}}, + FinalizeBlockEvents: []types.Event{{Type: evmtypes.EventTypeEthereumTx}}, }, ethtypes.Bloom{}, false, @@ -831,7 +832,7 @@ func (suite *BackendTestSuite) TestBlockBloom() { { "fail - nonblock bloom attribute key", &tmrpctypes.ResultBlockResults{ - EndBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: evmtypes.EventTypeBlockBloom, Attributes: []types.EventAttribute{ @@ -846,7 +847,7 @@ func (suite *BackendTestSuite) TestBlockBloom() { { "pass - block bloom attribute key", &tmrpctypes.ResultBlockResults{ - EndBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: evmtypes.EventTypeBlockBloom, Attributes: []types.EventAttribute{ @@ -885,22 +886,22 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { resBlock *tmrpctypes.ResultBlock blockRes *tmrpctypes.ResultBlockResults fullTx bool - registerMock func(sdk.Int, sdk.AccAddress, int64) + registerMock func(math.Int, sdk.AccAddress, int64) expTxs bool expPass bool }{ { "pass - block without tx", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(common.Address{}.Bytes()), int64(1), &tmrpctypes.ResultBlock{Block: emptyBlock}, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, false, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccount(queryClient, validator) @@ -921,10 +922,10 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, true, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFeeError(queryClient) RegisterValidatorAccount(queryClient, validator) @@ -937,7 +938,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, { "pass - block with tx - with ValidatorAccount error", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(common.Address{}.Bytes()), int64(1), &tmrpctypes.ResultBlock{ @@ -945,10 +946,10 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, true, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccountError(queryClient) @@ -961,7 +962,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, { "pass - block with tx - with ConsensusParams error - BlockMaxGas defaults to max uint32", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), int64(1), &tmrpctypes.ResultBlock{ @@ -969,10 +970,10 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, true, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccount(queryClient, validator) @@ -985,7 +986,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, { "pass - block with tx - with ShouldIgnoreGasUsed - empty txs", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), int64(1), &tmrpctypes.ResultBlock{ @@ -993,7 +994,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{ + TxsResults: []*types.ExecTxResult{ { Code: 11, GasUsed: 0, @@ -1002,7 +1003,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, }, true, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccount(queryClient, validator) @@ -1015,7 +1016,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, { "pass - block with tx - non fullTx", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), int64(1), &tmrpctypes.ResultBlock{ @@ -1023,10 +1024,10 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, false, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccount(queryClient, validator) @@ -1039,7 +1040,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, { "pass - block with tx", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), sdk.AccAddress(tests.GenerateAddress().Bytes()), int64(1), &tmrpctypes.ResultBlock{ @@ -1047,10 +1048,10 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, true, - func(baseFee sdk.Int, validator sdk.AccAddress, height int64) { + func(baseFee math.Int, validator sdk.AccAddress, height int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) RegisterValidatorAccount(queryClient, validator) @@ -1065,7 +1066,7 @@ func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.height) + tc.registerMock(math.NewIntFromBigInt(tc.baseFee), tc.validator, tc.height) block, err := suite.backend.RPCBlockFromTendermintBlock(tc.resBlock, tc.blockRes, tc.fullTx) @@ -1133,7 +1134,7 @@ func (suite *BackendTestSuite) TestEthMsgsFromTendermintBlock() { Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), }, &tmrpctypes.ResultBlockResults{ - TxsResults: []*types.ResponseDeliverTx{ + TxsResults: []*types.ExecTxResult{ { Code: 1, }, @@ -1147,7 +1148,7 @@ func (suite *BackendTestSuite) TestEthMsgsFromTendermintBlock() { Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), }, &tmrpctypes.ResultBlockResults{ - TxsResults: []*types.ResponseDeliverTx{ + TxsResults: []*types.ExecTxResult{ { Code: 1, Log: ethrpc.ExceedBlockGasLimitError, @@ -1162,7 +1163,7 @@ func (suite *BackendTestSuite) TestEthMsgsFromTendermintBlock() { Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), }, &tmrpctypes.ResultBlockResults{ - TxsResults: []*types.ResponseDeliverTx{ + TxsResults: []*types.ExecTxResult{ { Code: 0, Log: ethrpc.ExceedBlockGasLimitError, @@ -1191,14 +1192,14 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { name string blockNumber ethrpc.BlockNumber baseFee *big.Int - registerMock func(ethrpc.BlockNumber, sdk.Int) + registerMock func(ethrpc.BlockNumber, math.Int) expPass bool }{ { "fail - tendermint client failed to get block", ethrpc.BlockNumber(1), - sdk.NewInt(1).BigInt(), - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockError(client, height) @@ -1208,8 +1209,8 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { { "fail - block not found for height", ethrpc.BlockNumber(1), - sdk.NewInt(1).BigInt(), - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockNotFound(client, height) @@ -1219,8 +1220,8 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { { "fail - block not found for height", ethrpc.BlockNumber(1), - sdk.NewInt(1).BigInt(), - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlock(client, height, nil) @@ -1232,7 +1233,7 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { "pass - without Base Fee, failed to fetch from prunned block", ethrpc.BlockNumber(1), nil, - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlock(client, height, nil) @@ -1246,8 +1247,8 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { { "pass - blockNum = 1, without tx", ethrpc.BlockNumber(1), - sdk.NewInt(1).BigInt(), - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlock(client, height, nil) @@ -1261,8 +1262,8 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { { "pass - blockNum = 1, with tx", ethrpc.BlockNumber(1), - sdk.NewInt(1).BigInt(), - func(blockNum ethrpc.BlockNumber, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee math.Int) { height := blockNum.Int64() client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlock(client, height, bz) @@ -1278,7 +1279,7 @@ func (suite *BackendTestSuite) TestHeaderByNumber() { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(tc.blockNumber, sdk.NewIntFromBigInt(tc.baseFee)) + tc.registerMock(tc.blockNumber, math.NewIntFromBigInt(tc.baseFee)) header, err := suite.backend.HeaderByNumber(tc.blockNumber) if tc.expPass { @@ -1303,14 +1304,14 @@ func (suite *BackendTestSuite) TestHeaderByHash() { name string hash common.Hash baseFee *big.Int - registerMock func(common.Hash, sdk.Int) + registerMock func(common.Hash, math.Int) expPass bool }{ { "fail - tendermint client failed to get block", common.BytesToHash(block.Hash()), - sdk.NewInt(1).BigInt(), - func(hash common.Hash, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(hash common.Hash, baseFee math.Int) { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockByHashError(client, hash, bz) }, @@ -1319,8 +1320,8 @@ func (suite *BackendTestSuite) TestHeaderByHash() { { "fail - block not found for height", common.BytesToHash(block.Hash()), - sdk.NewInt(1).BigInt(), - func(hash common.Hash, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(hash common.Hash, baseFee math.Int) { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockByHashNotFound(client, hash, bz) }, @@ -1329,8 +1330,8 @@ func (suite *BackendTestSuite) TestHeaderByHash() { { "fail - block not found for height", common.BytesToHash(block.Hash()), - sdk.NewInt(1).BigInt(), - func(hash common.Hash, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(hash common.Hash, baseFee math.Int) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockByHash(client, hash, bz) @@ -1342,7 +1343,7 @@ func (suite *BackendTestSuite) TestHeaderByHash() { "pass - without Base Fee, failed to fetch from prunned block", common.BytesToHash(block.Hash()), nil, - func(hash common.Hash, baseFee sdk.Int) { + func(hash common.Hash, baseFee math.Int) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlockByHash(client, hash, bz) @@ -1356,8 +1357,8 @@ func (suite *BackendTestSuite) TestHeaderByHash() { { "pass - blockNum = 1, without tx", common.BytesToHash(emptyBlock.Hash()), - sdk.NewInt(1).BigInt(), - func(hash common.Hash, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(hash common.Hash, baseFee math.Int) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlockByHash(client, hash, nil) @@ -1371,8 +1372,8 @@ func (suite *BackendTestSuite) TestHeaderByHash() { { "pass - with tx", common.BytesToHash(block.Hash()), - sdk.NewInt(1).BigInt(), - func(hash common.Hash, baseFee sdk.Int) { + math.NewInt(1).BigInt(), + func(hash common.Hash, baseFee math.Int) { height := int64(1) client := suite.backend.clientCtx.Client.(*mocks.Client) expResultBlock, _ = RegisterBlockByHash(client, hash, bz) @@ -1388,7 +1389,7 @@ func (suite *BackendTestSuite) TestHeaderByHash() { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(tc.hash, sdk.NewIntFromBigInt(tc.baseFee)) + tc.registerMock(tc.hash, math.NewIntFromBigInt(tc.baseFee)) header, err := suite.backend.HeaderByHash(tc.hash) if tc.expPass { @@ -1446,14 +1447,14 @@ func (suite *BackendTestSuite) TestEthBlockByNumber() { RegisterBlockResults(client, blockNum.Int64()) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) RegisterBaseFee(queryClient, baseFee) }, ethtypes.NewBlock( ethrpc.EthHeaderFromTendermint( emptyBlock.Header, ethtypes.Bloom{}, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), ), []*ethtypes.Transaction{}, nil, @@ -1472,14 +1473,14 @@ func (suite *BackendTestSuite) TestEthBlockByNumber() { RegisterBlockResults(client, blockNum.Int64()) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) RegisterBaseFee(queryClient, baseFee) }, ethtypes.NewBlock( ethrpc.EthHeaderFromTendermint( emptyBlock.Header, ethtypes.Bloom{}, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), ), []*ethtypes.Transaction{msgEthereumTx.AsTransaction()}, nil, @@ -1521,21 +1522,21 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { baseFee *big.Int resBlock *tmrpctypes.ResultBlock blockRes *tmrpctypes.ResultBlockResults - registerMock func(sdk.Int, int64) + registerMock func(math.Int, int64) expEthBlock *ethtypes.Block expPass bool }{ { "pass - block without tx", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), &tmrpctypes.ResultBlock{ Block: emptyBlock, }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, }, - func(baseFee sdk.Int, blockNum int64) { + func(baseFee math.Int, blockNum int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) }, @@ -1543,7 +1544,7 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { ethrpc.EthHeaderFromTendermint( emptyBlock.Header, ethtypes.Bloom{}, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), ), []*ethtypes.Transaction{}, nil, @@ -1554,14 +1555,14 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { }, { "pass - block with tx", - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), &tmrpctypes.ResultBlock{ Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), }, &tmrpctypes.ResultBlockResults{ Height: 1, - TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, - EndBlockEvents: []types.Event{ + TxsResults: []*types.ExecTxResult{{Code: 0, GasUsed: 0}}, + FinalizeBlockEvents: []types.Event{ { Type: evmtypes.EventTypeBlockBloom, Attributes: []types.EventAttribute{ @@ -1570,7 +1571,7 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { }, }, }, - func(baseFee sdk.Int, blockNum int64) { + func(baseFee math.Int, blockNum int64) { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBaseFee(queryClient, baseFee) }, @@ -1578,7 +1579,7 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { ethrpc.EthHeaderFromTendermint( emptyBlock.Header, ethtypes.Bloom{}, - sdk.NewInt(1).BigInt(), + math.NewInt(1).BigInt(), ), []*ethtypes.Transaction{msgEthereumTx.AsTransaction()}, nil, @@ -1591,7 +1592,7 @@ func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { suite.SetupTest() // reset test and queries - tc.registerMock(sdk.NewIntFromBigInt(tc.baseFee), tc.blockRes.Height) + tc.registerMock(math.NewIntFromBigInt(tc.baseFee), tc.blockRes.Height) ethBlock, err := suite.backend.EthBlockFromTendermintBlock(tc.resBlock, tc.blockRes) diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index a3705284ad..15b4ba5a5f 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -5,7 +5,7 @@ import ( "fmt" "math/big" - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/math" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rlp" @@ -18,7 +18,7 @@ import ( func (suite *BackendTestSuite) TestResend() { txNonce := (hexutil.Uint64)(1) - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) gasPrice := new(hexutil.Big) toAddr := tests.GenerateAddress() chainID := (*hexutil.Big)(suite.backend.chainID) @@ -453,7 +453,7 @@ func (suite *BackendTestSuite) TestGasPrice() { RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, defaultGasPrice, true, @@ -469,7 +469,7 @@ func (suite *BackendTestSuite) TestGasPrice() { RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, defaultGasPrice, false, diff --git a/rpc/backend/chain_info.go b/rpc/backend/chain_info.go index 80c5367aca..b368b2baa4 100644 --- a/rpc/backend/chain_info.go +++ b/rpc/backend/chain_info.go @@ -20,6 +20,7 @@ import ( "math/big" "strconv" + "cosmossdk.io/math" rpcclient "github.com/cometbft/cometbft/rpc/client" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -64,10 +65,10 @@ func (b *Backend) ChainConfig() *params.ChainConfig { } // GlobalMinGasPrice returns MinGasPrice param from FeeMarket -func (b *Backend) GlobalMinGasPrice() (sdk.Dec, error) { +func (b *Backend) GlobalMinGasPrice() (math.LegacyDec, error) { res, err := b.queryClient.FeeMarket.Params(b.ctx, &feemarkettypes.QueryParamsRequest{}) if err != nil { - return sdk.ZeroDec(), err + return math.LegacyZeroDec(), err } return res.Params.MinGasPrice, nil } @@ -83,8 +84,8 @@ func (b *Backend) BaseFee(blockRes *tmrpctypes.ResultBlockResults) (*big.Int, er // we can't tell if it's london HF not enabled or the state is pruned, // in either case, we'll fallback to parsing from begin blocker event, // faster to iterate reversely - for i := len(blockRes.BeginBlockEvents) - 1; i >= 0; i-- { - evt := blockRes.BeginBlockEvents[i] + for i := len(blockRes.FinalizeBlockEvents) - 1; i >= 0; i-- { + evt := blockRes.FinalizeBlockEvents[i] if evt.Type == feemarkettypes.EventTypeFeeMarket && len(evt.Attributes) > 0 { baseFee, err := strconv.ParseInt(string(evt.Attributes[0].Value), 10, 64) if err == nil { diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index 222e40d393..cdec8c5a35 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" + "cosmossdk.io/math" "github.com/ethereum/go-ethereum/common/hexutil" ethrpc "github.com/ethereum/go-ethereum/rpc" rpc "github.com/evmos/ethermint/rpc/types" @@ -20,7 +21,7 @@ import ( ) func (suite *BackendTestSuite) TestBaseFee() { - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) testCases := []struct { name string @@ -43,7 +44,7 @@ func (suite *BackendTestSuite) TestBaseFee() { "fail - grpc BaseFee error - with non feemarket block event", &tmrpctypes.ResultBlockResults{ Height: 1, - BeginBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: evmtypes.EventTypeBlockBloom, }, @@ -60,7 +61,7 @@ func (suite *BackendTestSuite) TestBaseFee() { "fail - grpc BaseFee error - with feemarket block event", &tmrpctypes.ResultBlockResults{ Height: 1, - BeginBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: feemarkettypes.EventTypeFeeMarket, }, @@ -77,7 +78,7 @@ func (suite *BackendTestSuite) TestBaseFee() { "fail - grpc BaseFee error - with feemarket block event with wrong attribute value", &tmrpctypes.ResultBlockResults{ Height: 1, - BeginBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: feemarkettypes.EventTypeFeeMarket, Attributes: []types.EventAttribute{ @@ -97,7 +98,7 @@ func (suite *BackendTestSuite) TestBaseFee() { "fail - grpc baseFee error - with feemarket block event with baseFee attribute value", &tmrpctypes.ResultBlockResults{ Height: 1, - BeginBlockEvents: []types.Event{ + FinalizeBlockEvents: []types.Event{ { Type: feemarkettypes.EventTypeFeeMarket, Attributes: []types.EventAttribute{ @@ -288,7 +289,7 @@ func (suite *BackendTestSuite) TestGlobalMinGasPrice() { testCases := []struct { name string registerMock func() - expMinGasPrice sdk.Dec + expMinGasPrice math.LegacyDec expPass bool }{ { @@ -297,7 +298,7 @@ func (suite *BackendTestSuite) TestGlobalMinGasPrice() { feeMarketCleint := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) RegisterFeeMarketParamsError(feeMarketCleint, int64(1)) }, - sdk.ZeroDec(), + math.LegacyZeroDec(), false, }, } @@ -386,7 +387,7 @@ func (suite *BackendTestSuite) TestFeeHistory() { { "fail - Invalid base fee", func(validator sdk.AccAddress) { - // baseFee := sdk.NewInt(1) + // baseFee := math.NewInt(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 @@ -406,7 +407,7 @@ func (suite *BackendTestSuite) TestFeeHistory() { "pass - Valid FeeHistoryResults object", func(validator sdk.AccAddress) { var header metadata.MD - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index f280a074cd..493c7165de 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -180,7 +180,7 @@ func TestRegisterConsensusParams(t *testing.T) { func RegisterBlockResultsWithEventLog(client *mocks.Client, height int64) (*tmrpctypes.ResultBlockResults, error) { res := &tmrpctypes.ResultBlockResults{ Height: height, - TxsResults: []*abci.ResponseDeliverTx{ + TxsResults: []*abci.ExecTxResult{ {Code: 0, GasUsed: 0, Events: []abci.Event{{ Type: evmtypes.EventTypeTxLog, Attributes: []abci.EventAttribute{{ @@ -202,7 +202,7 @@ func RegisterBlockResults( ) (*tmrpctypes.ResultBlockResults, error) { res := &tmrpctypes.ResultBlockResults{ Height: height, - TxsResults: []*abci.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*abci.ExecTxResult{{Code: 0, GasUsed: 0}}, } client.On("BlockResults", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). @@ -223,7 +223,7 @@ func TestRegisterBlockResults(t *testing.T) { res, err := client.BlockResults(rpc.ContextWithHeight(height), &height) expRes := &tmrpctypes.ResultBlockResults{ Height: height, - TxsResults: []*abci.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + TxsResults: []*abci.ExecTxResult{{Code: 0, GasUsed: 0}}, } require.Equal(t, expRes, res) require.NoError(t, err) diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index 00adc0dcbd..d0ce059434 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -7,6 +7,7 @@ import ( "strconv" "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" @@ -157,7 +158,7 @@ func RegisterEstimateGas(queryClient *mocks.EVMQueryClient, args evmtypes.Transa } // BaseFee -func RegisterBaseFee(queryClient *mocks.EVMQueryClient, baseFee sdk.Int) { +func RegisterBaseFee(queryClient *mocks.EVMQueryClient, baseFee math.Int) { queryClient.On("BaseFee", rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}). Return(&evmtypes.QueryBaseFeeResponse{BaseFee: &baseFee}, nil) } @@ -175,7 +176,7 @@ func RegisterBaseFeeDisabled(queryClient *mocks.EVMQueryClient) { } func TestRegisterBaseFee(t *testing.T) { - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) queryClient := mocks.NewEVMQueryClient(t) RegisterBaseFee(queryClient, baseFee) res, err := queryClient.BaseFee(rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}) diff --git a/rpc/backend/mocks/client.go b/rpc/backend/mocks/client.go index 491222463e..3bd437159a 100644 --- a/rpc/backend/mocks/client.go +++ b/rpc/backend/mocks/client.go @@ -10,7 +10,7 @@ import ( coretypes "github.com/cometbft/cometbft/rpc/core/types" - log "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/libs/log" mock "github.com/stretchr/testify/mock" diff --git a/rpc/backend/node_info.go b/rpc/backend/node_info.go index 2737c84a2c..ea0d97c72f 100644 --- a/rpc/backend/node_info.go +++ b/rpc/backend/node_info.go @@ -21,6 +21,7 @@ import ( "time" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" tmtypes "github.com/cometbft/cometbft/types" "github.com/cosmos/cosmos-sdk/client/flags" @@ -99,11 +100,6 @@ func (b *Backend) SetEtherbase(etherbase common.Address) bool { withdrawAddr := sdk.AccAddress(etherbase.Bytes()) msg := distributiontypes.NewMsgSetWithdrawAddress(delAddr, withdrawAddr) - if err := msg.ValidateBasic(); err != nil { - b.logger.Debug("tx failed basic validation", "error", err.Error()) - return false - } - // Assemble transaction from fields builder, ok := b.clientCtx.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) if !ok { @@ -160,7 +156,7 @@ func (b *Backend) SetEtherbase(etherbase common.Address) bool { return false } - if err := tx.Sign(txFactory, keyInfo.Name, builder, false); err != nil { + if err := tx.Sign(b.clientCtx.CmdContext, txFactory, keyInfo.Name, builder, false); err != nil { b.logger.Debug("failed to sign tx", "error", err.Error()) return false } @@ -286,7 +282,7 @@ func (b *Backend) SetGasPrice(gasPrice hexutil.Big) bool { unit = minGasPrices[0].Denom } - c := sdk.NewDecCoin(unit, sdk.NewIntFromBigInt(gasPrice.ToInt())) + c := sdk.NewDecCoin(unit, math.NewIntFromBigInt(gasPrice.ToInt())) appConf.SetMinGasPrices(sdk.DecCoins{c}) sdkconfig.WriteConfigFile(b.clientCtx.Viper.ConfigFileUsed(), appConf) diff --git a/rpc/backend/node_info_test.go b/rpc/backend/node_info_test.go index 56f1551c3e..900cd749a8 100644 --- a/rpc/backend/node_info_test.go +++ b/rpc/backend/node_info_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" + "cosmossdk.io/math" tmrpcclient "github.com/cometbft/cometbft/rpc/client" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -254,7 +255,7 @@ func (suite *BackendTestSuite) TestSetEtherbase() { RegisterStatus(client) RegisterValidatorAccount(queryClient, suite.acc) RegisterParams(queryClient, &header, 1) - c := sdk.NewDecCoin("aphoton", sdk.NewIntFromBigInt(big.NewInt(1))) + c := sdk.NewDecCoin("aphoton", math.NewIntFromBigInt(big.NewInt(1))) suite.backend.cfg.SetMinGasPrices(sdk.DecCoins{c}) delAddr, _ := suite.backend.GetCoinbase() // account, _ := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, delAddr) @@ -279,7 +280,7 @@ func (suite *BackendTestSuite) TestSetEtherbase() { // queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) // RegisterStatus(client) // RegisterValidatorAccount(queryClient, suite.acc) - // c := sdk.NewDecCoin("aphoton", sdk.NewIntFromBigInt(big.NewInt(1))) + // c := sdk.NewDecCoin("aphoton", math.NewIntFromBigInt(big.NewInt(1))) // suite.backend.cfg.SetMinGasPrices(sdk.DecCoins{c}) // delAddr, _ := suite.backend.GetCoinbase() // account, _ := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, delAddr) diff --git a/rpc/backend/sign_tx.go b/rpc/backend/sign_tx.go index 0c16da0c34..1727120003 100644 --- a/rpc/backend/sign_tx.go +++ b/rpc/backend/sign_tx.go @@ -23,6 +23,7 @@ import ( errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" @@ -130,7 +131,7 @@ func (b *Backend) Sign(address common.Address, data hexutil.Bytes) (hexutil.Byte } // Sign the requested hash with the wallet - signature, _, err := b.clientCtx.Keyring.SignByAddress(from, data) + signature, _, err := b.clientCtx.Keyring.SignByAddress(from, data, signingtypes.SignMode_SIGN_MODE_TEXTUAL) if err != nil { b.logger.Error("keyring.SignByAddress failed", "address", address.Hex()) return nil, err @@ -156,7 +157,7 @@ func (b *Backend) SignTypedData(address common.Address, typedData apitypes.Typed } // Sign the requested hash with the wallet - signature, _, err := b.clientCtx.Keyring.SignByAddress(from, sigHash) + signature, _, err := b.clientCtx.Keyring.SignByAddress(from, sigHash, signingtypes.SignMode_SIGN_MODE_TEXTUAL) if err != nil { b.logger.Error("keyring.SignByAddress failed", "address", address.Hex()) return nil, err diff --git a/rpc/backend/sign_tx_test.go b/rpc/backend/sign_tx_test.go index eccf9ee131..076cc1628f 100644 --- a/rpc/backend/sign_tx_test.go +++ b/rpc/backend/sign_tx_test.go @@ -3,8 +3,10 @@ package backend import ( "fmt" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/crypto" sdk "github.com/cosmos/cosmos-sdk/types" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -25,7 +27,7 @@ func (suite *BackendTestSuite) TestSendTransaction() { priv, _ := ethsecp256k1.GenerateKey() from := common.BytesToAddress(priv.PubKey().Address().Bytes()) nonce := hexutil.Uint64(1) - baseFee := sdk.NewInt(1) + baseFee := math.NewInt(1) callArgsDefault := evmtypes.TransactionArgs{ From: &from, To: &toAddr, @@ -200,7 +202,7 @@ func (suite *BackendTestSuite) TestSign() { responseBz, err := suite.backend.Sign(tc.fromAddr, tc.inputBz) if tc.expPass { - signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), tc.inputBz) + signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), tc.inputBz, signingtypes.SignMode_SIGN_MODE_TEXTUAL) signature[goethcrypto.RecoveryIDOffset] += 27 suite.Require().NoError(err) suite.Require().Equal((hexutil.Bytes)(signature), responseBz) @@ -249,7 +251,7 @@ func (suite *BackendTestSuite) TestSignTypedData() { if tc.expPass { sigHash, _, err := apitypes.TypedDataAndHash(tc.inputTypedData) - signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), sigHash) + signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), sigHash, signingtypes.SignMode_SIGN_MODE_TEXTUAL) signature[goethcrypto.RecoveryIDOffset] += 27 suite.Require().NoError(err) suite.Require().Equal((hexutil.Bytes)(signature), responseBz) diff --git a/rpc/backend/tracing_test.go b/rpc/backend/tracing_test.go index 613c681687..ea929870f8 100644 --- a/rpc/backend/tracing_test.go +++ b/rpc/backend/tracing_test.go @@ -3,12 +3,12 @@ package backend import ( "fmt" - dbm "github.com/cometbft/cometbft-db" + tmlog "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - tmlog "github.com/cometbft/cometbft/libs/log" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cometbft/cometbft/types" tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/crypto" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -51,7 +51,7 @@ func (suite *BackendTestSuite) TestTraceTransaction() { name string registerMock func() block *types.Block - responseBlock []*abci.ResponseDeliverTx + responseBlock []*abci.ExecTxResult expResult interface{} expPass bool }{ @@ -59,7 +59,7 @@ func (suite *BackendTestSuite) TestTraceTransaction() { "fail - tx not found", func() {}, &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -85,7 +85,7 @@ func (suite *BackendTestSuite) TestTraceTransaction() { RegisterBlockError(client, 1) }, &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -112,7 +112,7 @@ func (suite *BackendTestSuite) TestTraceTransaction() { RegisterTraceTransactionWithPredecessors(queryClient, msgEthereumTx, []*evmtypes.MsgEthereumTx{msgEthereumTx}) }, &types.Block{Header: types.Header{Height: 1, ChainID: ChainID}, Data: types.Data{Txs: []types.Tx{txBz, txBz2}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -152,7 +152,7 @@ func (suite *BackendTestSuite) TestTraceTransaction() { RegisterTraceTransaction(queryClient, msgEthereumTx) }, &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index c8637ce596..936029c5d2 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -4,12 +4,12 @@ import ( "fmt" "math/big" - dbm "github.com/cometbft/cometbft-db" + tmlog "cosmossdk.io/log" + "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" - tmlog "github.com/cometbft/cometbft/libs/log" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cometbft/cometbft/types" - sdk "github.com/cosmos/cosmos-sdk/types" + dbm "github.com/cosmos/cosmos-db" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/evmos/ethermint/indexer" @@ -26,7 +26,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { txBz := suite.signAndEncodeEthTx(msgEthereumTx) block := &types.Block{Header: types.Header{Height: 1, ChainID: "test"}, Data: types.Data{Txs: []types.Tx{txBz}}} - responseDeliver := []*abci.ResponseDeliverTx{ + responseDeliver := []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -92,7 +92,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBlock(client, 1, txBz) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, msgEthereumTx, rpcTransaction, @@ -278,7 +278,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { msgEthTx, bz := suite.buildEthereumTx() defaultBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) - defaultResponseDeliverTx := []*abci.ResponseDeliverTx{ + defaultResponseDeliverTx := []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ @@ -346,7 +346,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { err := suite.backend.indexer.IndexBlock(block, defaultResponseDeliverTx) suite.Require().NoError(err) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, &tmrpctypes.ResultBlock{Block: defaultBlock}, 0, @@ -359,7 +359,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, &tmrpctypes.ResultBlock{Block: defaultBlock}, 0, @@ -422,7 +422,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockNumberAndIndex() { queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterBlock(client, 1, bz) RegisterBlockResults(client, 1) - RegisterBaseFee(queryClient, sdk.NewInt(1)) + RegisterBaseFee(queryClient, math.NewInt(1)) }, 0, 0, @@ -541,7 +541,7 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { registerMock func() tx *evmtypes.MsgEthereumTx block *types.Block - blockResult []*abci.ResponseDeliverTx + blockResult []*abci.ExecTxResult expTxReceipt map[string]interface{} expPass bool }{ @@ -558,7 +558,7 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { }, msgEthereumTx, &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, - []*abci.ResponseDeliverTx{ + []*abci.ExecTxResult{ { Code: 0, Events: []abci.Event{ diff --git a/rpc/backend/utils.go b/rpc/backend/utils.go index 3f4bb4fe9a..061e2581c9 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -33,8 +33,8 @@ import ( "github.com/ethereum/go-ethereum/consensus/misc" ethtypes "github.com/ethereum/go-ethereum/core/types" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cometbft/cometbft/proto/tendermint/crypto" @@ -276,7 +276,7 @@ func ParseTxLogsFromEvent(event abci.Event) ([]*ethtypes.Log, error) { // ShouldIgnoreGasUsed returns true if the gasUsed in result should be ignored // workaround for issue: https://github.com/cosmos/cosmos-sdk/issues/10832 -func ShouldIgnoreGasUsed(res *abci.ResponseDeliverTx) bool { +func ShouldIgnoreGasUsed(res *abci.ExecTxResult) bool { return res.GetCode() == 11 && strings.Contains(res.GetLog(), "no block gas left to run tx: out of gas") } diff --git a/rpc/namespaces/ethereum/debug/api.go b/rpc/namespaces/ethereum/debug/api.go index 9803e36c07..36b775ccc7 100644 --- a/rpc/namespaces/ethereum/debug/api.go +++ b/rpc/namespaces/ethereum/debug/api.go @@ -35,7 +35,7 @@ import ( "github.com/cosmos/cosmos-sdk/server" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/consensus/ethash" diff --git a/rpc/namespaces/ethereum/debug/utils.go b/rpc/namespaces/ethereum/debug/utils.go index 648a6986fd..41675b6176 100644 --- a/rpc/namespaces/ethereum/debug/utils.go +++ b/rpc/namespaces/ethereum/debug/utils.go @@ -22,7 +22,7 @@ import ( "runtime/pprof" "strings" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/server" ) diff --git a/rpc/namespaces/ethereum/eth/api.go b/rpc/namespaces/ethereum/eth/api.go index f1bacf1301..90d79ff336 100644 --- a/rpc/namespaces/ethereum/eth/api.go +++ b/rpc/namespaces/ethereum/eth/api.go @@ -22,7 +22,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" diff --git a/rpc/namespaces/ethereum/eth/filters/api.go b/rpc/namespaces/ethereum/eth/filters/api.go index b547bf7f68..d31c78f74b 100644 --- a/rpc/namespaces/ethereum/eth/filters/api.go +++ b/rpc/namespaces/ethereum/eth/filters/api.go @@ -24,7 +24,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/evmos/ethermint/rpc/types" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" coretypes "github.com/cometbft/cometbft/rpc/core/types" rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" @@ -350,16 +350,16 @@ func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, er return } - data, ok := ev.Data.(tmtypes.EventDataNewBlockHeader) + data, ok := ev.Data.(tmtypes.EventDataNewBlock) if !ok { api.logger.Debug("event data type mismatch", "type", fmt.Sprintf("%T", ev.Data)) continue } - baseFee := types.BaseFeeFromEvents(data.ResultBeginBlock.Events) + baseFee := types.BaseFeeFromEvents(data.ResultFinalizeBlock.Events) // TODO: fetch bloom from events - header := types.EthHeaderFromTendermint(data.Header, ethtypes.Bloom{}, baseFee) + header := types.EthHeaderFromTendermint(data.Block.Header, ethtypes.Bloom{}, baseFee) _ = notifier.Notify(rpcSub.ID, header) case <-rpcSub.Err(): headersSub.Unsubscribe(api.events) diff --git a/rpc/namespaces/ethereum/eth/filters/filter_system.go b/rpc/namespaces/ethereum/eth/filters/filter_system.go index efd04e6858..62be9f2baa 100644 --- a/rpc/namespaces/ethereum/eth/filters/filter_system.go +++ b/rpc/namespaces/ethereum/eth/filters/filter_system.go @@ -23,9 +23,9 @@ import ( "github.com/pkg/errors" - tmjson "github.com/cometbft/cometbft/libs/json" - "github.com/cometbft/cometbft/libs/log" - tmquery "github.com/cometbft/cometbft/libs/pubsub/query" + "cosmossdk.io/log" + cmtjson "github.com/cometbft/cometbft/libs/json" + cmtquery "github.com/cometbft/cometbft/libs/pubsub/query" coretypes "github.com/cometbft/cometbft/rpc/core/types" rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" tmtypes "github.com/cometbft/cometbft/types" @@ -43,7 +43,7 @@ import ( var ( txEvents = tmtypes.QueryForEvent(tmtypes.EventTx).String() - evmEvents = tmquery.MustParse(fmt.Sprintf("%s='%s' AND %s.%s='%s'", + evmEvents = cmtquery.MustCompile(fmt.Sprintf("%s='%s' AND %s.%s='%s'", tmtypes.EventTypeKey, tmtypes.EventTx, sdk.EventTypeMessage, @@ -290,7 +290,7 @@ func (es *EventSystem) consumeEvents() { if rpcResp.Error != nil { time.Sleep(5 * time.Second) continue - } else if err := tmjson.Unmarshal(rpcResp.Result, &ev); err != nil { + } else if err := cmtjson.Unmarshal(rpcResp.Result, &ev); err != nil { es.logger.Error("failed to JSON unmarshal ResponsesCh result event", "error", err.Error()) continue } diff --git a/rpc/namespaces/ethereum/eth/filters/filters.go b/rpc/namespaces/ethereum/eth/filters/filters.go index b45071e0d9..4e8764732e 100644 --- a/rpc/namespaces/ethereum/eth/filters/filters.go +++ b/rpc/namespaces/ethereum/eth/filters/filters.go @@ -24,7 +24,7 @@ import ( "github.com/evmos/ethermint/rpc/backend" "github.com/evmos/ethermint/rpc/types" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/pkg/errors" diff --git a/rpc/namespaces/ethereum/miner/api.go b/rpc/namespaces/ethereum/miner/api.go index 7fc4877408..09f7f692cb 100644 --- a/rpc/namespaces/ethereum/miner/api.go +++ b/rpc/namespaces/ethereum/miner/api.go @@ -21,7 +21,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/evmos/ethermint/rpc/backend" ) diff --git a/rpc/namespaces/ethereum/personal/api.go b/rpc/namespaces/ethereum/personal/api.go index 6c3cdad37e..f2a3614618 100644 --- a/rpc/namespaces/ethereum/personal/api.go +++ b/rpc/namespaces/ethereum/personal/api.go @@ -26,7 +26,7 @@ import ( "github.com/evmos/ethermint/crypto/hd" ethermint "github.com/evmos/ethermint/types" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/rpc/namespaces/ethereum/txpool/api.go b/rpc/namespaces/ethereum/txpool/api.go index ed465a51dd..cee9e885cf 100644 --- a/rpc/namespaces/ethereum/txpool/api.go +++ b/rpc/namespaces/ethereum/txpool/api.go @@ -16,7 +16,7 @@ package txpool import ( - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/ethereum/go-ethereum/common/hexutil" diff --git a/rpc/types/events.go b/rpc/types/events.go index 92e1163241..953191965d 100644 --- a/rpc/types/events.go +++ b/rpc/types/events.go @@ -89,7 +89,7 @@ type ParsedTxs struct { // ParseTxResult parse eth tx infos from cosmos-sdk events. // It supports two event formats, the formats are described in the comments of the format constants. -func ParseTxResult(result *abci.ResponseDeliverTx, tx sdk.Tx) (*ParsedTxs, error) { +func ParseTxResult(result *abci.ExecTxResult, tx sdk.Tx) (*ParsedTxs, error) { format := eventFormatUnknown // the index of current ethereum_tx event in format 1 or the second part of format 2 eventIndex := -1 diff --git a/rpc/types/events_test.go b/rpc/types/events_test.go index 2e869d6dda..2084e5b7eb 100644 --- a/rpc/types/events_test.go +++ b/rpc/types/events_test.go @@ -17,12 +17,12 @@ func TestParseTxResult(t *testing.T) { testCases := []struct { name string - response abci.ResponseDeliverTx + response abci.ExecTxResult expTxs []*ParsedTx // expected parse result, nil means expect error. }{ { "format 1 events", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: "coin_received", Attributes: []abci.EventAttribute{ @@ -78,7 +78,7 @@ func TestParseTxResult(t *testing.T) { }, { "format 2 events", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: "coin_received", Attributes: []abci.EventAttribute{ @@ -121,7 +121,7 @@ func TestParseTxResult(t *testing.T) { }, { "format 1 events, failed", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ @@ -148,7 +148,7 @@ func TestParseTxResult(t *testing.T) { }, { "format 1 events, failed", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ @@ -175,7 +175,7 @@ func TestParseTxResult(t *testing.T) { }, { "format 2 events failed", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ @@ -194,7 +194,7 @@ func TestParseTxResult(t *testing.T) { }, { "format 2 events failed", - abci.ResponseDeliverTx{ + abci.ExecTxResult{ GasUsed: 21000, Events: []abci.Event{ {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ diff --git a/rpc/types/utils.go b/rpc/types/utils.go index d06ad7ba0f..f248bf9302 100644 --- a/rpc/types/utils.go +++ b/rpc/types/utils.go @@ -276,12 +276,12 @@ func CheckTxFee(gasPrice *big.Int, gas uint64, cap float64) error { } // TxExceedBlockGasLimit returns true if the tx exceeds block gas limit. -func TxExceedBlockGasLimit(res *abci.ResponseDeliverTx) bool { +func TxExceedBlockGasLimit(res *abci.ExecTxResult) bool { return strings.Contains(res.Log, ExceedBlockGasLimitError) } // TxSuccessOrExceedsBlockGasLimit returns true if the transaction was successful // or if it failed with an ExceedBlockGasLimit error -func TxSuccessOrExceedsBlockGasLimit(res *abci.ResponseDeliverTx) bool { +func TxSuccessOrExceedsBlockGasLimit(res *abci.ExecTxResult) bool { return res.Code == 0 || TxExceedBlockGasLimit(res) } diff --git a/rpc/websockets.go b/rpc/websockets.go index 059f8749ae..135b349924 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -37,7 +37,7 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" tmtypes "github.com/cometbft/cometbft/types" diff --git a/server/config/config.go b/server/config/config.go index 212f7c16fd..2c23d0bfa4 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -26,11 +26,16 @@ import ( "github.com/cometbft/cometbft/libs/strings" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/tools/rosetta" "github.com/cosmos/cosmos-sdk/server/config" errortypes "github.com/cosmos/cosmos-sdk/types/errors" ) const ( + // ServerStartTime defines the time duration that the server need to stay running after startup + // for the startup be considered successful + ServerStartTime = 5 * time.Second + // DefaultGRPCAddress is the default address the gRPC server binds to. DefaultGRPCAddress = "0.0.0.0:9900" @@ -82,11 +87,12 @@ var evmTracers = []string{"json", "markdown", "struct", "access_list"} // Config defines the server's top level configuration. It includes the default app config // from the SDK as well as the EVM configuration to enable the JSON-RPC APIs. type Config struct { - config.Config + config.Config `mapstructure:",squash"` EVM EVMConfig `mapstructure:"evm"` JSONRPC JSONRPCConfig `mapstructure:"json-rpc"` TLS TLSConfig `mapstructure:"tls"` + Rosetta RosettaConfig `mapstructure:"rosetta"` } // EVMConfig defines the application configuration values for the EVM. @@ -148,6 +154,13 @@ type TLSConfig struct { KeyPath string `mapstructure:"key-path"` } +// RosettaConfig defines configuration for the Rosetta server. +type RosettaConfig struct { + rosetta.Config + // Enable defines if the Rosetta server should be enabled. + Enable bool `mapstructure:"enable"` +} + // AppConfig helps to override default appConfig template and configs. // return "", nil if no custom configuration is required for the application. func AppConfig(denom string) (string, interface{}) { diff --git a/server/indexer_cmd.go b/server/indexer_cmd.go index 2d19489232..96f37a5170 100644 --- a/server/indexer_cmd.go +++ b/server/indexer_cmd.go @@ -20,9 +20,9 @@ import ( "github.com/spf13/cobra" - tmnode "github.com/cometbft/cometbft/node" + cmtconfig "github.com/cometbft/cometbft/config" sm "github.com/cometbft/cometbft/state" - tmstore "github.com/cometbft/cometbft/store" + cmtstore "github.com/cometbft/cometbft/store" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/evmos/ethermint/indexer" @@ -63,13 +63,13 @@ func NewIndexTxCmd() *cobra.Command { idxer := indexer.NewKVIndexer(idxDB, logger.With("module", "evmindex"), clientCtx) // open local tendermint db, because the local rpc won't be available. - tmdb, err := tmnode.DefaultDBProvider(&tmnode.DBContext{ID: "blockstore", Config: cfg}) + tmdb, err := cmtconfig.DefaultDBProvider(&cmtconfig.DBContext{ID: "blockstore", Config: cfg}) if err != nil { return err } - blockStore := tmstore.NewBlockStore(tmdb) + blockStore := cmtstore.NewBlockStore(tmdb) - stateDB, err := tmnode.DefaultDBProvider(&tmnode.DBContext{ID: "state", Config: cfg}) + stateDB, err := cmtconfig.DefaultDBProvider(&cmtconfig.DBContext{ID: "state", Config: cfg}) if err != nil { return err } @@ -82,11 +82,11 @@ func NewIndexTxCmd() *cobra.Command { if blk == nil { return fmt.Errorf("block not found %d", height) } - resBlk, err := stateStore.LoadABCIResponses(height) + resBlk, err := stateStore.LoadFinalizeBlockResponse(height) if err != nil { return err } - if err := idxer.IndexBlock(blk, resBlk.DeliverTxs); err != nil { + if err := idxer.IndexBlock(blk, resBlk.TxResults); err != nil { return err } fmt.Println(height) diff --git a/server/json_rpc.go b/server/json_rpc.go index 7934a30c77..a835210f92 100644 --- a/server/json_rpc.go +++ b/server/json_rpc.go @@ -24,12 +24,11 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/types" ethlog "github.com/ethereum/go-ethereum/log" ethrpc "github.com/ethereum/go-ethereum/rpc" "github.com/evmos/ethermint/rpc" - "github.com/evmos/ethermint/server/config" + svrconfig "github.com/evmos/ethermint/server/config" ethermint "github.com/evmos/ethermint/types" ) @@ -38,7 +37,7 @@ func StartJSONRPC(ctx *server.Context, clientCtx client.Context, tmRPCAddr, tmEndpoint string, - config *config.Config, + config *svrconfig.Config, indexer ethermint.EVMTxIndexer, ) (*http.Server, chan struct{}, error) { tmWsClient := ConnectTmWS(tmRPCAddr, tmEndpoint, ctx.Logger) @@ -115,7 +114,7 @@ func StartJSONRPC(ctx *server.Context, case err := <-errCh: ctx.Logger.Error("failed to boot JSON-RPC server", "error", err.Error()) return nil, nil, err - case <-time.After(types.ServerStartTime): // assume JSON RPC server started successfully + case <-time.After(svrconfig.ServerStartTime): // assume JSON RPC server started successfully } ctx.Logger.Info("Starting JSON WebSocket server", "address", config.JSONRPC.WsAddress) diff --git a/server/start.go b/server/start.go index 1672552285..1b627d4add 100644 --- a/server/start.go +++ b/server/start.go @@ -29,36 +29,36 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/telemetry" + "golang.org/x/sync/errgroup" "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - dbm "github.com/cometbft/cometbft-db" abciserver "github.com/cometbft/cometbft/abci/server" tcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" - tmos "github.com/cometbft/cometbft/libs/os" + cmtcfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" pvm "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/proxy" rpcclient "github.com/cometbft/cometbft/rpc/client" "github.com/cometbft/cometbft/rpc/client/local" - - "cosmossdk.io/tools/rosetta" - crgserver "cosmossdk.io/tools/rosetta/lib/server" + dbm "github.com/cosmos/cosmos-db" ethmetricsexp "github.com/ethereum/go-ethereum/metrics/exp" errorsmod "cosmossdk.io/errors" pruningtypes "cosmossdk.io/store/pruning/types" + "cosmossdk.io/tools/rosetta" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" + servercmtlog "github.com/cosmos/cosmos-sdk/server/log" "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -156,13 +156,14 @@ which accepts a path for the resulting pprof file. serverCtx.Logger.Info("starting ABCI with Tendermint") // amino is needed here for backwards compatibility of REST routes - err = startInProcess(serverCtx, clientCtx, opts) - errCode, ok := err.(server.ErrorCode) - if !ok { + if err := startInProcess(serverCtx, clientCtx, opts); err != nil { return err } - serverCtx.Logger.Debug(fmt.Sprintf("received quit signal: %d", errCode.Code)) + serverCtx.Logger.Debug("received quit signal") + if err != nil { + serverCtx.Logger.Error(fmt.Sprintf("error on quit: %s", err.Error())) + } return nil }, } @@ -190,7 +191,6 @@ which accepts a path for the resulting pprof file. cmd.Flags().Bool(srvflags.GRPCEnable, true, "Define if the gRPC server should be enabled") cmd.Flags().String(srvflags.GRPCAddress, serverconfig.DefaultGRPCAddress, "the gRPC server address to listen on") cmd.Flags().Bool(srvflags.GRPCWebEnable, true, "Define if the gRPC-Web server should be enabled. (Note: gRPC must also be enabled.)") - cmd.Flags().String(srvflags.GRPCWebAddress, serverconfig.DefaultGRPCWebAddress, "The gRPC-Web server address to listen on") cmd.Flags().Bool(srvflags.RPCEnable, false, "Defines if Cosmos-sdk REST server should be enabled") cmd.Flags().Bool(srvflags.EnabledUnsafeCors, false, "Defines if CORS should be enabled (unsafe - use it at your own risk)") @@ -226,38 +226,38 @@ which accepts a path for the resulting pprof file. return cmd } -func startStandAlone(ctx *server.Context, opts StartOptions) error { - addr := ctx.Viper.GetString(srvflags.Address) - transport := ctx.Viper.GetString(srvflags.Transport) - home := ctx.Viper.GetString(flags.FlagHome) +func startStandAlone(svrCtx *server.Context, opts StartOptions) error { + addr := svrCtx.Viper.GetString(srvflags.Address) + transport := svrCtx.Viper.GetString(srvflags.Transport) + home := svrCtx.Viper.GetString(flags.FlagHome) - db, err := opts.DBOpener(ctx.Viper, home, server.GetAppDBBackend(ctx.Viper)) + db, err := opts.DBOpener(svrCtx.Viper, home, server.GetAppDBBackend(svrCtx.Viper)) if err != nil { return err } defer func() { if err := db.Close(); err != nil { - ctx.Logger.Error("error closing db", "error", err.Error()) + svrCtx.Logger.Error("error closing db", "error", err.Error()) } }() - traceWriterFile := ctx.Viper.GetString(srvflags.TraceStore) + traceWriterFile := svrCtx.Viper.GetString(srvflags.TraceStore) traceWriter, err := openTraceWriter(traceWriterFile) if err != nil { return err } - app := opts.AppCreator(ctx.Logger, db, traceWriter, ctx.Viper) + app := opts.AppCreator(svrCtx.Logger, db, traceWriter, svrCtx.Viper) - config, err := config.GetConfig(ctx.Viper) + config, err := config.GetConfig(svrCtx.Viper) if err != nil { - ctx.Logger.Error("failed to get server config", "error", err.Error()) + svrCtx.Logger.Error("failed to get server config", "error", err.Error()) return err } if err := config.ValidateBasic(); err != nil { - ctx.Logger.Error("invalid server config", "error", err.Error()) + svrCtx.Logger.Error("invalid server config", "error", err.Error()) return err } @@ -266,38 +266,43 @@ func startStandAlone(ctx *server.Context, opts StartOptions) error { return err } - svr, err := abciserver.NewServer(addr, transport, app) + cmtApp := server.NewCometABCIWrapper(app) + svr, err := abciserver.NewServer(addr, transport, cmtApp) if err != nil { return fmt.Errorf("error creating listener: %v", err) } - svr.SetLogger(ctx.Logger.With("server", "abci")) + svr.SetLogger(servercmtlog.CometLoggerWrapper{Logger: svrCtx.Logger.With("server", "abci")}) - err = svr.Start() - if err != nil { - tmos.Exit(err.Error()) - } + g, ctx := getCtx(svrCtx, false) - defer func() { - if err = svr.Stop(); err != nil { - tmos.Exit(err.Error()) + g.Go(func() error { + if err := svr.Start(); err != nil { + svrCtx.Logger.Error("failed to start out-of-process ABCI server", "err", err) + return err } - }() - // Wait for SIGINT or SIGTERM signal - return server.WaitForQuitSignals() + // Wait for the calling process to be canceled or close the provided context, + // so we can gracefully stop the ABCI server. + <-ctx.Done() + svrCtx.Logger.Info("stopping the ABCI server...") + return svr.Stop() + }) + + return g.Wait() } // legacyAminoCdc is used for the legacy REST API -func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOptions) (err error) { - cfg := ctx.Config +func startInProcess(svrCtx *server.Context, clientCtx client.Context, opts StartOptions) (err error) { + cfg := svrCtx.Config home := cfg.RootDir - logger := ctx.Logger + logger := svrCtx.Logger + g, ctx := getCtx(svrCtx, true) - if cpuProfile := ctx.Viper.GetString(srvflags.CPUProfile); cpuProfile != "" { + if cpuProfile := svrCtx.Viper.GetString(srvflags.CPUProfile); cpuProfile != "" { fp, err := ethdebug.ExpandHome(cpuProfile) if err != nil { - ctx.Logger.Debug("failed to get filepath for the CPU profile file", "error", err.Error()) + svrCtx.Logger.Debug("failed to get filepath for the CPU profile file", "error", err.Error()) return err } @@ -306,13 +311,13 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt return err } - ctx.Logger.Info("starting CPU profiler", "profile", cpuProfile) + svrCtx.Logger.Info("starting CPU profiler", "profile", cpuProfile) if err := pprof.StartCPUProfile(f); err != nil { return err } defer func() { - ctx.Logger.Info("stopping CPU profiler", "profile", cpuProfile) + svrCtx.Logger.Info("stopping CPU profiler", "profile", cpuProfile) pprof.StopCPUProfile() if err := f.Close(); err != nil { logger.Error("failed to close CPU profiler file", "error", err.Error()) @@ -320,7 +325,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt }() } - db, err := opts.DBOpener(ctx.Viper, home, server.GetAppDBBackend(ctx.Viper)) + db, err := opts.DBOpener(svrCtx.Viper, home, server.GetAppDBBackend(svrCtx.Viper)) if err != nil { logger.Error("failed to open DB", "error", err.Error()) return err @@ -328,18 +333,18 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt defer func() { if err := db.Close(); err != nil { - ctx.Logger.With("error", err).Error("error closing db") + svrCtx.Logger.With("error", err).Error("error closing db") } }() - traceWriterFile := ctx.Viper.GetString(srvflags.TraceStore) + traceWriterFile := svrCtx.Viper.GetString(srvflags.TraceStore) traceWriter, err := openTraceWriter(traceWriterFile) if err != nil { logger.Error("failed to open trace writer", "error", err.Error()) return err } - config, err := config.GetConfig(ctx.Viper) + config, err := config.GetConfig(svrCtx.Viper) if err != nil { logger.Error("failed to get server config", "error", err.Error()) return err @@ -350,7 +355,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt return err } - app := opts.AppCreator(ctx.Logger, db, traceWriter, ctx.Viper) + app := opts.AppCreator(svrCtx.Logger, db, traceWriter, svrCtx.Viper) nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile()) if err != nil { @@ -362,7 +367,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt var ( tmNode *node.Node - gRPCOnly = ctx.Viper.GetBool(srvflags.GRPCOnly) + gRPCOnly = svrCtx.Viper.GetBool(srvflags.GRPCOnly) ) if gRPCOnly { @@ -372,15 +377,16 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt } else { logger.Info("starting node with ABCI Tendermint in-process") + cmtApp := server.NewCometABCIWrapper(app) tmNode, err = node.NewNode( cfg, pvm.LoadOrGenFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()), nodeKey, - proxy.NewLocalClientCreator(app), + proxy.NewLocalClientCreator(cmtApp), genDocProvider, - node.DefaultDBProvider, + cmtcfg.DefaultDBProvider, node.DefaultMetricsProvider(cfg.Instrumentation), - ctx.Logger.With("server", "node"), + servercmtlog.CometLoggerWrapper{Logger: svrCtx.Logger.With("server", "node")}, ) if err != nil { logger.Error("failed init node", "error", err.Error()) @@ -407,7 +413,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt app.RegisterTxService(clientCtx) app.RegisterTendermintService(clientCtx) - app.RegisterNodeService(clientCtx) + app.RegisterNodeService(clientCtx, config.Config) } metrics, err := startTelemetry(config) @@ -417,19 +423,19 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt // Enable metrics if JSONRPC is enabled and --metrics is passed // Flag not added in config to avoid user enabling in config without passing in CLI - if config.JSONRPC.Enable && ctx.Viper.GetBool(srvflags.JSONRPCEnableMetrics) { + if config.JSONRPC.Enable && svrCtx.Viper.GetBool(srvflags.JSONRPCEnableMetrics) { ethmetricsexp.Setup(config.JSONRPC.MetricsAddress) } var idxer ethermint.EVMTxIndexer if config.JSONRPC.EnableIndexer { - idxDB, err := OpenIndexerDB(home, server.GetAppDBBackend(ctx.Viper)) + idxDB, err := OpenIndexerDB(home, server.GetAppDBBackend(svrCtx.Viper)) if err != nil { logger.Error("failed to open evm indexer DB", "error", err.Error()) return err } - idxLogger := ctx.Logger.With("indexer", "evm") + idxLogger := svrCtx.Logger.With("indexer", "evm") idxer = indexer.NewKVIndexer(idxDB, idxLogger, clientCtx) // FIXME: tmp solution to make code pass compilation tmClient, ok := clientCtx.Client.(rpcclient.Client) @@ -437,20 +443,11 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt panic("client doesn't implement rpcclient.Client") } indexerService := NewEVMIndexerService(idxer, tmClient) - indexerService.SetLogger(idxLogger) - - errCh := make(chan error) - go func() { - if err := indexerService.Start(); err != nil { - errCh <- err - } - }() + indexerService.SetLogger(servercmtlog.CometLoggerWrapper{Logger: idxLogger}) - select { - case err := <-errCh: - return err - case <-time.After(types.ServerStartTime): // assume server started successfully - } + g.Go(func() error { + return indexerService.Start() + }) } if config.API.Enable || config.JSONRPC.Enable { @@ -462,116 +459,23 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt clientCtx = clientCtx. WithHomeDir(home). WithChainID(genDoc.ChainID) - - // Set `GRPCClient` to `clientCtx` to enjoy concurrent grpc query. - // only use it if gRPC server is enabled. - if config.GRPC.Enable { - _, port, err := net.SplitHostPort(config.GRPC.Address) - if err != nil { - return errorsmod.Wrapf(err, "invalid grpc address %s", config.GRPC.Address) - } - - maxSendMsgSize := config.GRPC.MaxSendMsgSize - if maxSendMsgSize == 0 { - maxSendMsgSize = serverconfig.DefaultGRPCMaxSendMsgSize - } - - maxRecvMsgSize := config.GRPC.MaxRecvMsgSize - if maxRecvMsgSize == 0 { - maxRecvMsgSize = serverconfig.DefaultGRPCMaxRecvMsgSize - } - - grpcAddress := fmt.Sprintf("127.0.0.1:%s", port) - - // If grpc is enabled, configure grpc client for grpc gateway and json-rpc. - grpcClient, err := grpc.Dial( - grpcAddress, - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithDefaultCallOptions( - grpc.ForceCodec(codec.NewProtoCodec(clientCtx.InterfaceRegistry).GRPCCodec()), - grpc.MaxCallRecvMsgSize(maxRecvMsgSize), - grpc.MaxCallSendMsgSize(maxSendMsgSize), - ), - ) - if err != nil { - return err - } - - clientCtx = clientCtx.WithGRPCClient(grpcClient) - ctx.Logger.Debug("gRPC client assigned to client context", "address", grpcAddress) - } } - var apiSrv *api.Server - if config.API.Enable { - apiSrv = api.New(clientCtx, ctx.Logger.With("server", "api")) - app.RegisterAPIRoutes(apiSrv, config.API) - - if config.Telemetry.Enabled { - apiSrv.SetTelemetry(metrics) - } - - errCh := make(chan error) - go func() { - if err := apiSrv.Start(config.Config); err != nil { - errCh <- err - } - }() - - select { - case err := <-errCh: - return err - case <-time.After(types.ServerStartTime): // assume server started successfully - } - - defer apiSrv.Close() + grpcSrv, clientCtx, err := startGrpcServer(ctx, svrCtx, clientCtx, g, config.GRPC, app) + if err != nil { + return err } - - var ( - grpcSrv *grpc.Server - grpcWebSrv *http.Server - ) - - if config.GRPC.Enable { - grpcSrv, err = servergrpc.StartGRPCServer(clientCtx, app, config.GRPC) - if err != nil { - return err - } - defer grpcSrv.Stop() - if config.GRPCWeb.Enable { - grpcWebSrv, err = servergrpc.StartGRPCWeb(grpcSrv, config.Config) - if err != nil { - ctx.Logger.Error("failed to start grpc-web http server", "error", err.Error()) - return err - } - - defer func() { - if err := grpcWebSrv.Close(); err != nil { - logger.Error("failed to close the grpc-web http server", "error", err.Error()) - } - }() - } + if grpcSrv != nil { + defer grpcSrv.GracefulStop() } - var ( - httpSrv *http.Server - httpSrvDone chan struct{} - ) - - if config.JSONRPC.Enable { - genDoc, err := genDocProvider() - if err != nil { - return err - } - - clientCtx := clientCtx.WithChainID(genDoc.ChainID) + apiSrv := startAPIServer(ctx, svrCtx, clientCtx, g, config.Config, app, grpcSrv, metrics) + if apiSrv != nil { + defer apiSrv.Close() + } - tmEndpoint := "/websocket" - tmRPCAddr := cfg.RPC.ListenAddress - httpSrv, httpSrvDone, err = StartJSONRPC(ctx, clientCtx, tmRPCAddr, tmEndpoint, &config, idxer) - if err != nil { - return err - } + clientCtx, httpSrv, httpSrvDone, err := startJSONRPCServer(svrCtx, clientCtx, g, config, genDocProvider, cfg.RPC.ListenAddress, idxer) + if httpSrv != nil { defer func() { shutdownCtx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) defer cancelFn() @@ -591,60 +495,16 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt // we do not need to start Rosetta or handle any Tendermint related processes. if gRPCOnly { // wait for signal capture and gracefully return - return server.WaitForQuitSignals() + // we are guaranteed to be waiting for the "ListenForQuitSignals" goroutine. + return g.Wait() } - var rosettaSrv crgserver.Server - if config.Rosetta.Enable { - offlineMode := config.Rosetta.Offline - - // If GRPC is not enabled rosetta cannot work in online mode, so it works in - // offline mode. - if !config.GRPC.Enable { - offlineMode = true - } - - minGasPrices, err := sdk.ParseDecCoins(config.MinGasPrices) - if err != nil { - ctx.Logger.Error("failed to parse minimum-gas-prices", "error", err.Error()) - return err - } - - conf := &rosetta.Config{ - Blockchain: config.Rosetta.Blockchain, - Network: config.Rosetta.Network, - TendermintRPC: ctx.Config.RPC.ListenAddress, - GRPCEndpoint: config.GRPC.Address, - Addr: config.Rosetta.Address, - Retries: config.Rosetta.Retries, - Offline: offlineMode, - GasToSuggest: config.Rosetta.GasToSuggest, - EnableFeeSuggestion: config.Rosetta.EnableFeeSuggestion, - GasPrices: minGasPrices.Sort(), - Codec: clientCtx.Codec.(*codec.ProtoCodec), - InterfaceRegistry: clientCtx.InterfaceRegistry, - } - - rosettaSrv, err = rosetta.ServerFromConfig(conf) - if err != nil { - return err - } - - errCh := make(chan error) - go func() { - if err := rosettaSrv.Start(); err != nil { - errCh <- err - } - }() - - select { - case err := <-errCh: - return err - case <-time.After(types.ServerStartTime): // assume server started successfully - } + if err := startRosettaServer(svrCtx, clientCtx, g, config); err != nil { + return err } - // Wait for SIGINT or SIGTERM signal - return server.WaitForQuitSignals() + // wait for signal capture and gracefully return + // we are guaranteed to be waiting for the "ListenForQuitSignals" goroutine. + return g.Wait() } func openDB(_ types.AppOptions, rootDir string, backendType dbm.BackendType) (dbm.DB, error) { @@ -677,3 +537,198 @@ func startTelemetry(cfg config.Config) (*telemetry.Metrics, error) { } return telemetry.New(cfg.Telemetry) } + +func getCtx(svrCtx *server.Context, block bool) (*errgroup.Group, context.Context) { + ctx, cancelFn := context.WithCancel(context.Background()) + g, ctx := errgroup.WithContext(ctx) + // listen for quit signals so the calling parent process can gracefully exit + server.ListenForQuitSignals(g, block, cancelFn, svrCtx.Logger) + return g, ctx +} + +// startGrpcServer starts a gRPC server based on the provided configuration. +func startGrpcServer( + ctx context.Context, + svrCtx *server.Context, + clientCtx client.Context, + g *errgroup.Group, + config serverconfig.GRPCConfig, + app types.Application, +) (*grpc.Server, client.Context, error) { + if !config.Enable { + // return grpcServer as nil if gRPC is disabled + return nil, clientCtx, nil + } + _, _, err := net.SplitHostPort(config.Address) + if err != nil { + return nil, clientCtx, errorsmod.Wrapf(err, "invalid grpc address %s", config.Address) + } + + maxSendMsgSize := config.MaxSendMsgSize + if maxSendMsgSize == 0 { + maxSendMsgSize = serverconfig.DefaultGRPCMaxSendMsgSize + } + + maxRecvMsgSize := config.MaxRecvMsgSize + if maxRecvMsgSize == 0 { + maxRecvMsgSize = serverconfig.DefaultGRPCMaxRecvMsgSize + } + + // if gRPC is enabled, configure gRPC client for gRPC gateway and json-rpc + grpcClient, err := grpc.NewClient( + config.Address, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions( + grpc.ForceCodec(codec.NewProtoCodec(clientCtx.InterfaceRegistry).GRPCCodec()), + grpc.MaxCallRecvMsgSize(maxRecvMsgSize), + grpc.MaxCallSendMsgSize(maxSendMsgSize), + ), + ) + if err != nil { + return nil, clientCtx, err + } + // Set `GRPCClient` to `clientCtx` to enjoy concurrent grpc query. + // only use it if gRPC server is enabled. + clientCtx = clientCtx.WithGRPCClient(grpcClient) + svrCtx.Logger.Debug("gRPC client assigned to client context", "address", config.Address) + + grpcSrv, err := servergrpc.NewGRPCServer(clientCtx, app, config) + if err != nil { + return nil, clientCtx, err + } + + // Start the gRPC server in a goroutine. Note, the provided ctx will ensure + // that the server is gracefully shut down. + g.Go(func() error { + return servergrpc.StartGRPCServer(ctx, svrCtx.Logger.With("module", "grpc-server"), config, grpcSrv) + }) + return grpcSrv, clientCtx, nil +} + +// startAPIServer starts an API server based on the provided configuration and application context. +// Parameters: +// - ctx: The context used for managing the server's lifecycle, allowing for graceful shutdown. +// - svrCtx: The server context containing configuration, logger, and other stateful components. +// - clientCtx: The client context, which provides necessary information for API operations. +// - g: An errgroup.Group for managing goroutines and handling errors concurrently. +// - svrCfg: The server configuration that specifies whether the API server is enabled and other settings. +// - app: The application instance that registers API routes. +// - grpcSrv: A pointer to the gRPC server, which may be used by the API server. +// - metrics: A telemetry metrics instance for monitoring API server performance. +func startAPIServer( + ctx context.Context, + svrCtx *server.Context, + clientCtx client.Context, + g *errgroup.Group, + svrCfg serverconfig.Config, + app types.Application, + grpcSrv *grpc.Server, + metrics *telemetry.Metrics, +) *api.Server { + if !svrCfg.API.Enable { + return nil + } + + apiSrv := api.New(clientCtx, svrCtx.Logger.With("server", "api"), grpcSrv) + app.RegisterAPIRoutes(apiSrv, svrCfg.API) + + if svrCfg.Telemetry.Enabled { + apiSrv.SetTelemetry(metrics) + } + + g.Go(func() error { + return apiSrv.Start(ctx, svrCfg) + }) + return apiSrv +} + +// startJSONRPCServer starts a JSON-RPC server based on the provided configuration. +// Parameters: +// - svrCtx: The server context containing configuration, logger, and stateful components. +// - clientCtx: The client context, which may be updated with additional chain information. +// - g: An errgroup.Group to manage concurrent goroutines and error handling. +// - config: The server configuration that specifies whether the JSON-RPC server is enabled and other settings. +// - genDocProvider: A function that provides the Genesis document, used to retrieve the chain ID. +// - cmtRPCAddr: The address of the CometBFT RPC server for WebSocket connections. +// - idxer: The EVM transaction indexer for indexing transactions. +func startJSONRPCServer( + svrCtx *server.Context, + clientCtx client.Context, + g *errgroup.Group, + config config.Config, + genDocProvider node.GenesisDocProvider, + cmtRPCAddr string, + idxer ethermint.EVMTxIndexer, +) (ctx client.Context, httpSrv *http.Server, httpSrvDone chan struct{}, err error) { + ctx = clientCtx + if !config.JSONRPC.Enable { + return + } + + genDoc, err := genDocProvider() + if err != nil { + return ctx, httpSrv, httpSrvDone, err + } + + ctx = clientCtx.WithChainID(genDoc.ChainID) + cmtEndpoint := "/websocket" + g.Go(func() error { + httpSrv, httpSrvDone, err = StartJSONRPC(svrCtx, clientCtx, cmtRPCAddr, cmtEndpoint, &config, idxer) + return err + }) + return +} + +// startRosettaServer starts a Rosetta API server based on the provided configuration. +// Parameters: +// - svrCtx: The server context containing configuration and logging utilities. +// - clientCtx: The client context, which includes the codec and interface registry for the Rosetta server. +// - g: An errgroup.Group to manage goroutines and handle errors concurrently. +// - config: The main server configuration, including Rosetta and gRPC settings. +func startRosettaServer( + svrCtx *server.Context, + clientCtx client.Context, + g *errgroup.Group, + config config.Config, +) error { + if !config.Rosetta.Enable { + return nil + } + + offlineMode := config.Rosetta.Offline + + // If GRPC is not enabled rosetta cannot work in online mode, so it works in + // offline mode. + if !config.GRPC.Enable { + offlineMode = true + } + + minGasPrices, err := sdk.ParseDecCoins(config.MinGasPrices) + if err != nil { + svrCtx.Logger.Error("failed to parse minimum-gas-prices", "error", err.Error()) + return err + } + + conf := &rosetta.Config{ + Blockchain: config.Rosetta.Blockchain, + Network: config.Rosetta.Network, + TendermintRPC: svrCtx.Config.RPC.ListenAddress, + GRPCEndpoint: config.GRPC.Address, + Addr: config.Rosetta.Addr, + Retries: config.Rosetta.Retries, + Offline: offlineMode, + GasToSuggest: config.Rosetta.GasToSuggest, + EnableFeeSuggestion: config.Rosetta.EnableFeeSuggestion, + GasPrices: minGasPrices.Sort(), + Codec: clientCtx.Codec.(*codec.ProtoCodec), + InterfaceRegistry: clientCtx.InterfaceRegistry, + } + + rosettaSrv, err := rosetta.ServerFromConfig(conf) + if err != nil { + return err + } + + g.Go(rosettaSrv.Start) + return nil +} diff --git a/server/util.go b/server/util.go index 6b61f61fd3..a2920a2ee8 100644 --- a/server/util.go +++ b/server/util.go @@ -31,7 +31,7 @@ import ( "github.com/cosmos/cosmos-sdk/version" tmcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" - tmlog "github.com/cometbft/cometbft/libs/log" + tmlog "cosmossdk.io/log" rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" ) diff --git a/tests/importer/importer_test.go b/tests/importer/importer_test.go deleted file mode 100644 index 4b6f73f8cd..0000000000 --- a/tests/importer/importer_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package importer - -import ( - "flag" - "fmt" - "io" - "math/big" - "os" - "testing" - "time" - - "github.com/evmos/ethermint/app" - - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - evmkeeper "github.com/evmos/ethermint/x/evm/keeper" - "github.com/evmos/ethermint/x/evm/statedb" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/consensus/ethash" - ethcore "github.com/ethereum/go-ethereum/core" - ethtypes "github.com/ethereum/go-ethereum/core/types" - ethvm "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - ethparams "github.com/ethereum/go-ethereum/params" - ethrlp "github.com/ethereum/go-ethereum/rlp" - - "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmversion "github.com/cometbft/cometbft/proto/tendermint/version" - "github.com/cometbft/cometbft/version" - "github.com/evmos/ethermint/crypto/ethsecp256k1" -) - -var ( - flagBlockchain string - - rewardBig8 = big.NewInt(8) - rewardBig32 = big.NewInt(32) -) - -func init() { - flag.StringVar(&flagBlockchain, "blockchain", "blockchain", "ethereum block export file (blocks to import)") - testing.Init() - flag.Parse() -} - -type ImporterTestSuite struct { - suite.Suite - - app *app.EthermintApp - ctx sdk.Context -} - -// / DoSetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`. -func (suite *ImporterTestSuite) DoSetupTest(t require.TestingT) { - checkTx := false - suite.app = app.Setup(checkTx, nil) - // consensus key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(priv.PubKey().Address()) - suite.ctx = suite.app.BaseApp.NewContext(checkTx, tmproto.Header{ - Height: 1, - ChainID: "ethermint_9000-1", - Time: time.Now().UTC(), - ProposerAddress: consAddress.Bytes(), - Version: tmversion.Consensus{ - Block: version.BlockProtocol, - }, - LastBlockId: tmproto.BlockID{ - Hash: tmhash.Sum([]byte("block_id")), - PartSetHeader: tmproto.PartSetHeader{ - Total: 11, - Hash: tmhash.Sum([]byte("partset_header")), - }, - }, - AppHash: tmhash.Sum([]byte("app")), - DataHash: tmhash.Sum([]byte("data")), - EvidenceHash: tmhash.Sum([]byte("evidence")), - ValidatorsHash: tmhash.Sum([]byte("validators")), - NextValidatorsHash: tmhash.Sum([]byte("next_validators")), - ConsensusHash: tmhash.Sum([]byte("consensus")), - LastResultsHash: tmhash.Sum([]byte("last_result")), - }) -} - -func (suite *ImporterTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) -} - -func TestImporterTestSuite(t *testing.T) { - suite.Run(t, new(ImporterTestSuite)) -} - -func (suite *ImporterTestSuite) TestImportBlocks() { - chainContext := NewChainContext() - chainConfig := ethparams.MainnetChainConfig - vmConfig := ethvm.Config{} - - // open blockchain export file - blockchainInput, err := os.Open(flagBlockchain) - suite.Require().Nil(err) - - defer func() { - err := blockchainInput.Close() - suite.Require().NoError(err) - }() - - stream := ethrlp.NewStream(blockchainInput, 0) - startTime := time.Now() - - var block ethtypes.Block - - for { - err := stream.Decode(&block) - if err == io.EOF { - break - } - - suite.Require().NoError(err, "failed to decode block") - - var ( - usedGas = new(uint64) - gp = new(ethcore.GasPool).AddGas(block.GasLimit()) - ) - header := block.Header() - chainContext.Coinbase = header.Coinbase - - chainContext.SetHeader(block.NumberU64(), header) - tmheader := suite.ctx.BlockHeader() - // fix due to that begin block can't have height 0 - tmheader.Height = int64(block.NumberU64()) + 1 - suite.app.BeginBlock(types.RequestBeginBlock{ - Header: tmheader, - }) - ctx := suite.app.NewContext(false, tmheader) - ctx = ctx.WithBlockHeight(tmheader.Height) - vmdb := statedb.New(ctx, suite.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash().Bytes()))) - - if chainConfig.DAOForkSupport && chainConfig.DAOForkBlock != nil && chainConfig.DAOForkBlock.Cmp(block.Number()) == 0 { - applyDAOHardFork(vmdb) - } - - for _, tx := range block.Transactions() { - - receipt, gas, err := applyTransaction( - ctx, chainConfig, chainContext, nil, gp, suite.app.EvmKeeper, vmdb, header, tx, usedGas, vmConfig, - ) - suite.Require().NoError(err, "failed to apply tx at block %d; tx: %X; gas %d; receipt:%v", block.NumberU64(), tx.Hash(), gas, receipt) - suite.Require().NotNil(receipt) - } - - // apply mining rewards - accumulateRewards(chainConfig, vmdb, header, block.Uncles()) - - // simulate BaseApp EndBlocker commitment - endBR := types.RequestEndBlock{Height: tmheader.Height} - suite.app.EndBlocker(ctx, endBR) - suite.app.Commit() - - // block debugging output - if block.NumberU64() > 0 && block.NumberU64()%1000 == 0 { - fmt.Printf("processed block: %d (time so far: %v)\n", block.NumberU64(), time.Since(startTime)) - } - } -} - -// accumulateRewards credits the coinbase of the given block with the mining -// reward. The total reward consists of the static block reward and rewards for -// included uncles. The coinbase of each uncle block is also rewarded. -func accumulateRewards( - config *ethparams.ChainConfig, vmdb ethvm.StateDB, - header *ethtypes.Header, uncles []*ethtypes.Header, -) { - // select the correct block reward based on chain progression - blockReward := ethash.FrontierBlockReward - if config.IsByzantium(header.Number) { - blockReward = ethash.ByzantiumBlockReward - } - - // accumulate the rewards for the miner and any included uncles - reward := new(big.Int).Set(blockReward) - r := new(big.Int) - - for _, uncle := range uncles { - r.Add(uncle.Number, rewardBig8) - r.Sub(r, header.Number) - r.Mul(r, blockReward) - r.Div(r, rewardBig8) - vmdb.AddBalance(uncle.Coinbase, r) - r.Div(blockReward, rewardBig32) - reward.Add(reward, r) - } - - vmdb.AddBalance(header.Coinbase, reward) -} - -// ApplyDAOHardFork modifies the state database according to the DAO hard-fork -// rules, transferring all balances of a set of DAO accounts to a single refund -// contract. -// Code is pulled from go-ethereum 1.9 because the StateDB interface does not include the -// SetBalance function implementation -// Ref: https://github.com/ethereum/go-ethereum/blob/52f2461774bcb8cdd310f86b4bc501df5b783852/consensus/misc/dao.go#L74 -func applyDAOHardFork(vmdb ethvm.StateDB) { - // Retrieve the contract to refund balances into - if !vmdb.Exist(ethparams.DAORefundContract) { - vmdb.CreateAccount(ethparams.DAORefundContract) - } - - // Move every DAO account and extra-balance account funds into the refund contract - for _, addr := range ethparams.DAODrainList() { - vmdb.AddBalance(ethparams.DAORefundContract, vmdb.GetBalance(addr)) - } -} - -// ApplyTransaction attempts to apply a transaction to the given state database -// and uses the input parameters for its environment. It returns the receipt -// for the transaction, gas used and an error if the transaction failed, -// indicating the block was invalid. -// Function is also pulled from go-ethereum 1.9 because of the incompatible usage -// Ref: https://github.com/ethereum/go-ethereum/blob/52f2461774bcb8cdd310f86b4bc501df5b783852/core/state_processor.go#L88 -func applyTransaction( - ctx sdk.Context, config *ethparams.ChainConfig, bc ethcore.ChainContext, author *common.Address, - gp *ethcore.GasPool, evmKeeper *evmkeeper.Keeper, vmdb *statedb.StateDB, header *ethtypes.Header, - tx *ethtypes.Transaction, usedGas *uint64, cfg ethvm.Config, -) (*ethtypes.Receipt, uint64, error) { - msg, err := tx.AsMessage(ethtypes.MakeSigner(config, header.Number), sdk.ZeroInt().BigInt()) - if err != nil { - return nil, 0, err - } - - // Create a new context to be used in the EVM environment - blockCtx := ethcore.NewEVMBlockContext(header, bc, author) - txCtx := ethcore.NewEVMTxContext(msg) - - // Create a new environment which holds all relevant information - // about the transaction and calling mechanisms. - vmenv := ethvm.NewEVM(blockCtx, txCtx, vmdb, config, cfg) - - // Apply the transaction to the current state (included in the env) - execResult, err := ethcore.ApplyMessage(vmenv, msg, gp) - if err != nil { - // NOTE: ignore vm execution error (eg: tx out of gas at block 51169) as we care only about state transition errors - return ðtypes.Receipt{}, 0, nil - } - - root := common.Hash{}.Bytes() - *usedGas += execResult.UsedGas - - // Create a new receipt for the transaction, storing the intermediate root and gas used by the tx - // based on the eip phase, we're passing whether the root touch-delete accounts. - receipt := ethtypes.NewReceipt(root, execResult.Failed(), *usedGas) - receipt.TxHash = tx.Hash() - receipt.GasUsed = execResult.UsedGas - - // if the transaction created a contract, store the creation address in the receipt. - if msg.To() == nil { - receipt.ContractAddress = crypto.CreateAddress(vmenv.TxContext.Origin, tx.Nonce()) - } - - // Set the receipt logs and create a bloom for filtering - receipt.Logs = vmdb.Logs() - receipt.Bloom = ethtypes.CreateBloom(ethtypes.Receipts{receipt}) - receipt.BlockHash = header.Hash() - receipt.BlockNumber = header.Number - receipt.TransactionIndex = uint(evmKeeper.GetTxIndexTransient(ctx)) - - return receipt, execResult.UsedGas, err -} diff --git a/tests/signer.go b/tests/signer.go deleted file mode 100644 index 0ec74fab19..0000000000 --- a/tests/signer.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2021 Evmos Foundation -// This file is part of Evmos' Ethermint library. -// -// The Ethermint library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The Ethermint library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the Ethermint library. If not, see https://github.com/evmos/ethermint/blob/main/LICENSE -package tests - -import ( - "fmt" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/evmos/ethermint/crypto/ethsecp256k1" -) - -// NewAddrKey generates an Ethereum address and its corresponding private key. -func NewAddrKey() (common.Address, cryptotypes.PrivKey) { - privkey, _ := ethsecp256k1.GenerateKey() - key, err := privkey.ToECDSA() - if err != nil { - return common.Address{}, nil - } - - addr := crypto.PubkeyToAddress(key.PublicKey) - - return addr, privkey -} - -// GenerateAddress generates an Ethereum address. -func GenerateAddress() common.Address { - addr, _ := NewAddrKey() - return addr -} - -var _ keyring.Signer = &Signer{} - -// Signer defines a type that is used on testing for signing MsgEthereumTx -type Signer struct { - privKey cryptotypes.PrivKey -} - -func NewSigner(sk cryptotypes.PrivKey) keyring.Signer { - return &Signer{ - privKey: sk, - } -} - -// Sign signs the message using the underlying private key -func (s Signer) Sign(_ string, msg []byte) ([]byte, cryptotypes.PubKey, error) { - if s.privKey.Type() != ethsecp256k1.KeyType { - return nil, nil, fmt.Errorf( - "invalid private key type for signing ethereum tx; expected %s, got %s", - ethsecp256k1.KeyType, - s.privKey.Type(), - ) - } - - sig, err := s.privKey.Sign(msg) - if err != nil { - return nil, nil, err - } - - return sig, s.privKey.PubKey(), nil -} - -// SignByAddress sign byte messages with a user key providing the address. -func (s Signer) SignByAddress(address sdk.Address, msg []byte) ([]byte, cryptotypes.PubKey, error) { - signer := sdk.AccAddress(s.privKey.PubKey().Address()) - if !signer.Equals(address) { - return nil, nil, fmt.Errorf("address mismatch: signer %s ≠ given address %s", signer, address) - } - - return s.Sign("", msg) -} diff --git a/testutil/abci.go b/testutil/abci.go index 58a8be5013..e05d2e0182 100644 --- a/testutil/abci.go +++ b/testutil/abci.go @@ -1,13 +1,21 @@ package testutil import ( + "fmt" "time" + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttypes "github.com/cometbft/cometbft/types" tmtypes "github.com/cometbft/cometbft/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil/tx" ) // Commit commits a block at a given time. Reminder: At the end of each @@ -17,32 +25,213 @@ import ( // 3. EndBlock // 4. Commit func Commit(ctx sdk.Context, app *app.EthermintApp, t time.Duration, vs *tmtypes.ValidatorSet) (sdk.Context, error) { + header, err := commit(ctx, app, t, vs) + if err != nil { + return ctx, err + } + + return ctx.WithBlockHeader(header), nil +} + +// CommitAndCreateNewCtx commits a block at a given time creating a ctx with the current settings +// This is useful to keep test settings that could be affected by EndBlockers, e.g. +// setting a baseFee == 0 and expecting this condition to continue after commit +func CommitAndCreateNewCtx(ctx sdk.Context, app *app.EthermintApp, t time.Duration, vs *cmttypes.ValidatorSet) (sdk.Context, error) { + header, err := commit(ctx, app, t, vs) + if err != nil { + return ctx, err + } + + // NewContext function keeps the multistore + // but resets other context fields + // GasMeter is set as InfiniteGasMeter + newCtx := app.BaseApp.NewContextLegacy(false, header) + // set the reseted fields to keep the current ctx settings + newCtx = newCtx.WithMinGasPrices(ctx.MinGasPrices()) + newCtx = newCtx.WithEventManager(ctx.EventManager()) + newCtx = newCtx.WithKVGasConfig(ctx.KVGasConfig()) + newCtx = newCtx.WithTransientKVGasConfig(ctx.TransientKVGasConfig()) + + return newCtx, nil +} + +// DeliverTx delivers a cosmos tx for a given set of msgs +func DeliverTx( + ctx sdk.Context, + appEvmos *app.EthermintApp, + priv cryptotypes.PrivKey, + gasPrice *math.Int, + msgs ...sdk.Msg, +) (abci.ExecTxResult, error) { + txConfig := appEvmos.TxConfig() + tx, err := tx.PrepareCosmosTx( + ctx, + appEvmos, + tx.CosmosTxArgs{ + TxCfg: txConfig, + Priv: priv, + ChainID: ctx.ChainID(), + Gas: 10_000_000, + GasPrice: gasPrice, + Msgs: msgs, + }, + ) + if err != nil { + return abci.ExecTxResult{}, err + } + return BroadcastTxBytes(appEvmos, txConfig.TxEncoder(), tx) +} + +// DeliverEthTx generates and broadcasts a Cosmos Tx populated with MsgEthereumTx messages. +// If a private key is provided, it will attempt to sign all messages with the given private key, +// otherwise, it will assume the messages have already been signed. +// func DeliverEthTx( +// appEvmos *app.EthermintApp, +// priv cryptotypes.PrivKey, +// msgs ...sdk.Msg, +// ) (abci.ExecTxResult, error) { +// txConfig := appEvmos.TxConfig() + +// tx, err := tx.PrepareEthTx(txConfig, priv, msgs...) +// if err != nil { +// return abci.ExecTxResult{}, err +// } +// res, err := BroadcastTxBytes(appEvmos, txConfig.TxEncoder(), tx) +// if err != nil { +// return res, err +// } + +// codec := appEvmos.AppCodec() +// if _, err := CheckEthTxResponse(res, codec); err != nil { +// return res, err +// } +// return res, nil +// } + +// CheckTx checks a cosmos tx for a given set of msgs +func CheckTx( + ctx sdk.Context, + appEvmos *app.EthermintApp, + priv cryptotypes.PrivKey, + gasPrice *math.Int, + msgs ...sdk.Msg, +) (abci.ResponseCheckTx, error) { + txConfig := appEvmos.TxConfig() + + tx, err := tx.PrepareCosmosTx( + ctx, + appEvmos, + tx.CosmosTxArgs{ + TxCfg: txConfig, + Priv: priv, + ChainID: ctx.ChainID(), + GasPrice: gasPrice, + Gas: 10_000_000, + Msgs: msgs, + }, + ) + if err != nil { + return abci.ResponseCheckTx{}, err + } + return checkTxBytes(appEvmos, txConfig.TxEncoder(), tx) +} + +// CheckEthTx checks a Ethereum tx for a given set of msgs +// func CheckEthTx( +// appEvmos *app.EthermintApp, +// priv cryptotypes.PrivKey, +// msgs ...sdk.Msg, +// ) (abci.ResponseCheckTx, error) { +// txConfig := appEvmos.TxConfig() + +// tx, err := tx.PrepareEthTx(txConfig, priv, msgs...) +// if err != nil { +// return abci.ResponseCheckTx{}, err +// } +// return checkTxBytes(appEvmos, txConfig.TxEncoder(), tx) +// } + +// BroadcastTxBytes encodes a transaction and calls DeliverTx on the app. +func BroadcastTxBytes(app *app.EthermintApp, txEncoder sdk.TxEncoder, tx sdk.Tx) (abci.ExecTxResult, error) { + // bz are bytes to be broadcasted over the network + bz, err := txEncoder(tx) + if err != nil { + return abci.ExecTxResult{}, err + } + + req := abci.RequestFinalizeBlock{Txs: [][]byte{bz}} + + res, err := app.BaseApp.FinalizeBlock(&req) + if err != nil { + return abci.ExecTxResult{}, err + } + if len(res.TxResults) != 1 { + return abci.ExecTxResult{}, fmt.Errorf("unexpected transaction results. Expected 1, got: %d", len(res.TxResults)) + } + txRes := res.TxResults[0] + if txRes.Code != 0 { + return abci.ExecTxResult{}, errorsmod.Wrapf(errortypes.ErrInvalidRequest, "log: %s", txRes.Log) + } + + return *txRes, nil +} + +// commit is a private helper function that runs the EndBlocker logic, commits the changes, +// updates the header, runs the BeginBlocker function and returns the updated header +func commit(ctx sdk.Context, app *app.EthermintApp, t time.Duration, vs *cmttypes.ValidatorSet) (tmproto.Header, error) { header := ctx.BlockHeader() + req := abci.RequestFinalizeBlock{Height: header.Height} if vs != nil { - res := app.EndBlock(abci.RequestEndBlock{Height: header.Height}) + res, err := app.FinalizeBlock(&req) + if err != nil { + return header, err + } nextVals, err := applyValSetChanges(vs, res.ValidatorUpdates) if err != nil { - return ctx, err + return header, err } header.ValidatorsHash = vs.Hash() header.NextValidatorsHash = nextVals.Hash() } else { - app.EndBlocker(ctx, abci.RequestEndBlock{Height: header.Height}) + if _, err := app.EndBlocker(ctx); err != nil { + return header, err + } } - _ = app.Commit() + if _, err := app.Commit(); err != nil { + return header, err + } header.Height++ header.Time = header.Time.Add(t) header.AppHash = app.LastCommitID().Hash - app.BeginBlock(abci.RequestBeginBlock{ - Header: header, - }) + if _, err := app.BeginBlocker(ctx); err != nil { + return header, err + } - return ctx.WithBlockHeader(header), nil + return header, nil +} + +// checkTxBytes encodes a transaction and calls checkTx on the app. +func checkTxBytes(app *app.EthermintApp, txEncoder sdk.TxEncoder, tx sdk.Tx) (abci.ResponseCheckTx, error) { + bz, err := txEncoder(tx) + if err != nil { + return abci.ResponseCheckTx{}, err + } + + req := abci.RequestCheckTx{Tx: bz} + res, err := app.BaseApp.CheckTx(&req) + if err != nil { + return abci.ResponseCheckTx{}, err + } + if res.Code != 0 { + return abci.ResponseCheckTx{}, errorsmod.Wrapf(errortypes.ErrInvalidRequest, "log: %s", res.Log) + } + + return *res, nil } // applyValSetChanges takes in tmtypes.ValidatorSet and []abci.ValidatorUpdate and will return a new tmtypes.ValidatorSet which has the diff --git a/testutil/network/network.go b/testutil/network/network.go index 3aef248999..8c20e95074 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -24,30 +24,32 @@ import ( "net/http" "net/url" "os" + "os/signal" "path/filepath" "strings" "sync" + "syscall" "testing" "time" + "cosmossdk.io/log" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" - dbm "github.com/cometbft/cometbft-db" - tmcfg "github.com/cometbft/cometbft/config" - tmflags "github.com/cometbft/cometbft/libs/cli/flags" - "github.com/cometbft/cometbft/libs/log" tmrand "github.com/cometbft/cometbft/libs/rand" "github.com/cometbft/cometbft/node" tmclient "github.com/cometbft/cometbft/rpc/client" + dbm "github.com/cosmos/cosmos-db" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" + "golang.org/x/sync/errgroup" "google.golang.org/grpc" "cosmossdk.io/simapp" "cosmossdk.io/simapp/params" + pruningtypes "cosmossdk.io/store/pruning/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" - pruningtypes "github.com/cosmos/cosmos-sdk/client/pruning" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -74,8 +76,11 @@ import ( "github.com/evmos/ethermint/app" ) -// network lock to only allow one test network at a time -var lock = new(sync.Mutex) +// package-wide network lock to only allow one test network at a time +var ( + lock = new(sync.Mutex) + portPool = make(chan string, 200) +) // AppConstructor defines a function which accepts a network configuration and // creates an ABCI Application to provide to Tendermint. @@ -85,8 +90,8 @@ type AppConstructor = func(val Validator) servertypes.Application func NewAppConstructor(encodingCfg params.EncodingConfig) AppConstructor { return func(val Validator) servertypes.Application { return app.NewEthermintApp( - val.Ctx.Logger, dbm.NewMemDB(), nil, true, make(map[int64]bool), val.Ctx.Config.RootDir, 0, - encodingCfg, + val.Ctx.Logger, dbm.NewMemDB(), nil, true, make(map[int64]bool), + val.Ctx.Config.RootDir, simtestutil.EmptyAppOptions{}, baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), @@ -191,12 +196,15 @@ type ( RPCClient tmclient.Client JSONRPCClient *ethclient.Client + app servertypes.Application tmNode *node.Node api *api.Server grpc *grpc.Server grpcWeb *http.Server jsonrpc *http.Server jsonrpcDone chan struct{} + errGroup *errgroup.Group + cancelFn context.CancelFunc } ) @@ -270,13 +278,13 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { appCfg.Telemetry.GlobalLabels = [][]string{{"chain_id", cfg.ChainID}} ctx := server.NewDefaultContext() - tmCfg := ctx.Config - tmCfg.Consensus.TimeoutCommit = cfg.TimeoutCommit + cmtCfg := ctx.Config + cmtCfg.Consensus.TimeoutCommit = cfg.TimeoutCommit // Only allow the first validator to expose an RPC, API and gRPC // server/client due to Tendermint in-process constraints. apiAddr := "" - tmCfg.RPC.ListenAddress = "" + cmtCfg.RPC.ListenAddress = "" appCfg.GRPC.Enable = false appCfg.GRPCWeb.Enable = false apiListenAddr := "" @@ -284,11 +292,11 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { if cfg.APIAddress != "" { apiListenAddr = cfg.APIAddress } else { - var err error - apiListenAddr, _, err = server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for API server") } + port := <-portPool + apiListenAddr = fmt.Sprintf("tcp://0.0.0.0:%s", port) } appCfg.API.Address = apiListenAddr @@ -299,41 +307,35 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { apiAddr = fmt.Sprintf("http://%s:%s", apiURL.Hostname(), apiURL.Port()) if cfg.RPCAddress != "" { - tmCfg.RPC.ListenAddress = cfg.RPCAddress + cmtCfg.RPC.ListenAddress = cfg.RPCAddress } else { - rpcAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for RPC server") } - tmCfg.RPC.ListenAddress = rpcAddr + port := <-portPool + cmtCfg.RPC.ListenAddress = fmt.Sprintf("tcp://0.0.0.0:%s", port) } if cfg.GRPCAddress != "" { appCfg.GRPC.Address = cfg.GRPCAddress } else { - _, grpcPort, err := server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for GRPC server") } - appCfg.GRPC.Address = fmt.Sprintf("0.0.0.0:%s", grpcPort) + port := <-portPool + appCfg.GRPC.Address = fmt.Sprintf("0.0.0.0:%s", port) } appCfg.GRPC.Enable = true - - _, grpcWebPort, err := server.FreeTCPAddr() - if err != nil { - return nil, err - } - appCfg.GRPCWeb.Address = fmt.Sprintf("0.0.0.0:%s", grpcWebPort) appCfg.GRPCWeb.Enable = true if cfg.JSONRPCAddress != "" { appCfg.JSONRPC.Address = cfg.JSONRPCAddress } else { - _, jsonRPCPort, err := server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for JSON-RPC server") } - appCfg.JSONRPC.Address = fmt.Sprintf("127.0.0.1:%s", jsonRPCPort) + port := <-portPool + appCfg.JSONRPC.Address = fmt.Sprintf("0.0.0.0:%s", port) } appCfg.JSONRPC.Enable = true appCfg.JSONRPC.API = config.GetAPINamespaces() @@ -341,8 +343,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { logger := log.NewNopLogger() if cfg.EnableTMLogging { - logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger, _ = tmflags.ParseLogLevel("info", logger, tmcfg.DefaultLogLevel) + logger = log.NewLogger(os.Stdout) } ctx.Logger = logger @@ -362,25 +363,27 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { return nil, err } - tmCfg.SetRoot(nodeDir) - tmCfg.Moniker = nodeDirName + cmtCfg.SetRoot(nodeDir) + cmtCfg.Moniker = nodeDirName monikers[i] = nodeDirName - proxyAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for Proxy server") } - tmCfg.ProxyApp = proxyAddr + port := <-portPool + proxyAddr := fmt.Sprintf("tcp://0.0.0.0:%s", port) + cmtCfg.ProxyApp = proxyAddr - p2pAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err + if len(portPool) == 0 { + return nil, fmt.Errorf("failed to get port for Proxy server") } - tmCfg.P2P.ListenAddress = p2pAddr - tmCfg.P2P.AddrBookStrict = false - tmCfg.P2P.AllowDuplicateIP = true + port = <-portPool + p2pAddr := fmt.Sprintf("tcp://0.0.0.0:%s", port) + cmtCfg.P2P.ListenAddress = p2pAddr + cmtCfg.P2P.AddrBookStrict = false + cmtCfg.P2P.AllowDuplicateIP = true - nodeID, pubKey, err := genutil.InitializeNodeValidatorFiles(tmCfg) + nodeID, pubKey, err := genutil.InitializeNodeValidatorFiles(cmtCfg) if err != nil { return nil, err } @@ -426,14 +429,14 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { sdk.NewCoin(cfg.BondDenom, cfg.StakingTokens), ) - genFiles = append(genFiles, tmCfg.GenesisFile()) + genFiles = append(genFiles, cmtCfg.GenesisFile()) genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: balances.Sort()}) genAccounts = append(genAccounts, ðermint.EthAccount{ BaseAccount: authtypes.NewBaseAccount(addr, nil, 0, 0), CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), }) - commission, err := sdk.NewDecFromStr("0.5") + commission, err := math.LegacyNewDecFromStr("0.5") if err != nil { return nil, err } @@ -443,8 +446,8 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { valPubKeys[i], sdk.NewCoin(cfg.BondDenom, cfg.BondedTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), - stakingtypes.NewCommissionRates(commission, sdk.OneDec(), sdk.OneDec()), - sdk.ZeroInt(), + stakingtypes.NewCommissionRates(commission, math.LegacyOneDec(), math.LegacyOneDec()), + math.OneInt(), ) if err != nil { return nil, err @@ -473,7 +476,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { WithKeybase(kb). WithTxConfig(cfg.TxConfig) - if err := tx.Sign(txFactory, nodeDirName, txBuilder, true); err != nil { + if err := tx.Sign(context.Background(), txFactory, nodeDirName, txBuilder, true); err != nil { return nil, err } @@ -500,7 +503,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { clientCtx := client.Context{}. WithKeyringDir(clientDir). WithKeyring(kb). - WithHomeDir(tmCfg.RootDir). + WithHomeDir(cmtCfg.RootDir). WithChainID(cfg.ChainID). WithInterfaceRegistry(cfg.InterfaceRegistry). WithCodec(cfg.Codec). @@ -516,8 +519,8 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { NodeID: nodeID, PubKey: pubKey, Moniker: nodeDirName, - RPCAddress: tmCfg.RPC.ListenAddress, - P2PAddress: tmCfg.P2P.ListenAddress, + RPCAddress: cmtCfg.RPC.ListenAddress, + P2PAddress: cmtCfg.P2P.ListenAddress, APIAddress: apiAddr, Address: addr, ValAddress: sdk.ValAddress(addr), @@ -545,7 +548,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { // Ensure we cleanup incase any test was abruptly halted (e.g. SIGINT) as any // defer in a test would not be called. - server.TrapSignal(network.Cleanup) + trapSignal(network.Cleanup) return network, nil } @@ -710,3 +713,27 @@ func centerText(text string, width int) string { return fmt.Sprintf("%s%s%s", leftBuffer, text, rightBuffer) } + +// trapSignal traps SIGINT and SIGTERM and calls os.Exit once a signal is received. +func trapSignal(cleanupFunc func()) { + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + + go func() { + sig := <-sigs + + if cleanupFunc != nil { + cleanupFunc() + } + exitCode := 128 + + switch sig { + case syscall.SIGINT: + exitCode += int(syscall.SIGINT) + case syscall.SIGTERM: + exitCode += int(syscall.SIGTERM) + } + + os.Exit(exitCode) + }() +} diff --git a/testutil/network/util.go b/testutil/network/util.go index 957cf118c0..e0936cbd67 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -16,11 +16,13 @@ package network import ( + "context" "encoding/json" "fmt" "path/filepath" - "time" + "cosmossdk.io/log" + cmtcfg "github.com/cometbft/cometbft/config" tmos "github.com/cometbft/cometbft/libs/os" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" @@ -30,10 +32,12 @@ import ( "github.com/cometbft/cometbft/types" tmtime "github.com/cometbft/cometbft/types/time" "github.com/ethereum/go-ethereum/ethclient" + "golang.org/x/sync/errgroup" + sdkserver "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" - srvtypes "github.com/cosmos/cosmos-sdk/server/types" + servercmtlog "github.com/cosmos/cosmos-sdk/server/log" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" @@ -51,30 +55,32 @@ import ( func startInProcess(cfg Config, val *Validator) error { logger := val.Ctx.Logger - tmCfg := val.Ctx.Config - tmCfg.Instrumentation.Prometheus = false + cmtCfg := val.Ctx.Config + cmtCfg.Instrumentation.Prometheus = false if err := val.AppConfig.ValidateBasic(); err != nil { return err } - nodeKey, err := p2p.LoadOrGenNodeKey(tmCfg.NodeKeyFile()) + nodeKey, err := p2p.LoadOrGenNodeKey(cmtCfg.NodeKeyFile()) if err != nil { return err } app := cfg.AppConstructor(*val) + val.app = app - genDocProvider := node.DefaultGenesisDocProviderFunc(tmCfg) + genDocProvider := node.DefaultGenesisDocProviderFunc(cmtCfg) + cmtApp := sdkserver.NewCometABCIWrapper(app) tmNode, err := node.NewNode( - tmCfg, - pvm.LoadOrGenFilePV(tmCfg.PrivValidatorKeyFile(), tmCfg.PrivValidatorStateFile()), + cmtCfg, + pvm.LoadOrGenFilePV(cmtCfg.PrivValidatorKeyFile(), cmtCfg.PrivValidatorStateFile()), nodeKey, - proxy.NewLocalClientCreator(app), + proxy.NewLocalClientCreator(cmtApp), genDocProvider, - node.DefaultDBProvider, - node.DefaultMetricsProvider(tmCfg.Instrumentation), - logger.With("module", val.Moniker), + cmtcfg.DefaultDBProvider, + node.DefaultMetricsProvider(cmtCfg.Instrumentation), + servercmtlog.CometLoggerWrapper{Logger: logger.With("module", val.Moniker)}, ) if err != nil { return err @@ -100,43 +106,37 @@ func startInProcess(cfg Config, val *Validator) error { // Add the tendermint queries service in the gRPC router. app.RegisterTendermintService(val.ClientCtx) + app.RegisterNodeService(val.ClientCtx, val.AppConfig.Config) } + ctx := context.Background() + ctx, val.cancelFn = context.WithCancel(ctx) + val.errGroup, ctx = errgroup.WithContext(ctx) + if val.AppConfig.API.Enable && val.APIAddress != "" { - apiSrv := api.New(val.ClientCtx, logger.With("module", "api-server")) + apiSrv := api.New(val.ClientCtx, logger.With("module", "api-server"), val.grpc) app.RegisterAPIRoutes(apiSrv, val.AppConfig.API) - errCh := make(chan error) - - go func() { - if err := apiSrv.Start(val.AppConfig.Config); err != nil { - errCh <- err - } - }() - - select { - case err := <-errCh: - return err - case <-time.After(srvtypes.ServerStartTime): // assume server started successfully - } + val.errGroup.Go(func() error { + return apiSrv.Start(ctx, val.AppConfig.Config) + }) val.api = apiSrv } if val.AppConfig.GRPC.Enable { - grpcSrv, err := servergrpc.StartGRPCServer(val.ClientCtx, app, val.AppConfig.GRPC) + grpcSrv, err := servergrpc.NewGRPCServer(val.ClientCtx, app, val.AppConfig.GRPC) if err != nil { return err } - val.grpc = grpcSrv + // Start the gRPC server in a goroutine. Note, the provided ctx will ensure + // that the server is gracefully shut down. + val.errGroup.Go(func() error { + return servergrpc.StartGRPCServer(ctx, logger.With(log.ModuleKey, "grpc-server"), val.AppConfig.GRPC, grpcSrv) + }) - if val.AppConfig.GRPCWeb.Enable { - val.grpcWeb, err = servergrpc.StartGRPCWeb(grpcSrv, val.AppConfig.Config) - if err != nil { - return err - } - } + val.grpc = grpcSrv } if val.AppConfig.JSONRPC.Enable && val.AppConfig.JSONRPC.Address != "" { @@ -167,24 +167,24 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { genTime := tmtime.Now() for i := 0; i < cfg.NumValidators; i++ { - tmCfg := vals[i].Ctx.Config + cmtCfg := vals[i].Ctx.Config nodeDir := filepath.Join(outputDir, vals[i].Moniker, "evmosd") gentxsDir := filepath.Join(outputDir, "gentxs") - tmCfg.Moniker = vals[i].Moniker - tmCfg.SetRoot(nodeDir) + cmtCfg.Moniker = vals[i].Moniker + cmtCfg.SetRoot(nodeDir) initCfg := genutiltypes.NewInitConfig(cfg.ChainID, gentxsDir, vals[i].NodeID, vals[i].PubKey) - genFile := tmCfg.GenesisFile() - genDoc, err := types.GenesisDocFromFile(genFile) + genFile := cmtCfg.GenesisFile() + appGenesis, err := genutiltypes.AppGenesisFromFile(genFile) if err != nil { return err } appState, err := genutil.GenAppStateFromConfig(cfg.Codec, cfg.TxConfig, - tmCfg, initCfg, *genDoc, banktypes.GenesisBalancesIterator{}, gtypes.DefaultMessageValidator) + cmtCfg, initCfg, appGenesis, banktypes.GenesisBalancesIterator{}, gtypes.DefaultMessageValidator, cfg.TxConfig.SigningContext().ValidatorAddressCodec()) if err != nil { return err } diff --git a/testutil/tx/cosmos.go b/testutil/tx/cosmos.go index 1e2ad4e250..91ce574057 100644 --- a/testutil/tx/cosmos.go +++ b/testutil/tx/cosmos.go @@ -31,7 +31,7 @@ import ( var ( feeAmt = math.Pow10(16) - DefaultFee = sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewIntFromUint64(uint64(feeAmt))) + DefaultFee = sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewIntFromUint64(uint64(feeAmt))) ) // CosmosTxArgs contains the params to create a cosmos tx @@ -101,12 +101,17 @@ func signCosmosTx( return nil, err } + signMode, err := authsigning.APISignModeToInternal(args.TxCfg.SignModeHandler().DefaultMode()) + if err != nil { + return nil, err + } + // First round: we gather all the signer infos. We use the "set empty // signature" hack to do that. sigV2 := signing.SignatureV2{ PubKey: args.Priv.PubKey(), Data: &signing.SingleSignatureData{ - SignMode: args.TxCfg.SignModeHandler().DefaultMode(), + SignMode: signMode, Signature: nil, }, Sequence: seq, @@ -126,7 +131,8 @@ func signCosmosTx( Sequence: seq, } sigV2, err = tx.SignWithPrivKey( - args.TxCfg.SignModeHandler().DefaultMode(), + ctx, + signMode, signerData, txBuilder, args.Priv, args.TxCfg, seq, diff --git a/testutil/tx/eip712.go b/testutil/tx/eip712.go index 73bb9803fd..93e1fff7f9 100644 --- a/testutil/tx/eip712.go +++ b/testutil/tx/eip712.go @@ -25,11 +25,11 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/crypto" - cryptocodec "github.com/evmos/ethermint/crypto/codec" - + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + "github.com/ethereum/go-ethereum/crypto" + cryptocodec "github.com/evmos/ethermint/crypto/codec" "github.com/evmos/ethermint/ethereum/eip712" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -113,7 +113,7 @@ func PrepareEIP712CosmosTx( fee := legacytx.NewStdFee(txArgs.Gas, txArgs.Fees) //nolint: staticcheck msgs := txArgs.Msgs - data := legacytx.StdSignBytes(ctx.ChainID(), accNumber, nonce, 0, fee, msgs, "", nil) + data := legacytx.StdSignBytes(ctx.ChainID(), accNumber, nonce, 0, fee, msgs, "") typedDataArgs := typedDataArgs{ chainID: chainIDNum, @@ -199,7 +199,7 @@ func signCosmosEIP712Tx( } keyringSigner := NewSigner(priv) - signature, pubKey, err := keyringSigner.SignByAddress(from, sigHash) + signature, pubKey, err := keyringSigner.SignByAddress(from, sigHash, signingtypes.SignMode_SIGN_MODE_DIRECT) if err != nil { return nil, err } diff --git a/testutil/tx/signer.go b/testutil/tx/signer.go index 2d0d6a4417..9bc81063f8 100644 --- a/testutil/tx/signer.go +++ b/testutil/tx/signer.go @@ -21,10 +21,39 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/evmos/ethermint/crypto/ethsecp256k1" ) +// NewAddrKey generates an Ethereum address and its corresponding private key. +func NewAddrKey() (common.Address, *ethsecp256k1.PrivKey) { + privkey, _ := ethsecp256k1.GenerateKey() + key, err := privkey.ToECDSA() + if err != nil { + return common.Address{}, nil + } + + addr := crypto.PubkeyToAddress(key.PublicKey) + + return addr, privkey +} + +// NewAccAddressAndKey generates a private key and its corresponding +// Cosmos SDK address. +func NewAccAddressAndKey() (sdk.AccAddress, *ethsecp256k1.PrivKey) { + addr, privKey := NewAddrKey() + return sdk.AccAddress(addr.Bytes()), privKey +} + +// GenerateAddress generates an Ethereum address. +func GenerateAddress() common.Address { + addr, _ := NewAddrKey() + return addr +} + var _ keyring.Signer = &Signer{} // Signer defines a type that is used on testing for signing MsgEthereumTx @@ -39,7 +68,7 @@ func NewSigner(sk cryptotypes.PrivKey) keyring.Signer { } // Sign signs the message using the underlying private key -func (s Signer) Sign(_ string, msg []byte) ([]byte, cryptotypes.PubKey, error) { +func (s Signer) Sign(_ string, msg []byte, _ signing.SignMode) ([]byte, cryptotypes.PubKey, error) { if s.privKey.Type() != ethsecp256k1.KeyType { return nil, nil, fmt.Errorf( "invalid private key type for signing ethereum tx; expected %s, got %s", @@ -57,11 +86,11 @@ func (s Signer) Sign(_ string, msg []byte) ([]byte, cryptotypes.PubKey, error) { } // SignByAddress sign byte messages with a user key providing the address. -func (s Signer) SignByAddress(address sdk.Address, msg []byte) ([]byte, cryptotypes.PubKey, error) { +func (s Signer) SignByAddress(address sdk.Address, msg []byte, signMode signing.SignMode) ([]byte, cryptotypes.PubKey, error) { signer := sdk.AccAddress(s.privKey.PubKey().Address()) if !signer.Equals(address) { return nil, nil, fmt.Errorf("address mismatch: signer %s ≠ given address %s", signer, address) } - return s.Sign("", msg) + return s.Sign("", msg, signMode) } diff --git a/types/account.go b/types/account.go index a93dcc17ec..65d381b5ab 100644 --- a/types/account.go +++ b/types/account.go @@ -19,6 +19,7 @@ import ( "bytes" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/ethereum/go-ethereum/common" @@ -60,7 +61,7 @@ type EthAccountI interface { // ProtoAccount defines the prototype function for BaseAccount used for an // AccountKeeper. -func ProtoAccount() authtypes.AccountI { +func ProtoAccount() sdk.AccountI { return &EthAccount{ BaseAccount: &authtypes.BaseAccount{}, CodeHash: common.BytesToHash(emptyCodeHash).String(), diff --git a/types/block.go b/types/block.go index ed1eae3391..5d0db44b9e 100644 --- a/types/block.go +++ b/types/block.go @@ -30,7 +30,7 @@ func BlockGasLimit(ctx sdk.Context) uint64 { // Otherwise get from the consensus parameters cp := ctx.ConsensusParams() - if cp == nil || cp.Block == nil { + if cp.Block == nil { return 0 } diff --git a/types/gasmeter.go b/types/gasmeter.go index 342f40a276..bf634708df 100644 --- a/types/gasmeter.go +++ b/types/gasmeter.go @@ -19,7 +19,7 @@ import ( fmt "fmt" math "math" - sdk "github.com/cosmos/cosmos-sdk/types" + storetypes "cosmossdk.io/store/types" ) // ErrorNegativeGasConsumed defines an error thrown when the amount of gas refunded results in a @@ -36,27 +36,27 @@ type ErrorGasOverflow struct { } type infiniteGasMeterWithLimit struct { - consumed sdk.Gas - limit sdk.Gas + consumed storetypes.Gas + limit storetypes.Gas } // NewInfiniteGasMeterWithLimit returns a reference to a new infiniteGasMeter. -func NewInfiniteGasMeterWithLimit(limit sdk.Gas) sdk.GasMeter { +func NewInfiniteGasMeterWithLimit(limit storetypes.Gas) storetypes.GasMeter { return &infiniteGasMeterWithLimit{ consumed: 0, limit: limit, } } -func (g *infiniteGasMeterWithLimit) GasConsumed() sdk.Gas { +func (g *infiniteGasMeterWithLimit) GasConsumed() storetypes.Gas { return g.consumed } -func (g *infiniteGasMeterWithLimit) GasConsumedToLimit() sdk.Gas { +func (g *infiniteGasMeterWithLimit) GasConsumedToLimit() storetypes.Gas { return g.consumed } -func (g *infiniteGasMeterWithLimit) Limit() sdk.Gas { +func (g *infiniteGasMeterWithLimit) Limit() storetypes.Gas { return g.limit } @@ -70,7 +70,7 @@ func addUint64Overflow(a, b uint64) (uint64, bool) { return a + b, false } -func (g *infiniteGasMeterWithLimit) ConsumeGas(amount sdk.Gas, descriptor string) { +func (g *infiniteGasMeterWithLimit) ConsumeGas(amount storetypes.Gas, descriptor string) { var overflow bool // TODO: Should we set the consumed field after overflow checking? g.consumed, overflow = addUint64Overflow(g.consumed, amount) @@ -85,7 +85,7 @@ func (g *infiniteGasMeterWithLimit) ConsumeGas(amount sdk.Gas, descriptor string // Use case: This functionality enables refunding gas to the trasaction or block gas pools so that // EVM-compatible chains can fully support the go-ethereum StateDb interface. // See https://github.com/cosmos/cosmos-sdk/pull/9403 for reference. -func (g *infiniteGasMeterWithLimit) RefundGas(amount sdk.Gas, descriptor string) { +func (g *infiniteGasMeterWithLimit) RefundGas(amount storetypes.Gas, descriptor string) { if g.consumed < amount { panic(ErrorNegativeGasConsumed{Descriptor: descriptor}) } @@ -105,6 +105,6 @@ func (g *infiniteGasMeterWithLimit) String() string { return fmt.Sprintf("InfiniteGasMeter:\n consumed: %d", g.consumed) } -func (g *infiniteGasMeterWithLimit) GasRemaining() sdk.Gas { +func (g *infiniteGasMeterWithLimit) GasRemaining() storetypes.Gas { return math.MaxUint64 } diff --git a/types/indexer.go b/types/indexer.go index f27e77fbb8..fb6acbf07c 100644 --- a/types/indexer.go +++ b/types/indexer.go @@ -25,7 +25,7 @@ import ( type EVMTxIndexer interface { // LastIndexedBlock returns -1 if indexer db is empty LastIndexedBlock() (int64, error) - IndexBlock(*tmtypes.Block, []*abci.ResponseDeliverTx) error + IndexBlock(*tmtypes.Block, []*abci.ExecTxResult) error // GetByTxHash returns nil if tx not found. GetByTxHash(common.Hash) (*TxResult, error) diff --git a/types/validation_test.go b/types/validation_test.go index d9b2ecedfc..db55bc155a 100644 --- a/types/validation_test.go +++ b/types/validation_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common" - "github.com/evmos/ethermint/tests" + utiltx "github.com/evmos/ethermint/testutil/tx" "github.com/evmos/ethermint/types" "github.com/stretchr/testify/require" ) @@ -71,7 +71,7 @@ func TestValidateAddress(t *testing.T) { "zero address", common.Address{}.String(), false, }, { - "valid address", tests.GenerateAddress().Hex(), false, + "valid address", utiltx.GenerateAddress().Hex(), false, }, } @@ -102,7 +102,7 @@ func TestValidateNonZeroAddress(t *testing.T) { "zero address", common.Address{}.String(), true, }, { - "valid address", tests.GenerateAddress().Hex(), false, + "valid address", utiltx.GenerateAddress().Hex(), false, }, } diff --git a/x/evm/keeper/integration_test.go b/x/evm/keeper/integration_test.go index 5e98ac85aa..2e49cd1e9c 100644 --- a/x/evm/keeper/integration_test.go +++ b/x/evm/keeper/integration_test.go @@ -21,9 +21,10 @@ import ( "github.com/evmos/ethermint/testutil" "github.com/evmos/ethermint/x/feemarket/types" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" + "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" + dbm "github.com/cosmos/cosmos-db" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -55,7 +56,7 @@ var _ = Describe("Feemarket", func() { // 100_000`. With the fee calculation `Fee = (baseFee + tip) * gasLimit`, // a `minGasPrices = 5_000_000_000` results in `minGlobalFee = // 500_000_000_000_000` - privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), sdk.NewInt(baseFee)) + privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), math.NewInt(baseFee)) }) Context("during CheckTx", func() { @@ -144,7 +145,7 @@ func setupTest(localMinGasPrices string) (*ethsecp256k1.PrivKey, banktypes.MsgSe setupChain(localMinGasPrices) privKey, address := generateKey() - amount, ok := sdk.NewIntFromString("10000000000000000000") + amount, ok := math.NewIntFromString("10000000000000000000") s.Require().True(ok) initBalance := sdk.Coins{sdk.Coin{ Denom: s.denom, @@ -157,7 +158,7 @@ func setupTest(localMinGasPrices string) (*ethsecp256k1.PrivKey, banktypes.MsgSe ToAddress: address.String(), Amount: sdk.Coins{sdk.Coin{ Denom: s.denom, - Amount: sdk.NewInt(10000), + Amount: math.NewInt(10000), }}, } s.Commit() @@ -266,7 +267,7 @@ func prepareEthTx(priv *ethsecp256k1.PrivKey, msgEthereumTx *evmtypes.MsgEthereu s.Require().NoError(err) evmDenom := s.app.EvmKeeper.GetParams(s.ctx).EvmDenom - fees := sdk.Coins{{Denom: evmDenom, Amount: sdk.NewIntFromBigInt(txData.Fee())}} + fees := sdk.Coins{{Denom: evmDenom, Amount: math.NewIntFromBigInt(txData.Fee())}} builder.SetFeeAmount(fees) builder.SetGasLimit(msgEthereumTx.GetGas()) diff --git a/x/evm/keeper/keeper.go b/x/evm/keeper/keeper.go index ca9d9d5a93..3c0a3f9158 100644 --- a/x/evm/keeper/keeper.go +++ b/x/evm/keeper/keeper.go @@ -21,7 +21,7 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/evm/spec/06_hooks.md b/x/evm/spec/06_hooks.md index 9a2b175999..4444562126 100644 --- a/x/evm/spec/06_hooks.md +++ b/x/evm/spec/06_hooks.md @@ -149,7 +149,7 @@ func (k Keeper) PostTxProcessing( // NOTE: assume that if they are burning the token that has been registered as a pair, they want to mint a Cosmos coin // create the corresponding sdk.Coin that is paired with ERC20 - coins := sdk.Coins{{Denom: pair.Denom, Amount: sdk.NewIntFromBigInt(tokens)}} + coins := sdk.Coins{{Denom: pair.Denom, Amount: math.NewIntFromBigInt(tokens)}} // Mint the coin only if ERC20 is external switch pair.ContractOwner { diff --git a/x/evm/types/interfaces.go b/x/evm/types/interfaces.go index 89ba85afe7..a9f0c4145f 100644 --- a/x/evm/types/interfaces.go +++ b/x/evm/types/interfaces.go @@ -16,8 +16,10 @@ package types import ( + context "context" "math/big" + "cosmossdk.io/core/address" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -31,30 +33,31 @@ import ( // AccountKeeper defines the expected account keeper interface type AccountKeeper interface { - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI + NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI GetModuleAddress(moduleName string) sdk.AccAddress - GetAllAccounts(ctx sdk.Context) (accounts []authtypes.AccountI) - IterateAccounts(ctx sdk.Context, cb func(account authtypes.AccountI) bool) - GetSequence(sdk.Context, sdk.AccAddress) (uint64, error) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, account authtypes.AccountI) - RemoveAccount(ctx sdk.Context, account authtypes.AccountI) - GetParams(ctx sdk.Context) (params authtypes.Params) + IterateAccounts(ctx context.Context, cb func(account sdk.AccountI) bool) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + SetAccount(ctx context.Context, account sdk.AccountI) + RemoveAccount(ctx context.Context, account sdk.AccountI) + GetParams(ctx context.Context) (params authtypes.Params) + GetSequence(context.Context, sdk.AccAddress) (uint64, error) + AddressCodec() address.Codec } // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { authtypes.BankKeeper - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx context.Context, moduleName string, amt sdk.Coins) error } // StakingKeeper returns the historical headers kept in store. type StakingKeeper interface { - GetHistoricalInfo(ctx sdk.Context, height int64) (stakingtypes.HistoricalInfo, bool) - GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator stakingtypes.Validator, found bool) + GetHistoricalInfo(ctx context.Context, height int64) (stakingtypes.HistoricalInfo, error) + GetValidatorByConsAddr(ctx context.Context, consAddr sdk.ConsAddress) (stakingtypes.Validator,error) + ValidatorAddressCodec() address.Codec } // FeeMarketKeeper diff --git a/x/feemarket/keeper/integration_test.go b/x/feemarket/keeper/integration_test.go index e840a048bb..57ccf97d24 100644 --- a/x/feemarket/keeper/integration_test.go +++ b/x/feemarket/keeper/integration_test.go @@ -8,6 +8,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/tx" @@ -26,9 +27,9 @@ import ( "github.com/evmos/ethermint/testutil" "github.com/evmos/ethermint/x/feemarket/types" - dbm "github.com/cometbft/cometbft-db" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" + dbm "github.com/cosmos/cosmos-db" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -126,7 +127,7 @@ var _ = Describe("Feemarket", func() { Context("with MinGasPrices (feemarket param) < min-gas-prices (local)", func() { BeforeEach(func() { - privKey, msg = setupTestWithContext("5", sdk.NewDec(3), sdk.NewInt(5)) + privKey, msg = setupTestWithContext("5", sdk.NewDec(3), math.NewInt(5)) }) Context("during CheckTx", func() { It("should reject transactions with gasPrice < MinGasPrices", func() { diff --git a/x/feemarket/keeper/keeper.go b/x/feemarket/keeper/keeper.go index 518a23ab88..baffe3d48e 100644 --- a/x/feemarket/keeper/keeper.go +++ b/x/feemarket/keeper/keeper.go @@ -19,7 +19,7 @@ import ( "math/big" storetypes "cosmossdk.io/store/types" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" diff --git a/x/feemarket/keeper/keeper_test.go b/x/feemarket/keeper/keeper_test.go index 457ae7a8d1..e9b1e45d41 100644 --- a/x/feemarket/keeper/keeper_test.go +++ b/x/feemarket/keeper/keeper_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "cosmossdk.io/math" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -198,9 +199,9 @@ func (suite *KeeperTestSuite) TestSetGetGasFee() { { "with last block given", func() { - suite.app.FeeMarketKeeper.SetBaseFee(suite.ctx, sdk.OneDec().BigInt()) + suite.app.FeeMarketKeeper.SetBaseFee(suite.ctx, math.LegacyOneDec().BigInt()) }, - sdk.OneDec().BigInt(), + math.LegacyOneDec().BigInt(), }, } diff --git a/x/feemarket/keeper/params.go b/x/feemarket/keeper/params.go index f8a1f3744f..687c050409 100644 --- a/x/feemarket/keeper/params.go +++ b/x/feemarket/keeper/params.go @@ -18,6 +18,7 @@ package keeper import ( "math/big" + "cosmossdk.io/math" "github.com/evmos/ethermint/x/feemarket/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -79,7 +80,7 @@ func (k Keeper) GetBaseFee(ctx sdk.Context) *big.Int { // SetBaseFee set's the base fee in the store func (k Keeper) SetBaseFee(ctx sdk.Context, baseFee *big.Int) { params := k.GetParams(ctx) - params.BaseFee = sdk.NewIntFromBigInt(baseFee) + params.BaseFee = math.NewIntFromBigInt(baseFee) err := k.SetParams(ctx, params) if err != nil { return diff --git a/x/feemarket/migrations/v2/migrate.go b/x/feemarket/migrations/v2/migrate.go index 23784c75a8..03dc8e3911 100644 --- a/x/feemarket/migrations/v2/migrate.go +++ b/x/feemarket/migrations/v2/migrate.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" + "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -40,7 +41,7 @@ func MigrateStore( switch { case store.Has(KeyPrefixBaseFeeV1): bz := store.Get(KeyPrefixBaseFeeV1) - baseFee = sdk.NewIntFromBigInt(new(big.Int).SetBytes(bz)) + baseFee = math.NewIntFromBigInt(new(big.Int).SetBytes(bz)) case paramstore.Has(ctx, v2types.ParamStoreKeyNoBaseFee): paramstore.GetIfExists(ctx, v2types.ParamStoreKeyBaseFee, &baseFee) } diff --git a/x/feemarket/migrations/v2/types/params.go b/x/feemarket/migrations/v2/types/params.go index 732ba4378f..be789cde19 100644 --- a/x/feemarket/migrations/v2/types/params.go +++ b/x/feemarket/migrations/v2/types/params.go @@ -3,6 +3,7 @@ package types import ( "fmt" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/ethereum/go-ethereum/params" @@ -30,7 +31,7 @@ func NewParams(noBaseFee bool, baseFeeChangeDenom, elasticityMultiplier uint32, NoBaseFee: noBaseFee, BaseFeeChangeDenominator: baseFeeChangeDenom, ElasticityMultiplier: elasticityMultiplier, - BaseFee: sdk.NewIntFromUint64(baseFee), + BaseFee: math.NewIntFromUint64(baseFee), EnableHeight: enableHeight, } } @@ -41,7 +42,7 @@ func DefaultParams() Params { NoBaseFee: false, BaseFeeChangeDenominator: params.BaseFeeChangeDenominator, ElasticityMultiplier: params.ElasticityMultiplier, - BaseFee: sdk.NewIntFromUint64(params.InitialBaseFee), + BaseFee: math.NewIntFromUint64(params.InitialBaseFee), EnableHeight: 0, } } diff --git a/x/feemarket/migrations/v4/types/params.go b/x/feemarket/migrations/v4/types/params.go index c2312921c1..b8044b8920 100644 --- a/x/feemarket/migrations/v4/types/params.go +++ b/x/feemarket/migrations/v4/types/params.go @@ -5,6 +5,7 @@ import ( "github.com/evmos/ethermint/x/feemarket/types" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -195,7 +196,7 @@ func validateMinGasMultiplier(i interface{}) error { return fmt.Errorf("value cannot be negative: %s", v) } - if v.GT(sdk.OneDec()) { + if v.GT(math.LegacyOneDec()) { return fmt.Errorf("value cannot be greater than 1: %s", v) } return nil diff --git a/x/feemarket/types/params.go b/x/feemarket/types/params.go index a3f1f6d696..2258cc1e1a 100644 --- a/x/feemarket/types/params.go +++ b/x/feemarket/types/params.go @@ -18,6 +18,7 @@ package types import ( "fmt" + "cosmossdk.io/math" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -212,7 +213,7 @@ func validateMinGasMultiplier(i interface{}) error { return fmt.Errorf("value cannot be negative: %s", v) } - if v.GT(sdk.OneDec()) { + if v.GT(math.LegacyOneDec()) { return fmt.Errorf("value cannot be greater than 1: %s", v) } return nil