diff --git a/app/abci.go b/app/abci.go index 49d4b70231..a22c9de1a1 100644 --- a/app/abci.go +++ b/app/abci.go @@ -4,16 +4,44 @@ import ( "context" "time" + "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/utils/metrics" abci "github.com/tendermint/tendermint/abci/types" ) -func (app *App) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { +func (app *App) BeginBlock( + ctx sdk.Context, + height int64, + votes []abci.VoteInfo, + byzantineValidators []abci.Misbehavior, + checkHeight bool, +) (res abci.ResponseBeginBlock) { spanCtx, beginBlockSpan := app.GetBaseApp().TracingInfo.StartWithContext("BeginBlock", ctx.TraceSpanContext()) defer beginBlockSpan.End() ctx = ctx.WithTraceSpanContext(spanCtx) - return app.BaseApp.BeginBlock(ctx, req) + ctx = ctx.WithEventManager(sdk.NewEventManager()) + defer telemetry.MeasureSince(time.Now(), "abci", "begin_block") + // inline begin block + if checkHeight { + if err := app.ValidateHeight(height); err != nil { + panic(err) + } + } + metrics.GaugeSeidVersionAndCommit(app.versionInfo.Version, app.versionInfo.GitCommit) + // check if we've reached a target height, if so, execute any applicable handlers + if app.forkInitializer != nil { + app.forkInitializer(ctx) + app.forkInitializer = nil + } + if app.HardForkManager.TargetHeightReached(ctx) { + app.HardForkManager.ExecuteForTargetHeight(ctx) + } + legacyabci.BeginBlock(ctx, height, votes, byzantineValidators, app.BeginBlockKeepers) + return abci.ResponseBeginBlock{ + Events: sdk.MarkEventsToIndex(ctx.EventManager().ABCIEvents(), app.IndexEvents), + } } func (app *App) MidBlock(ctx sdk.Context, height int64) []abci.Event { diff --git a/app/app.go b/app/app.go index 0d8d877554..35c1d0302c 100644 --- a/app/app.go +++ b/app/app.go @@ -108,6 +108,7 @@ import ( "github.com/sei-protocol/sei-chain/aclmapping" aclutils "github.com/sei-protocol/sei-chain/aclmapping/utils" "github.com/sei-protocol/sei-chain/app/antedecorators" + "github.com/sei-protocol/sei-chain/app/legacyabci" appparams "github.com/sei-protocol/sei-chain/app/params" "github.com/sei-protocol/sei-chain/app/upgrades" v0upgrade "github.com/sei-protocol/sei-chain/app/upgrades/v0" @@ -351,6 +352,8 @@ type App struct { TokenFactoryKeeper tokenfactorykeeper.Keeper + BeginBlockKeepers legacyabci.BeginBlockKeepers + // mm is the module manager mm *module.Manager @@ -762,36 +765,17 @@ func New( // this line is used by starport scaffolding # stargate/app/appModule ) - // During begin block slashing happens after distr.BeginBlocker so that - // there is nothing left over in the validator fee pool, so as to keep the - // CanWithdrawInvariant invariant. - // NOTE: staking module is required if HistoricalEntries param > 0 - app.mm.SetOrderBeginBlockers( - epochmoduletypes.ModuleName, - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - minttypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - evidencetypes.ModuleName, - stakingtypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - govtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - ibchost.ModuleName, - ibctransfertypes.ModuleName, - oracletypes.ModuleName, - evmtypes.ModuleName, - wasm.ModuleName, - tokenfactorytypes.ModuleName, - acltypes.ModuleName, - ) + app.BeginBlockKeepers = legacyabci.BeginBlockKeepers{ + EpochKeeper: &app.EpochKeeper, + UpgradeKeeper: &app.UpgradeKeeper, + CapabilityKeeper: app.CapabilityKeeper, + DistrKeeper: &app.DistrKeeper, + SlashingKeeper: &app.SlashingKeeper, + EvidenceKeeper: &app.EvidenceKeeper, + StakingKeeper: &app.StakingKeeper, + IBCKeeper: app.IBCKeeper, + EvmKeeper: &app.EvmKeeper, + } app.mm.SetOrderMidBlockers( oracletypes.ModuleName, @@ -875,7 +859,6 @@ func New( // initialize BaseApp app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) signModeHandler := encodingConfig.TxConfig.SignModeHandler() // app.batchVerifier = ante.NewSR25519BatchVerifier(app.AccountKeeper, signModeHandler) @@ -1060,20 +1043,6 @@ func (app *App) GetBaseApp() *baseapp.BaseApp { return app.BaseApp } // GetStateStore returns the state store of the application func (app *App) GetStateStore() seidb.StateStore { return app.stateStore } -// BeginBlocker application updates every begin block -func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - metrics.GaugeSeidVersionAndCommit(app.versionInfo.Version, app.versionInfo.GitCommit) - // check if we've reached a target height, if so, execute any applicable handlers - if app.forkInitializer != nil { - app.forkInitializer(ctx) - app.forkInitializer = nil - } - if app.HardForkManager.TargetHeightReached(ctx) { - app.HardForkManager.ExecuteForTargetHeight(ctx) - } - return app.mm.BeginBlock(ctx, req) -} - // MidBlocker application updates every mid block func (app *App) MidBlocker(ctx sdk.Context, height int64) []abci.Event { return app.mm.MidBlock(ctx, height) @@ -1626,29 +1595,7 @@ func (app *App) ProcessBlock(ctx sdk.Context, txs [][]byte, req BlockProcessRequ ctx = ctx.WithTraceSpanContext(blockSpanCtx) events = []abci.Event{} - beginBlockReq := abci.RequestBeginBlock{ - Hash: req.GetHash(), - ByzantineValidators: utils.Map(req.GetByzantineValidators(), func(mis abci.Misbehavior) abci.Evidence { - return abci.Evidence(mis) - }), - LastCommitInfo: abci.LastCommitInfo{ - Round: lastCommit.Round, - Votes: utils.Map(lastCommit.Votes, func(vote abci.VoteInfo) abci.VoteInfo { - return abci.VoteInfo{ - Validator: vote.Validator, - SignedLastBlock: vote.SignedLastBlock, - } - }), - }, - Header: tmproto.Header{ - ChainID: app.ChainID, - Height: req.GetHeight(), - Time: req.GetTime(), - ProposerAddress: ctx.BlockHeader().ProposerAddress, - }, - Simulate: simulate, - } - beginBlockResp := app.BeginBlock(ctx, beginBlockReq) + beginBlockResp := app.BeginBlock(ctx, req.GetHeight(), lastCommit.Votes, req.GetByzantineValidators(), true) events = append(events, beginBlockResp.Events...) evmTxs := make([]*evmtypes.MsgEVMTransaction, len(txs)) // nil for non-EVM txs @@ -1932,7 +1879,7 @@ func (app *App) RegisterTendermintService(clientCtx client.Context) { } if app.evmRPCConfig.HTTPEnabled { - evmHTTPServer, err := evmrpc.NewEVMHTTPServer(app.Logger(), app.evmRPCConfig, clientCtx.Client, &app.EvmKeeper, app.BaseApp, app.TracerAnteHandler, app.RPCContextProvider, txConfigProvider, DefaultNodeHome, nil) + evmHTTPServer, err := evmrpc.NewEVMHTTPServer(app.Logger(), app.evmRPCConfig, clientCtx.Client, &app.EvmKeeper, app.BeginBlockKeepers, app.BaseApp, app.TracerAnteHandler, app.RPCContextProvider, txConfigProvider, DefaultNodeHome, nil) if err != nil { panic(err) } @@ -1945,7 +1892,7 @@ func (app *App) RegisterTendermintService(clientCtx client.Context) { } if app.evmRPCConfig.WSEnabled { - evmWSServer, err := evmrpc.NewEVMWebSocketServer(app.Logger(), app.evmRPCConfig, clientCtx.Client, &app.EvmKeeper, app.BaseApp, app.TracerAnteHandler, app.RPCContextProvider, txConfigProvider, DefaultNodeHome) + evmWSServer, err := evmrpc.NewEVMWebSocketServer(app.Logger(), app.evmRPCConfig, clientCtx.Client, &app.EvmKeeper, app.BeginBlockKeepers, app.BaseApp, app.TracerAnteHandler, app.RPCContextProvider, txConfigProvider, DefaultNodeHome) if err != nil { panic(err) } diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index b5c6c3e2d9..b41ead0d45 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -16,6 +16,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/sei-protocol/sei-chain/app/legacyabci" minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" @@ -67,7 +68,7 @@ func (s *KeeperTestHelper) Commit() { panic(err) } newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: oldHeader.ChainID, Time: time.Now().UTC()} - s.App.BeginBlock(s.Ctx, abci.RequestBeginBlock{Header: newHeader}) + legacyabci.BeginBlock(s.Ctx, newHeader.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, s.App.BeginBlockKeepers) s.Ctx = s.App.GetBaseApp().NewContext(false, newHeader) } diff --git a/app/legacyabci/begin_block.go b/app/legacyabci/begin_block.go new file mode 100644 index 0000000000..a59986c0a8 --- /dev/null +++ b/app/legacyabci/begin_block.go @@ -0,0 +1,61 @@ +package legacyabci + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/telemetry" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/capability" + capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/x/distribution" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + + "github.com/cosmos/cosmos-sdk/x/evidence" + evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + + "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" + + ibcclient "github.com/cosmos/ibc-go/v3/modules/core/02-client" + ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper" + epochmodulekeeper "github.com/sei-protocol/sei-chain/x/epoch/keeper" + evmkeeper "github.com/sei-protocol/sei-chain/x/evm/keeper" +) + +type BeginBlockKeepers struct { + EpochKeeper *epochmodulekeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper + CapabilityKeeper *capabilitykeeper.Keeper + DistrKeeper *distrkeeper.Keeper + SlashingKeeper *slashingkeeper.Keeper + EvidenceKeeper *evidencekeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + IBCKeeper *ibckeeper.Keeper + EvmKeeper *evmkeeper.Keeper +} + +func BeginBlock( + ctx sdk.Context, + height int64, + votes []abci.VoteInfo, + byzantineValidators []abci.Misbehavior, + keepers BeginBlockKeepers, +) { + defer telemetry.MeasureSince(time.Now(), "module", "total_begin_block") + + keepers.EpochKeeper.BeginBlock(ctx) + upgrade.BeginBlocker(*keepers.UpgradeKeeper, ctx) + capability.BeginBlocker(ctx, *keepers.CapabilityKeeper) + distribution.BeginBlocker(ctx, votes, *keepers.DistrKeeper) + slashing.BeginBlocker(ctx, votes, *keepers.SlashingKeeper) + evidence.BeginBlocker(ctx, byzantineValidators, *keepers.EvidenceKeeper) + staking.BeginBlocker(ctx, *keepers.StakingKeeper) + ibcclient.BeginBlocker(ctx, keepers.IBCKeeper.ClientKeeper) + keepers.EvmKeeper.BeginBlock(ctx) +} diff --git a/app/test_helpers.go b/app/test_helpers.go index d0a0ae3875..187317cf3f 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -45,6 +45,7 @@ import ( 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/sei-protocol/sei-chain/app/legacyabci" minttypes "github.com/sei-protocol/sei-chain/x/mint/types" ) @@ -194,9 +195,8 @@ func (s *TestWrapper) BeginBlock() { SignedLastBlock: true, }}, } - reqBeginBlock := abci.RequestBeginBlock{Header: header, LastCommitInfo: lastCommitInfo} - s.App.BeginBlocker(s.Ctx, reqBeginBlock) + legacyabci.BeginBlock(s.Ctx, header.Height, lastCommitInfo.Votes, []abci.Misbehavior{}, s.App.BeginBlockKeepers) } func (s *TestWrapper) EndBlock() { diff --git a/app/upgrades/fork_manager_test.go b/app/upgrades/fork_manager_test.go index 5a74192dec..fbc67a134c 100644 --- a/app/upgrades/fork_manager_test.go +++ b/app/upgrades/fork_manager_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/sei-protocol/sei-chain/app/apptesting" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/app/upgrades" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" @@ -86,7 +87,7 @@ func (suite *ForkTestSuite) TestHardForkManager() { // increments height and runs begin block suite.Ctx = suite.Ctx.WithBlockHeight(2) newHeader := tmtypes.Header{Height: suite.Ctx.BlockHeight(), ChainID: suite.Ctx.ChainID(), Time: time.Now().UTC()} - suite.App.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{Header: newHeader}) + legacyabci.BeginBlock(suite.Ctx, newHeader.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, suite.App.BeginBlockKeepers) suite.Require().False(runFlag1) suite.Require().False(runFlag2) suite.Require().False(runFlag3) @@ -96,7 +97,7 @@ func (suite *ForkTestSuite) TestHardForkManager() { // run with height of 3 - runflag 1 should now be true suite.Ctx = suite.Ctx.WithBlockHeight(3) newHeader = tmtypes.Header{Height: suite.Ctx.BlockHeight(), ChainID: suite.Ctx.ChainID(), Time: time.Now().UTC()} - suite.App.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{Header: newHeader}) + suite.App.BeginBlock(suite.Ctx, newHeader.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, false) suite.Require().True(runFlag1) suite.Require().False(runFlag2) suite.Require().False(runFlag3) @@ -107,7 +108,7 @@ func (suite *ForkTestSuite) TestHardForkManager() { suite.Require().Panics(func() { suite.Ctx = suite.Ctx.WithBlockHeight(4) newHeader = tmtypes.Header{Height: suite.Ctx.BlockHeight(), ChainID: suite.Ctx.ChainID(), Time: time.Now().UTC()} - suite.App.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{Header: newHeader}) + suite.App.BeginBlock(suite.Ctx, newHeader.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, false) }) suite.Require().True(runFlag3) suite.Require().False(runFlag4) diff --git a/evmrpc/send.go b/evmrpc/send.go index 8cf5df1599..ab180b900d 100644 --- a/evmrpc/send.go +++ b/evmrpc/send.go @@ -17,6 +17,7 @@ import ( "github.com/ethereum/go-ethereum/export" "github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/signer/core/apitypes" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/precompiles/wasmd" "github.com/sei-protocol/sei-chain/x/evm/keeper" "github.com/sei-protocol/sei-chain/x/evm/types" @@ -44,6 +45,7 @@ func NewSendAPI( txConfigProvider func(int64) client.TxConfig, sendConfig *SendConfig, k *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, ctxProvider func(int64) sdk.Context, homeDir string, simulateConfig *SimulateConfig, @@ -60,7 +62,7 @@ func NewSendAPI( keeper: k, ctxProvider: ctxProvider, homeDir: homeDir, - backend: NewBackend(ctxProvider, k, txConfigProvider, tmClient, simulateConfig, app, antehandler, globalBlockCache, cacheCreationMutex), + backend: NewBackend(ctxProvider, k, beginBlockKeepers, txConfigProvider, tmClient, simulateConfig, app, antehandler, globalBlockCache, cacheCreationMutex), connectionType: connectionType, } } diff --git a/evmrpc/server.go b/evmrpc/server.go index d1506905bc..fb6258ab2e 100644 --- a/evmrpc/server.go +++ b/evmrpc/server.go @@ -10,6 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/evmrpc/stats" evmCfg "github.com/sei-protocol/sei-chain/x/evm/config" "github.com/sei-protocol/sei-chain/x/evm/keeper" @@ -35,6 +36,7 @@ func NewEVMHTTPServer( config Config, tmClient rpcclient.Client, k *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, app *baseapp.BaseApp, antehandler sdk.AnteHandler, ctxProvider func(int64) sdk.Context, @@ -63,20 +65,20 @@ func NewEVMHTTPServer( } globalBlockCache := NewBlockCache(3000) cacheCreationMutex := &sync.Mutex{} - sendAPI := NewSendAPI(tmClient, txConfigProvider, &SendConfig{slow: config.Slow}, k, ctxProvider, homeDir, simulateConfig, app, antehandler, ConnectionTypeHTTP, globalBlockCache, cacheCreationMutex) + sendAPI := NewSendAPI(tmClient, txConfigProvider, &SendConfig{slow: config.Slow}, k, beginBlockKeepers, ctxProvider, homeDir, simulateConfig, app, antehandler, ConnectionTypeHTTP, globalBlockCache, cacheCreationMutex) ctx := ctxProvider(LatestCtxHeight) watermarks := NewWatermarkManager(tmClient, ctxProvider, nil, k.ReceiptStore()) txAPI := NewTransactionAPI(tmClient, k, ctxProvider, txConfigProvider, homeDir, ConnectionTypeHTTP, watermarks, globalBlockCache, cacheCreationMutex) - debugAPI := NewDebugAPI(tmClient, k, ctxProvider, txConfigProvider, simulateConfig, app, antehandler, ConnectionTypeHTTP, config, globalBlockCache, cacheCreationMutex) + debugAPI := NewDebugAPI(tmClient, k, beginBlockKeepers, ctxProvider, txConfigProvider, simulateConfig, app, antehandler, ConnectionTypeHTTP, config, globalBlockCache, cacheCreationMutex) if isPanicOrSyntheticTxFunc == nil { isPanicOrSyntheticTxFunc = func(ctx context.Context, hash common.Hash) (bool, error) { return debugAPI.isPanicOrSyntheticTx(ctx, hash) } } seiTxAPI := NewSeiTransactionAPI(tmClient, k, ctxProvider, txConfigProvider, homeDir, ConnectionTypeHTTP, isPanicOrSyntheticTxFunc, watermarks, globalBlockCache, cacheCreationMutex) - seiDebugAPI := NewSeiDebugAPI(tmClient, k, ctxProvider, txConfigProvider, simulateConfig, app, antehandler, ConnectionTypeHTTP, config, globalBlockCache, cacheCreationMutex) + seiDebugAPI := NewSeiDebugAPI(tmClient, k, beginBlockKeepers, ctxProvider, txConfigProvider, simulateConfig, app, antehandler, ConnectionTypeHTTP, config, globalBlockCache, cacheCreationMutex) dbReadSemaphore := make(chan struct{}, MaxDBReadConcurrency) globalLogSlicePool := NewLogSlicePool() @@ -119,7 +121,7 @@ func NewEVMHTTPServer( }, { Namespace: "eth", - Service: NewSimulationAPI(ctxProvider, k, txConfigProvider, tmClient, simulateConfig, app, antehandler, ConnectionTypeHTTP, globalBlockCache, cacheCreationMutex), + Service: NewSimulationAPI(ctxProvider, k, beginBlockKeepers, txConfigProvider, tmClient, simulateConfig, app, antehandler, ConnectionTypeHTTP, globalBlockCache, cacheCreationMutex), }, { Namespace: "net", @@ -207,6 +209,7 @@ func NewEVMWebSocketServer( config Config, tmClient rpcclient.Client, k *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, app *baseapp.BaseApp, antehandler sdk.AnteHandler, ctxProvider func(int64) sdk.Context, @@ -260,11 +263,11 @@ func NewEVMWebSocketServer( }, { Namespace: "eth", - Service: NewSendAPI(tmClient, txConfigProvider, &SendConfig{slow: config.Slow}, k, ctxProvider, homeDir, simulateConfig, app, antehandler, ConnectionTypeWS, globalBlockCache, cacheCreationMutex), + Service: NewSendAPI(tmClient, txConfigProvider, &SendConfig{slow: config.Slow}, k, beginBlockKeepers, ctxProvider, homeDir, simulateConfig, app, antehandler, ConnectionTypeWS, globalBlockCache, cacheCreationMutex), }, { Namespace: "eth", - Service: NewSimulationAPI(ctxProvider, k, txConfigProvider, tmClient, simulateConfig, app, antehandler, ConnectionTypeWS, globalBlockCache, cacheCreationMutex), + Service: NewSimulationAPI(ctxProvider, k, beginBlockKeepers, txConfigProvider, tmClient, simulateConfig, app, antehandler, ConnectionTypeWS, globalBlockCache, cacheCreationMutex), }, { Namespace: "net", diff --git a/evmrpc/setup_test.go b/evmrpc/setup_test.go index eba36b23b3..d73623e412 100644 --- a/evmrpc/setup_test.go +++ b/evmrpc/setup_test.go @@ -582,7 +582,7 @@ func init() { panic(err) } txConfigProvider := func(int64) client.TxConfig { return TxConfig } - HttpServer, err := evmrpc.NewEVMHTTPServer(infoLog, goodConfig, &MockClient{}, EVMKeeper, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "", isPanicTxFunc) + HttpServer, err := evmrpc.NewEVMHTTPServer(infoLog, goodConfig, &MockClient{}, EVMKeeper, testApp.BeginBlockKeepers, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "", isPanicTxFunc) if err != nil { panic(err) } @@ -594,7 +594,7 @@ func init() { badConfig := evmrpc.DefaultConfig badConfig.HTTPPort = TestBadPort badConfig.FilterTimeout = 500 * time.Millisecond - badHTTPServer, err := evmrpc.NewEVMHTTPServer(infoLog, badConfig, &MockBadClient{}, EVMKeeper, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "", nil) + badHTTPServer, err := evmrpc.NewEVMHTTPServer(infoLog, badConfig, &MockBadClient{}, EVMKeeper, testApp.BeginBlockKeepers, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "", nil) if err != nil { panic(err) } @@ -613,6 +613,7 @@ func init() { strictConfig, &MockClient{}, EVMKeeper, + testApp.BeginBlockKeepers, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, @@ -637,6 +638,7 @@ func init() { archiveConfig, &MockClient{}, EVMKeeper, + testApp.BeginBlockKeepers, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, @@ -652,7 +654,7 @@ func init() { } // Start ws server - wsServer, err := evmrpc.NewEVMWebSocketServer(infoLog, goodConfig, &MockClient{}, EVMKeeper, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "") + wsServer, err := evmrpc.NewEVMWebSocketServer(infoLog, goodConfig, &MockClient{}, EVMKeeper, testApp.BeginBlockKeepers, testApp.BaseApp, testApp.TracerAnteHandler, ctxProvider, txConfigProvider, "") if err != nil { panic(err) } diff --git a/evmrpc/simulate.go b/evmrpc/simulate.go index b939ab060b..590d6b6d7e 100644 --- a/evmrpc/simulate.go +++ b/evmrpc/simulate.go @@ -31,6 +31,7 @@ import ( "github.com/ethereum/go-ethereum/export" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/precompiles/wasmd" "github.com/sei-protocol/sei-chain/utils" "github.com/sei-protocol/sei-chain/x/evm/keeper" @@ -56,6 +57,7 @@ type SimulationAPI struct { func NewSimulationAPI( ctxProvider func(int64) sdk.Context, keeper *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, txConfigProvider func(int64) client.TxConfig, tmClient rpcclient.Client, config *SimulateConfig, @@ -66,7 +68,7 @@ func NewSimulationAPI( cacheCreationMutex *sync.Mutex, ) *SimulationAPI { api := &SimulationAPI{ - backend: NewBackend(ctxProvider, keeper, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex), + backend: NewBackend(ctxProvider, keeper, beginBlockKeepers, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex), connectionType: connectionType, } if config.MaxConcurrentSimulationCalls > 0 { @@ -222,6 +224,7 @@ type Backend struct { tmClient rpcclient.Client config *SimulateConfig app *baseapp.BaseApp + beginBlockKeepers legacyabci.BeginBlockKeepers antehandler sdk.AnteHandler globalBlockCache BlockCache cacheCreationMutex *sync.Mutex @@ -230,6 +233,7 @@ type Backend struct { func NewBackend( ctxProvider func(int64) sdk.Context, keeper *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, txConfigProvider func(int64) client.TxConfig, tmClient rpcclient.Client, config *SimulateConfig, @@ -241,6 +245,7 @@ func NewBackend( return &Backend{ ctxProvider: ctxProvider, keeper: keeper, + beginBlockKeepers: beginBlockKeepers, txConfigProvider: txConfigProvider, tmClient: tmClient, config: config, @@ -524,7 +529,7 @@ func (b *Backend) initializeBlock(ctx context.Context, block *ethtypes.Block) (s reqBeginBlock := tmBlock.Block.ToReqBeginBlock(res.Validators) reqBeginBlock.Simulate = true sdkCtx := b.ctxProvider(prevBlockHeight).WithBlockHeight(blockNumber).WithBlockTime(tmBlock.Block.Time) - _ = b.app.BeginBlock(sdkCtx, reqBeginBlock) + legacyabci.BeginBlock(sdkCtx, blockNumber, reqBeginBlock.LastCommitInfo.Votes, tmBlock.Block.Evidence.ToABCI(), b.beginBlockKeepers) sdkCtx = sdkCtx.WithNextMs( b.ctxProvider(sdkCtx.BlockHeight()).MultiStore(), []string{"oracle", "oracle_mem"}, diff --git a/evmrpc/simulate_test.go b/evmrpc/simulate_test.go index 90443865c3..0c1f6910c5 100644 --- a/evmrpc/simulate_test.go +++ b/evmrpc/simulate_test.go @@ -17,6 +17,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/export" "github.com/sei-protocol/sei-chain/app" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/evmrpc" "github.com/sei-protocol/sei-chain/example/contracts/simplestorage" testkeeper "github.com/sei-protocol/sei-chain/testutil/keeper" @@ -128,6 +129,7 @@ func TestChainConfigReflectsSstoreParam(t *testing.T) { backend := evmrpc.NewBackend( ctxProvider, &testApp.EvmKeeper, + legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return encodingCfg.TxConfig }, &mock.Client{}, &SConfig, @@ -289,7 +291,7 @@ func TestConvertBlockNumber(t *testing.T) { return sdk.Context{}.WithBlockHeight(1000) } return sdk.Context{} - }, nil, nil, &MockClient{}, nil, nil, nil, evmrpc.NewBlockCache(3000), &sync.Mutex{}) + }, nil, legacyabci.BeginBlockKeepers{}, nil, &MockClient{}, nil, nil, nil, evmrpc.NewBlockCache(3000), &sync.Mutex{}) require.Equal(t, int64(10), backend.ConvertBlockNumber(10)) require.Equal(t, int64(1), backend.ConvertBlockNumber(0)) require.Equal(t, int64(1000), backend.ConvertBlockNumber(-2)) @@ -327,6 +329,7 @@ func TestPreV620UpgradeUsesBaseFeeNil(t *testing.T) { backend := evmrpc.NewBackend( ctxProvider, &testApp.EvmKeeper, + legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &MockClient{}, config, @@ -361,6 +364,7 @@ func TestPreV620UpgradeUsesBaseFeeNil(t *testing.T) { backendDifferentChain := evmrpc.NewBackend( ctxProviderDifferentChain, &testApp.EvmKeeper, + legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &MockClient{}, config, @@ -387,6 +391,7 @@ func TestGasLimitUsesConsensusOrConfig(t *testing.T) { cfg := &evmrpc.SimulateConfig{GasCap: 10_000_000, EVMTimeout: time.Second} backend := evmrpc.NewBackend(ctxProvider, &testApp.EvmKeeper, + legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &MockClient{}, cfg, testApp.BaseApp, testApp.TracerAnteHandler, evmrpc.NewBlockCache(3000), &sync.Mutex{}) @@ -407,13 +412,13 @@ func TestGasLimitFallbackToDefault(t *testing.T) { cfg := &evmrpc.SimulateConfig{GasCap: 20_000_000, EVMTimeout: time.Second} // Case 1: BlockResults fails - backend1 := evmrpc.NewBackend(ctxProvider, &testApp.EvmKeeper, func(int64) client.TxConfig { return TxConfig }, &brFailClient{MockClient: &MockClient{}}, cfg, testApp.BaseApp, testApp.TracerAnteHandler, evmrpc.NewBlockCache(3000), &sync.Mutex{}) + backend1 := evmrpc.NewBackend(ctxProvider, &testApp.EvmKeeper, legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &brFailClient{MockClient: &MockClient{}}, cfg, testApp.BaseApp, testApp.TracerAnteHandler, evmrpc.NewBlockCache(3000), &sync.Mutex{}) h1, err := backend1.HeaderByNumber(context.Background(), 1) require.NoError(t, err) require.Equal(t, uint64(10_000_000), h1.GasLimit) // DefaultBlockGasLimit // Case 2: Block fails - backend2 := evmrpc.NewBackend(ctxProvider, &testApp.EvmKeeper, func(int64) client.TxConfig { return TxConfig }, &bcFailClient{MockClient: &MockClient{}}, cfg, testApp.BaseApp, testApp.TracerAnteHandler, evmrpc.NewBlockCache(3000), &sync.Mutex{}) + backend2 := evmrpc.NewBackend(ctxProvider, &testApp.EvmKeeper, legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &bcFailClient{MockClient: &MockClient{}}, cfg, testApp.BaseApp, testApp.TracerAnteHandler, evmrpc.NewBlockCache(3000), &sync.Mutex{}) h2, err := backend2.HeaderByNumber(context.Background(), 1) require.NoError(t, err) require.Equal(t, uint64(10_000_000), h2.GasLimit) // DefaultBlockGasLimit @@ -456,6 +461,7 @@ func TestSimulationAPIRequestLimiter(t *testing.T) { simAPI := evmrpc.NewSimulationAPI( ctxProvider, EVMKeeper, + legacyabci.BeginBlockKeepers{}, func(int64) client.TxConfig { return TxConfig }, &MockClient{}, config, diff --git a/evmrpc/tests/utils.go b/evmrpc/tests/utils.go index a673917f3f..be51667ce0 100644 --- a/evmrpc/tests/utils.go +++ b/evmrpc/tests/utils.go @@ -145,6 +145,7 @@ func setupTestServer( cfg, mockClient, &a.EvmKeeper, + a.BeginBlockKeepers, a.BaseApp, a.TracerAnteHandler, ctxProvider, diff --git a/evmrpc/tracers.go b/evmrpc/tracers.go index bd886e4742..6a1ba4b3db 100644 --- a/evmrpc/tracers.go +++ b/evmrpc/tracers.go @@ -19,6 +19,7 @@ import ( "github.com/ethereum/go-ethereum/export" "github.com/ethereum/go-ethereum/rpc" "github.com/hashicorp/golang-lru/v2/expirable" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/sei-protocol/sei-chain/x/evm/keeper" "github.com/sei-protocol/sei-chain/x/evm/state" rpcclient "github.com/tendermint/tendermint/rpc/client" @@ -61,6 +62,7 @@ type SeiDebugAPI struct { func NewDebugAPI( tmClient rpcclient.Client, k *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, ctxProvider func(int64) sdk.Context, txConfigProvider func(int64) client.TxConfig, config *SimulateConfig, @@ -71,7 +73,7 @@ func NewDebugAPI( globalBlockCache BlockCache, cacheCreationMutex *sync.Mutex, ) *DebugAPI { - backend := NewBackend(ctxProvider, k, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex) + backend := NewBackend(ctxProvider, k, beginBlockKeepers, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex) tracersAPI := tracers.NewAPI(backend) evictCallback := func(key common.Hash, value bool) {} isPanicCache := expirable.NewLRU[common.Hash, bool](IsPanicCacheSize, evictCallback, IsPanicCacheTTL) @@ -99,6 +101,7 @@ func NewDebugAPI( func NewSeiDebugAPI( tmClient rpcclient.Client, k *keeper.Keeper, + beginBlockKeepers legacyabci.BeginBlockKeepers, ctxProvider func(int64) sdk.Context, txConfigProvider func(int64) client.TxConfig, config *SimulateConfig, @@ -109,7 +112,7 @@ func NewSeiDebugAPI( globalBlockCache BlockCache, cacheCreationMutex *sync.Mutex, ) *SeiDebugAPI { - backend := NewBackend(ctxProvider, k, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex) + backend := NewBackend(ctxProvider, k, beginBlockKeepers, txConfigProvider, tmClient, config, app, antehandler, globalBlockCache, cacheCreationMutex) tracersAPI := tracers.NewAPI(backend) var sem chan struct{} diff --git a/sei-cosmos/baseapp/abci.go b/sei-cosmos/baseapp/abci.go index 6a6e7864e3..4be718bd60 100644 --- a/sei-cosmos/baseapp/abci.go +++ b/sei-cosmos/baseapp/abci.go @@ -130,30 +130,12 @@ func (app *BaseApp) Info(ctx context.Context, req *abci.RequestInfo) (*abci.Resp }, nil } -// BeginBlock implements the ABCI application interface. -func (app *BaseApp) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { - defer telemetry.MeasureSince(time.Now(), "abci", "begin_block") - - if !req.Simulate { - if err := app.validateHeight(req); err != nil { - panic(err) - } - } - - if app.beginBlocker != nil { - res = app.beginBlocker(ctx, req) - res.Events = sdk.MarkEventsToIndex(res.Events, app.indexEvents) - } - - return res -} - func (app *BaseApp) MidBlock(ctx sdk.Context, height int64) (events []abci.Event) { defer telemetry.MeasureSince(time.Now(), "abci", "mid_block") if app.midBlocker != nil { midBlockEvents := app.midBlocker(ctx, height) - events = sdk.MarkEventsToIndex(midBlockEvents, app.indexEvents) + events = sdk.MarkEventsToIndex(midBlockEvents, app.IndexEvents) } return events @@ -168,7 +150,7 @@ func (app *BaseApp) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) (res abc if app.endBlocker != nil { res = app.endBlocker(ctx, req) - res.Events = sdk.MarkEventsToIndex(res.Events, app.indexEvents) + res.Events = sdk.MarkEventsToIndex(res.Events, app.IndexEvents) } if cp := app.GetConsensusParams(ctx); cp != nil { @@ -279,9 +261,9 @@ func (app *BaseApp) DeliverTx(ctx sdk.Context, req abci.RequestDeliverTx, tx sdk resultStr = "failed" // if we have a result, use those events instead of just the anteEvents if result != nil { - return sdkerrors.ResponseDeliverTxWithEvents(err, gInfo.GasWanted, gInfo.GasUsed, sdk.MarkEventsToIndex(result.Events, app.indexEvents), app.trace) + return sdkerrors.ResponseDeliverTxWithEvents(err, gInfo.GasWanted, gInfo.GasUsed, sdk.MarkEventsToIndex(result.Events, app.IndexEvents), app.trace) } - return sdkerrors.ResponseDeliverTxWithEvents(err, gInfo.GasWanted, gInfo.GasUsed, sdk.MarkEventsToIndex(anteEvents, app.indexEvents), app.trace) + return sdkerrors.ResponseDeliverTxWithEvents(err, gInfo.GasWanted, gInfo.GasUsed, sdk.MarkEventsToIndex(anteEvents, app.IndexEvents), app.trace) } res = abci.ResponseDeliverTx{ @@ -289,7 +271,7 @@ func (app *BaseApp) DeliverTx(ctx sdk.Context, req abci.RequestDeliverTx, tx sdk GasUsed: int64(gInfo.GasUsed), // TODO: Should type accept unsigned ints? Log: result.Log, Data: result.Data, - Events: sdk.MarkEventsToIndex(result.Events, app.indexEvents), + Events: sdk.MarkEventsToIndex(result.Events, app.IndexEvents), } if resCtx.IsEVM() { res.EvmTxInfo = &abci.EvmTxInfo{ @@ -1162,7 +1144,7 @@ func (app *BaseApp) FinalizeBlock(ctx context.Context, req *abci.RequestFinalize if err != nil { return nil, err } - res.Events = sdk.MarkEventsToIndex(res.Events, app.indexEvents) + res.Events = sdk.MarkEventsToIndex(res.Events, app.IndexEvents) // set the signed validators for addition to context in deliverTx app.setVotesInfo(req.DecidedLastCommit.GetVotes()) diff --git a/sei-cosmos/baseapp/baseapp.go b/sei-cosmos/baseapp/baseapp.go index b4372a2a20..b81a28fc02 100644 --- a/sei-cosmos/baseapp/baseapp.go +++ b/sei-cosmos/baseapp/baseapp.go @@ -155,7 +155,7 @@ type BaseApp struct { //nolint: maligned // indexEvents defines the set of events in the form {eventType}.{attributeKey}, // which informs Tendermint what to index. If empty, all events will be indexed. - indexEvents map[string]struct{} + IndexEvents map[string]struct{} ChainID string @@ -196,10 +196,9 @@ type moduleRouter struct { } type abciData struct { - initChainer sdk.InitChainer // initialize state with validators and state blob - beginBlocker sdk.BeginBlocker // logic to run before any txs - midBlocker sdk.MidBlocker // logic to run after all txs, and to determine valset changes - endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes + initChainer sdk.InitChainer // initialize state with validators and state blob + midBlocker sdk.MidBlocker // logic to run after all txs, and to determine valset changes + endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes // absent validators from begin block voteInfos []abci.VoteInfo @@ -516,10 +515,10 @@ func (app *BaseApp) setTrace(trace bool) { } func (app *BaseApp) setIndexEvents(ie []string) { - app.indexEvents = make(map[string]struct{}) + app.IndexEvents = make(map[string]struct{}) for _, e := range ie { - app.indexEvents[e] = struct{}{} + app.IndexEvents[e] = struct{}{} } } @@ -748,9 +747,9 @@ func (app *BaseApp) StoreConsensusParams(ctx sdk.Context, cp *tmproto.ConsensusP app.paramStore.Set(ctx, ParamStoreKeyABCIParams, cp.Abci) } -func (app *BaseApp) validateHeight(req abci.RequestBeginBlock) error { - if req.Header.Height < 1 { - return fmt.Errorf("invalid height: %d", req.Header.Height) +func (app *BaseApp) ValidateHeight(height int64) error { + if height < 1 { + return fmt.Errorf("invalid height: %d", height) } // expectedHeight holds the expected height to validate. @@ -768,8 +767,8 @@ func (app *BaseApp) validateHeight(req abci.RequestBeginBlock) error { expectedHeight = app.LastBlockHeight() + 1 } - if req.Header.Height != expectedHeight { - return fmt.Errorf("invalid height: %d; expected: %d", req.Header.Height, expectedHeight) + if height != expectedHeight { + return fmt.Errorf("invalid height: %d; expected: %d", height, expectedHeight) } return nil @@ -1020,7 +1019,7 @@ func (app *BaseApp) runTx(ctx sdk.Context, mode runTxMode, tx sdk.Tx, checksum [ } var events []abci.Event = []abci.Event{} if result != nil { - events = sdk.MarkEventsToIndex(result.Events, app.indexEvents) + events = sdk.MarkEventsToIndex(result.Events, app.IndexEvents) } for _, hook := range app.deliverTxHooks { hook(ctx, tx, checksum, sdk.DeliverTxHookInput{ diff --git a/sei-cosmos/baseapp/deliver_tx_batch_test.go b/sei-cosmos/baseapp/deliver_tx_batch_test.go index 16ece77699..dc5eafebfd 100644 --- a/sei-cosmos/baseapp/deliver_tx_batch_test.go +++ b/sei-cosmos/baseapp/deliver_tx_batch_test.go @@ -111,7 +111,6 @@ func TestDeliverTxBatch(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) var requests []*sdk.DeliverTxEntry for i := 0; i < txPerHeight; i++ { @@ -170,7 +169,6 @@ func TestDeliverTxBatchEmpty(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) var requests []*sdk.DeliverTxEntry responses := app.DeliverTxBatch(app.deliverState.ctx, sdk.DeliverTxBatchRequest{TxEntries: requests}) diff --git a/sei-cosmos/baseapp/deliver_tx_test.go b/sei-cosmos/baseapp/deliver_tx_test.go index 4a5ddd8816..06476e1fee 100644 --- a/sei-cosmos/baseapp/deliver_tx_test.go +++ b/sei-cosmos/baseapp/deliver_tx_test.go @@ -221,7 +221,6 @@ func TestWithRouter(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) for i := 0; i < txPerHeight; i++ { counter := int64(blockN*txPerHeight + i) @@ -324,7 +323,6 @@ func TestQuery(t *testing.T) { // query is still empty after a DeliverTx before we commit header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) _, resTx, err = app.Deliver(aminoTxEncoder(), tx) require.NoError(t, err) @@ -352,7 +350,6 @@ func TestGRPCQuery(t *testing.T) { app.InitChain(context.Background(), &abci.RequestInitChain{}) header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -433,7 +430,6 @@ func TestMultiMsgDeliverTx(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(0, 0, 1, 2) txBytes, err := codec.Marshal(tx) require.NoError(t, err) @@ -517,7 +513,6 @@ func TestSimulateTx(t *testing.T) { count := int64(blockN + 1) header := tmproto.Header{Height: count} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(count, count) txBytes, err := cdc.Marshal(tx) @@ -576,7 +571,6 @@ func TestRunInvalidTransaction(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // transaction with no messages { @@ -703,7 +697,6 @@ func TestTxGasLimits(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) testCases := []struct { tx *txTest @@ -873,7 +866,6 @@ func TestCustomRunTxPanicHandler(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.AddRunTxRecoveryHandler(func(recoveryObj interface{}) error { err, ok := recoveryObj.(error) @@ -923,7 +915,6 @@ func TestBaseAppAnteHandler(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // execute a tx that will fail ante handler execution // @@ -1013,7 +1004,6 @@ func TestPrecommitHandlerPanic(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // execute a tx that will fail ante handler execution // @@ -1131,7 +1121,6 @@ func TestGasConsumptionBadTx(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(5, 0) tx.setFailOnAnte(true) @@ -1221,7 +1210,6 @@ func TestInitChainer(t *testing.T) { // commit and ensure we can still query header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1246,39 +1234,6 @@ func TestInitChain_WithInitialHeight(t *testing.T) { require.Equal(t, int64(3), app.LastBlockHeight()) } -func TestBeginBlock_WithInitialHeight(t *testing.T) { - name := t.Name() - db := dbm.NewMemDB() - logger := defaultLogger() - cc := codec.NewLegacyAmino() - app := NewBaseApp(name, logger, db, testTxDecoder(cc), nil, &testutil.TestAppOpts{}) - - app.InitChain( - context.Background(), &abci.RequestInitChain{ - InitialHeight: 3, - }, - ) - - app.setDeliverState(tmproto.Header{Height: 4}) - require.PanicsWithError(t, "invalid height: 4; expected: 3", func() { - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{ - Header: tmproto.Header{ - Height: 4, - }, - }) - }) - - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{ - Header: tmproto.Header{ - Height: 3, - }, - }) - app.SetDeliverStateToCommit() - app.Commit(context.Background()) - - require.Equal(t, int64(3), app.LastBlockHeight()) -} - // Simple tx with a list of Msgs. type txTest struct { Msgs []sdk.Msg @@ -1560,7 +1515,6 @@ func TestCheckTx(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) app.checkState.ctx = app.checkState.ctx.WithHeaderHash([]byte("hash")) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header, Hash: []byte("hash")}) require.NotEmpty(t, app.checkState.ctx.HeaderHash()) @@ -1602,7 +1556,6 @@ func TestDeliverTx(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) for i := 0; i < txPerHeight; i++ { // every even i is an evm tx @@ -1663,7 +1616,6 @@ func TestDeliverTxHooks(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // every even i is an evm tx counter := int64(1) @@ -1755,9 +1707,6 @@ func TestBaseAppOptionSeal(t *testing.T) { require.Panics(t, func() { app.SetInitChainer(nil) }) - require.Panics(t, func() { - app.SetBeginBlocker(nil) - }) require.Panics(t, func() { app.SetEndBlocker(nil) }) @@ -1819,7 +1768,6 @@ func TestLoadVersionInvalid(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1870,7 +1818,6 @@ func setupBaseAppWithSnapshots(t *testing.T, blocks uint, blockTxs int, options keyCounter := 0 for height := int64(1); height <= int64(blocks); height++ { app.setDeliverState(tmproto.Header{Height: height}) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: tmproto.Header{Height: height}}) for txNum := 0; txNum < blockTxs; txNum++ { tx := txTest{Msgs: []sdk.Msg{}} for msgNum := 0; msgNum < 100; msgNum++ { @@ -1947,14 +1894,12 @@ func TestLoadVersion(t *testing.T) { // execute a block, collect commit ID header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) // execute a block, collect commit ID header = tmproto.Header{Height: 2} app.setDeliverState(header) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) } @@ -2037,7 +1982,6 @@ func TestSetLoader(t *testing.T) { // "execute" one block app.setDeliverState(tmproto.Header{Height: 2}) - app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: tmproto.Header{Height: 2}}) app.SetDeliverStateToCommit() app.Commit(context.Background()) diff --git a/sei-cosmos/baseapp/options.go b/sei-cosmos/baseapp/options.go index d918927683..79c5558ac0 100644 --- a/sei-cosmos/baseapp/options.go +++ b/sei-cosmos/baseapp/options.go @@ -159,14 +159,6 @@ func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) { app.initChainer = initChainer } -func (app *BaseApp) SetBeginBlocker(beginBlocker sdk.BeginBlocker) { - if app.sealed { - panic("SetBeginBlocker() on sealed BaseApp") - } - - app.beginBlocker = beginBlocker -} - func (app *BaseApp) SetMidBlocker(midBlocker sdk.MidBlocker) { if app.sealed { panic("SetMidBlocker() on sealed BaseApp") diff --git a/sei-cosmos/store/rootmulti/rollback_test.go b/sei-cosmos/store/rootmulti/rollback_test.go index c895b72cae..f1ef61287b 100644 --- a/sei-cosmos/store/rootmulti/rollback_test.go +++ b/sei-cosmos/store/rootmulti/rollback_test.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/sei-protocol/sei-chain/app" + "github.com/sei-protocol/sei-chain/app/legacyabci" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -58,7 +59,7 @@ func TestRollback(t *testing.T) { Height: ver0 + i, AppHash: a.LastCommitID().Hash, } - a.BeginBlock(sdk.Context{}, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(sdk.Context{}, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, a.BeginBlockKeepers) ctx := a.NewContext(false, header) store := ctx.KVStore(a.GetKey("bank")) store.Set([]byte("key"), []byte(fmt.Sprintf("value%d", i))) @@ -85,7 +86,7 @@ func TestRollback(t *testing.T) { Height: ver0 + i, AppHash: a.LastCommitID().Hash, } - a.BeginBlock(sdk.Context{}, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(sdk.Context{}, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, a.BeginBlockKeepers) ctx := a.NewContext(false, header) store := ctx.KVStore(a.GetKey("bank")) store.Set([]byte("key"), []byte(fmt.Sprintf("VALUE%d", i))) diff --git a/sei-cosmos/types/abci.go b/sei-cosmos/types/abci.go index 3d056cd2a3..3ab3827cfd 100644 --- a/sei-cosmos/types/abci.go +++ b/sei-cosmos/types/abci.go @@ -8,12 +8,6 @@ import ( // InitChainer initializes application state at genesis type InitChainer func(ctx Context, req abci.RequestInitChain) abci.ResponseInitChain -// BeginBlocker runs code before the transactions in a block -// -// Note: applications which set create_empty_blocks=false will not have regular block timing and should use -// e.g. BFT timestamps rather than block height for any periodic BeginBlock logic -type BeginBlocker func(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock - // MidBlocker runs code after the early transactions in a block and return any relevant events type MidBlocker func(ctx Context, height int64) []abci.Event diff --git a/sei-cosmos/types/module/module.go b/sei-cosmos/types/module/module.go index f7e305453c..7ca036a682 100644 --- a/sei-cosmos/types/module/module.go +++ b/sei-cosmos/types/module/module.go @@ -258,9 +258,6 @@ func (gam GenesisOnlyAppModule) RegisterServices(Configurator) {} // ConsensusVersion implements AppModule/ConsensusVersion. func (gam GenesisOnlyAppModule) ConsensusVersion() uint64 { return 1 } -// BeginBlock returns an empty module begin-block -func (gam GenesisOnlyAppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} - // EndBlock returns an empty module end-block func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} @@ -272,7 +269,6 @@ type Manager struct { Modules map[string]AppModule OrderInitGenesis []string OrderExportGenesis []string - OrderBeginBlockers []string OrderMidBlockers []string OrderEndBlockers []string OrderMigrations []string @@ -292,7 +288,6 @@ func NewManager(modules ...AppModule) *Manager { Modules: moduleMap, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, - OrderBeginBlockers: modulesStr, OrderEndBlockers: modulesStr, } } @@ -309,12 +304,6 @@ func (m *Manager) SetOrderExportGenesis(moduleNames ...string) { m.OrderExportGenesis = moduleNames } -// SetOrderBeginBlockers sets the order of set begin-blocker calls -func (m *Manager) SetOrderBeginBlockers(moduleNames ...string) { - m.assertNoForgottenModules("SetOrderBeginBlockers", moduleNames) - m.OrderBeginBlockers = moduleNames -} - // SetOrderMidBlockers sets the order of set mid-blocker calls func (m *Manager) SetOrderMidBlockers(moduleNames ...string) { m.OrderMidBlockers = moduleNames @@ -595,27 +584,6 @@ func (m Manager) RunMigrations(ctx sdk.Context, cfg Configurator, fromVM Version return updatedVM, nil } -// BeginBlock performs begin block functionality for all modules. It creates a -// child context with an event manager to aggregate events emitted from all -// modules. -func (m *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - defer telemetry.MeasureSince(time.Now(), "module", "total_begin_block") - for _, moduleName := range m.OrderBeginBlockers { - module, ok := m.Modules[moduleName].(BeginBlockAppModule) - if ok { - moduleStartTime := time.Now() - module.BeginBlock(ctx, req) - telemetry.ModuleMeasureSince(moduleName, moduleStartTime, "module", "begin_block") - } - } - - return abci.ResponseBeginBlock{ - Events: ctx.EventManager().ABCIEvents(), - } -} - // EndBlock performs end block functionality for all modules. It creates a // child context with an event manager to aggregate events emitted from all // modules. diff --git a/sei-cosmos/types/module/module_test.go b/sei-cosmos/types/module/module_test.go index 41ff61186f..68e358dd50 100644 --- a/sei-cosmos/types/module/module_test.go +++ b/sei-cosmos/types/module/module_test.go @@ -107,10 +107,6 @@ func TestManagerOrderSetters(t *testing.T) { mm.SetOrderExportGenesis("module2", "module1") require.Equal(t, []string{"module2", "module1"}, mm.OrderExportGenesis) - require.Equal(t, []string{"module1", "module2"}, mm.OrderBeginBlockers) - mm.SetOrderBeginBlockers("module2", "module1") - require.Equal(t, []string{"module2", "module1"}, mm.OrderBeginBlockers) - // we expect none of the modules to be included by default require.Empty(t, mm.OrderMidBlockers) mm.SetOrderMidBlockers("module2", "module1") @@ -247,25 +243,6 @@ func TestManager_ExportGenesis(t *testing.T) { require.Equal(t, want, mm.ExportGenesis(ctx, cdc)) } -func TestManager_BeginBlock(t *testing.T) { - mockCtrl := gomock.NewController(t) - t.Cleanup(mockCtrl.Finish) - - mockAppModule1 := mocks.NewMockAppModule(mockCtrl) - mockAppModule2 := mocks.NewMockAppModule(mockCtrl) - mockAppModule1.EXPECT().Name().Times(2).Return("module1") - mockAppModule2.EXPECT().Name().Times(2).Return("module2") - mm := module.NewManager(mockAppModule1, mockAppModule2) - require.NotNil(t, mm) - require.Equal(t, 2, len(mm.Modules)) - - req := abci.RequestBeginBlock{Hash: []byte("test")} - - mockAppModule1.EXPECT().BeginBlock(gomock.Any(), gomock.Eq(req)).Times(1) - mockAppModule2.EXPECT().BeginBlock(gomock.Any(), gomock.Eq(req)).Times(1) - mm.BeginBlock(sdk.NewContext(nil, tmproto.Header{}, false, nil), req) -} - func TestManager_MidBlock(t *testing.T) { mockCtrl := gomock.NewController(t) t.Cleanup(mockCtrl.Finish) diff --git a/sei-cosmos/x/accesscontrol/module.go b/sei-cosmos/x/accesscontrol/module.go index 33cc6cc987..a1529d1049 100644 --- a/sei-cosmos/x/accesscontrol/module.go +++ b/sei-cosmos/x/accesscontrol/module.go @@ -170,9 +170,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 2 } -// BeginBlock returns the begin blocker for the accesscontrol module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {} - // EndBlock returns the end blocker for the accesscontrol module. It returns no validator // updates. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/sei-cosmos/x/authz/module/module.go b/sei-cosmos/x/authz/module/module.go index 285c7c9fc8..fa83845472 100644 --- a/sei-cosmos/x/authz/module/module.go +++ b/sei-cosmos/x/authz/module/module.go @@ -167,5 +167,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } - -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} diff --git a/sei-cosmos/x/capability/capability_test.go b/sei-cosmos/x/capability/capability_test.go index 2d6843c11f..1465960eec 100644 --- a/sei-cosmos/x/capability/capability_test.go +++ b/sei-cosmos/x/capability/capability_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/suite" - abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" @@ -60,8 +59,7 @@ func (suite *CapabilityTestSuite) TestInitializeMemStore() { // Mock app beginblock and ensure that no gas has been consumed and memstore is initialized ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) - restartedModule := capability.NewAppModule(suite.cdc, *newKeeper) - restartedModule.BeginBlock(ctx, abci.RequestBeginBlock{}) + capability.BeginBlocker(ctx, *newKeeper) suite.Require().True(newKeeper.IsInitialized(ctx), "memstore initialized flag not set") // Mock the first transaction getting capability and subsequently failing @@ -79,7 +77,7 @@ func (suite *CapabilityTestSuite) TestInitializeMemStore() { // Ensure the capabilities don't get reinitialized on next BeginBlock // by testing to see if capability returns same pointer // also check that initialized flag is still set - restartedModule.BeginBlock(ctx, abci.RequestBeginBlock{}) + capability.BeginBlocker(ctx, *newKeeper) recap, ok := newSk1.GetCapability(ctx, "transfer") suite.Require().True(ok) suite.Require().Equal(cap1, recap, "capabilities got reinitialized after second BeginBlock") diff --git a/sei-cosmos/x/capability/module.go b/sei-cosmos/x/capability/module.go index a54040248d..4273f0dda1 100644 --- a/sei-cosmos/x/capability/module.go +++ b/sei-cosmos/x/capability/module.go @@ -3,7 +3,6 @@ package capability import ( "encoding/json" "fmt" - "time" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -14,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/capability/keeper" @@ -155,11 +153,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlocker calls InitMemStore to assert that the memory store is initialized. -// It's safe to run multiple times. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - am.keeper.InitMemStore(ctx) -} diff --git a/sei-cosmos/x/distribution/abci.go b/sei-cosmos/x/distribution/abci.go index 5ec474cfef..57e64ba561 100644 --- a/sei-cosmos/x/distribution/abci.go +++ b/sei-cosmos/x/distribution/abci.go @@ -12,12 +12,12 @@ import ( // BeginBlocker sets the proposer for determining distribution during endblock // and distribute rewards for the previous block -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { +func BeginBlocker(ctx sdk.Context, votes []abci.VoteInfo, k keeper.Keeper) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) // determine the total power signing the block var previousTotalPower, sumPreviousPrecommitPower int64 - for _, voteInfo := range req.LastCommitInfo.GetVotes() { + for _, voteInfo := range votes { previousTotalPower += voteInfo.Validator.Power if voteInfo.SignedLastBlock { sumPreviousPrecommitPower += voteInfo.Validator.Power @@ -28,10 +28,10 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) // ref https://github.com/cosmos/cosmos-sdk/issues/3095 if ctx.BlockHeight() > 1 { previousProposer := k.GetPreviousProposerConsAddr(ctx) - k.AllocateTokens(ctx, sumPreviousPrecommitPower, previousTotalPower, previousProposer, req.LastCommitInfo.GetVotes()) + k.AllocateTokens(ctx, sumPreviousPrecommitPower, previousTotalPower, previousProposer, votes) } // record the proposer for when we payout on the next block - consAddr := sdk.ConsAddress(req.Header.ProposerAddress) + consAddr := sdk.ConsAddress(ctx.BlockHeader().ProposerAddress) k.SetPreviousProposerConsAddr(ctx, consAddr) } diff --git a/sei-cosmos/x/distribution/module.go b/sei-cosmos/x/distribution/module.go index 2199874fe6..bf2944d46c 100644 --- a/sei-cosmos/x/distribution/module.go +++ b/sei-cosmos/x/distribution/module.go @@ -178,8 +178,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 2 } - -// BeginBlock returns the begin blocker for the distribution module. -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} diff --git a/sei-cosmos/x/evidence/abci.go b/sei-cosmos/x/evidence/abci.go index 05f6acf86e..04201fdb98 100644 --- a/sei-cosmos/x/evidence/abci.go +++ b/sei-cosmos/x/evidence/abci.go @@ -13,15 +13,15 @@ import ( // BeginBlocker iterates through and handles any newly discovered evidence of // misbehavior submitted by Tendermint. Currently, only equivocation is handled. -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { +func BeginBlocker(ctx sdk.Context, byzantineValidators []abci.Misbehavior, k keeper.Keeper) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - for _, tmEvidence := range req.ByzantineValidators { + for _, tmEvidence := range byzantineValidators { switch tmEvidence.Type { // It's still ongoing discussion how should we treat and slash attacks with // premeditation. So for now we agree to treat them in the same way. case abci.MisbehaviorType_DUPLICATE_VOTE, abci.MisbehaviorType_LIGHT_CLIENT_ATTACK: - evidence := types.FromABCIEvidence(tmEvidence) + evidence := types.FromABCIEvidence(abci.Evidence(tmEvidence)) k.HandleEquivocationEvidence(ctx, evidence.(*types.Equivocation)) default: diff --git a/sei-cosmos/x/evidence/keeper/infraction_test.go b/sei-cosmos/x/evidence/keeper/infraction_test.go index df72d54a30..8072d00168 100644 --- a/sei-cosmos/x/evidence/keeper/infraction_test.go +++ b/sei-cosmos/x/evidence/keeper/infraction_test.go @@ -52,7 +52,7 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign() { }, }, } - slashing.BeginBlocker(ctx, req, suite.app.SlashingKeeper) + slashing.BeginBlocker(ctx, req.LastCommitInfo.Votes, suite.app.SlashingKeeper) // double sign less than max age oldTokens := suite.app.StakingKeeper.Validator(ctx, operatorAddr).GetTokens() diff --git a/sei-cosmos/x/evidence/module.go b/sei-cosmos/x/evidence/module.go index 4ceea59867..5052ce8267 100644 --- a/sei-cosmos/x/evidence/module.go +++ b/sei-cosmos/x/evidence/module.go @@ -192,8 +192,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock executes all ABCI BeginBlock logic respective to the evidence module. -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} diff --git a/sei-cosmos/x/gov/abci_test.go b/sei-cosmos/x/gov/abci_test.go index ef62a8227c..7487bb4912 100644 --- a/sei-cosmos/x/gov/abci_test.go +++ b/sei-cosmos/x/gov/abci_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/staking" seiapp "github.com/sei-protocol/sei-chain/app" + "github.com/sei-protocol/sei-chain/app/legacyabci" ) func TestTickExpiredDepositPeriod(t *testing.T) { @@ -301,7 +302,7 @@ func TestProposalPassedEndblocker(t *testing.T) { stakingHandler := staking.NewHandler(app.StakingKeeper) header := tmproto.Header{Height: app.LastBlockHeight() + 1} - app.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, app.BeginBlockKeepers) valAddr := sdk.ValAddress(addrs[0]) @@ -382,7 +383,7 @@ func TestExpeditedProposalPassAndConvertToRegular(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) SortAddresses(addrs) header := tmproto.Header{Height: app.LastBlockHeight() + 1} - app.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, app.BeginBlockKeepers) valAddr := sdk.ValAddress(addrs[0]) diff --git a/sei-cosmos/x/slashing/abci.go b/sei-cosmos/x/slashing/abci.go index de0af653d4..08f63d5363 100644 --- a/sei-cosmos/x/slashing/abci.go +++ b/sei-cosmos/x/slashing/abci.go @@ -21,7 +21,7 @@ type SlashingWriteInfo struct { // BeginBlocker check for infraction evidence or downtime of validators // on every begin block -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { +func BeginBlocker(ctx sdk.Context, votes []abci.VoteInfo, k keeper.Keeper) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) var wg sync.WaitGroup @@ -30,9 +30,9 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) // which have missed too many blocks in a row (downtime slashing) // this allows us to preserve the original ordering for writing purposes - slashingWriteInfo := make([]*SlashingWriteInfo, len(req.LastCommitInfo.GetVotes())) + slashingWriteInfo := make([]*SlashingWriteInfo, len(votes)) - allVotes := req.LastCommitInfo.GetVotes() + allVotes := votes for i := range allVotes { wg.Add(1) go func(valIndex int) { diff --git a/sei-cosmos/x/slashing/abci_test.go b/sei-cosmos/x/slashing/abci_test.go index ede67cb67c..05d8b797fd 100644 --- a/sei-cosmos/x/slashing/abci_test.go +++ b/sei-cosmos/x/slashing/abci_test.go @@ -65,7 +65,7 @@ func TestBeginBlocker(t *testing.T) { Votes: trueVotes, }, } - slashing.BeginBlocker(ctx, req, app.SlashingKeeper) + slashing.BeginBlocker(ctx, req.LastCommitInfo.Votes, app.SlashingKeeper) for i := 0; i < 5; i++ { info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(pks[i].Address())) @@ -86,7 +86,7 @@ func TestBeginBlocker(t *testing.T) { }, } - slashing.BeginBlocker(ctx, req, app.SlashingKeeper) + slashing.BeginBlocker(ctx, req.LastCommitInfo.Votes, app.SlashingKeeper) } // for 5000 blocks, mark the validator as having not signed @@ -98,7 +98,7 @@ func TestBeginBlocker(t *testing.T) { }, } - slashing.BeginBlocker(ctx, req, app.SlashingKeeper) + slashing.BeginBlocker(ctx, req.LastCommitInfo.Votes, app.SlashingKeeper) } // end block @@ -160,7 +160,7 @@ func TestResizeTrimResetValidatorMissedBlocksArray(t *testing.T) { app.SlashingKeeper.SetParams(ctx, params) ctx = ctx.WithBlockHeight(18) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true).LastCommitInfo.Votes, app.SlashingKeeper) bitGroup = uint64(0) missedInfo, found := app.SlashingKeeper.GetValidatorMissedBlocks(ctx, consAddr) @@ -219,7 +219,7 @@ func TestResizeExpandValidatorMissedBlocksArray(t *testing.T) { app.SlashingKeeper.SetValidatorMissedBlocks(ctx, consAddr, tooSmallArray) ctx = ctx.WithBlockHeight(39) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true).LastCommitInfo.Votes, app.SlashingKeeper) bitGroup = uint64(0) bitGroup |= 1 << 1 @@ -281,7 +281,7 @@ func TestResizeExpandShiftValidatorMissedBlocksArrayMultipleBitGroups(t *testing app.SlashingKeeper.SetValidatorMissedBlocks(ctx, consAddr, tooSmallArray) ctx = ctx.WithBlockHeight(2053) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true).LastCommitInfo.Votes, app.SlashingKeeper) bg0 = uint64(0) bg0 |= 1 << 0 @@ -350,7 +350,7 @@ func TestResizeExpandShiftValidatorMissedBlocksArrayMultipleBitGroupsBeforeAndAf app.SlashingKeeper.SetValidatorMissedBlocks(ctx, consAddr, tooSmallArray) ctx = ctx.WithBlockHeight(509) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true).LastCommitInfo.Votes, app.SlashingKeeper) bg0 = uint64(0) bg0 |= 1 << 0 @@ -423,7 +423,7 @@ func TestResizeTrimValidatorMissedBlocksArrayMultipleBitGroups(t *testing.T) { app.SlashingKeeper.SetValidatorMissedBlocks(ctx, consAddr, tooSmallArray) ctx = ctx.WithBlockHeight(509) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, false).LastCommitInfo.Votes, app.SlashingKeeper) missedInfo, found := app.SlashingKeeper.GetValidatorMissedBlocks(ctx, consAddr) require.True(t, found) @@ -486,7 +486,7 @@ func TestResizeTrimValidatorMissedBlocksArrayEliminateBitGroup(t *testing.T) { app.SlashingKeeper.SetValidatorMissedBlocks(ctx, consAddr, tooSmallArray) ctx = ctx.WithBlockHeight(509) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 200, true).LastCommitInfo.Votes, app.SlashingKeeper) missedInfo, found := app.SlashingKeeper.GetValidatorMissedBlocks(ctx, consAddr) require.True(t, found) diff --git a/sei-cosmos/x/slashing/handler_test.go b/sei-cosmos/x/slashing/handler_test.go index ef4d02943e..9a5ddede26 100644 --- a/sei-cosmos/x/slashing/handler_test.go +++ b/sei-cosmos/x/slashing/handler_test.go @@ -173,7 +173,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 1000 first blocks OK for ; height < app.SlashingKeeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true).LastCommitInfo.Votes, app.SlashingKeeper) } info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -183,7 +183,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 500 blocks missed for ; height < app.SlashingKeeper.SignedBlocksWindow(ctx)+(app.SlashingKeeper.SignedBlocksWindow(ctx)-app.SlashingKeeper.MinSignedPerWindow(ctx)); height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) } info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -199,7 +199,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 501st block missed ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -221,7 +221,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 502nd block *also* missed (since the LastCommit would have still included the just-unbonded validator) height++ ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -265,7 +265,7 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should not be immediately jailed again height++ ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, stakingtypes.Bonded, validator.GetStatus()) @@ -273,7 +273,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight := height + app.SlashingKeeper.MinSignedPerWindow(ctx) + 1 for ; height < nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) } // end block @@ -283,7 +283,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight = height + app.SlashingKeeper.MinSignedPerWindow(ctx) + 1 for ; height <= nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) } // end block diff --git a/sei-cosmos/x/slashing/keeper/keeper_test.go b/sei-cosmos/x/slashing/keeper/keeper_test.go index 3cbbd37c64..fa2e783043 100644 --- a/sei-cosmos/x/slashing/keeper/keeper_test.go +++ b/sei-cosmos/x/slashing/keeper/keeper_test.go @@ -106,9 +106,9 @@ func TestHandleNewValidator(t *testing.T) { require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) // Now a validator, for two blocks - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 100, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 100, true).LastCommitInfo.Votes, app.SlashingKeeper) ctx = ctx.WithBlockHeight(app.SlashingKeeper.SignedBlocksWindow(ctx) + 2) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 100, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), 100, false).LastCommitInfo.Votes, app.SlashingKeeper) info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -155,13 +155,13 @@ func TestHandleAlreadyJailed(t *testing.T) { height := int64(0) for ; height < app.SlashingKeeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true).LastCommitInfo.Votes, app.SlashingKeeper) } // 501 blocks missed for ; height < app.SlashingKeeper.SignedBlocksWindow(ctx)+(app.SlashingKeeper.SignedBlocksWindow(ctx)-app.SlashingKeeper.MinSignedPerWindow(ctx))+1; height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) } // end block @@ -177,7 +177,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // another block missed ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, false).LastCommitInfo.Votes, app.SlashingKeeper) // validator should not have been slashed twice validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -215,7 +215,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { height := int64(0) for ; height < int64(100); height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), power, true).LastCommitInfo.Votes, app.SlashingKeeper) } // kick first validator out of validator set @@ -237,7 +237,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { newPower := int64(150) // validator misses a block - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false).LastCommitInfo.Votes, app.SlashingKeeper) height++ // shouldn't be jailed/kicked yet @@ -247,7 +247,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest := height for ; height < latest+500; height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false).LastCommitInfo.Votes, app.SlashingKeeper) } // should now be jailed & kicked @@ -270,7 +270,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator rejoins and starts signing again app.StakingKeeper.Unjail(ctx, consAddr) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, true), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, true).LastCommitInfo.Votes, app.SlashingKeeper) height++ // validator should not be kicked since we reset counter/array when it was jailed @@ -281,7 +281,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest = height for ; height < latest+501; height++ { ctx = ctx.WithBlockHeight(height) - slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false), app.SlashingKeeper) + slashing.BeginBlocker(ctx, testslashing.CreateBeginBlockReq(val.Address(), newPower, false).LastCommitInfo.Votes, app.SlashingKeeper) } // validator should now be jailed & kicked diff --git a/sei-cosmos/x/slashing/module.go b/sei-cosmos/x/slashing/module.go index 568cd80db9..e8aa4a467c 100644 --- a/sei-cosmos/x/slashing/module.go +++ b/sei-cosmos/x/slashing/module.go @@ -178,8 +178,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 4 } - -// BeginBlock returns the begin blocker for the slashing module. -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} diff --git a/sei-cosmos/x/staking/module.go b/sei-cosmos/x/staking/module.go index abbba21b33..ce412479b5 100644 --- a/sei-cosmos/x/staking/module.go +++ b/sei-cosmos/x/staking/module.go @@ -178,11 +178,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 2 } -// BeginBlock returns the begin blocker for the staking module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - // EndBlock returns the end blocker for the staking module. It returns no validator // updates. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/sei-cosmos/x/upgrade/abci.go b/sei-cosmos/x/upgrade/abci.go index 33779f1d82..f7ee7d9d1f 100644 --- a/sei-cosmos/x/upgrade/abci.go +++ b/sei-cosmos/x/upgrade/abci.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/x/upgrade/types" - abci "github.com/tendermint/tendermint/abci/types" ) // BeginBlock will check if there is a scheduled plan and if it is ready to be executed. @@ -20,7 +19,7 @@ import ( // The purpose is to ensure the binary is switched EXACTLY at the desired block, and to allow // a migration to be executed if needed upon this switch (migration defined in the new binary) // skipUpgradeHeightArray is a set of block heights for which the upgrade must be skipped -func BeginBlocker(k keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) { +func BeginBlocker(k keeper.Keeper, ctx sdk.Context) { if ctx.IsTracing() { return } diff --git a/sei-cosmos/x/upgrade/abci_test.go b/sei-cosmos/x/upgrade/abci_test.go index 2399023354..c62a1408cf 100644 --- a/sei-cosmos/x/upgrade/abci_test.go +++ b/sei-cosmos/x/upgrade/abci_test.go @@ -24,7 +24,6 @@ import ( ) type TestSuite struct { - module module.BeginBlockAppModule keeper keeper.Keeper querier sdk.Querier handler govtypes.Handler @@ -53,8 +52,7 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) TestSuite { s.keeper = app.UpgradeKeeper s.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: height, Time: time.Now()}) - s.module = upgrade.NewAppModule(s.keeper) - s.querier = s.module.LegacyQuerierHandler(app.LegacyAmino()) + s.querier = upgrade.NewAppModule(s.keeper).LegacyQuerierHandler(app.LegacyAmino()) s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return s } @@ -98,9 +96,8 @@ func VerifyDoUpgrade(t *testing.T) { t.Log("Verify that a panic happens at the upgrade height") newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} require.Panics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) t.Log("Verify that the upgrade can be successfully applied with a handler") @@ -108,7 +105,7 @@ func VerifyDoUpgrade(t *testing.T) { return vm, nil }) require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) VerifyCleared(t, newCtx) @@ -116,9 +113,8 @@ func VerifyDoUpgrade(t *testing.T) { func VerifyDoUpgradeWithCtx(t *testing.T, newCtx sdk.Context, proposalName string) { t.Log("Verify that a panic happens at the upgrade height") - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} require.Panics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) t.Log("Verify that the upgrade can be successfully applied with a handler") @@ -126,7 +122,7 @@ func VerifyDoUpgradeWithCtx(t *testing.T, newCtx sdk.Context, proposalName strin return vm, nil }) require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) VerifyCleared(t, newCtx) @@ -142,9 +138,8 @@ func TestHaltIfTooNew(t *testing.T) { }) newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) require.Equal(t, 0, called) @@ -152,16 +147,15 @@ func TestHaltIfTooNew(t *testing.T) { err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "future", Height: s.ctx.BlockHeight() + 3}}) require.NoError(t, err) require.Panics(t, func() { - s.module.BeginBlock(newCtx, req) + upgrade.BeginBlocker(s.keeper, newCtx) }) require.Equal(t, 0, called) t.Log("Verify we no longer panic if the plan is on time") futCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 3).WithBlockTime(time.Now()) - req = abci.RequestBeginBlock{Header: futCtx.BlockHeader()} require.NotPanics(t, func() { - s.module.BeginBlock(futCtx, req) + upgrade.BeginBlocker(s.keeper, futCtx) }) require.Equal(t, 1, called) @@ -202,9 +196,8 @@ func TestCantApplySameUpgradeTwice(t *testing.T) { func TestNoSpuriousUpgrades(t *testing.T) { s := setupTest(t, 10, map[int64]bool{}) t.Log("Verify that no upgrade panic is triggered in the BeginBlocker when we haven't scheduled an upgrade") - req := abci.RequestBeginBlock{Header: s.ctx.BlockHeader()} require.NotPanics(t, func() { - s.module.BeginBlock(s.ctx, req) + upgrade.BeginBlocker(s.keeper, s.ctx) }) } @@ -367,14 +360,14 @@ func TestBinaryVersion(t *testing.T) { } for _, tc := range testCases { - ctx, req := tc.preRun() + ctx, _ := tc.preRun() if tc.expectPanic { require.Panics(t, func() { - s.module.BeginBlock(ctx, req) + upgrade.BeginBlocker(s.keeper, ctx) }) } else { require.NotPanics(t, func() { - s.module.BeginBlock(ctx, req) + upgrade.BeginBlocker(s.keeper, ctx) }) } } diff --git a/sei-cosmos/x/upgrade/module.go b/sei-cosmos/x/upgrade/module.go index 3a8b79652d..7889b83b56 100644 --- a/sei-cosmos/x/upgrade/module.go +++ b/sei-cosmos/x/upgrade/module.go @@ -141,10 +141,3 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock calls the upgrade module hooks -// -// CONTRACT: this is registered in BeginBlocker *before* all other modules' BeginBlock functions -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(am.keeper, ctx, req) -} diff --git a/sei-wasmd/app/app.go b/sei-wasmd/app/app.go index 5476dd502a..5142392125 100644 --- a/sei-wasmd/app/app.go +++ b/sei-wasmd/app/app.go @@ -574,34 +574,6 @@ func NewWasmApp( crisis.NewAppModule(&app.crisisKeeper, skipGenesisInvariants), // always be last to make sure that it checks for all invariants and not only part of them ) - // During begin block slashing happens after distr.BeginBlocker so that - // there is nothing left over in the validator fee pool, so as to keep the - // CanWithdrawInvariant invariant. - // NOTE: staking module is required if HistoricalEntries param > 0 - app.mm.SetOrderBeginBlockers( - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - minttypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - evidencetypes.ModuleName, - stakingtypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - govtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - // additional non simd modules - ibctransfertypes.ModuleName, - ibchost.ModuleName, - icatypes.ModuleName, - wasm.ModuleName, - ) - app.mm.SetOrderEndBlockers( crisistypes.ModuleName, govtypes.ModuleName, @@ -694,7 +666,6 @@ func NewWasmApp( app.SetAnteHandler(anteHandler) app.SetAnteDepGenerator(anteDepGenerator) app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetPrepareProposalHandler(app.PrepareProposalHandler) app.SetProcessProposalHandler(app.ProcessProposalHandler) @@ -751,35 +722,13 @@ func (app *WasmApp) ProcessProposalHandler(ctx sdk.Context, req *abci.RequestPro } func (app *WasmApp) FinalizeBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { + capability.BeginBlocker(ctx, *app.capabilityKeeper) + distr.BeginBlocker(ctx, []abci.VoteInfo{}, app.distrKeeper) + slashing.BeginBlocker(ctx, []abci.VoteInfo{}, *&app.slashingKeeper) + evidence.BeginBlocker(ctx, []abci.Misbehavior{}, *&app.evidenceKeeper) + staking.BeginBlocker(ctx, app.stakingKeeper) + ibcclient.BeginBlocker(ctx, app.ibcKeeper.ClientKeeper) events := []abci.Event{} - beginBlockResp := app.BeginBlock(ctx, abci.RequestBeginBlock{ - Hash: req.Hash, - ByzantineValidators: utils.Map(req.ByzantineValidators, func(mis abci.Misbehavior) abci.Evidence { - return abci.Evidence{ - Type: abci.MisbehaviorType(mis.Type), - Validator: abci.Validator(mis.Validator), - Height: mis.Height, - Time: mis.Time, - TotalVotingPower: mis.TotalVotingPower, - } - }), - LastCommitInfo: abci.LastCommitInfo{ - Round: req.DecidedLastCommit.Round, - Votes: utils.Map(req.DecidedLastCommit.Votes, func(vote abci.VoteInfo) abci.VoteInfo { - return abci.VoteInfo{ - Validator: abci.Validator(vote.Validator), - SignedLastBlock: vote.SignedLastBlock, - } - }), - }, - Header: tmproto.Header{ - ChainID: app.ChainID, - Height: req.Height, - Time: req.Time, - ProposerAddress: ctx.BlockHeader().ProposerAddress, - }, - }) - events = append(events, beginBlockResp.Events...) typedTxs := []sdk.Tx{} for _, tx := range req.Txs { @@ -846,11 +795,6 @@ func (app *WasmApp) FinalizeBlocker(ctx sdk.Context, req *abci.RequestFinalizeBl }, nil } -// application updates every begin block -func (app *WasmApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.mm.BeginBlock(ctx, req) -} - // EndBlocker application updates every end block func (app *WasmApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { return app.mm.EndBlock(ctx, req) @@ -935,6 +879,22 @@ func (app *WasmApp) AppCodec() codec.Codec { return app.appCodec } +func (app *WasmApp) GetCapabilityKeeper() *capabilitykeeper.Keeper { + return app.capabilityKeeper +} + +func (app *WasmApp) GetDistrKeeper() *distrkeeper.Keeper { + return &app.distrKeeper +} + +func (app *WasmApp) GetSlashingKeeper() *slashingkeeper.Keeper { + return &app.slashingKeeper +} + +func (app *WasmApp) GetEvidenceKeeper() *evidencekeeper.Keeper { + return &app.evidenceKeeper +} + // RegisterSwaggerAPI registers swagger route with API Server func RegisterSwaggerAPI(rtr *mux.Router) { statikFS, err := fs.New() diff --git a/sei-wasmd/app/test_helpers.go b/sei-wasmd/app/test_helpers.go index 6a605747d5..7b6b806bb3 100644 --- a/sei-wasmd/app/test_helpers.go +++ b/sei-wasmd/app/test_helpers.go @@ -12,6 +12,7 @@ import ( "time" "github.com/cosmos/cosmos-sdk/testutil" + ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper" bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -25,7 +26,18 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/capability" + capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/cosmos/cosmos-sdk/x/evidence" + evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + ibcclient "github.com/cosmos/ibc-go/v3/modules/core/02-client" minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -329,7 +341,6 @@ func SignCheckDeliver( } // Simulate a sending a transaction and committing a block - app.BeginBlock(app.GetContextForDeliverTx([]byte{}), abci.RequestBeginBlock{Header: header}) gInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx) if expPass { @@ -350,7 +361,8 @@ func SignCheckDeliver( // SignAndDeliver signs and delivers a transaction. No simulation occurs as the // ibc testing package causes checkState and deliverState to diverge in block time. func SignAndDeliver( - t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, + t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, + ibcKeeper *ibckeeper.Keeper, stakingKeeper stakingkeeper.Keeper, capabilityKeeper *capabilitykeeper.Keeper, distrKeeper *distrkeeper.Keeper, slashingKeeper *slashingkeeper.Keeper, evidenceKeeper *evidencekeeper.Keeper, header tmproto.Header, msgs []sdk.Msg, chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { tx, err := seiapp.GenTx( @@ -366,7 +378,13 @@ func SignAndDeliver( require.NoError(t, err) // Simulate a sending a transaction and committing a block - app.BeginBlock(app.GetContextForDeliverTx([]byte{}), abci.RequestBeginBlock{Header: header}) + ctx := app.GetContextForDeliverTx([]byte{}).WithBlockHeader(header) + capability.BeginBlocker(ctx, *capabilityKeeper) + distribution.BeginBlocker(ctx, []abci.VoteInfo{}, *distrKeeper) + slashing.BeginBlocker(ctx, []abci.VoteInfo{}, *slashingKeeper) + evidence.BeginBlocker(ctx, []abci.Misbehavior{}, *evidenceKeeper) + staking.BeginBlocker(ctx, stakingKeeper) + ibcclient.BeginBlocker(ctx, ibcKeeper.ClientKeeper) gInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx) if expPass { diff --git a/sei-wasmd/benchmarks/app_test.go b/sei-wasmd/benchmarks/app_test.go index ce14f4ec67..9ca3ca9159 100644 --- a/sei-wasmd/benchmarks/app_test.go +++ b/sei-wasmd/benchmarks/app_test.go @@ -5,12 +5,10 @@ import ( "encoding/json" "io/ioutil" "testing" - "time" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/client" @@ -22,6 +20,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm" wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" seiapp "github.com/sei-protocol/sei-chain/app" + "github.com/sei-protocol/sei-chain/app/legacyabci" ) func setup(t *testing.T, db dbm.DB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*seiapp.App, seiapp.GenesisState) { @@ -65,7 +64,7 @@ func SetupWithGenesisAccounts(b testing.TB, db dbm.DB, genAccs []authtypes.Genes wasmApp.SetDeliverStateToCommit() wasmApp.Commit(context.Background()) - wasmApp.BeginBlock(wasmApp.GetContextForDeliverTx([]byte{}), abci.RequestBeginBlock{Header: tmproto.Header{Height: wasmApp.LastBlockHeight() + 1}}) + legacyabci.BeginBlock(wasmApp.GetContextForDeliverTx([]byte{}), wasmApp.LastBlockHeight()+1, []abci.VoteInfo{}, []abci.Misbehavior{}, wasmApp.BeginBlockKeepers) return wasmApp } @@ -115,7 +114,7 @@ func InitializeWasmApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { // add wasm contract height := int64(2) txGen := seiapp.MakeEncodingConfig().TxConfig - wasmApp.BeginBlock(wasmApp.GetContextForDeliverTx([]byte{}), abci.RequestBeginBlock{Header: tmproto.Header{Height: height, Time: time.Now()}}) + legacyabci.BeginBlock(wasmApp.GetContextForDeliverTx([]byte{}), height, []abci.VoteInfo{}, []abci.Misbehavior{}, wasmApp.BeginBlockKeepers) // upload the code cw20Code, err := ioutil.ReadFile("./testdata/cw20_base.wasm") diff --git a/sei-wasmd/benchmarks/bench_test.go b/sei-wasmd/benchmarks/bench_test.go index a117fa7f6b..6a3fbbd5bb 100644 --- a/sei-wasmd/benchmarks/bench_test.go +++ b/sei-wasmd/benchmarks/bench_test.go @@ -4,13 +4,11 @@ import ( "context" "encoding/json" "testing" - "time" "github.com/stretchr/testify/require" "github.com/syndtr/goleveldb/leveldb/opt" abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" @@ -104,7 +102,6 @@ func BenchmarkTxSending(b *testing.B) { b.ResetTimer() for i := 0; i < b.N/blockSize; i++ { - appInfo.App.BeginBlock(appInfo.App.GetContextForDeliverTx([]byte{}), abci.RequestBeginBlock{Header: tmproto.Header{Height: height, Time: time.Now()}}) for j := 0; j < blockSize; j++ { idx := i*blockSize + j diff --git a/sei-wasmd/x/wasm/ibctesting/chain.go b/sei-wasmd/x/wasm/ibctesting/chain.go index ef494b9bc9..c5ce896d3a 100644 --- a/sei-wasmd/x/wasm/ibctesting/chain.go +++ b/sei-wasmd/x/wasm/ibctesting/chain.go @@ -293,6 +293,12 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { chain.t, chain.TxConfig, chain.App.GetBaseApp(), + chain.App.GetIBCKeeper(), + chain.App.GetStakingKeeper(), + chain.App.(*TestingAppDecorator).GetCapabilityKeeper(), + chain.App.(*TestingAppDecorator).GetDistrKeeper(), + chain.App.(*TestingAppDecorator).GetSlashingKeeper(), + chain.App.(*TestingAppDecorator).GetEvidenceKeeper(), chain.GetContext().BlockHeader(), msgs, chain.ChainID, @@ -548,6 +554,7 @@ func CreateSortedSignerArray(altPrivVal, suitePrivVal tmtypes.PrivValidator, // NOTE: only creation of a capbility for a transfer or mock port is supported // Other applications must bind to the port in InitGenesis or modify this code. func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID string) { + // ensure the chain has the latest time // check if the portId is already binded, if not bind it _, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), host.PortPath(portID)) if !ok { @@ -580,6 +587,7 @@ func (chain *TestChain) GetPortCapability(portID string) *capabilitytypes.Capabi // if it does not already exist. This function will fail testing on any resulting error. The // scoped keeper passed in will claim the new capability. func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID, channelID string) { + // ensure the chain has the latest time capName := host.ChannelCapabilityPath(portID, channelID) // check if the portId is already binded, if not bind it _, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), capName) diff --git a/sei-wasmd/x/wasm/module.go b/sei-wasmd/x/wasm/module.go index 8c54e880b6..7d7ca9fa1f 100644 --- a/sei-wasmd/x/wasm/module.go +++ b/sei-wasmd/x/wasm/module.go @@ -203,9 +203,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- return chRaw } -// BeginBlock returns the begin blocker for the wasm module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - // EndBlock returns the end blocker for the wasm module. It returns no validator // updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/x/epoch/keeper/abci.go b/x/epoch/keeper/abci.go new file mode 100644 index 0000000000..fcd476b9ea --- /dev/null +++ b/x/epoch/keeper/abci.go @@ -0,0 +1,38 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sei-protocol/sei-chain/utils/metrics" + "github.com/sei-protocol/sei-chain/x/epoch/types" +) + +func (k Keeper) BeginBlock(ctx sdk.Context) { + lastEpoch := k.GetEpoch(ctx) + ctx.Logger().Info(fmt.Sprintf("Current block time %s, last %s; duration %d", ctx.BlockTime().String(), lastEpoch.CurrentEpochStartTime.String(), lastEpoch.EpochDuration)) + + if ctx.BlockTime().Sub(lastEpoch.CurrentEpochStartTime) > lastEpoch.EpochDuration { + k.AfterEpochEnd(ctx, lastEpoch) + + newEpoch := types.Epoch{ + GenesisTime: lastEpoch.GenesisTime, + EpochDuration: lastEpoch.EpochDuration, + CurrentEpoch: lastEpoch.CurrentEpoch + 1, + CurrentEpochStartTime: ctx.BlockTime(), + CurrentEpochHeight: ctx.BlockHeight(), + } + k.SetEpoch(ctx, newEpoch) + k.BeforeEpochStart(ctx, newEpoch) + + ctx.EventManager().EmitEvent( + sdk.NewEvent(types.EventTypeNewEpoch, + sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprint(newEpoch.CurrentEpoch)), + sdk.NewAttribute(types.AttributeEpochTime, newEpoch.CurrentEpochStartTime.String()), + sdk.NewAttribute(types.AttributeEpochHeight, fmt.Sprint(newEpoch.CurrentEpochHeight)), + ), + ) + + metrics.SetEpochNew(newEpoch.CurrentEpoch) + } +} diff --git a/x/epoch/module.go b/x/epoch/module.go index f978e59193..34232b2d45 100644 --- a/x/epoch/module.go +++ b/x/epoch/module.go @@ -18,7 +18,6 @@ import ( cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/sei-protocol/sei-chain/utils/metrics" "github.com/sei-protocol/sei-chain/x/epoch/client/cli" "github.com/sei-protocol/sei-chain/x/epoch/keeper" "github.com/sei-protocol/sei-chain/x/epoch/types" @@ -188,36 +187,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 2 } -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - lastEpoch := am.keeper.GetEpoch(ctx) - ctx.Logger().Info(fmt.Sprintf("Current block time %s, last %s; duration %d", ctx.BlockTime().String(), lastEpoch.CurrentEpochStartTime.String(), lastEpoch.EpochDuration)) - - if ctx.BlockTime().Sub(lastEpoch.CurrentEpochStartTime) > lastEpoch.EpochDuration { - am.keeper.AfterEpochEnd(ctx, lastEpoch) - - newEpoch := types.Epoch{ - GenesisTime: lastEpoch.GenesisTime, - EpochDuration: lastEpoch.EpochDuration, - CurrentEpoch: lastEpoch.CurrentEpoch + 1, - CurrentEpochStartTime: ctx.BlockTime(), - CurrentEpochHeight: ctx.BlockHeight(), - } - am.keeper.SetEpoch(ctx, newEpoch) - am.keeper.BeforeEpochStart(ctx, newEpoch) - - ctx.EventManager().EmitEvent( - sdk.NewEvent(types.EventTypeNewEpoch, - sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprint(newEpoch.CurrentEpoch)), - sdk.NewAttribute(types.AttributeEpochTime, newEpoch.CurrentEpochStartTime.String()), - sdk.NewAttribute(types.AttributeEpochHeight, fmt.Sprint(newEpoch.CurrentEpochHeight)), - ), - ) - - metrics.SetEpochNew(newEpoch.CurrentEpoch) - } -} - // EndBlock executes all ABCI EndBlock logic respective to the capability module. It // returns no validator updates. func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/x/epoch/module_test.go b/x/epoch/module_test.go index 7156387d9f..3790030fde 100644 --- a/x/epoch/module_test.go +++ b/x/epoch/module_test.go @@ -82,12 +82,6 @@ func TestBeginBlock(t *testing.T) { t.Parallel() // Create a mock context and keeper app := app.Setup(t, false, false, false) - appModule := epoch.NewAppModule( - app.AppCodec(), - app.EpochKeeper, - app.AccountKeeper, - app.BankKeeper, - ) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) now := time.Now() ctx = ctx.WithBlockTime(now) @@ -102,7 +96,7 @@ func TestBeginBlock(t *testing.T) { } app.EpochKeeper.SetEpoch(ctx, lastEpoch) - appModule.BeginBlock(ctx, abci.RequestBeginBlock{}) + app.EpochKeeper.BeginBlock(ctx) newEpoch := app.EpochKeeper.GetEpoch(ctx) ctx.EventManager().Events() @@ -115,7 +109,7 @@ func TestBeginBlock(t *testing.T) { ctx = ctx.WithBlockTime(lastEpoch.CurrentEpochStartTime.Add(30 * time.Minute)) // only 30 minutes passed app.EpochKeeper.SetEpoch(ctx, lastEpoch) - appModule.BeginBlock(ctx, abci.RequestBeginBlock{}) + app.EpochKeeper.BeginBlock(ctx) newEpoch = app.EpochKeeper.GetEpoch(ctx) require.Equal(t, lastEpoch.CurrentEpoch, newEpoch.CurrentEpoch) diff --git a/x/evm/keeper/abci.go b/x/evm/keeper/abci.go new file mode 100644 index 0000000000..44f72bb33d --- /dev/null +++ b/x/evm/keeper/abci.go @@ -0,0 +1,51 @@ +package keeper + +import ( + "math" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/sei-protocol/sei-chain/x/evm/state" + "github.com/sei-protocol/sei-chain/x/evm/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +func (k *Keeper) BeginBlock(ctx sdk.Context) { + // clear tx/tx responses from last block + if !ctx.IsTracing() { + k.SetMsgs([]*types.MsgEVMTransaction{}) + k.SetTxResults([]*abci.ExecTxResult{}) + } + // mock beacon root if replaying + if k.EthReplayConfig.Enabled { + if beaconRoot := k.ReplayBlock.BeaconRoot(); beaconRoot != nil { + blockCtx, err := k.GetVMBlockContext(ctx, core.GasPool(math.MaxUint64)) + if err != nil { + panic(err) + } + statedb := state.NewDBImpl(ctx, k, false) + vmenv := vm.NewEVM(*blockCtx, statedb, types.DefaultChainConfig().EthereumConfig(k.ChainID(ctx)), vm.Config{}, k.CustomPrecompiles(ctx)) + core.ProcessBeaconBlockRoot(*beaconRoot, vmenv) + _, err = statedb.Finalize() + if err != nil { + panic(err) + } + } + } + if k.EthBlockTestConfig.Enabled { + parentHash := common.BytesToHash(ctx.BlockHeader().LastBlockId.Hash) + blockCtx, err := k.GetVMBlockContext(ctx, core.GasPool(math.MaxUint64)) + if err != nil { + panic(err) + } + statedb := state.NewDBImpl(ctx, k, false) + vmenv := vm.NewEVM(*blockCtx, statedb, types.DefaultChainConfig().EthereumConfig(k.ChainID(ctx)), vm.Config{}, k.CustomPrecompiles(ctx)) + core.ProcessParentBlockHash(parentHash, vmenv) + _, err = statedb.Finalize() + if err != nil { + panic(err) + } + } +} diff --git a/x/evm/module.go b/x/evm/module.go index dd342f80e5..cb635d522e 100644 --- a/x/evm/module.go +++ b/x/evm/module.go @@ -4,13 +4,10 @@ import ( "context" "encoding/json" "fmt" - "math" // this line is used by starport scaffolding # 1 "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" @@ -291,45 +288,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 21 } -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - // clear tx/tx responses from last block - if !ctx.IsTracing() { - am.keeper.SetMsgs([]*types.MsgEVMTransaction{}) - am.keeper.SetTxResults([]*abci.ExecTxResult{}) - } - // mock beacon root if replaying - if am.keeper.EthReplayConfig.Enabled { - if beaconRoot := am.keeper.ReplayBlock.BeaconRoot(); beaconRoot != nil { - blockCtx, err := am.keeper.GetVMBlockContext(ctx, core.GasPool(math.MaxUint64)) - if err != nil { - panic(err) - } - statedb := state.NewDBImpl(ctx, am.keeper, false) - vmenv := vm.NewEVM(*blockCtx, statedb, types.DefaultChainConfig().EthereumConfig(am.keeper.ChainID(ctx)), vm.Config{}, am.keeper.CustomPrecompiles(ctx)) - core.ProcessBeaconBlockRoot(*beaconRoot, vmenv) - _, err = statedb.Finalize() - if err != nil { - panic(err) - } - } - } - if am.keeper.EthBlockTestConfig.Enabled { - parentHash := common.BytesToHash(ctx.BlockHeader().LastBlockId.Hash) - blockCtx, err := am.keeper.GetVMBlockContext(ctx, core.GasPool(math.MaxUint64)) - if err != nil { - panic(err) - } - statedb := state.NewDBImpl(ctx, am.keeper, false) - vmenv := vm.NewEVM(*blockCtx, statedb, types.DefaultChainConfig().EthereumConfig(am.keeper.ChainID(ctx)), vm.Config{}, am.keeper.CustomPrecompiles(ctx)) - core.ProcessParentBlockHash(parentHash, vmenv) - _, err = statedb.Finalize() - if err != nil { - panic(err) - } - } -} - // EndBlock executes all ABCI EndBlock logic respective to the evm module. It // returns no validator updates. func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/x/evm/module_test.go b/x/evm/module_test.go index 452a8d295d..850056ed65 100644 --- a/x/evm/module_test.go +++ b/x/evm/module_test.go @@ -73,7 +73,7 @@ func TestABCI(t *testing.T) { k.BankKeeper().SendCoinsFromModuleToAccount(ctx, types.ModuleName, sdk.AccAddress(evmAddr1[:]), amt) m := evm.NewAppModule(nil, k) // first block - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) // 1st tx s := state.NewDBImpl(ctx.WithTxIndex(1), k, false) s.SubBalance(evmAddr1, uint256.NewInt(10000000000000), tracing.BalanceChangeUnspecified) @@ -100,7 +100,7 @@ func TestABCI(t *testing.T) { require.Equal(t, uint64(2), k.BankKeeper().GetBalance(ctx, k.AccountKeeper().GetModuleAddress(authtypes.FeeCollectorName), "usei").Amount.Uint64()) // second block - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) // 2nd tx s = state.NewDBImpl(ctx.WithTxIndex(2), k, false) s.SubBalance(evmAddr2, uint256.NewInt(3000000000000), tracing.BalanceChangeUnspecified) @@ -116,7 +116,7 @@ func TestABCI(t *testing.T) { require.Equal(t, uint64(2), k.BankKeeper().GetBalance(ctx, k.AccountKeeper().GetModuleAddress(authtypes.FeeCollectorName), "usei").Amount.Uint64()) // third block - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) msg := mockEVMTransactionMessage(t) k.SetMsgs([]*types.MsgEVMTransaction{msg}) k.SetTxResults([]*abci.ExecTxResult{{Code: 1, Log: "test error"}}) @@ -129,7 +129,7 @@ func TestABCI(t *testing.T) { require.Equal(t, receipt.VmError, "test error") // disallow creating vesting account for coinbase address - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) coinbase := state.GetCoinbaseAddress(2) vms := vesting.NewMsgServerImpl(*k.AccountKeeper(), k.BankKeeper()) _, err = vms.CreateVestingAccount(sdk.WrapSDKContext(ctx), &vestingtypes.MsgCreateVestingAccount{ @@ -162,7 +162,7 @@ func TestLegacyReceiptMigrationInterval(t *testing.T) { interval := int64(10) // mirror keeper.LegacyReceiptMigrationInterval for i := int64(1); i <= interval; i++ { ctx = ctx.WithBlockHeight(i) - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) m.EndBlock(ctx, abci.RequestEndBlock{}) } require.NoError(t, k.FlushTransientReceipts(ctx)) @@ -187,7 +187,7 @@ func TestAnteSurplus(t *testing.T) { ctx := a.GetContextForDeliverTx([]byte{}) m := evm.NewAppModule(nil, &k) // first block - m.BeginBlock(ctx, abci.RequestBeginBlock{}) + k.BeginBlock(ctx) k.AddAnteSurplus(ctx, common.BytesToHash([]byte("1234")), sdk.NewInt(1_000_000_000_001)) m.EndBlock(ctx, abci.RequestEndBlock{}) require.Equal(t, uint64(1), k.BankKeeper().GetBalance(ctx, k.AccountKeeper().GetModuleAddress(types.ModuleName), "usei").Amount.Uint64()) diff --git a/x/mint/keeper/hooks_test.go b/x/mint/keeper/hooks_test.go index eb3e5a773e..062dafeb37 100644 --- a/x/mint/keeper/hooks_test.go +++ b/x/mint/keeper/hooks_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/sei-protocol/sei-chain/app/legacyabci" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" "github.com/sei-protocol/sei-chain/x/epoch/types" minttypes "github.com/sei-protocol/sei-chain/x/mint/types" @@ -39,7 +40,7 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { Height: seiApp.LastBlockHeight() + 1, Time: time.Now().UTC(), } - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) require.Equal(t, int64(0), seiApp.MintKeeper.GetMinter(ctx).GetLastMintAmountCoin().Amount.Int64()) }) @@ -51,7 +52,7 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { Height: seiApp.LastBlockHeight() + 1, Time: time.Now().UTC(), } - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) genesisTime := header.Time tokenReleaseSchedle := []minttypes.ScheduledTokenRelease{ { @@ -96,7 +97,7 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { Height: seiApp.LastBlockHeight() + 1, Time: time.Now().UTC(), } - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) genesisTime := header.Time tokenReleaseSchedle := []minttypes.ScheduledTokenRelease{ @@ -142,7 +143,7 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { Height: seiApp.LastBlockHeight() + 1, Time: time.Now().UTC(), } - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) genesisTime := header.Time tokenReleaseSchedle := []minttypes.ScheduledTokenRelease{ @@ -200,7 +201,7 @@ func TestEndOfEpochMintedCoinDistribution(t *testing.T) { Height: seiApp.LastBlockHeight() + 1, Time: time.Now().UTC(), } - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) genesisTime := header.Time tokenReleaseSchedle := []minttypes.ScheduledTokenRelease{ @@ -271,7 +272,7 @@ func TestNoEpochPassedNoDistribution(t *testing.T) { ctx := seiApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) header := tmproto.Header{Height: seiApp.LastBlockHeight() + 1} - seiApp.BeginBlock(ctx, abci.RequestBeginBlock{Header: header}) + legacyabci.BeginBlock(ctx, header.Height, []abci.VoteInfo{}, []abci.Misbehavior{}, seiApp.BeginBlockKeepers) // Get mint params mintParams := seiApp.MintKeeper.GetParams(ctx) genesisTime := time.Date(2022, time.Month(7), 18, 10, 0, 0, 0, time.UTC) diff --git a/x/mint/module.go b/x/mint/module.go index f161a31db6..3dcd35d618 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -175,9 +175,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 3 } -// BeginBlock returns the begin blocker for the mint module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - // EndBlock returns the end blocker for the mint module. It returns no validator // updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { diff --git a/x/oracle/module.go b/x/oracle/module.go index b323b8a7e6..febb8f72a9 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -183,9 +183,6 @@ func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <- // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 6 } -// BeginBlock returns the begin blocker for the oracle module. -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - // EndBlock returns the end blocker for the oracle module. func (am AppModule) MidBlock(ctx sdk.Context, _ int64) { MidBlocker(ctx, am.keeper) diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index caf6599c54..cde0f397de 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -194,9 +194,6 @@ func (am AppModuleBasic) ValidateGenesisStream(cdc codec.JSONCodec, config clien // ConsensusVersion implements ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 5 } -// BeginBlock executes all ABCI BeginBlock logic respective to the tokenfactory module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - // EndBlock executes all ABCI EndBlock logic respective to the tokenfactory module. It // returns no validator updates. func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate {