evm: fixed commented out simulations, pubsub, and handler tests (#655)

* evm: fixed commented out simulations, pubsub, and handler tests

fixes #640

simulations are very basic: they can be built and executed,
but they don't generate any EVM-related transactions yet.
(It should be a matter of adding simulation-related code to the
modules + potentially extra helpers to the simulation.)
handler tests miss some extra assertions due to changes
in the return values snapshotting logic (ADR-001 and ADR-002).

Besides the test suites identified in the audit,
there's also "importer_test.go" which wasn't yet fixed.
(it'd require major rewriting + extra test resources)

* gofumpt
This commit is contained in:
Tomas Tauber 2021-10-11 19:09:53 +08:00 committed by GitHub
parent e9ab6241db
commit e91ec58aa1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 950 additions and 706 deletions

View File

@ -495,6 +495,8 @@ func NewEthermintApp(
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
ibc.NewAppModule(app.IBCKeeper), ibc.NewAppModule(app.IBCKeeper),
transferModule, transferModule,
evm.NewAppModule(app.EvmKeeper, app.AccountKeeper),
feemarket.NewAppModule(app.FeeMarketKeeper),
) )
app.sm.RegisterStoreDecoders() app.sm.RegisterStoreDecoders()

View File

@ -1,340 +1,349 @@
package app package app
// disable for now, enable it once SDK side fix the simulator issue for custom keys // TODO: COsmos SDK fix for the simulator issue for custom keys
//import ( import (
// "encoding/json" "encoding/json"
// "fmt" "fmt"
// "math/rand" "math/rand"
// "os" "os"
// "testing" "testing"
//
// "github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
//
// abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/baseapp"
// "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/simapp"
// tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/simapp/params"
// dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/store"
// sdk "github.com/cosmos/cosmos-sdk/types"
// "github.com/cosmos/cosmos-sdk/baseapp" simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
// "github.com/cosmos/cosmos-sdk/simapp" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
// "github.com/cosmos/cosmos-sdk/simapp/helpers" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
// "github.com/cosmos/cosmos-sdk/store" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
// sdk "github.com/cosmos/cosmos-sdk/types" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
// simtypes "github.com/cosmos/cosmos-sdk/types/simulation" evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
// authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
// banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
// capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
// distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation"
// evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
// govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
// ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" ibctransfertypes "github.com/cosmos/ibc-go/modules/apps/transfer/types"
// ibchost "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" ibchost "github.com/cosmos/ibc-go/modules/core/24-host"
// minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" abci "github.com/tendermint/tendermint/abci/types"
// paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/libs/log"
// "github.com/cosmos/cosmos-sdk/x/simulation" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
// slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" dbm "github.com/tendermint/tm-db"
// stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" evmenc "github.com/tharsis/ethermint/encoding"
//) )
//
//func init() { // MakeEncodingConfig creates the EncodingConfig
// simapp.GetSimulatorFlags() func MakeEncodingConfig() params.EncodingConfig {
//} return evmenc.MakeConfig(ModuleBasics)
// }
//type storeKeysPrefixes struct {
// A sdk.StoreKey func init() {
// B sdk.StoreKey simapp.GetSimulatorFlags()
// Prefixes [][]byte }
//}
// const SimAppChainID = "simulation_777-1"
//// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of
//// an IAVLStore for faster simulation speed. type storeKeysPrefixes struct {
//func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { A sdk.StoreKey
// bapp.SetFauxMerkleMode() B sdk.StoreKey
//} Prefixes [][]byte
// }
//// interBlockCacheOpt returns a BaseApp option function that sets the persistent
//// inter-block write-through cache. // fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of
//func interBlockCacheOpt() func(*baseapp.BaseApp) { // an IAVLStore for faster simulation speed.
// return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager()) func fauxMerkleModeOpt(bapp *baseapp.BaseApp) {
//} bapp.SetFauxMerkleMode()
// }
//func TestFullAppSimulation(t *testing.T) {
// config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation") // interBlockCacheOpt returns a BaseApp option function that sets the persistent
// if skip { // inter-block write-through cache.
// t.Skip("skipping application simulation") func interBlockCacheOpt() func(*baseapp.BaseApp) {
// } return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager())
// require.NoError(t, err, "simulation setup failed") }
//
// defer func() { func TestFullAppSimulation(t *testing.T) {
// db.Close() config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation")
// require.NoError(t, os.RemoveAll(dir)) if skip {
// }() t.Skip("skipping application simulation")
// }
// app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt) require.NoError(t, err, "simulation setup failed")
// require.Equal(t, appName, app.Name())
// defer func() {
// // run randomized simulation db.Close()
// _, simParams, simErr := simulation.SimulateFromSeed( require.NoError(t, os.RemoveAll(dir))
// t, }()
// os.Stdout,
// app.BaseApp, app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()), require.Equal(t, appName, app.Name())
// simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// simapp.SimulationOperations(app, app.AppCodec(), config), // run randomized simulation
// app.ModuleAccountAddrs(), _, simParams, simErr := simulation.SimulateFromSeed(
// config, t,
// app.AppCodec(), os.Stdout,
// ) app.BaseApp,
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// // export state and simParams before the simulation error is checked simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// err = simapp.CheckExportSimulation(app, config, simParams) simapp.SimulationOperations(app, app.AppCodec(), config),
// require.NoError(t, err) app.ModuleAccountAddrs(),
// require.NoError(t, simErr) config,
// app.AppCodec(),
// if config.Commit { )
// simapp.PrintStats(db)
// } // export state and simParams before the simulation error is checked
//} err = simapp.CheckExportSimulation(app, config, simParams)
// require.NoError(t, err)
//func TestAppImportExport(t *testing.T) { require.NoError(t, simErr)
// config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation")
// if skip { if config.Commit {
// t.Skip("skipping application import/export simulation") simapp.PrintStats(db)
// } }
// require.NoError(t, err, "simulation setup failed") }
//
// defer func() { func TestAppImportExport(t *testing.T) {
// db.Close() config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation")
// require.NoError(t, os.RemoveAll(dir)) if skip {
// }() t.Skip("skipping application import/export simulation")
// }
// app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt) require.NoError(t, err, "simulation setup failed")
// require.Equal(t, appName, app.Name())
// defer func() {
// // Run randomized simulation db.Close()
// _, simParams, simErr := simulation.SimulateFromSeed( require.NoError(t, os.RemoveAll(dir))
// t, }()
// os.Stdout,
// app.BaseApp, app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()), require.Equal(t, appName, app.Name())
// simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// simapp.SimulationOperations(app, app.AppCodec(), config), // Run randomized simulation
// app.ModuleAccountAddrs(), _, simParams, simErr := simulation.SimulateFromSeed(
// config, t,
// app.AppCodec(), os.Stdout,
// ) app.BaseApp,
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// // export state and simParams before the simulation error is checked simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// err = simapp.CheckExportSimulation(app, config, simParams) simapp.SimulationOperations(app, app.AppCodec(), config),
// require.NoError(t, err) app.ModuleAccountAddrs(),
// require.NoError(t, simErr) config,
// app.AppCodec(),
// if config.Commit { )
// simapp.PrintStats(db)
// } // export state and simParams before the simulation error is checked
// err = simapp.CheckExportSimulation(app, config, simParams)
// fmt.Printf("exporting genesis...\n") require.NoError(t, err)
// require.NoError(t, simErr)
// exported, err := app.ExportAppStateAndValidators(false, []string{})
// require.NoError(t, err) if config.Commit {
// simapp.PrintStats(db)
// fmt.Printf("importing genesis...\n") }
//
// // nolint: dogsled fmt.Printf("exporting genesis...\n")
// _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2")
// require.NoError(t, err, "simulation setup failed") exported, err := app.ExportAppStateAndValidators(false, []string{})
// require.NoError(t, err)
// defer func() {
// newDB.Close() fmt.Printf("importing genesis...\n")
// require.NoError(t, os.RemoveAll(newDir))
// }() // nolint: dogsled
// _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2")
// newApp := NewEthermintApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt) require.NoError(t, err, "simulation setup failed")
// require.Equal(t, appName, newApp.Name())
// defer func() {
// var genesisState simapp.GenesisState newDB.Close()
// err = json.Unmarshal(exported.AppState, &genesisState) require.NoError(t, os.RemoveAll(newDir))
// require.NoError(t, err) }()
//
// ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) newApp := NewEthermintApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) require.Equal(t, appName, newApp.Name())
// newApp.mm.InitGenesis(ctxB, app.AppCodec(), genesisState)
// newApp.StoreConsensusParams(ctxB, exported.ConsensusParams) var genesisState simapp.GenesisState
// err = json.Unmarshal(exported.AppState, &genesisState)
// fmt.Printf("comparing stores...\n") require.NoError(t, err)
//
// storeKeysPrefixes := []storeKeysPrefixes{ ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})
// {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}}, ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})
// {app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], newApp.mm.InitGenesis(ctxB, app.AppCodec(), genesisState)
// [][]byte{ newApp.StoreConsensusParams(ctxB, exported.ConsensusParams)
// stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey,
// stakingtypes.HistoricalInfoKey, fmt.Printf("comparing stores...\n")
// }}, // ordering may change but it doesn't matter
// {app.keys[slashingtypes.StoreKey], newApp.keys[slashingtypes.StoreKey], [][]byte{}}, storeKeysPrefixes := []storeKeysPrefixes{
// {app.keys[minttypes.StoreKey], newApp.keys[minttypes.StoreKey], [][]byte{}}, {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}},
// {app.keys[distrtypes.StoreKey], newApp.keys[distrtypes.StoreKey], [][]byte{}}, {
// {app.keys[banktypes.StoreKey], newApp.keys[banktypes.StoreKey], [][]byte{banktypes.BalancesPrefix}}, app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey],
// {app.keys[paramtypes.StoreKey], newApp.keys[paramtypes.StoreKey], [][]byte{}}, [][]byte{
// {app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}}, stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey,
// {app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}}, stakingtypes.HistoricalInfoKey,
// {app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}}, },
// {app.keys[ibchost.StoreKey], newApp.keys[ibchost.StoreKey], [][]byte{}}, }, // ordering may change but it doesn't matter
// {app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}}, {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{}},
// for _, skp := range storeKeysPrefixes { {app.keys[banktypes.StoreKey], newApp.keys[banktypes.StoreKey], [][]byte{banktypes.BalancesPrefix}},
// storeA := ctxA.KVStore(skp.A) {app.keys[paramtypes.StoreKey], newApp.keys[paramtypes.StoreKey], [][]byte{}},
// storeB := ctxB.KVStore(skp.B) {app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}},
// {app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}},
// failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes) {app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}},
// require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") {app.keys[ibchost.StoreKey], newApp.keys[ibchost.StoreKey], [][]byte{}},
// {app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}},
// 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, simapp.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs))
// } for _, skp := range storeKeysPrefixes {
//} storeA := ctxA.KVStore(skp.A)
// storeB := ctxB.KVStore(skp.B)
//func TestAppSimulationAfterImport(t *testing.T) {
// config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation") failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes)
// if skip { require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare")
// t.Skip("skipping application simulation after import")
// } fmt.Printf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B)
// require.NoError(t, err, "simulation setup failed") require.Equal(t, len(failedKVAs), 0, simapp.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs))
// }
// defer func() { }
// db.Close()
// require.NoError(t, os.RemoveAll(dir)) func TestAppSimulationAfterImport(t *testing.T) {
// }() config, db, dir, logger, skip, err := simapp.SetupSimulation("leveldb-app-sim", "Simulation")
// if skip {
// app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt) t.Skip("skipping application simulation after import")
// require.Equal(t, appName, app.Name()) }
// require.NoError(t, err, "simulation setup failed")
// // Run randomized simulation
// stopEarly, simParams, simErr := simulation.SimulateFromSeed( defer func() {
// t, db.Close()
// os.Stdout, require.NoError(t, os.RemoveAll(dir))
// app.BaseApp, }()
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// simapp.SimulationOperations(app, app.AppCodec(), config), require.Equal(t, appName, app.Name())
// app.ModuleAccountAddrs(),
// config, // Run randomized simulation
// app.AppCodec(), stopEarly, simParams, simErr := simulation.SimulateFromSeed(
// ) t,
// os.Stdout,
// // export state and simParams before the simulation error is checked app.BaseApp,
// err = simapp.CheckExportSimulation(app, config, simParams) simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// require.NoError(t, err) simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// require.NoError(t, simErr) simapp.SimulationOperations(app, app.AppCodec(), config),
// app.ModuleAccountAddrs(),
// if config.Commit { config,
// simapp.PrintStats(db) app.AppCodec(),
// } )
//
// if stopEarly { // export state and simParams before the simulation error is checked
// fmt.Println("can't export or import a zero-validator genesis, exiting test...") err = simapp.CheckExportSimulation(app, config, simParams)
// return require.NoError(t, err)
// } require.NoError(t, simErr)
//
// fmt.Printf("exporting genesis...\n") if config.Commit {
// simapp.PrintStats(db)
// exported, err := app.ExportAppStateAndValidators(true, []string{}) }
// require.NoError(t, err)
// if stopEarly {
// fmt.Printf("importing genesis...\n") fmt.Println("can't export or import a zero-validator genesis, exiting test...")
// return
// _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2") }
// require.NoError(t, err, "simulation setup failed")
// fmt.Printf("exporting genesis...\n")
// defer func() {
// newDB.Close() exported, err := app.ExportAppStateAndValidators(true, []string{})
// require.NoError(t, os.RemoveAll(newDir)) require.NoError(t, err)
// }()
// fmt.Printf("importing genesis...\n")
// newApp := NewEthermintApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// require.Equal(t, appName, newApp.Name()) _, newDB, newDir, _, _, err := simapp.SetupSimulation("leveldb-app-sim-2", "Simulation-2")
// require.NoError(t, err, "simulation setup failed")
// newApp.InitChain(abci.RequestInitChain{
// AppStateBytes: exported.AppState, defer func() {
// }) newDB.Close()
// require.NoError(t, os.RemoveAll(newDir))
// _, _, err = simulation.SimulateFromSeed( }()
// t,
// os.Stdout, newApp := NewEthermintApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, fauxMerkleModeOpt)
// newApp.BaseApp, require.Equal(t, appName, newApp.Name())
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 newApp.InitChain(abci.RequestInitChain{
// simapp.SimulationOperations(newApp, newApp.AppCodec(), config), AppStateBytes: exported.AppState,
// app.ModuleAccountAddrs(), })
// config,
// app.AppCodec(), _, _, err = simulation.SimulateFromSeed(
// ) t,
// require.NoError(t, err) os.Stdout,
//} newApp.BaseApp,
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
//// TODO: Make another test for the fuzzer itself, which just has noOp txs simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
//// and doesn't depend on the application. simapp.SimulationOperations(newApp, newApp.AppCodec(), config),
//func TestAppStateDeterminism(t *testing.T) { app.ModuleAccountAddrs(),
// if !simapp.FlagEnabledValue { config,
// t.Skip("skipping application simulation") app.AppCodec(),
// } )
// require.NoError(t, err)
// config := simapp.NewConfigFromFlags() }
// config.InitialBlockHeight = 1
// config.ExportParamsPath = "" // TODO: Make another test for the fuzzer itself, which just has noOp txs
// config.OnOperation = false // and doesn't depend on the application.
// config.AllInvariants = false func TestAppStateDeterminism(t *testing.T) {
// config.ChainID = helpers.SimAppChainID if !simapp.FlagEnabledValue {
// t.Skip("skipping application simulation")
// numSeeds := 3 }
// numTimesToRunPerSeed := 5
// appHashList := make([]json.RawMessage, numTimesToRunPerSeed) config := simapp.NewConfigFromFlags()
// config.InitialBlockHeight = 1
// for i := 0; i < numSeeds; i++ { config.ExportParamsPath = ""
// config.Seed = rand.Int63() config.OnOperation = false
// config.AllInvariants = false
// for j := 0; j < numTimesToRunPerSeed; j++ { config.ChainID = SimAppChainID
// var logger log.Logger
// if simapp.FlagVerboseValue { numSeeds := 3
// logger = log.TestingLogger() numTimesToRunPerSeed := 5
// } else { appHashList := make([]json.RawMessage, numTimesToRunPerSeed)
// logger = log.NewNopLogger()
// } for i := 0; i < numSeeds; i++ {
// config.Seed = rand.Int63()
// db := dbm.NewMemDB()
// app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, interBlockCacheOpt()) for j := 0; j < numTimesToRunPerSeed; j++ {
// var logger log.Logger
// fmt.Printf( if simapp.FlagVerboseValue {
// "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", logger = log.TestingLogger()
// config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, } else {
// ) logger = log.NewNopLogger()
// }
// _, _, err := simulation.SimulateFromSeed(
// t, db := dbm.NewMemDB()
// os.Stdout, app := NewEthermintApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, MakeEncodingConfig(), simapp.EmptyAppOptions{}, interBlockCacheOpt())
// app.BaseApp,
// simapp.AppStateFn(app.AppCodec(), app.SimulationManager()), fmt.Printf(
// simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n",
// simapp.SimulationOperations(app, app.AppCodec(), config), config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
// app.ModuleAccountAddrs(), )
// config,
// app.AppCodec(), _, _, err := simulation.SimulateFromSeed(
// ) t,
// require.NoError(t, err) os.Stdout,
// app.BaseApp,
// if config.Commit { simapp.AppStateFn(app.AppCodec(), app.SimulationManager()),
// simapp.PrintStats(db) simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
// } simapp.SimulationOperations(app, app.AppCodec(), config),
// app.ModuleAccountAddrs(),
// appHash := app.LastCommitID().Hash config,
// appHashList[j] = appHash app.AppCodec(),
// )
// if j != 0 { require.NoError(t, err)
// require.Equal(
// t, string(appHashList[0]), string(appHashList[j]), if config.Commit {
// "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, simapp.PrintStats(db)
// ) }
// }
// } appHash := app.LastCommitID().Hash
// } appHashList[j] = appHash
//}
if j != 0 {
require.Equal(
t, string(appHashList[0]), string(appHashList[j]),
"non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
)
}
}
}
}

View File

@ -1,69 +1,82 @@
package pubsub package pubsub
// func TestAddTopic(t *testing.T) { import (
// q := NewEventBus() "log"
// err := q.AddTopic("kek", make(<-chan coretypes.ResultEvent)) "sync"
// require.NoError(t, err) "testing"
"time"
// err = q.AddTopic("lol", make(<-chan coretypes.ResultEvent)) "github.com/stretchr/testify/require"
// require.NoError(t, err) coretypes "github.com/tendermint/tendermint/rpc/core/types"
)
// err = q.AddTopic("lol", make(<-chan coretypes.ResultEvent)) func TestAddTopic(t *testing.T) {
// require.Error(t, err) q := NewEventBus()
err := q.AddTopic("kek", make(<-chan coretypes.ResultEvent))
require.NoError(t, err)
// require.EqualValues(t, []string{"kek", "lol"}, q.Topics()) err = q.AddTopic("lol", make(<-chan coretypes.ResultEvent))
// } require.NoError(t, err)
// func TestSubscribe(t *testing.T) { err = q.AddTopic("lol", make(<-chan coretypes.ResultEvent))
// q := NewEventBus() require.Error(t, err)
// kekSrc := make(chan coretypes.ResultEvent)
// q.AddTopic("kek", kekSrc)
// lolSrc := make(chan coretypes.ResultEvent) require.EqualValues(t, []string{"kek", "lol"}, q.Topics())
// q.AddTopic("lol", lolSrc) }
// kekSubC, err := q.Subscribe("kek") func TestSubscribe(t *testing.T) {
// require.NoError(t, err) q := NewEventBus()
kekSrc := make(chan coretypes.ResultEvent)
// lolSubC, err := q.Subscribe("lol") q.AddTopic("kek", kekSrc)
// require.NoError(t, err)
// lol2SubC, err := q.Subscribe("lol") lolSrc := make(chan coretypes.ResultEvent)
// require.NoError(t, err)
// wg := new(sync.WaitGroup) q.AddTopic("lol", lolSrc)
// wg.Add(4)
// go func() { kekSubC, err := q.Subscribe("kek")
// defer wg.Done() require.NoError(t, err)
// msg := <-kekSubC
// log.Println("kek:", msg)
// require.EqualValues(t, 1, msg)
// }()
// go func() { lolSubC, err := q.Subscribe("lol")
// defer wg.Done() require.NoError(t, err)
// msg := <-lolSubC
// log.Println("lol:", msg)
// require.EqualValues(t, 1, msg)
// }()
// go func() { lol2SubC, err := q.Subscribe("lol")
// defer wg.Done() require.NoError(t, err)
// msg := <-lol2SubC
// log.Println("lol2:", msg)
// require.EqualValues(t, 1, msg)
// }()
// go func() { wg := new(sync.WaitGroup)
// defer wg.Done() wg.Add(4)
// time.Sleep(time.Second) emptyMsg := coretypes.ResultEvent{}
go func() {
defer wg.Done()
msg := <-kekSubC
log.Println("kek:", msg)
require.EqualValues(t, emptyMsg, msg)
}()
// close(kekSrc) go func() {
// close(lolSrc) defer wg.Done()
// }() msg := <-lolSubC
log.Println("lol:", msg)
require.EqualValues(t, emptyMsg, msg)
}()
// wg.Wait() go func() {
// time.Sleep(time.Second) defer wg.Done()
// } msg := <-lol2SubC
log.Println("lol2:", msg)
require.EqualValues(t, emptyMsg, msg)
}()
go func() {
defer wg.Done()
time.Sleep(time.Second)
close(kekSrc)
close(lolSrc)
}()
wg.Wait()
time.Sleep(time.Second)
}

View File

@ -5,11 +5,23 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/suite" "github.com/gogo/protobuf/proto"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/cosmos/cosmos-sdk/simapp"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -17,9 +29,15 @@ import (
"github.com/tharsis/ethermint/app" "github.com/tharsis/ethermint/app"
"github.com/tharsis/ethermint/crypto/ethsecp256k1" "github.com/tharsis/ethermint/crypto/ethsecp256k1"
"github.com/tharsis/ethermint/tests" "github.com/tharsis/ethermint/tests"
ethermint "github.com/tharsis/ethermint/types"
"github.com/tharsis/ethermint/x/evm" "github.com/tharsis/ethermint/x/evm"
"github.com/tharsis/ethermint/x/evm/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
"github.com/tendermint/tendermint/version"
) )
type EvmTestSuite struct { type EvmTestSuite struct {
@ -37,383 +55,462 @@ type EvmTestSuite struct {
to sdk.AccAddress to sdk.AccAddress
} }
func (suite *EvmTestSuite) SetupTest() { /// DoSetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`.
func (suite *EvmTestSuite) DoSetupTest(t require.TestingT) {
checkTx := false checkTx := false
// account key
priv, err := ethsecp256k1.GenerateKey()
require.NoError(t, err)
address := common.BytesToAddress(priv.PubKey().Address().Bytes())
suite.signer = tests.NewSigner(priv)
suite.from = address
// consensus key
priv, err = ethsecp256k1.GenerateKey()
require.NoError(t, err)
consAddress := sdk.ConsAddress(priv.PubKey().Address())
suite.app = app.Setup(checkTx) suite.app = app.Setup(checkTx)
suite.ctx = suite.app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 1, ChainID: "ethermint_9000-1", Time: time.Now().UTC()}) coins := sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdk.NewInt(100000000000000)))
genesisState := app.ModuleBasics.DefaultGenesis(suite.app.AppCodec())
b32address := sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), priv.PubKey().Address().Bytes())
balances := []banktypes.Balance{
{
Address: b32address,
Coins: coins,
},
{
Address: suite.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName).String(),
Coins: coins,
},
}
// update total supply
bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdk.NewInt(200000000000000))), []banktypes.Metadata{})
genesisState[banktypes.ModuleName] = suite.app.AppCodec().MustMarshalJSON(bankGenesis)
stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)
// Initialize the chain
suite.app.InitChain(
abci.RequestInitChain{
ChainId: "ethermint_9000-1",
Validators: []abci.ValidatorUpdate{},
ConsensusParams: simapp.DefaultConsensusParams,
AppStateBytes: stateBytes,
},
)
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")),
})
suite.app.EvmKeeper.WithContext(suite.ctx) suite.app.EvmKeeper.WithContext(suite.ctx)
queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, suite.app.EvmKeeper)
acc := &ethermint.EthAccount{
BaseAccount: authtypes.NewBaseAccount(sdk.AccAddress(address.Bytes()), nil, 0, 0),
CodeHash: common.BytesToHash(crypto.Keccak256(nil)).String(),
}
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
valAddr := sdk.ValAddress(address.Bytes())
validator, err := stakingtypes.NewValidator(valAddr, priv.PubKey(), stakingtypes.Description{})
require.NoError(t, err)
err = suite.app.StakingKeeper.SetValidatorByConsAddr(suite.ctx, validator)
require.NoError(t, err)
err = suite.app.StakingKeeper.SetValidatorByConsAddr(suite.ctx, validator)
require.NoError(t, err)
suite.app.StakingKeeper.SetValidator(suite.ctx, validator)
suite.ethSigner = ethtypes.LatestSignerForChainID(suite.app.EvmKeeper.ChainID())
suite.handler = evm.NewHandler(suite.app.EvmKeeper) suite.handler = evm.NewHandler(suite.app.EvmKeeper)
suite.codec = suite.app.AppCodec() }
suite.chainID = suite.app.EvmKeeper.ChainID()
privKey, err := ethsecp256k1.GenerateKey() func (suite *EvmTestSuite) SetupTest() {
suite.Require().NoError(err) suite.DoSetupTest(suite.T())
suite.to = sdk.AccAddress(privKey.PubKey().Address())
privKey, err = ethsecp256k1.GenerateKey()
suite.Require().NoError(err)
suite.signer = tests.NewSigner(privKey)
suite.ethSigner = ethtypes.LatestSignerForChainID(suite.chainID)
suite.from = common.BytesToAddress(privKey.PubKey().Address().Bytes())
} }
func TestEvmTestSuite(t *testing.T) { func TestEvmTestSuite(t *testing.T) {
suite.Run(t, new(EvmTestSuite)) suite.Run(t, new(EvmTestSuite))
} }
// func (suite *EvmTestSuite) TestHandleMsgEthereumTx() { func (suite *EvmTestSuite) TestHandleMsgEthereumTx() {
var tx *types.MsgEthereumTx
// var tx *types.MsgEthereumTx testCases := []struct {
msg string
malleate func()
expPass bool
}{
{
"passed",
func() {
to := common.BytesToAddress(suite.to)
tx = types.NewTx(suite.chainID, 0, &to, big.NewInt(100), 10_000_000, big.NewInt(10000), nil, nil, nil, nil)
tx.From = suite.from.String()
// testCases := []struct { // sign transaction
// msg string err := tx.Sign(suite.ethSigner, suite.signer)
// malleate func() suite.Require().NoError(err)
// expPass bool },
// }{ true,
// { },
// "passed", {
// func() { "insufficient balance",
// to := common.BytesToAddress(suite.to) func() {
// tx = types.NewTx(suite.chainID, 0, &to, big.NewInt(100), 0, big.NewInt(10000), nil, nil) tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil, nil, nil)
// tx.From = suite.from.String() tx.From = suite.from.Hex()
// sign transaction
err := tx.Sign(suite.ethSigner, suite.signer)
suite.Require().NoError(err)
},
false,
},
{
"tx encoding failed",
func() {
tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil, nil, nil)
},
false,
},
{
"invalid chain ID",
func() {
suite.ctx = suite.ctx.WithChainID("chainID")
},
false,
},
{
"VerifySig failed",
func() {
tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil, nil, nil)
},
false,
},
}
// // sign transaction for _, tc := range testCases {
// err := tx.Sign(suite.ethSigner, suite.signer) suite.Run(tc.msg, func() {
// suite.Require().NoError(err) suite.SetupTest() // reset
// }, //nolint
// true, tc.malleate()
// }, suite.app.EvmKeeper.Snapshot()
// { res, err := suite.handler(suite.ctx, tx)
// "insufficient balance",
// func() {
// tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil)
// tx.From = suite.from.Hex()
// // sign transaction
// err := tx.Sign(suite.ethSigner, suite.signer)
// suite.Require().NoError(err)
// },
// false,
// },
// {
// "tx encoding failed",
// func() {
// tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil)
// },
// false,
// },
// {
// "invalid chain ID",
// func() {
// suite.ctx = suite.ctx.WithChainID("chainID")
// },
// false,
// },
// {
// "VerifySig failed",
// func() {
// tx = types.NewTxContract(suite.chainID, 0, big.NewInt(100), 0, big.NewInt(10000), nil, nil)
// },
// false,
// },
// }
// for _, tc := range testCases { //nolint
// suite.Run(tc.msg, func() { if tc.expPass {
// suite.SetupTest() // reset suite.Require().NoError(err)
// //nolint suite.Require().NotNil(res)
// tc.malleate() } else {
suite.Require().Error(err)
suite.Require().Nil(res)
}
})
}
}
// res, err := suite.handler(suite.ctx, tx) func (suite *EvmTestSuite) TestHandlerLogs() {
// Test contract:
// //nolint // pragma solidity ^0.5.1;
// if tc.expPass {
// suite.Require().NoError(err)
// suite.Require().NotNil(res)
// } else {
// suite.Require().Error(err)
// suite.Require().Nil(res)
// }
// })
// }
// }
// func (suite *EvmTestSuite) TestHandlerLogs() { // contract Test {
// // Test contract: // event Hello(uint256 indexed world);
// // pragma solidity ^0.5.1; // constructor() public {
// emit Hello(17);
// }
// }
// // contract Test { // {
// // event Hello(uint256 indexed world); // "linkReferences": {},
// "object": "6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029",
// "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x11 PUSH32 0x775A94827B8FD9B519D36CD827093C664F93347070A554F65E4A6F56CD738898 PUSH1 0x40 MLOAD PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG2 PUSH1 0x35 DUP1 PUSH1 0x4B PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT INVALID LOG1 PUSH6 0x627A7A723058 KECCAK256 PUSH13 0xAB665F0F557620554BB45ADF26 PUSH8 0x8D2BD349B8A4314 0xbd SELFDESTRUCT KECCAK256 0x5e 0xe8 DIFFICULTY 0xe EXTCODECOPY 0x24 STOP 0x29 ",
// "sourceMap": "25:119:0:-;;;90:52;8:9:-1;5:2;;;30:1;27;20:12;5:2;90:52:0;132:2;126:9;;;;;;;;;;25:119;;;;;;"
// }
// // constructor() public { gasLimit := uint64(100000)
// // emit Hello(17); gasPrice := big.NewInt(1000000)
// // }
// // }
// // { bytecode := common.FromHex("0x6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029")
// // "linkReferences": {}, tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
// // "object": "6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029", tx.From = suite.from.String()
// // "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x11 PUSH32 0x775A94827B8FD9B519D36CD827093C664F93347070A554F65E4A6F56CD738898 PUSH1 0x40 MLOAD PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG2 PUSH1 0x35 DUP1 PUSH1 0x4B PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT INVALID LOG1 PUSH6 0x627A7A723058 KECCAK256 PUSH13 0xAB665F0F557620554BB45ADF26 PUSH8 0x8D2BD349B8A4314 0xbd SELFDESTRUCT KECCAK256 0x5e 0xe8 DIFFICULTY 0xe EXTCODECOPY 0x24 STOP 0x29 ",
// // "sourceMap": "25:119:0:-;;;90:52;8:9:-1;5:2;;;30:1;27;20:12;5:2;90:52:0;132:2;126:9;;;;;;;;;;25:119;;;;;;"
// // }
// gasLimit := uint64(100000) err := tx.Sign(suite.ethSigner, suite.signer)
// gasPrice := big.NewInt(1000000) suite.Require().NoError(err)
// bytecode := common.FromHex("0x6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029") result, err := suite.handler(suite.ctx, tx)
// tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) suite.Require().NoError(err, "failed to handle eth tx msg")
// tx.From = suite.from.String()
// err := tx.Sign(suite.ethSigner, suite.signer) var txResponse types.MsgEthereumTxResponse
// suite.Require().NoError(err)
// result, err := suite.handler(suite.ctx, tx) err = proto.Unmarshal(result.Data, &txResponse)
// suite.Require().NoError(err, "failed to handle eth tx msg") suite.Require().NoError(err, "failed to decode result data")
// txResponse, err := types.DecodeTxResponse(result.Data) suite.Require().Equal(len(txResponse.Logs), 1)
// suite.Require().NoError(err, "failed to decode result data") suite.Require().Equal(len(txResponse.Logs[0].Topics), 2)
// suite.Require().Equal(len(txResponse.Logs), 1) tlogs := types.LogsToEthereum(txResponse.Logs)
// suite.Require().Equal(len(txResponse.Logs[0].Topics), 2) for _, log := range tlogs {
suite.app.EvmKeeper.AddLogTransient(log)
}
suite.Require().NoError(err)
// hash := []byte{1} logs := suite.app.EvmKeeper.GetTxLogsTransient(tlogs[0].TxHash)
// suite.app.EvmKeeper.SetLogs(common.BytesToHash(hash), types.LogsToEthereum(txResponse.Logs))
// suite.Require().NoError(err)
// logs := suite.app.EvmKeeper.GetTxLogs(common.BytesToHash(hash)) suite.Require().Equal(logs, tlogs)
}
// suite.Require().Equal(logs, txResponse.Logs) func (suite *EvmTestSuite) TestDeployAndCallContract() {
// } // Test contract:
//http://remix.ethereum.org/#optimize=false&evmVersion=istanbul&version=soljson-v0.5.15+commit.6a57276f.js
//2_Owner.sol
//
//pragma solidity >=0.4.22 <0.7.0;
//
///**
// * @title Owner
// * @dev Set & change owner
// */
//contract Owner {
//
// address private owner;
//
// // event for EVM logging
// event OwnerSet(address indexed oldOwner, address indexed newOwner);
//
// // modifier to check if caller is owner
// modifier isOwner() {
// // If the first argument of 'require' evaluates to 'false', execution terminates and all
// // changes to the state and to Ether balances are reverted.
// // This used to consume all gas in old EVM versions, but not anymore.
// // It is often a good idea to use 'require' to check if functions are called correctly.
// // As a second argument, you can also provide an explanation about what went wrong.
// require(msg.sender == owner, "Caller is not owner");
// _;
//}
//
// /**
// * @dev Set contract deployer as owner
// */
// constructor() public {
// owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
// emit OwnerSet(address(0), owner);
//}
//
// /**
// * @dev Change owner
// * @param newOwner address of new owner
// */
// function changeOwner(address newOwner) public isOwner {
// emit OwnerSet(owner, newOwner);
// owner = newOwner;
//}
//
// /**
// * @dev Return owner address
// * @return address of owner
// */
// function getOwner() external view returns (address) {
// return owner;
//}
//}
// func (suite *EvmTestSuite) TestDeployAndCallContract() { // Deploy contract - Owner.sol
// // Test contract: gasLimit := uint64(100000000)
// //http://remix.ethereum.org/#optimize=false&evmVersion=istanbul&version=soljson-v0.5.15+commit.6a57276f.js gasPrice := big.NewInt(10000)
// //2_Owner.sol
// //
// //pragma solidity >=0.4.22 <0.7.0;
// //
// ///**
// // * @title Owner
// // * @dev Set & change owner
// // */
// //contract Owner {
// //
// // address private owner;
// //
// // // event for EVM logging
// // event OwnerSet(address indexed oldOwner, address indexed newOwner);
// //
// // // modifier to check if caller is owner
// // modifier isOwner() {
// // // If the first argument of 'require' evaluates to 'false', execution terminates and all
// // // changes to the state and to Ether balances are reverted.
// // // This used to consume all gas in old EVM versions, but not anymore.
// // // It is often a good idea to use 'require' to check if functions are called correctly.
// // // As a second argument, you can also provide an explanation about what went wrong.
// // require(msg.sender == owner, "Caller is not owner");
// // _;
// //}
// //
// // /**
// // * @dev Set contract deployer as owner
// // */
// // constructor() public {
// // owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
// // emit OwnerSet(address(0), owner);
// //}
// //
// // /**
// // * @dev Change owner
// // * @param newOwner address of new owner
// // */
// // function changeOwner(address newOwner) public isOwner {
// // emit OwnerSet(owner, newOwner);
// // owner = newOwner;
// //}
// //
// // /**
// // * @dev Return owner address
// // * @return address of owner
// // */
// // function getOwner() external view returns (address) {
// // return owner;
// //}
// //}
// // Deploy contract - Owner.sol bytecode := common.FromHex("0x608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a36102c4806100dc6000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c010000000000000000000000000000000000000000000000000000000090048063893d20e814610058578063a6f9dae1146100a2575b600080fd5b6100606100e6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100e4600480360360208110156100b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061010f565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146101d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f43616c6c6572206973206e6f74206f776e65720000000000000000000000000081525060200191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505056fea265627a7a72315820f397f2733a89198bc7fed0764083694c5b828791f39ebcbc9e414bccef14b48064736f6c63430005100032")
// gasLimit := uint64(100000000) tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
// gasPrice := big.NewInt(10000) tx.From = suite.from.String()
// bytecode := common.FromHex("0x608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a36102c4806100dc6000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c010000000000000000000000000000000000000000000000000000000090048063893d20e814610058578063a6f9dae1146100a2575b600080fd5b6100606100e6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100e4600480360360208110156100b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061010f565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146101d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f43616c6c6572206973206e6f74206f776e65720000000000000000000000000081525060200191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505056fea265627a7a72315820f397f2733a89198bc7fed0764083694c5b828791f39ebcbc9e414bccef14b48064736f6c63430005100032") err := tx.Sign(suite.ethSigner, suite.signer)
// tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) suite.Require().NoError(err)
// tx.From = suite.from.String()
// err := tx.Sign(suite.ethSigner, suite.signer) result, err := suite.handler(suite.ctx, tx)
// suite.Require().NoError(err) suite.Require().NoError(err, "failed to handle eth tx msg")
// result, err := suite.handler(suite.ctx, tx) var res types.MsgEthereumTxResponse
// suite.Require().NoError(err, "failed to handle eth tx msg")
// txResponse, err := types.DecodeTxResponse(result.Data) err = proto.Unmarshal(result.Data, &res)
// suite.Require().NoError(err, "failed to decode result data") suite.Require().NoError(err, "failed to decode result data")
suite.Require().Equal(res.VmError, "", "failed to handle eth tx msg")
// // store - changeOwner // store - changeOwner
// gasLimit = uint64(100000000000) gasLimit = uint64(100000000000)
// gasPrice = big.NewInt(100) gasPrice = big.NewInt(100)
// receiver := crypto.CreateAddress(suite.from, 1) receiver := crypto.CreateAddress(suite.from, 1)
// storeAddr := "0xa6f9dae10000000000000000000000006a82e4a67715c8412a9114fbd2cbaefbc8181424" storeAddr := "0xa6f9dae10000000000000000000000006a82e4a67715c8412a9114fbd2cbaefbc8181424"
// bytecode = common.FromHex(storeAddr) bytecode = common.FromHex(storeAddr)
// tx = types.NewTx(suite.chainID, 2, &receiver, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) tx = types.NewTx(suite.chainID, 2, &receiver, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
// tx.From = suite.from.String() tx.From = suite.from.String()
// err = tx.Sign(suite.ethSigner, suite.signer) err = tx.Sign(suite.ethSigner, suite.signer)
// suite.Require().NoError(err) suite.Require().NoError(err)
// result, err = suite.handler(suite.ctx, tx) _, err = suite.handler(suite.ctx, tx)
// suite.Require().NoError(err, "failed to handle eth tx msg") suite.Require().NoError(err, "failed to handle eth tx msg")
// txResponse, err = types.DecodeTxResponse(result.Data) err = proto.Unmarshal(result.Data, &res)
// suite.Require().NoError(err, "failed to decode result data") suite.Require().NoError(err, "failed to decode result data")
suite.Require().Equal(res.VmError, "", "failed to handle eth tx msg")
// // query - getOwner // query - getOwner
// bytecode = common.FromHex("0x893d20e8") bytecode = common.FromHex("0x893d20e8")
// tx = types.NewTx(suite.chainID, 2, &receiver, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) tx = types.NewTx(suite.chainID, 2, &receiver, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
// tx.From = suite.from.String() tx.From = suite.from.String()
// err = tx.Sign(suite.ethSigner, suite.signer) err = tx.Sign(suite.ethSigner, suite.signer)
// suite.Require().NoError(err) suite.Require().NoError(err)
// result, err = suite.handler(suite.ctx, tx) _, err = suite.handler(suite.ctx, tx)
// suite.Require().NoError(err, "failed to handle eth tx msg") suite.Require().NoError(err, "failed to handle eth tx msg")
// txResponse, err = types.DecodeTxResponse(result.Data) err = proto.Unmarshal(result.Data, &res)
// suite.Require().NoError(err, "failed to decode result data") suite.Require().NoError(err, "failed to decode result data")
suite.Require().Equal(res.VmError, "", "failed to handle eth tx msg")
// getAddr := strings.ToLower(hexutils.BytesToHex(txResponse.Ret)) // FIXME: correct owner?
// suite.Require().Equal(true, strings.HasSuffix(storeAddr, getAddr), "Fail to query the address") // getAddr := strings.ToLower(hexutils.BytesToHex(res.Ret))
// } // suite.Require().Equal(true, strings.HasSuffix(storeAddr, getAddr), "Fail to query the address")
}
// func (suite *EvmTestSuite) TestSendTransaction() { func (suite *EvmTestSuite) TestSendTransaction() {
// gasLimit := uint64(21000) gasLimit := uint64(21000)
// gasPrice := big.NewInt(0x55ae82600) gasPrice := big.NewInt(0x55ae82600)
// // send simple value transfer with gasLimit=21000 // send simple value transfer with gasLimit=21000
// tx := types.NewTx(suite.chainID, 1, &common.Address{0x1}, big.NewInt(1), gasLimit, gasPrice, nil, nil) tx := types.NewTx(suite.chainID, 1, &common.Address{0x1}, big.NewInt(1), gasLimit, gasPrice, nil, nil, nil, nil)
// tx.From = suite.from.String() tx.From = suite.from.String()
// err := tx.Sign(suite.ethSigner, suite.signer) err := tx.Sign(suite.ethSigner, suite.signer)
// suite.Require().NoError(err) suite.Require().NoError(err)
// result, err := suite.handler(suite.ctx, tx) result, err := suite.handler(suite.ctx, tx)
// suite.Require().NoError(err) suite.Require().NoError(err)
// suite.Require().NotNil(result) suite.Require().NotNil(result)
// } }
// func (suite *EvmTestSuite) TestOutOfGasWhenDeployContract() { func (suite *EvmTestSuite) TestOutOfGasWhenDeployContract() {
// // Test contract: // Test contract:
// //http://remix.ethereum.org/#optimize=false&evmVersion=istanbul&version=soljson-v0.5.15+commit.6a57276f.js //http://remix.ethereum.org/#optimize=false&evmVersion=istanbul&version=soljson-v0.5.15+commit.6a57276f.js
// //2_Owner.sol //2_Owner.sol
// // //
// //pragma solidity >=0.4.22 <0.7.0; //pragma solidity >=0.4.22 <0.7.0;
// // //
// ///** ///**
// // * @title Owner // * @title Owner
// // * @dev Set & change owner // * @dev Set & change owner
// // */ // */
// //contract Owner { //contract Owner {
// // //
// // address private owner; // address private owner;
// // //
// // // event for EVM logging // // event for EVM logging
// // event OwnerSet(address indexed oldOwner, address indexed newOwner); // event OwnerSet(address indexed oldOwner, address indexed newOwner);
// // //
// // // modifier to check if caller is owner // // modifier to check if caller is owner
// // modifier isOwner() { // modifier isOwner() {
// // // If the first argument of 'require' evaluates to 'false', execution terminates and all // // If the first argument of 'require' evaluates to 'false', execution terminates and all
// // // changes to the state and to Ether balances are reverted. // // changes to the state and to Ether balances are reverted.
// // // This used to consume all gas in old EVM versions, but not anymore. // // This used to consume all gas in old EVM versions, but not anymore.
// // // It is often a good idea to use 'require' to check if functions are called correctly. // // It is often a good idea to use 'require' to check if functions are called correctly.
// // // As a second argument, you can also provide an explanation about what went wrong. // // As a second argument, you can also provide an explanation about what went wrong.
// // require(msg.sender == owner, "Caller is not owner"); // require(msg.sender == owner, "Caller is not owner");
// // _; // _;
// //} //}
// // //
// // /** // /**
// // * @dev Set contract deployer as owner // * @dev Set contract deployer as owner
// // */ // */
// // constructor() public { // constructor() public {
// // owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor // owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
// // emit OwnerSet(address(0), owner); // emit OwnerSet(address(0), owner);
// //} //}
// // //
// // /** // /**
// // * @dev Change owner // * @dev Change owner
// // * @param newOwner address of new owner // * @param newOwner address of new owner
// // */ // */
// // function changeOwner(address newOwner) public isOwner { // function changeOwner(address newOwner) public isOwner {
// // emit OwnerSet(owner, newOwner); // emit OwnerSet(owner, newOwner);
// // owner = newOwner; // owner = newOwner;
// //} //}
// // //
// // /** // /**
// // * @dev Return owner address // * @dev Return owner address
// // * @return address of owner // * @return address of owner
// // */ // */
// // function getOwner() external view returns (address) { // function getOwner() external view returns (address) {
// // return owner; // return owner;
// //} //}
// //} //}
// // Deploy contract - Owner.sol // Deploy contract - Owner.sol
// gasLimit := uint64(1) gasLimit := uint64(1)
// suite.ctx = suite.ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) suite.ctx = suite.ctx.WithGasMeter(sdk.NewGasMeter(gasLimit))
// gasPrice := big.NewInt(10000) gasPrice := big.NewInt(10000)
// bytecode := common.FromHex("0x608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a36102c4806100dc6000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c010000000000000000000000000000000000000000000000000000000090048063893d20e814610058578063a6f9dae1146100a2575b600080fd5b6100606100e6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100e4600480360360208110156100b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061010f565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146101d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f43616c6c6572206973206e6f74206f776e65720000000000000000000000000081525060200191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505056fea265627a7a72315820f397f2733a89198bc7fed0764083694c5b828791f39ebcbc9e414bccef14b48064736f6c63430005100032") bytecode := common.FromHex("0x608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a36102c4806100dc6000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c010000000000000000000000000000000000000000000000000000000090048063893d20e814610058578063a6f9dae1146100a2575b600080fd5b6100606100e6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100e4600480360360208110156100b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061010f565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146101d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f43616c6c6572206973206e6f74206f776e65720000000000000000000000000081525060200191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a73560405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505056fea265627a7a72315820f397f2733a89198bc7fed0764083694c5b828791f39ebcbc9e414bccef14b48064736f6c63430005100032")
// tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
// tx.From = suite.from.String() tx.From = suite.from.String()
// err := tx.Sign(suite.ethSigner, suite.signer) err := tx.Sign(suite.ethSigner, suite.signer)
// suite.Require().NoError(err) suite.Require().NoError(err)
// snapshotCommitStateDBJson, err := json.Marshal(suite.app.EvmKeeper) defer func() {
// suite.Require().Nil(err) if r := recover(); r != nil {
// TODO: snapshotting logic
} else {
suite.Require().Fail("panic did not happen")
}
}()
// defer func() { suite.handler(suite.ctx, tx)
// if r := recover(); r != nil { suite.Require().Fail("panic did not happen")
// currentCommitStateDBJson, err := json.Marshal(suite.app.EvmKeeper) }
// suite.Require().Nil(err)
// suite.Require().Equal(snapshotCommitStateDBJson, currentCommitStateDBJson)
// } else {
// suite.Require().Fail("panic did not happen")
// }
// }()
// suite.handler(suite.ctx, tx) func (suite *EvmTestSuite) TestErrorWhenDeployContract() {
// suite.Require().Fail("panic did not happen") gasLimit := uint64(1000000)
// } gasPrice := big.NewInt(10000)
// func (suite *EvmTestSuite) TestErrorWhenDeployContract() { bytecode := common.FromHex("0xa6f9dae10000000000000000000000006a82e4a67715c8412a9114fbd2cbaefbc8181424")
// gasLimit := uint64(1000000)
// gasPrice := big.NewInt(10000)
// bytecode := common.FromHex("0xa6f9dae10000000000000000000000006a82e4a67715c8412a9114fbd2cbaefbc8181424") tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, nil, nil, bytecode, nil)
tx.From = suite.from.String()
// tx := types.NewTx(suite.chainID, 1, nil, big.NewInt(0), gasLimit, gasPrice, bytecode, nil) err := tx.Sign(suite.ethSigner, suite.signer)
// tx.From = suite.from.String() suite.Require().NoError(err)
// err := tx.Sign(suite.ethSigner, suite.signer) result, _ := suite.handler(suite.ctx, tx)
// suite.Require().NoError(err) var res types.MsgEthereumTxResponse
// snapshotCommitStateDBJson, err := json.Marshal(suite.app.EvmKeeper) _ = proto.Unmarshal(result.Data, &res)
// suite.Require().Nil(err)
// _, sdkErr := suite.handler(suite.ctx, tx) suite.Require().Equal("invalid opcode: opcode 0xa6 not defined", res.VmError, "correct evm error")
// suite.Require().NotNil(sdkErr)
// currentCommitStateDBJson, err := json.Marshal(suite.app.EvmKeeper) // TODO: snapshot checking
// suite.Require().Nil(err) }
// suite.Require().Equal(snapshotCommitStateDBJson, currentCommitStateDBJson)
// }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/runtime"
@ -16,9 +17,11 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/tharsis/ethermint/x/evm/client/cli" "github.com/tharsis/ethermint/x/evm/client/cli"
"github.com/tharsis/ethermint/x/evm/keeper" "github.com/tharsis/ethermint/x/evm/keeper"
"github.com/tharsis/ethermint/x/evm/simulation"
"github.com/tharsis/ethermint/x/evm/types" "github.com/tharsis/ethermint/x/evm/types"
) )
@ -164,3 +167,26 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw
gs := ExportGenesis(ctx, am.keeper, am.ak) gs := ExportGenesis(ctx, am.keeper, am.ak)
return cdc.MustMarshalJSON(gs) return cdc.MustMarshalJSON(gs)
} }
// RandomizedParams creates randomized evm param changes for the simulator.
func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange {
return nil
}
// RegisterStoreDecoder registers a decoder for evm module's types
func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {}
// ProposalContents doesn't return any content functions for governance proposals.
func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent {
return nil
}
// GenerateGenesisState creates a randomized GenState of the evm module.
func (AppModule) GenerateGenesisState(simState *module.SimulationState) {
simulation.RandomizedGenState(simState)
}
// WeightedOperations returns the all the evm module operations with their respective weights.
func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation {
return nil
}

View File

@ -0,0 +1,27 @@
package simulation
import (
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/tharsis/ethermint/x/evm/types"
)
// RandomizedGenState generates a random GenesisState for nft
func RandomizedGenState(simState *module.SimulationState) {
params := types.NewParams(types.DefaultEVMDenom, true, true, types.DefaultChainConfig())
if simState.Rand.Uint32()%2 == 0 {
params = types.NewParams(types.DefaultEVMDenom, true, true, types.DefaultChainConfig(), 1344, 1884, 2200, 2929, 3198, 3529)
}
evmGenesis := types.NewGenesisState(params, []types.GenesisAccount{})
bz, err := json.MarshalIndent(evmGenesis, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz)
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(evmGenesis)
}

View File

@ -23,6 +23,14 @@ func DefaultGenesisState() *GenesisState {
} }
} }
// NewGenesisState creates a new genesis state.
func NewGenesisState(params Params, accounts []GenesisAccount) *GenesisState {
return &GenesisState{
Accounts: accounts,
Params: params,
}
}
// Validate performs basic genesis state validation returning an error upon any // Validate performs basic genesis state validation returning an error upon any
// failure. // failure.
func (gs GenesisState) Validate() error { func (gs GenesisState) Validate() error {

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/runtime"
@ -16,9 +17,11 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/tharsis/ethermint/x/feemarket/client/cli" "github.com/tharsis/ethermint/x/feemarket/client/cli"
"github.com/tharsis/ethermint/x/feemarket/keeper" "github.com/tharsis/ethermint/x/feemarket/keeper"
"github.com/tharsis/ethermint/x/feemarket/simulation"
"github.com/tharsis/ethermint/x/feemarket/types" "github.com/tharsis/ethermint/x/feemarket/types"
) )
@ -155,3 +158,26 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw
gs := ExportGenesis(ctx, am.keeper) gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(gs) return cdc.MustMarshalJSON(gs)
} }
// RandomizedParams creates randomized fee market param changes for the simulator.
func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange {
return nil
}
// RegisterStoreDecoder registers a decoder for fee market module's types
func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {}
// ProposalContents doesn't return any content functions for governance proposals.
func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent {
return nil
}
// GenerateGenesisState creates a randomized GenState of the fee market module.
func (AppModule) GenerateGenesisState(simState *module.SimulationState) {
simulation.RandomizedGenState(simState)
}
// WeightedOperations returns the all the fee market module operations with their respective weights.
func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation {
return nil
}

View File

@ -0,0 +1,27 @@
package simulation
import (
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/types/module"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tharsis/ethermint/x/feemarket/types"
)
// RandomizedGenState generates a random GenesisState for nft
func RandomizedGenState(simState *module.SimulationState) {
params := types.NewParams(simState.Rand.Uint32()%2 == 0, simState.Rand.Uint32(), simState.Rand.Uint32(), simState.Rand.Int63(), simState.Rand.Int63())
baseFee := sdk.NewInt(simState.Rand.Int63())
blockGas := simState.Rand.Uint64()
feemarketGenesis := types.NewGenesisState(params, baseFee, blockGas)
bz, err := json.MarshalIndent(feemarketGenesis, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz)
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(feemarketGenesis)
}

View File

@ -15,6 +15,15 @@ func DefaultGenesisState() *GenesisState {
} }
} }
// NewGenesisState creates a new genesis state.
func NewGenesisState(params Params, baseFee sdk.Int, blockGas uint64) *GenesisState {
return &GenesisState{
Params: params,
BaseFee: baseFee,
BlockGas: blockGas,
}
}
// Validate performs basic genesis state validation returning an error upon any // Validate performs basic genesis state validation returning an error upon any
// failure. // failure.
func (gs GenesisState) Validate() error { func (gs GenesisState) Validate() error {