From de4287545594f3c357ee5f22e4bb6f23d4494990 Mon Sep 17 00:00:00 2001 From: mmsqe Date: Tue, 23 Apr 2024 09:30:29 +0800 Subject: [PATCH 1/2] Problem: app utils triggers import cycle easily mv to testutil and config --- app/ante/ante_test.go | 8 +- app/ante/utils_test.go | 7 +- app/app.go | 2 + app/app_test.go | 16 +- app/benchmark_test.go | 24 +- app/simulation_test.go | 83 ++--- app/utils.go | 375 ---------------------- cmd/ethermintd/root.go | 9 +- encoding/config_test.go | 4 +- ethereum/eip712/eip712_test.go | 4 +- indexer/kv_indexer_test.go | 4 +- rpc/backend/backend_suite_test.go | 10 +- tests/importer/importer_test.go | 7 +- testutil/app.go | 198 ++++++++++++ testutil/base_test_suite.go | 105 +++++- testutil/config/encoding.go | 66 ++++ testutil/network/network.go | 31 +- x/evm/handler_test.go | 4 +- x/evm/keeper/state_transition_test.go | 18 +- x/evm/keeper/utils_test.go | 2 +- x/evm/statedb/statedb_test.go | 4 +- x/evm/types/msg_test.go | 4 +- x/evm/types/utils_test.go | 4 +- x/feemarket/migrations/v4/migrate_test.go | 4 +- 24 files changed, 498 insertions(+), 495 deletions(-) delete mode 100644 app/utils.go create mode 100644 testutil/app.go create mode 100644 testutil/config/encoding.go diff --git a/app/ante/ante_test.go b/app/ante/ante_test.go index 456ed27820..bca6bfa7e4 100644 --- a/app/ante/ante_test.go +++ b/app/ante/ante_test.go @@ -27,10 +27,10 @@ import ( "github.com/ethereum/go-ethereum/core/types" ethparams "github.com/ethereum/go-ethereum/params" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/app/ante" "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/tests" + "github.com/evmos/ethermint/testutil" evmtypes "github.com/evmos/ethermint/x/evm/types" amino "github.com/cosmos/cosmos-sdk/codec" @@ -937,7 +937,7 @@ func (suite *AnteTestSuite) TestAnteHandler() { suite.Run(tc.name, func() { setup() - suite.ctx = suite.ctx.WithIsCheckTx(tc.checkTx).WithIsReCheckTx(tc.reCheckTx).WithConsensusParams(*app.DefaultConsensusParams) + suite.ctx = suite.ctx.WithIsCheckTx(tc.checkTx).WithIsReCheckTx(tc.reCheckTx).WithConsensusParams(*testutil.DefaultConsensusParams) suite.app.EvmKeeper.RemoveParamsCache(suite.ctx) // expConsumed := params.TxGasContractCreation + params.TxGas @@ -1208,7 +1208,7 @@ func (suite *AnteTestSuite) TestAnteHandlerWithDynamicTxFee() { suite.Require().NoError(acc.SetSequence(1)) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) - suite.ctx = suite.ctx.WithIsCheckTx(tc.checkTx).WithIsReCheckTx(tc.reCheckTx).WithConsensusParams(*app.DefaultConsensusParams) + suite.ctx = suite.ctx.WithIsCheckTx(tc.checkTx).WithIsReCheckTx(tc.reCheckTx).WithConsensusParams(*testutil.DefaultConsensusParams) suite.app.EvmKeeper.SetBalance(suite.ctx, addr, big.NewInt((ethparams.InitialBaseFee+10)*100000), evmtypes.DefaultEVMDenom) _, err := suite.anteHandler(suite.ctx, tc.txFn(), false) if tc.expPass { @@ -1337,7 +1337,7 @@ func (suite *AnteTestSuite) TestAnteHandlerWithParams() { suite.Require().NoError(acc.SetSequence(1)) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) - suite.ctx = suite.ctx.WithIsCheckTx(true).WithConsensusParams(*app.DefaultConsensusParams) + suite.ctx = suite.ctx.WithIsCheckTx(true).WithConsensusParams(*testutil.DefaultConsensusParams) suite.app.EvmKeeper.SetBalance(suite.ctx, addr, big.NewInt((ethparams.InitialBaseFee+10)*100000), evmtypes.DefaultEVMDenom) _, err := suite.anteHandler(suite.ctx, tc.txFn(), false) if tc.expErr == nil { diff --git a/app/ante/utils_test.go b/app/ante/utils_test.go index 6bb964b483..99a917124f 100644 --- a/app/ante/utils_test.go +++ b/app/ante/utils_test.go @@ -18,6 +18,7 @@ import ( "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/testutil" + "github.com/evmos/ethermint/testutil/config" utiltx "github.com/evmos/ethermint/testutil/tx" "github.com/ethereum/go-ethereum/common" @@ -82,7 +83,7 @@ func (suite *AnteTestSuite) SetupTest() { suite.Require().NoError(err) suite.priv = priv - suite.app = app.Setup(checkTx, func(app *app.EthermintApp, genesis app.GenesisState) app.GenesisState { + suite.app = testutil.Setup(checkTx, func(app *app.EthermintApp, genesis app.GenesisState) app.GenesisState { if suite.enableFeemarket { // setup feemarketGenesis params feemarketGenesis := feemarkettypes.DefaultGenesisState() @@ -111,7 +112,7 @@ func (suite *AnteTestSuite) SetupTest() { }) header := tmproto.Header{Height: 2, ChainID: testutil.TestnetChainID + "-1", Time: time.Now().UTC()} suite.ctx = suite.app.BaseApp.NewUncachedContext(checkTx, header). - WithConsensusParams(*app.DefaultConsensusParams). + WithConsensusParams(*testutil.DefaultConsensusParams). WithMinGasPrices(sdk.NewDecCoins(sdk.NewDecCoin(evmtypes.DefaultEVMDenom, sdkmath.OneInt()))). WithBlockGasMeter(storetypes.NewGasMeter(1000000000000000000)) suite.app.EvmKeeper.WithChainID(suite.ctx) @@ -123,7 +124,7 @@ func (suite *AnteTestSuite) SetupTest() { acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) - encodingConfig := app.MakeConfigForTest() + encodingConfig := config.MakeConfigForTest(suite.app.BasicModuleManager) // We're using TestMsg amino encoding in some tests, so register it here. encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil) eip712.SetEncodingConfig(encodingConfig) diff --git a/app/app.go b/app/app.go index a9fa320282..42bcd4014f 100644 --- a/app/app.go +++ b/app/app.go @@ -187,6 +187,8 @@ var ( _ servertypes.Application = (*EthermintApp)(nil) ) +type GenesisState map[string]json.RawMessage + // var _ server.Application (*EthermintApp)(nil) // EthermintApp implements an extended ABCI application. It is an application diff --git a/app/app_test.go b/app/app_test.go index 9fcb822c41..8b98589ba2 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -1,9 +1,11 @@ -package app +package app_test import ( "os" "testing" + "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil" "github.com/stretchr/testify/require" "cosmossdk.io/log" @@ -15,18 +17,18 @@ import ( func TestEthermintAppExport(t *testing.T) { db := dbm.NewMemDB() - app := SetupWithDB(false, nil, db) - app.Commit() + ethApp := testutil.SetupWithDB(false, nil, db) + ethApp.Commit() // Making a new app object with the db, so that initchain hasn't been called - app2 := NewEthermintApp( + ethApp2 := app.NewEthermintApp( log.NewLogger(os.Stdout), db, nil, true, - simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), - baseapp.SetChainID(ChainID), + simtestutil.NewAppOptionsWithFlagHome(app.DefaultNodeHome), + baseapp.SetChainID(testutil.ChainID), ) - _, err := app2.ExportAppStateAndValidators(false, []string{}, []string{}) + _, err := ethApp2.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 0977723c50..07b6d5bac1 100644 --- a/app/benchmark_test.go +++ b/app/benchmark_test.go @@ -1,4 +1,4 @@ -package app +package app_test import ( "encoding/json" @@ -10,46 +10,48 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil" ) func BenchmarkEthermintApp_ExportAppStateAndValidators(b *testing.B) { db := dbm.NewMemDB() - app := NewEthermintApp( + app1 := app.NewEthermintApp( log.NewLogger(io.Discard), db, nil, true, - simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), - baseapp.SetChainID(ChainID), + simtestutil.NewAppOptionsWithFlagHome(app.DefaultNodeHome), + baseapp.SetChainID(testutil.ChainID), ) - genesisState := NewTestGenesisState(app.AppCodec(), app.DefaultGenesis()) + genesisState := testutil.NewTestGenesisState(app1.AppCodec(), app1.DefaultGenesis()) stateBytes, err := json.MarshalIndent(genesisState, "", " ") if err != nil { b.Fatal(err) } // Initialize the chain - app.InitChain( + app1.InitChain( &abci.RequestInitChain{ - ChainId: ChainID, + ChainId: testutil.ChainID, Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes, }, ) - app.Commit() + app1.Commit() b.ResetTimer() 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( + app2 := app.NewEthermintApp( log.NewLogger(io.Discard), db, nil, true, - simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), - baseapp.SetChainID(ChainID), + simtestutil.NewAppOptionsWithFlagHome(app.DefaultNodeHome), + baseapp.SetChainID(testutil.ChainID), ) if _, err := app2.ExportAppStateAndValidators(false, []string{}, []string{}); err != nil { b.Fatal(err) diff --git a/app/simulation_test.go b/app/simulation_test.go index a55fde0a9a..9ff347d168 100644 --- a/app/simulation_test.go +++ b/app/simulation_test.go @@ -1,4 +1,4 @@ -package app +package app_test // TODO: COsmos SDK fix for the simulator issue for custom keys import ( @@ -39,7 +39,9 @@ import ( capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" + "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/app/ante" + "github.com/evmos/ethermint/testutil" ) func init() { @@ -47,6 +49,7 @@ func init() { } const ( + appName = "ethermintd" SimAppChainID = "simulation_777-1" SimBlockMaxGas = 815000000 ) @@ -64,11 +67,11 @@ func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { } // NewSimApp disable feemarket on native tx, otherwise the cosmos-sdk simulation tests will fail. -func NewSimApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*baseapp.BaseApp)) (*EthermintApp, error) { +func NewSimApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*baseapp.BaseApp)) (*app.EthermintApp, error) { appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = DefaultNodeHome + appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - app := NewEthermintApp(logger, db, nil, false, appOptions, baseAppOptions...) + app := app.NewEthermintApp(logger, db, nil, false, appOptions, baseAppOptions...) // disable feemarket on native tx anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{ AccountKeeper: app.AccountKeeper, @@ -123,8 +126,8 @@ func TestFullAppSimulation(t *testing.T) { t, os.Stdout, app.BaseApp, - StateFn(app), - RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + testutil.StateFn(app), + testutil.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, @@ -156,25 +159,25 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app, err := NewSimApp(logger, db, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) + simApp, err := NewSimApp(logger, db, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) require.NoError(t, err) - require.Equal(t, appName, app.Name()) + require.Equal(t, appName, simApp.Name()) // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, - app.BaseApp, - StateFn(app), - RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simtestutil.SimulationOperations(app, app.AppCodec(), config), - app.ModuleAccountAddrs(), + simApp.BaseApp, + testutil.StateFn(simApp), + testutil.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simtestutil.SimulationOperations(simApp, simApp.AppCodec(), config), + simApp.ModuleAccountAddrs(), config, - app.AppCodec(), + simApp.AppCodec(), ) // export state and simParams before the simulation error is checked - err = simtestutil.CheckExportSimulation(app, config, simParams) + err = simtestutil.CheckExportSimulation(simApp, config, simParams) require.NoError(t, err) require.NoError(t, simErr) @@ -184,7 +187,7 @@ func TestAppImportExport(t *testing.T) { fmt.Printf("exporting genesis...\n") - exported, err := app.ExportAppStateAndValidators(false, []string{}, []string{}) + exported, err := simApp.ExportAppStateAndValidators(false, []string{}, []string{}) require.NoError(t, err) fmt.Printf("importing genesis...\n") @@ -202,7 +205,7 @@ func TestAppImportExport(t *testing.T) { require.Equal(t, appName, newApp.Name()) require.NoError(t, err) - var genesisState GenesisState + var genesisState app.GenesisState err = json.Unmarshal(exported.AppState, &genesisState) require.NoError(t, err) @@ -217,33 +220,33 @@ func TestAppImportExport(t *testing.T) { } }() - ctxA := app.NewContextLegacy(true, tmproto.Header{Height: app.LastBlockHeight(), ChainID: SimAppChainID}) - ctxB := newApp.NewContextLegacy(true, tmproto.Header{Height: app.LastBlockHeight(), ChainID: SimAppChainID}) - newApp.ModuleManager.InitGenesis(ctxB, app.AppCodec(), genesisState) + ctxA := simApp.NewContextLegacy(true, tmproto.Header{Height: simApp.LastBlockHeight(), ChainID: SimAppChainID}) + ctxB := newApp.NewContextLegacy(true, tmproto.Header{Height: simApp.LastBlockHeight(), ChainID: SimAppChainID}) + newApp.ModuleManager.InitGenesis(ctxB, simApp.AppCodec(), genesisState) newApp.StoreConsensusParams(ctxB, exported.ConsensusParams) fmt.Printf("comparing stores...\n") storeKeysPrefixes := []storeKeysPrefixes{ - {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}}, + {simApp.GetKey(authtypes.StoreKey), newApp.GetKey(authtypes.StoreKey), [][]byte{}}, { - app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], + simApp.GetKey(stakingtypes.StoreKey), newApp.GetKey(stakingtypes.StoreKey), [][]byte{ stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, stakingtypes.HistoricalInfoKey, stakingtypes.UnbondingIDKey, stakingtypes.UnbondingIndexKey, stakingtypes.UnbondingTypeKey, stakingtypes.ValidatorUpdatesKey, }, }, // ordering may change but it doesn't matter - {app.keys[slashingtypes.StoreKey], newApp.keys[slashingtypes.StoreKey], [][]byte{}}, - {app.keys[minttypes.StoreKey], newApp.keys[minttypes.StoreKey], [][]byte{}}, - {app.keys[distrtypes.StoreKey], newApp.keys[distrtypes.StoreKey], [][]byte{}}, - {app.keys[banktypes.StoreKey], newApp.keys[banktypes.StoreKey], [][]byte{banktypes.BalancesPrefix}}, - {app.keys[paramtypes.StoreKey], newApp.keys[paramtypes.StoreKey], [][]byte{}}, - {app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}}, - {app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}}, - {app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}}, - {app.keys[authzkeeper.StoreKey], newApp.keys[authzkeeper.StoreKey], [][]byte{authzkeeper.GrantKey, authzkeeper.GrantQueuePrefix}}, - {app.keys[ibcexported.StoreKey], newApp.keys[ibcexported.StoreKey], [][]byte{}}, - {app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}}, + {simApp.GetKey(slashingtypes.StoreKey), newApp.GetKey(slashingtypes.StoreKey), [][]byte{}}, + {simApp.GetKey(minttypes.StoreKey), newApp.GetKey(minttypes.StoreKey), [][]byte{}}, + {simApp.GetKey(distrtypes.StoreKey), newApp.GetKey(distrtypes.StoreKey), [][]byte{}}, + {simApp.GetKey(banktypes.StoreKey), newApp.GetKey(banktypes.StoreKey), [][]byte{banktypes.BalancesPrefix}}, + {simApp.GetKey(paramtypes.StoreKey), newApp.GetKey(paramtypes.StoreKey), [][]byte{}}, + {simApp.GetKey(govtypes.StoreKey), newApp.GetKey(govtypes.StoreKey), [][]byte{}}, + {simApp.GetKey(evidencetypes.StoreKey), newApp.GetKey(evidencetypes.StoreKey), [][]byte{}}, + {simApp.GetKey(capabilitytypes.StoreKey), newApp.GetKey(capabilitytypes.StoreKey), [][]byte{}}, + {simApp.GetKey(authzkeeper.StoreKey), newApp.GetKey(authzkeeper.StoreKey), [][]byte{authzkeeper.GrantKey, authzkeeper.GrantQueuePrefix}}, + {simApp.GetKey(ibcexported.StoreKey), newApp.GetKey(ibcexported.StoreKey), [][]byte{}}, + {simApp.GetKey(ibctransfertypes.StoreKey), newApp.GetKey(ibctransfertypes.StoreKey), [][]byte{}}, } for _, skp := range storeKeysPrefixes { @@ -254,7 +257,7 @@ func TestAppImportExport(t *testing.T) { require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") fmt.Printf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) - require.Equal(t, len(failedKVAs), 0, simtestutil.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) + require.Equal(t, len(failedKVAs), 0, simtestutil.GetSimulationLog(skp.A.Name(), simApp.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) } } @@ -284,8 +287,8 @@ func TestAppSimulationAfterImport(t *testing.T) { t, os.Stdout, app.BaseApp, - StateFn(app), - RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + testutil.StateFn(app), + testutil.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, @@ -334,8 +337,8 @@ func TestAppSimulationAfterImport(t *testing.T) { t, os.Stdout, newApp.BaseApp, - StateFn(app), - RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + testutil.StateFn(app), + testutil.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config), app.ModuleAccountAddrs(), config, @@ -386,8 +389,8 @@ func TestAppStateDeterminism(t *testing.T) { t, os.Stdout, app.BaseApp, - StateFn(app), - RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + testutil.StateFn(app), + testutil.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), app.ModuleAccountAddrs(), config, diff --git a/app/utils.go b/app/utils.go deleted file mode 100644 index 7e23b4c429..0000000000 --- a/app/utils.go +++ /dev/null @@ -1,375 +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 app - -import ( - "encoding/json" - "math/rand" - "time" - - "cosmossdk.io/log" - sdkmath "cosmossdk.io/math" - "cosmossdk.io/x/evidence" - feegrantmodule "cosmossdk.io/x/feegrant/module" - "cosmossdk.io/x/upgrade" - abci "github.com/cometbft/cometbft/abci/types" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtypes "github.com/cometbft/cometbft/types" - dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/testutil/mock" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" - "github.com/cosmos/cosmos-sdk/x/bank" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/consensus" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/gov" - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" - paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/ibc-go/modules/capability" - "github.com/cosmos/ibc-go/v8/modules/apps/transfer" - ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/evmos/ethermint/crypto/ethsecp256k1" - "github.com/evmos/ethermint/encoding" - ethermint "github.com/evmos/ethermint/types" - "github.com/evmos/ethermint/x/evm" - evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/evmos/ethermint/x/feemarket" - - "github.com/cosmos/cosmos-sdk/x/auth" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" -) - -type GenesisState map[string]json.RawMessage - -// DefaultConsensusParams defines the default Tendermint consensus params used in -// EthermintApp testing. -var DefaultConsensusParams = &cmtproto.ConsensusParams{ - Block: &cmtproto.BlockParams{ - MaxBytes: 1048576, - MaxGas: 81500000, // default limit - }, - Evidence: &cmtproto.EvidenceParams{ - MaxAgeNumBlocks: 302400, - MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration - MaxBytes: 10000, - }, - Validator: &cmtproto.ValidatorParams{ - PubKeyTypes: []string{ - tmtypes.ABCIPubKeyTypeEd25519, - }, - }, -} - -// Setup initializes a new EthermintApp. A Nop logger is set in EthermintApp. -func Setup(isCheckTx bool, patch func(*EthermintApp, GenesisState) GenesisState) *EthermintApp { - return SetupWithDB(isCheckTx, patch, dbm.NewMemDB()) -} - -func SetupWithOpts( - isCheckTx bool, - patch func(*EthermintApp, GenesisState) GenesisState, - appOptions simtestutil.AppOptionsMap, -) *EthermintApp { - return SetupWithDBAndOpts(isCheckTx, patch, dbm.NewMemDB(), appOptions) -} - -const ChainID = "ethermint_9000-1" - -func SetupWithDB(isCheckTx bool, patch func(*EthermintApp, GenesisState) GenesisState, db dbm.DB) *EthermintApp { - return SetupWithDBAndOpts(isCheckTx, patch, db, nil) -} - -// SetupWithDBAndOpts initializes a new EthermintApp. A Nop logger is set in EthermintApp. -func SetupWithDBAndOpts( - isCheckTx bool, - patch func(*EthermintApp, GenesisState) GenesisState, - db dbm.DB, - appOptions simtestutil.AppOptionsMap, -) *EthermintApp { - if appOptions == nil { - appOptions = make(simtestutil.AppOptionsMap, 0) - } - appOptions[server.FlagInvCheckPeriod] = 5 - appOptions[flags.FlagHome] = DefaultNodeHome - app := NewEthermintApp(log.NewNopLogger(), - db, - nil, - true, - appOptions, - baseapp.SetChainID(ChainID), - ) - - if !isCheckTx { - // init chain must be called to stop deliverState from being nil - genesisState := NewTestGenesisState(app.AppCodec(), app.DefaultGenesis()) - if patch != nil { - genesisState = patch(app, genesisState) - } - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - if err != nil { - panic(err) - } - - // Initialize the chain - consensusParams := DefaultConsensusParams - initialHeight := app.LastBlockHeight() + 1 - consensusParams.Abci = &cmtproto.ABCIParams{VoteExtensionsEnableHeight: initialHeight} - if _, err := app.InitChain( - &abci.RequestInitChain{ - ChainId: ChainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: consensusParams, - AppStateBytes: stateBytes, - InitialHeight: initialHeight, - }, - ); err != nil { - panic(err) - } - } - if _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ - Height: app.LastBlockHeight() + 1, - Hash: app.LastCommitID().Hash, - }); err != nil { - panic(err) - } - return app -} - -// RandomGenesisAccounts is used by the auth module to create random genesis accounts in simulation when a genesis.json is not specified. -// In contrast, the default auth module's RandomGenesisAccounts implementation creates only base accounts and vestings accounts. -func RandomGenesisAccounts(simState *module.SimulationState) authtypes.GenesisAccounts { - emptyCodeHash := crypto.Keccak256(nil) - genesisAccs := make(authtypes.GenesisAccounts, len(simState.Accounts)) - for i, acc := range simState.Accounts { - bacc := authtypes.NewBaseAccountWithAddress(acc.Address) - - ethacc := ðermint.EthAccount{ - BaseAccount: bacc, - CodeHash: common.BytesToHash(emptyCodeHash).String(), - } - genesisAccs[i] = ethacc - } - - return genesisAccs -} - -// RandomAccounts creates random accounts with an ethsecp256k1 private key -// TODO: replace secp256k1.GenPrivKeyFromSecret() with similar function in go-ethereum -func RandomAccounts(r *rand.Rand, n int) []simtypes.Account { - accs := make([]simtypes.Account, n) - - for i := 0; i < n; i++ { - // don't need that much entropy for simulation - privkeySeed := make([]byte, 15) - _, _ = r.Read(privkeySeed) - - prv := secp256k1.GenPrivKeyFromSecret(privkeySeed) - ethPrv := ðsecp256k1.PrivKey{} - _ = ethPrv.UnmarshalAmino(prv.Bytes()) // UnmarshalAmino simply copies the bytes and assigns them to ethPrv.Key - accs[i].PrivKey = ethPrv - accs[i].PubKey = accs[i].PrivKey.PubKey() - accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) - - accs[i].ConsKey = ed25519.GenPrivKeyFromSecret(privkeySeed) - } - - return accs -} - -// StateFn returns the initial application state using a genesis or the simulation parameters. -// It is a wrapper of simapp.AppStateFn to replace evm param EvmDenom with staking param BondDenom. -func StateFn(app *EthermintApp) simtypes.AppStateFn { - var bondDenom string - return simtestutil.AppStateFnWithExtendedCbs( - app.AppCodec(), - app.SimulationManager(), - app.DefaultGenesis(), - func(moduleName string, genesisState interface{}) { - if moduleName == stakingtypes.ModuleName { - stakingState := genesisState.(*stakingtypes.GenesisState) - bondDenom = stakingState.Params.BondDenom - } - }, - func(rawState map[string]json.RawMessage) { - evmStateBz, ok := rawState[evmtypes.ModuleName] - if !ok { - panic("evm genesis state is missing") - } - - evmState := new(evmtypes.GenesisState) - app.AppCodec().MustUnmarshalJSON(evmStateBz, evmState) - - // we should replace the EvmDenom with BondDenom - evmState.Params.EvmDenom = bondDenom - - // change appState back - rawState[evmtypes.ModuleName] = app.AppCodec().MustMarshalJSON(evmState) - }, - ) -} - -// NewTestGenesisState generate genesis state with single validator -func NewTestGenesisState(codec codec.Codec, genesisState map[string]json.RawMessage) GenesisState { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - // generate genesis account - senderPrivKey := secp256k1.GenPrivKey() - 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, sdkmath.NewInt(100000000000000))), - } - - return genesisStateWithValSet(codec, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) -} - -func genesisStateWithValSet(codec codec.Codec, genesisState GenesisState, - valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, - balances ...banktypes.Balance, -) GenesisState { - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = codec.MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.DefaultPowerReduction - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromCmtPubKeyInterface(val.PubKey) - if err != nil { - panic(err) - } - pkAny, err := codectypes.NewAnyWithValue(pk) - if err != nil { - panic(err) - } - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdkmath.LegacyOneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec()), - MinSelfDelegation: sdkmath.ZeroInt(), - } - validators = append(validators, validator) - delegation := stakingtypes.NewDelegation(genAccs[0].GetAddress().String(), sdk.ValAddress(val.Address).String(), sdkmath.LegacyOneDec()) - delegations = append(delegations, delegation) - } - // set validators and delegations - stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) - genesisState[stakingtypes.ModuleName] = codec.MustMarshalJSON(stakingGenesis) - - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens to total supply - totalSupply = totalSupply.Add(b.Coins...) - } - - for range delegations { - // add delegated tokens to total supply - totalSupply = totalSupply.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState( - banktypes.DefaultGenesisState().Params, - balances, - totalSupply, - []banktypes.Metadata{}, - []banktypes.SendEnabled{}, - ) - genesisState[banktypes.ModuleName] = codec.MustMarshalJSON(bankGenesis) - - return genesisState -} - -var ModuleBasicsForTest = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distr.AppModuleBasic{}, - gov.NewAppModuleBasic([]govclient.ProposalHandler{paramsclient.ProposalHandler}), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - ibctm.AppModuleBasic{}, - authzmodule.AppModuleBasic{}, - feegrantmodule.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, - consensus.AppModuleBasic{}, - // Ethermint modules - evm.AppModuleBasic{}, - feemarket.AppModuleBasic{}, -) - -func MakeConfigForTest() ethermint.EncodingConfig { - config := encoding.MakeConfig() - ModuleBasicsForTest.RegisterLegacyAminoCodec(config.Amino) - ModuleBasicsForTest.RegisterInterfaces(config.InterfaceRegistry) - return config -} diff --git a/cmd/ethermintd/root.go b/cmd/ethermintd/root.go index 903f1de4ec..5e13604f32 100644 --- a/cmd/ethermintd/root.go +++ b/cmd/ethermintd/root.go @@ -60,7 +60,10 @@ import ( ethermint "github.com/evmos/ethermint/types" ) -const EnvPrefix = "ETHERMINT" +const ( + EnvPrefix = "ETHERMINT" + ChainID = "ethermint_9000-1" +) type emptyAppOptions struct{} @@ -272,13 +275,13 @@ func appExport( } if height != -1 { - ethermintApp = app.NewEthermintApp(logger, db, traceStore, false, appOpts, baseapp.SetChainID(app.ChainID)) + ethermintApp = app.NewEthermintApp(logger, db, traceStore, false, appOpts, baseapp.SetChainID(ChainID)) if err := ethermintApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } } else { - ethermintApp = app.NewEthermintApp(logger, db, traceStore, true, appOpts, baseapp.SetChainID(app.ChainID)) + ethermintApp = app.NewEthermintApp(logger, db, traceStore, true, appOpts, baseapp.SetChainID(ChainID)) } return ethermintApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) diff --git a/encoding/config_test.go b/encoding/config_test.go index 357064c6d6..53a4f573a5 100644 --- a/encoding/config_test.go +++ b/encoding/config_test.go @@ -8,8 +8,8 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/tests" + "github.com/evmos/ethermint/testutil/config" evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -24,7 +24,7 @@ func TestTxEncoding(t *testing.T) { err := msg.Sign(ethSigner, signer) require.NoError(t, err) - cfg := app.MakeConfigForTest() + cfg := config.MakeConfigForTest(nil) _, err = cfg.TxConfig.TxEncoder()(msg) require.Error(t, err, "encoding failed") diff --git a/ethereum/eip712/eip712_test.go b/ethereum/eip712/eip712_test.go index 6d9a39b3f3..086d333d87 100644 --- a/ethereum/eip712/eip712_test.go +++ b/ethereum/eip712/eip712_test.go @@ -14,7 +14,6 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/crypto/ethsecp256k1" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -28,6 +27,7 @@ import ( "github.com/evmos/ethermint/cmd/config" "github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/testutil" + testutilconfig "github.com/evmos/ethermint/testutil/config" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/suite" @@ -67,7 +67,7 @@ func TestEIP712TestSuite(t *testing.T) { } func (suite *EIP712TestSuite) SetupTest() { - suite.config = app.MakeConfigForTest() + suite.config = testutilconfig.MakeConfigForTest(nil) suite.clientCtx = client.Context{}.WithTxConfig(suite.config.TxConfig) suite.denom = evmtypes.DefaultEVMDenom diff --git a/indexer/kv_indexer_test.go b/indexer/kv_indexer_test.go index 967140b17d..30443b70fa 100644 --- a/indexer/kv_indexer_test.go +++ b/indexer/kv_indexer_test.go @@ -11,10 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/indexer" "github.com/evmos/ethermint/tests" + "github.com/evmos/ethermint/testutil/config" "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" ) @@ -34,7 +34,7 @@ func TestKVIndexer(t *testing.T) { require.NoError(t, tx.Sign(ethSigner, signer)) txHash := tx.AsTransaction().Hash() - encodingConfig := app.MakeConfigForTest() + encodingConfig := config.MakeConfigForTest(nil) clientCtx := client.Context{}.WithTxConfig(encodingConfig.TxConfig).WithCodec(encodingConfig.Codec) // build cosmos-sdk wrapper tx diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index e1f971c20b..7694574684 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -18,13 +18,14 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/suite" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/crypto/hd" + "github.com/evmos/ethermint/encoding" "github.com/evmos/ethermint/indexer" "github.com/evmos/ethermint/rpc/backend/mocks" rpctypes "github.com/evmos/ethermint/rpc/types" "github.com/evmos/ethermint/tests" + "github.com/evmos/ethermint/testutil/config" evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -69,7 +70,7 @@ func (suite *BackendTestSuite) SetupTest() { suite.Require().NoError(err) suite.signerAddress = sdk.AccAddress(priv.PubKey().Address().Bytes()) - encodingConfig := app.MakeConfigForTest() + encodingConfig := config.MakeConfigForTest(nil) clientCtx := client.Context{}.WithChainID(ChainID). WithHeight(1). WithTxConfig(encodingConfig.TxConfig). @@ -87,8 +88,7 @@ func (suite *BackendTestSuite) SetupTest() { suite.backend.ctx = rpctypes.ContextWithHeight(1) // Add codec - encCfg := app.MakeConfigForTest() - suite.backend.clientCtx.Codec = encCfg.Codec + suite.backend.clientCtx.Codec = encodingConfig.Codec } // buildEthereumTx returns an example legacy Ethereum transaction @@ -167,7 +167,7 @@ func (suite *BackendTestSuite) buildFormattedBlock( func (suite *BackendTestSuite) generateTestKeyring(clientDir string) (keyring.Keyring, error) { buf := bufio.NewReader(os.Stdin) - encCfg := app.MakeConfigForTest() + encCfg := encoding.MakeConfig() return keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, encCfg.Codec, []keyring.Option{hd.EthSecp256k1Option()}...) } diff --git a/tests/importer/importer_test.go b/tests/importer/importer_test.go index e029920bcd..0d22f641fc 100644 --- a/tests/importer/importer_test.go +++ b/tests/importer/importer_test.go @@ -11,6 +11,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -60,7 +61,7 @@ type ImporterTestSuite struct { // / 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) + suite.app = testutil.Setup(checkTx, nil) // consensus key priv, err := ethsecp256k1.GenerateKey() require.NoError(t, err) @@ -87,7 +88,7 @@ func (suite *ImporterTestSuite) DoSetupTest(t require.TestingT) { NextValidatorsHash: tmhash.Sum([]byte("next_validators")), ConsensusHash: tmhash.Sum([]byte("consensus")), LastResultsHash: tmhash.Sum([]byte("last_result")), - }).WithConsensusParams(*app.DefaultConsensusParams) + }).WithConsensusParams(*testutil.DefaultConsensusParams) } func (suite *ImporterTestSuite) SetupTest() { @@ -136,7 +137,7 @@ func (suite *ImporterTestSuite) TestImportBlocks() { tmheader := suite.ctx.BlockHeader() // fix due to that begin block can't have height 0 tmheader.Height = int64(block.NumberU64()) + 1 - ctx := suite.app.NewUncachedContext(false, tmheader).WithConsensusParams(*app.DefaultConsensusParams) + ctx := suite.app.NewUncachedContext(false, tmheader).WithConsensusParams(*testutil.DefaultConsensusParams) suite.app.BeginBlocker(ctx) vmdb := statedb.New(ctx, suite.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash()))) diff --git a/testutil/app.go b/testutil/app.go new file mode 100644 index 0000000000..f581651a29 --- /dev/null +++ b/testutil/app.go @@ -0,0 +1,198 @@ +package testutil + +import ( + "encoding/json" + "math/rand" + "time" + + "cosmossdk.io/log" + abci "github.com/cometbft/cometbft/abci/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/server" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + ethermint "github.com/evmos/ethermint/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" +) + +// DefaultConsensusParams defines the default Tendermint consensus params used in +// EthermintApp testing. +var DefaultConsensusParams = &cmtproto.ConsensusParams{ + Block: &cmtproto.BlockParams{ + MaxBytes: 1048576, + MaxGas: 81500000, // default limit + }, + Evidence: &cmtproto.EvidenceParams{ + MaxAgeNumBlocks: 302400, + MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration + MaxBytes: 10000, + }, + Validator: &cmtproto.ValidatorParams{ + PubKeyTypes: []string{ + tmtypes.ABCIPubKeyTypeEd25519, + }, + }, +} + +// Setup initializes a new EthermintApp. A Nop logger is set in EthermintApp. +func Setup(isCheckTx bool, patch func(*app.EthermintApp, app.GenesisState) app.GenesisState) *app.EthermintApp { + return SetupWithDB(isCheckTx, patch, dbm.NewMemDB()) +} + +func SetupWithOpts( + isCheckTx bool, + patch func(*app.EthermintApp, app.GenesisState) app.GenesisState, + appOptions simtestutil.AppOptionsMap, +) *app.EthermintApp { + return SetupWithDBAndOpts(isCheckTx, patch, dbm.NewMemDB(), appOptions) +} + +const ChainID = "ethermint_9000-1" + +func SetupWithDB(isCheckTx bool, patch func(*app.EthermintApp, app.GenesisState) app.GenesisState, db dbm.DB) *app.EthermintApp { + return SetupWithDBAndOpts(isCheckTx, patch, db, nil) +} + +// SetupWithDBAndOpts initializes a new EthermintApp. A Nop logger is set in EthermintApp. +func SetupWithDBAndOpts( + isCheckTx bool, + patch func(*app.EthermintApp, app.GenesisState) app.GenesisState, + db dbm.DB, + appOptions simtestutil.AppOptionsMap, +) *app.EthermintApp { + if appOptions == nil { + appOptions = make(simtestutil.AppOptionsMap, 0) + } + appOptions[server.FlagInvCheckPeriod] = 5 + appOptions[flags.FlagHome] = app.DefaultNodeHome + app := app.NewEthermintApp(log.NewNopLogger(), + db, + nil, + true, + appOptions, + baseapp.SetChainID(ChainID), + ) + + if !isCheckTx { + // init chain must be called to stop deliverState from being nil + genesisState := NewTestGenesisState(app.AppCodec(), app.DefaultGenesis()) + if patch != nil { + genesisState = patch(app, genesisState) + } + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + if err != nil { + panic(err) + } + + // Initialize the chain + consensusParams := DefaultConsensusParams + initialHeight := app.LastBlockHeight() + 1 + consensusParams.Abci = &cmtproto.ABCIParams{VoteExtensionsEnableHeight: initialHeight} + if _, err := app.InitChain( + &abci.RequestInitChain{ + ChainId: ChainID, + Validators: []abci.ValidatorUpdate{}, + ConsensusParams: consensusParams, + AppStateBytes: stateBytes, + InitialHeight: initialHeight, + }, + ); err != nil { + panic(err) + } + } + if _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ + Height: app.LastBlockHeight() + 1, + Hash: app.LastCommitID().Hash, + }); err != nil { + panic(err) + } + return app +} + +// RandomGenesisAccounts is used by the auth module to create random genesis accounts in simulation when a genesis.json is not specified. +// In contrast, the default auth module's RandomGenesisAccounts implementation creates only base accounts and vestings accounts. +func RandomGenesisAccounts(simState *module.SimulationState) authtypes.GenesisAccounts { + emptyCodeHash := crypto.Keccak256(nil) + genesisAccs := make(authtypes.GenesisAccounts, len(simState.Accounts)) + for i, acc := range simState.Accounts { + bacc := authtypes.NewBaseAccountWithAddress(acc.Address) + + ethacc := ðermint.EthAccount{ + BaseAccount: bacc, + CodeHash: common.BytesToHash(emptyCodeHash).String(), + } + genesisAccs[i] = ethacc + } + + return genesisAccs +} + +// RandomAccounts creates random accounts with an ethsecp256k1 private key +// TODO: replace secp256k1.GenPrivKeyFromSecret() with similar function in go-ethereum +func RandomAccounts(r *rand.Rand, n int) []simtypes.Account { + accs := make([]simtypes.Account, n) + + for i := 0; i < n; i++ { + // don't need that much entropy for simulation + privkeySeed := make([]byte, 15) + _, _ = r.Read(privkeySeed) + + prv := secp256k1.GenPrivKeyFromSecret(privkeySeed) + ethPrv := ðsecp256k1.PrivKey{} + _ = ethPrv.UnmarshalAmino(prv.Bytes()) // UnmarshalAmino simply copies the bytes and assigns them to ethPrv.Key + accs[i].PrivKey = ethPrv + accs[i].PubKey = accs[i].PrivKey.PubKey() + accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) + + accs[i].ConsKey = ed25519.GenPrivKeyFromSecret(privkeySeed) + } + + return accs +} + +// StateFn returns the initial application state using a genesis or the simulation parameters. +// It is a wrapper of simapp.AppStateFn to replace evm param EvmDenom with staking param BondDenom. +func StateFn(a *app.EthermintApp) simtypes.AppStateFn { + var bondDenom string + return simtestutil.AppStateFnWithExtendedCbs( + a.AppCodec(), + a.SimulationManager(), + a.DefaultGenesis(), + func(moduleName string, genesisState interface{}) { + if moduleName == stakingtypes.ModuleName { + stakingState := genesisState.(*stakingtypes.GenesisState) + bondDenom = stakingState.Params.BondDenom + } + }, + func(rawState map[string]json.RawMessage) { + evmStateBz, ok := rawState[evmtypes.ModuleName] + if !ok { + panic("evm genesis state is missing") + } + + evmState := new(evmtypes.GenesisState) + a.AppCodec().MustUnmarshalJSON(evmStateBz, evmState) + + // we should replace the EvmDenom with BondDenom + evmState.Params.EvmDenom = bondDenom + + // change appState back + rawState[evmtypes.ModuleName] = a.AppCodec().MustMarshalJSON(evmState) + }, + ) +} diff --git a/testutil/base_test_suite.go b/testutil/base_test_suite.go index ba28f44254..a0ac2a70f3 100644 --- a/testutil/base_test_suite.go +++ b/testutil/base_test_suite.go @@ -11,10 +11,15 @@ import ( storetypes "cosmossdk.io/store/types" abci "github.com/cometbft/cometbft/abci/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/testutil/mock" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" @@ -85,12 +90,12 @@ func (suite *BaseTestSuite) SetupTestWithCbAndOpts( appOptions simtestutil.AppOptionsMap, ) { checkTx := false - suite.App = app.SetupWithOpts(checkTx, patch, appOptions) + suite.App = SetupWithOpts(checkTx, patch, appOptions) suite.Ctx = suite.App.NewUncachedContext(checkTx, tmproto.Header{ Height: 1, - ChainID: app.ChainID, + ChainID: ChainID, Time: time.Now().UTC(), - }).WithChainID(app.ChainID) + }).WithChainID(ChainID) } func (suite *BaseTestSuite) StateDB() *statedb.StateDB { @@ -403,3 +408,97 @@ func (suite *EVMTestSuiteWithAccountAndQueryClient) EvmDenom() string { rsp, _ := suite.EvmQueryClient.Params(suite.Ctx, &types.QueryParamsRequest{}) return rsp.Params.EvmDenom } + +// NewTestGenesisState generate genesis state with single validator +func NewTestGenesisState(codec codec.Codec, genesisState map[string]json.RawMessage) app.GenesisState { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + 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, sdkmath.NewInt(100000000000000))), + } + return genesisStateWithValSet(codec, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) +} + +func genesisStateWithValSet(codec codec.Codec, genesisState app.GenesisState, + valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, + balances ...banktypes.Balance, +) app.GenesisState { + // set genesis accounts + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = codec.MustMarshalJSON(authGenesis) + + validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) + + bondAmt := sdk.DefaultPowerReduction + + for _, val := range valSet.Validators { + pk, err := cryptocodec.FromCmtPubKeyInterface(val.PubKey) + if err != nil { + panic(err) + } + pkAny, err := codectypes.NewAnyWithValue(pk) + if err != nil { + panic(err) + } + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bondAmt, + DelegatorShares: sdkmath.LegacyOneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec(), sdkmath.LegacyOneDec()), + MinSelfDelegation: sdkmath.ZeroInt(), + } + validators = append(validators, validator) + delegation := stakingtypes.NewDelegation(genAccs[0].GetAddress().String(), sdk.ValAddress(val.Address).String(), sdkmath.LegacyOneDec()) + delegations = append(delegations, delegation) + } + // set validators and delegations + stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) + genesisState[stakingtypes.ModuleName] = codec.MustMarshalJSON(stakingGenesis) + + totalSupply := sdk.NewCoins() + for _, b := range balances { + // add genesis acc tokens to total supply + totalSupply = totalSupply.Add(b.Coins...) + } + + for range delegations { + // add delegated tokens to total supply + totalSupply = totalSupply.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)) + } + + // add bonded amount to bonded pool module account + balances = append(balances, banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)}, + }) + + // update total supply + bankGenesis := banktypes.NewGenesisState( + banktypes.DefaultGenesisState().Params, + balances, + totalSupply, + []banktypes.Metadata{}, + []banktypes.SendEnabled{}, + ) + genesisState[banktypes.ModuleName] = codec.MustMarshalJSON(bankGenesis) + + return genesisState +} diff --git a/testutil/config/encoding.go b/testutil/config/encoding.go new file mode 100644 index 0000000000..eedd363f38 --- /dev/null +++ b/testutil/config/encoding.go @@ -0,0 +1,66 @@ +package config + +import ( + "cosmossdk.io/x/evidence" + feegrantmodule "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/upgrade" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/consensus" + "github.com/cosmos/cosmos-sdk/x/crisis" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/cosmos/cosmos-sdk/x/gov" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/ibc-go/modules/capability" + "github.com/cosmos/ibc-go/v8/modules/apps/transfer" + ibc "github.com/cosmos/ibc-go/v8/modules/core" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + "github.com/evmos/ethermint/encoding" + "github.com/evmos/ethermint/types" + "github.com/evmos/ethermint/x/evm" + "github.com/evmos/ethermint/x/feemarket" +) + +func MakeConfigForTest(moduleManager module.BasicManager) types.EncodingConfig { + config := encoding.MakeConfig() + if moduleManager == nil { + moduleManager = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distr.AppModuleBasic{}, + gov.NewAppModuleBasic([]govclient.ProposalHandler{paramsclient.ProposalHandler}), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + ibc.AppModuleBasic{}, + ibctm.AppModuleBasic{}, + authzmodule.AppModuleBasic{}, + feegrantmodule.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, + vesting.AppModuleBasic{}, + consensus.AppModuleBasic{}, + // Ethermint modules + evm.AppModuleBasic{}, + feemarket.AppModuleBasic{}, + ) + } + moduleManager.RegisterLegacyAminoCodec(config.Amino) + moduleManager.RegisterInterfaces(config.InterfaceRegistry) + return config +} diff --git a/testutil/network/network.go b/testutil/network/network.go index 5fbbceda31..e3d5e0c52d 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -65,6 +65,7 @@ import ( "github.com/evmos/ethermint/crypto/hd" "github.com/evmos/ethermint/server/config" + testutilconfig "github.com/evmos/ethermint/testutil/config" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" @@ -131,7 +132,7 @@ type Config struct { // DefaultConfig returns a sane default configuration suitable for nearly all // testing requirements. func DefaultConfig() Config { - encCfg := app.MakeConfigForTest() + encCfg := testutilconfig.MakeConfigForTest(nil) chainID := fmt.Sprintf("ethermint_%d-1", cmtrand.Int63n(9999999999999)+1) return Config{ Codec: encCfg.Codec, @@ -140,20 +141,20 @@ func DefaultConfig() Config { InterfaceRegistry: encCfg.InterfaceRegistry, AccountRetriever: authtypes.AccountRetriever{}, AppConstructor: NewAppConstructor(chainID), - GenesisState: app.ModuleBasicsForTest.DefaultGenesis(encCfg.Codec), - TimeoutCommit: 2 * time.Second, - ChainID: chainID, - NumValidators: 4, - BondDenom: ethermint.AttoPhoton, - MinGasPrices: fmt.Sprintf("0.000006%s", ethermint.AttoPhoton), - AccountTokens: sdk.TokensFromConsensusPower(1000, ethermint.PowerReduction), - StakingTokens: sdk.TokensFromConsensusPower(500, ethermint.PowerReduction), - BondedTokens: sdk.TokensFromConsensusPower(100, ethermint.PowerReduction), - PruningStrategy: pruningtypes.PruningOptionNothing, - CleanupDir: true, - SigningAlgo: string(hd.EthSecp256k1Type), - KeyringOptions: []keyring.Option{hd.EthSecp256k1Option()}, - PrintMnemonic: false, + // GenesisState: app.ModuleBasicsForTest.DefaultGenesis(encCfg.Codec), // TOFIX + TimeoutCommit: 2 * time.Second, + ChainID: chainID, + NumValidators: 4, + BondDenom: ethermint.AttoPhoton, + MinGasPrices: fmt.Sprintf("0.000006%s", ethermint.AttoPhoton), + AccountTokens: sdk.TokensFromConsensusPower(1000, ethermint.PowerReduction), + StakingTokens: sdk.TokensFromConsensusPower(500, ethermint.PowerReduction), + BondedTokens: sdk.TokensFromConsensusPower(100, ethermint.PowerReduction), + PruningStrategy: pruningtypes.PruningOptionNothing, + CleanupDir: true, + SigningAlgo: string(hd.EthSecp256k1Type), + KeyringOptions: []keyring.Option{hd.EthSecp256k1Option()}, + PrintMnemonic: false, } } diff --git a/x/evm/handler_test.go b/x/evm/handler_test.go index 56b582ab5b..6de98d43df 100644 --- a/x/evm/handler_test.go +++ b/x/evm/handler_test.go @@ -121,7 +121,7 @@ func (suite *HandlerTestSuite) TestHandleMsgEthereumTx() { { "invalid chain ID", func() { - suite.Ctx = suite.Ctx.WithChainID("chainID").WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithChainID("chainID").WithConsensusParams(*testutil.DefaultConsensusParams) }, false, }, @@ -352,7 +352,7 @@ func (suite *HandlerTestSuite) TestOutOfGasWhenDeployContract() { // Deploy contract - Owner.sol gasLimit := uint64(1) - suite.Ctx = suite.Ctx.WithGasMeter(storetypes.NewGasMeter(gasLimit)).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithGasMeter(storetypes.NewGasMeter(gasLimit)).WithConsensusParams(*testutil.DefaultConsensusParams) gasPrice := big.NewInt(10000) bytecode := common.FromHex("0x608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a36102c4806100dc6000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c010000000000000000000000000000000000000000000000000000000090048063893d20e814610058578063a6f9dae1146100a2575b600080fd5b6100606100e6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100e4600480360360208110156100b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061010f565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146101d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f43616c6c6572206973206e6f74206f776e65720000000000000000000000000081525060200191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505056fea265627a7a72315820f397f2733a89198bc7fed0764083694c5b828791f39ebcbc9e414bccef14b48064736f6c63430005100032") diff --git a/x/evm/keeper/state_transition_test.go b/x/evm/keeper/state_transition_test.go index 2c381fd87e..3883d4a298 100644 --- a/x/evm/keeper/state_transition_test.go +++ b/x/evm/keeper/state_transition_test.go @@ -99,7 +99,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { "case 1.1: context hash cached", uint64(suite.Ctx.BlockHeight()), func() { - suite.Ctx = suite.Ctx.WithHeaderHash(tmhash.Sum([]byte("header"))).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithHeaderHash(tmhash.Sum([]byte("header"))).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.BytesToHash(tmhash.Sum([]byte("header"))), }, @@ -109,7 +109,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { func() { header := tmproto.Header{} header.Height = suite.Ctx.BlockHeight() - suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.Hash{}, }, @@ -117,7 +117,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { "case 1.3: hash calculated from Tendermint header", uint64(suite.Ctx.BlockHeight()), func() { - suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.BytesToHash(hash), }, @@ -125,7 +125,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { "case 2.1: height lower than current one, hist info not found", 1, func() { - suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.Hash{}, }, @@ -134,7 +134,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { 1, func() { suite.App.StakingKeeper.SetHistoricalInfo(suite.Ctx, 1, &stakingtypes.HistoricalInfo{}) - suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.Hash{}, }, @@ -146,7 +146,7 @@ func (suite *StateTransitionTestSuite) TestGetHashFn() { Header: header, } suite.App.StakingKeeper.SetHistoricalInfo(suite.Ctx, 1, histInfo) - suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeight(10).WithConsensusParams(*testutil.DefaultConsensusParams) }, common.BytesToHash(hash), }, @@ -183,7 +183,7 @@ func (suite *StateTransitionTestSuite) TestGetCoinbaseAddress() { func() { header := suite.Ctx.BlockHeader() header.ProposerAddress = []byte{1} - suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*testutil.DefaultConsensusParams) }, false, }, @@ -206,7 +206,7 @@ func (suite *StateTransitionTestSuite) TestGetCoinbaseAddress() { header := suite.Ctx.BlockHeader() header.ProposerAddress = valConsAddr.Bytes() - suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeader(header).WithConsensusParams(*testutil.DefaultConsensusParams) _, err = suite.App.StakingKeeper.GetValidatorByConsAddr(suite.Ctx, valConsAddr.Bytes()) suite.Require().NoError(err) @@ -329,7 +329,7 @@ func (suite *StateTransitionTestSuite) TestGetEthIntrinsicGas() { ethCfg.HomesteadBlock = big.NewInt(2) ethCfg.IstanbulBlock = big.NewInt(3) signer := ethtypes.LatestSignerForChainID(suite.App.EvmKeeper.ChainID()) - suite.Ctx = suite.Ctx.WithBlockHeight(tc.height).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithBlockHeight(tc.height).WithConsensusParams(*testutil.DefaultConsensusParams) nonce := suite.App.EvmKeeper.GetNonce(suite.Ctx, suite.Address) m, err := newNativeMessage( nonce, diff --git a/x/evm/keeper/utils_test.go b/x/evm/keeper/utils_test.go index 53c470d07b..f5d7127ea0 100644 --- a/x/evm/keeper/utils_test.go +++ b/x/evm/keeper/utils_test.go @@ -451,7 +451,7 @@ func (suite *UtilsTestSuite) TestVerifyFeeAndDeductTxCostsFromUserBalance() { expectPassDeduct: true, from: suite.Address.String(), malleate: func() { - suite.Ctx = suite.Ctx.WithIsCheckTx(true).WithConsensusParams(*app.DefaultConsensusParams) + suite.Ctx = suite.Ctx.WithIsCheckTx(true).WithConsensusParams(*testutil.DefaultConsensusParams) }, }, } diff --git a/x/evm/statedb/statedb_test.go b/x/evm/statedb/statedb_test.go index 5f6ae7d097..5060e4abbf 100644 --- a/x/evm/statedb/statedb_test.go +++ b/x/evm/statedb/statedb_test.go @@ -25,7 +25,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" - "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil/config" ethermint "github.com/evmos/ethermint/types" evmkeeper "github.com/evmos/ethermint/x/evm/keeper" "github.com/evmos/ethermint/x/evm/statedb" @@ -797,7 +797,7 @@ func cloneRawState(t *testing.T, cms storetypes.MultiStore) map[string]map[strin } func newTestKeeper(t *testing.T, cms storetypes.MultiStore) (sdk.Context, *evmkeeper.Keeper) { - appCodec := app.MakeConfigForTest().Codec + appCodec := config.MakeConfigForTest(nil).Codec authAddr := authtypes.NewModuleAddress(govtypes.ModuleName).String() accountKeeper := authkeeper.NewAccountKeeper( appCodec, diff --git a/x/evm/types/msg_test.go b/x/evm/types/msg_test.go index c7de17773b..ce72dcee77 100644 --- a/x/evm/types/msg_test.go +++ b/x/evm/types/msg_test.go @@ -13,9 +13,9 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/app" "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/tests" + "github.com/evmos/ethermint/testutil/config" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -51,7 +51,7 @@ func (suite *MsgsTestSuite) SetupTest() { suite.chainID = big.NewInt(1) suite.hundredBigInt = big.NewInt(100) - encodingConfig := app.MakeConfigForTest() + encodingConfig := config.MakeConfigForTest(nil) suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig) } diff --git a/x/evm/types/utils_test.go b/x/evm/types/utils_test.go index 4cc70aca18..a8a7ef8f05 100644 --- a/x/evm/types/utils_test.go +++ b/x/evm/types/utils_test.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" proto "github.com/cosmos/gogoproto/proto" - "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil/config" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/evmos/ethermint/tests" @@ -51,7 +51,7 @@ func TestUnwrapEthererumMsg(t *testing.T) { _, err := evmtypes.UnwrapEthereumMsg(nil, common.Hash{}) require.NotNil(t, err) - encodingConfig := app.MakeConfigForTest() + encodingConfig := config.MakeConfigForTest(nil) clientCtx := client.Context{}.WithTxConfig(encodingConfig.TxConfig) builder, _ := clientCtx.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) diff --git a/x/feemarket/migrations/v4/migrate_test.go b/x/feemarket/migrations/v4/migrate_test.go index 60bc092d7a..7f281dda98 100644 --- a/x/feemarket/migrations/v4/migrate_test.go +++ b/x/feemarket/migrations/v4/migrate_test.go @@ -6,7 +6,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/testutil/config" v4 "github.com/evmos/ethermint/x/feemarket/migrations/v4" "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/require" @@ -29,7 +29,7 @@ func (ms mockSubspace) GetParamSetIfExists(ctx sdk.Context, ps types.LegacyParam } func TestMigrate(t *testing.T) { - encCfg := app.MakeConfigForTest() + encCfg := config.MakeConfigForTest(nil) cdc := encCfg.Codec storeKey := storetypes.NewKVStoreKey(types.ModuleName) From ee0677e2d8fc74f82c91b4492a276b94abbb28b8 Mon Sep 17 00:00:00 2001 From: mmsqe Date: Thu, 25 Apr 2024 21:27:41 +0800 Subject: [PATCH 2/2] less deps --- encoding/config_test.go | 7 ++--- testutil/config/encoding.go | 33 +---------------------- x/evm/types/msg_test.go | 11 +++----- x/evm/types/utils_test.go | 4 +-- x/feemarket/migrations/v4/migrate_test.go | 4 +-- 5 files changed, 11 insertions(+), 48 deletions(-) diff --git a/encoding/config_test.go b/encoding/config_test.go index 53a4f573a5..88e3d830fb 100644 --- a/encoding/config_test.go +++ b/encoding/config_test.go @@ -8,8 +8,8 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/evmos/ethermint/encoding" "github.com/evmos/ethermint/tests" - "github.com/evmos/ethermint/testutil/config" evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -23,10 +23,7 @@ func TestTxEncoding(t *testing.T) { ethSigner := ethtypes.LatestSignerForChainID(big.NewInt(1)) err := msg.Sign(ethSigner, signer) require.NoError(t, err) - - cfg := config.MakeConfigForTest(nil) - - _, err = cfg.TxConfig.TxEncoder()(msg) + _, err = encoding.MakeConfig().TxConfig.TxEncoder()(msg) require.Error(t, err, "encoding failed") // FIXME: transaction hashing is hardcoded on Terndermint: diff --git a/testutil/config/encoding.go b/testutil/config/encoding.go index eedd363f38..4f2c3d689d 100644 --- a/testutil/config/encoding.go +++ b/testutil/config/encoding.go @@ -1,30 +1,14 @@ package config import ( - "cosmossdk.io/x/evidence" - feegrantmodule "cosmossdk.io/x/feegrant/module" - "cosmossdk.io/x/upgrade" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/consensus" - "github.com/cosmos/cosmos-sdk/x/crisis" distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/cosmos/cosmos-sdk/x/gov" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/ibc-go/modules/capability" - "github.com/cosmos/ibc-go/v8/modules/apps/transfer" - ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" "github.com/evmos/ethermint/encoding" "github.com/evmos/ethermint/types" "github.com/evmos/ethermint/x/evm" @@ -36,25 +20,10 @@ func MakeConfigForTest(moduleManager module.BasicManager) types.EncodingConfig { if moduleManager == nil { moduleManager = module.NewBasicManager( auth.AppModuleBasic{}, - genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, distr.AppModuleBasic{}, gov.NewAppModuleBasic([]govclient.ProposalHandler{paramsclient.ProposalHandler}), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - ibctm.AppModuleBasic{}, - authzmodule.AppModuleBasic{}, - feegrantmodule.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, - consensus.AppModuleBasic{}, + staking.AppModuleBasic{}, // Ethermint modules evm.AppModuleBasic{}, feemarket.AppModuleBasic{}, diff --git a/x/evm/types/msg_test.go b/x/evm/types/msg_test.go index ce72dcee77..11076e7264 100644 --- a/x/evm/types/msg_test.go +++ b/x/evm/types/msg_test.go @@ -13,13 +13,12 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/crypto/ethsecp256k1" - "github.com/evmos/ethermint/tests" - "github.com/evmos/ethermint/testutil/config" - "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + "github.com/evmos/ethermint/encoding" + "github.com/evmos/ethermint/tests" "github.com/evmos/ethermint/x/evm/types" ) @@ -50,9 +49,7 @@ func (suite *MsgsTestSuite) SetupTest() { suite.to = tests.GenerateAddress() suite.chainID = big.NewInt(1) suite.hundredBigInt = big.NewInt(100) - - encodingConfig := config.MakeConfigForTest(nil) - suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig) + suite.clientCtx = client.Context{}.WithTxConfig(encoding.MakeConfig().TxConfig) } func (suite *MsgsTestSuite) TestMsgEthereumTx_Constructor() { diff --git a/x/evm/types/utils_test.go b/x/evm/types/utils_test.go index a8a7ef8f05..95175835ae 100644 --- a/x/evm/types/utils_test.go +++ b/x/evm/types/utils_test.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" proto "github.com/cosmos/gogoproto/proto" - "github.com/evmos/ethermint/testutil/config" + "github.com/evmos/ethermint/encoding" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/evmos/ethermint/tests" @@ -51,7 +51,7 @@ func TestUnwrapEthererumMsg(t *testing.T) { _, err := evmtypes.UnwrapEthereumMsg(nil, common.Hash{}) require.NotNil(t, err) - encodingConfig := config.MakeConfigForTest(nil) + encodingConfig := encoding.MakeConfig() clientCtx := client.Context{}.WithTxConfig(encodingConfig.TxConfig) builder, _ := clientCtx.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) diff --git a/x/feemarket/migrations/v4/migrate_test.go b/x/feemarket/migrations/v4/migrate_test.go index 7f281dda98..f92ec545eb 100644 --- a/x/feemarket/migrations/v4/migrate_test.go +++ b/x/feemarket/migrations/v4/migrate_test.go @@ -6,7 +6,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/evmos/ethermint/testutil/config" + "github.com/evmos/ethermint/encoding" v4 "github.com/evmos/ethermint/x/feemarket/migrations/v4" "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/require" @@ -29,7 +29,7 @@ func (ms mockSubspace) GetParamSetIfExists(ctx sdk.Context, ps types.LegacyParam } func TestMigrate(t *testing.T) { - encCfg := config.MakeConfigForTest(nil) + encCfg := encoding.MakeConfig() cdc := encCfg.Codec storeKey := storetypes.NewKVStoreKey(types.ModuleName)