Skip to content

Commit

Permalink
replace with SetPreBeginBlocker
Browse files Browse the repository at this point in the history
  • Loading branch information
mmsqe committed Aug 16, 2023
1 parent 281eb94 commit c93ac40
Show file tree
Hide file tree
Showing 12 changed files with 57 additions and 43 deletions.
4 changes: 2 additions & 2 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ This guide provides instructions for upgrading to specific versions of Cosmos SD

**Users using `depinject` / app v2 do not need any changes, this is abstracted for them.**
```diff
+ app.BaseApp.SetMigrationModuleManager(app.ModuleManager)
+ app.BaseApp.SetPreBeginBlocker(app.ModuleManager)
```
BaseApp added `SetMigrationModuleManager` for apps to set their ModuleManager which implements `RunMigrationBeginBlock`. This is essential for BaseApp to run `BeginBlock` of upgrade module and inject `ConsensusParams` to context for `beginBlocker` during `beginBlock`.
BaseApp added `SetPreBeginBlocker` for apps to set their ModuleManager which implements `RunMigrationBeginBlock`. This is essential for BaseApp to run `BeginBlock` of upgrade module and inject `ConsensusParams` to context for `beginBlocker` during `beginBlock`.


### Migration to CometBFT (Part 1)
Expand Down
22 changes: 12 additions & 10 deletions baseapp/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,18 +192,20 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg
WithHeaderHash(req.Hash)
}

if app.beginBlocker != nil {
ctx := app.deliverState.ctx
if app.migrationModuleManager != nil && app.migrationModuleManager.RunMigrationBeginBlock(ctx, req) {
cp := ctx.ConsensusParams()
// Manager skips this step if Block is non-nil since upgrade module is expected to set this params
// and consensus parameters should not be overwritten.
if cp == nil || cp.Block == nil {
if cp = app.GetConsensusParams(ctx); cp != nil {
ctx = ctx.WithConsensusParams(cp)
}
ctx := app.deliverState.ctx
if app.preBeginBlocker != nil {
app.preBeginBlocker(ctx, req)

// Manager skips this step if Block is non-nil since upgrade module is expected to set this params
// and consensus parameters should not be overwritten.
if cp := ctx.ConsensusParams(); cp == nil || cp.Block == nil {
if cp = app.GetConsensusParams(ctx); cp != nil {
ctx = ctx.WithConsensusParams(cp)
}
}
}

if app.beginBlocker != nil {
res = app.beginBlocker(ctx, req)
res.Events = sdk.MarkEventsToIndex(res.Events, app.indexEvents)
}
Expand Down
15 changes: 1 addition & 14 deletions baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,6 @@ type (
StoreLoader func(ms storetypes.CommitMultiStore) error
)

// MigrationModuleManager is the interface that a migration module manager should implement to handle
// the execution of migration logic during the beginning of a block.
type MigrationModuleManager interface {
RunMigrationBeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) bool
}

const (
runTxModeCheck runTxMode = iota // Check a transaction
runTxModeReCheck // Recheck a (pending) transaction after a commit
Expand Down Expand Up @@ -70,6 +64,7 @@ type BaseApp struct { //nolint: maligned
anteHandler sdk.AnteHandler // ante handler for fee and auth
postHandler sdk.PostHandler // post handler, optional, e.g. for tips
initChainer sdk.InitChainer // initialize state with validators and state blob
preBeginBlocker sdk.PreBeginBlocker // logic to run before BeginBlocker
beginBlocker sdk.BeginBlocker // logic to run before any txs
processProposal sdk.ProcessProposalHandler // the handler which runs on ABCI ProcessProposal
prepareProposal sdk.PrepareProposalHandler // the handler which runs on ABCI PrepareProposal
Expand All @@ -81,9 +76,6 @@ type BaseApp struct { //nolint: maligned
// manages snapshots, i.e. dumps of app state at certain intervals
snapshotManager *snapshots.Manager

// manages migrate module
migrationModuleManager MigrationModuleManager

// volatile states:
//
// checkState is set on InitChain and reset on Commit
Expand Down Expand Up @@ -244,11 +236,6 @@ func (app *BaseApp) SetCircuitBreaker(cb CircuitBreaker) {
app.msgServiceRouter.SetCircuit(cb)
}

// SetMigrationModuleManager sets the MigrationModuleManager of a BaseApp.
func (app *BaseApp) SetMigrationModuleManager(migrationModuleManager MigrationModuleManager) {
app.migrationModuleManager = migrationModuleManager
}

// MountStores mounts all IAVL or DB stores to the provided keys in the BaseApp
// multistore.
func (app *BaseApp) MountStores(keys ...storetypes.StoreKey) {
Expand Down
8 changes: 8 additions & 0 deletions baseapp/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,14 @@ func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) {
app.initChainer = initChainer
}

func (app *BaseApp) SetPreBeginBlocker(preBeginBlocker sdk.PreBeginBlocker) {
if app.sealed {
panic("preBeginBlocker() on sealed BaseApp")
}

app.preBeginBlocker = preBeginBlocker
}

func (app *BaseApp) SetBeginBlocker(beginBlocker sdk.BeginBlocker) {
if app.sealed {
panic("SetBeginBlocker() on sealed BaseApp")
Expand Down
4 changes: 2 additions & 2 deletions docs/docs/building-apps/03-app-upgrade.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ This section is currently incomplete. Track the progress of this document [here]
Users using `depinject` / app v2 do not need any changes, this is abstracted for them.
:::

After app initiation, call `SetMigrationModuleManager` with ModuleManager to give BaseApp access to `RunMigrationBeginBlock`:
After app initiation, call `SetPreBeginBlocker` with ModuleManager to give BaseApp access to `RunMigrationBeginBlock`:

```go
app.BaseApp.SetMigrationModuleManager(app.ModuleManager)
app.BaseApp.SetPreBeginBlocker(app.ModuleManager)
```

## Pre-Upgrade Handling
Expand Down
2 changes: 1 addition & 1 deletion runtime/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (a *AppBuilder) Build(
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(a.app.interfaceRegistry)
bApp.MountStores(a.app.storeKeys...)
bApp.SetMigrationModuleManager(a.app.ModuleManager)
bApp.SetPreBeginBlocker(a.app.ModuleManager.PreBeginBlocker)

a.app.BaseApp = bApp
a.app.configurator = module.NewConfigurator(a.app.cdc, a.app.MsgServiceRouter(), a.app.GRPCQueryRouter())
Expand Down
2 changes: 1 addition & 1 deletion simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ func NewSimApp(
nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper),
)
bApp.SetMigrationModuleManager(app.ModuleManager)
bApp.SetPreBeginBlocker(app.ModuleManager)

// 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
Expand Down
6 changes: 6 additions & 0 deletions types/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (
// InitChainer initializes application state at genesis
type InitChainer func(ctx Context, req abci.RequestInitChain) abci.ResponseInitChain

// PreBeginBlocker 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 PreBeginBlocker func(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock

// 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
Expand Down
21 changes: 13 additions & 8 deletions types/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ type HasConsensusVersion interface {
ConsensusVersion() uint64
}

type PreBeginBlockAppModule interface {
AppModule
PreBeginBlock(sdk.Context, abci.RequestBeginBlock)
}

// BeginBlockAppModule is an extension interface that contains information about the AppModule and BeginBlock.
type BeginBlockAppModule interface {
AppModule
Expand Down Expand Up @@ -557,19 +562,19 @@ func (m Manager) RunMigrations(ctx sdk.Context, cfg Configurator, fromVM Version
return updatedVM, nil
}

// RunMigrationBeginBlock performs begin block functionality for upgrade module.
// PreBeginBlocker performs begin block functionality for upgrade module.
// It takes the current context as a parameter and returns a boolean value
// indicating whether the migration was successfully executed or not.
func (m *Manager) RunMigrationBeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) bool {
func (m *Manager) PreBeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
ctx = ctx.WithEventManager(sdk.NewEventManager())
for _, moduleName := range m.OrderBeginBlockers {
if mod, ok := m.Modules[moduleName].(BeginBlockAppModule); ok {
if _, ok := mod.(UpgradeModule); ok {
mod.BeginBlock(ctx, req)
return true
}
if module, ok := m.Modules[moduleName].(PreBeginBlockAppModule); ok {
module.PreBeginBlock(ctx, req)
}
}
return false
return abci.ResponseBeginBlock{
Events: ctx.EventManager().ABCIEvents(),
}
}

// BeginBlock performs begin block functionality for all modules. It creates a
Expand Down
4 changes: 2 additions & 2 deletions types/module/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,14 @@ func TestManager_RunMigrationBeginBlock(t *testing.T) {
mockReq := gomock.Eq(req)
mockAppModule1.EXPECT().BeginBlock(gomock.Any(), mockReq).Times(0)
mockAppModule2.EXPECT().BeginBlock(gomock.Any(), mockReq).Times(1)
success := mm.RunMigrationBeginBlock(sdk.Context{}, req)
success := mm.BeginBlock(sdk.Context{}, req)
require.Equal(t, true, success)

// test false
mockAppModule3 := mock.NewMockBeginBlockAppModule(mockCtrl)
mockAppModule3.EXPECT().Name().Times(2).Return("module3")
mm = module.NewManager(mockAppModule3)
success = mm.RunMigrationBeginBlock(sdk.Context{}, req)
success = mm.BeginBlock(sdk.Context{}, req)
require.Equal(t, false, success)
}

Expand Down
4 changes: 2 additions & 2 deletions x/upgrade/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ import (
"github.com/cosmos/cosmos-sdk/x/upgrade/types"
)

// BeginBlock will check if there is a scheduled plan and if it is ready to be executed.
// PreBeginBlock will check if there is a scheduled plan and if it is ready to be executed.
// If the current height is in the provided set of heights to skip, it will skip and clear the upgrade plan.
// If it is ready, it will execute it if the handler is installed, and panic/abort otherwise.
// If the plan is not ready, it will ensure the handler is not registered too early (and abort otherwise).
//
// 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 PreBeginBlocker(k *keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker)

plan, found := k.GetUpgradePlan(ctx)
Expand Down
8 changes: 7 additions & 1 deletion x/upgrade/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,17 @@ func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMe
// ConsensusVersion implements AppModule/ConsensusVersion.
func (AppModule) ConsensusVersion() uint64 { return consensusVersion }

// PreBeginBlock calls the upgrade module hooks
//
// CONTRACT: this is registered in BeginBlocker *before* all other modules' BeginBlock functions
func (am AppModule) PreBeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {
PreBeginBlocker(am.keeper, ctx, req)
}

// 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)
}

// IsUpgradeModule implements the module.UpgradeModule interface.
Expand Down

0 comments on commit c93ac40

Please sign in to comment.