From 52a138425aeccf4cdf02ef1c462a106dd2b19028 Mon Sep 17 00:00:00 2001 From: MSalopek Date: Fri, 13 Oct 2023 16:07:19 +0200 Subject: [PATCH] consumer: update consumer app v50 and make buildable (#1354) * consumer: update app.go * consumer: update cmd and export * consumer: update keeper to implement v50 Staking keeper * consumer: rm TestEvidenceKeeper definition * consumer: revert queryCmd registration to old way --- app/consumer/abci.go | 84 +++++++++++ app/consumer/app.go | 199 +++++++++++++++---------- app/consumer/export.go | 8 +- app/provider/app.go | 1 - cmd/interchain-security-cd/cmd/root.go | 30 ++-- cmd/interchain-security-cd/main.go | 11 +- cmd/interchain-security-pd/cmd/root.go | 1 + x/ccv/consumer/keeper/hooks.go | 4 +- x/ccv/consumer/keeper/keeper.go | 18 ++- x/ccv/consumer/keeper/params.go | 7 +- x/ccv/consumer/keeper/validators.go | 102 +++++++------ x/ccv/types/expected_keepers.go | 2 +- 12 files changed, 311 insertions(+), 156 deletions(-) create mode 100644 app/consumer/abci.go diff --git a/app/consumer/abci.go b/app/consumer/abci.go new file mode 100644 index 0000000000..94b34cc3bb --- /dev/null +++ b/app/consumer/abci.go @@ -0,0 +1,84 @@ +package app + +import ( + "bytes" + "crypto/rand" + "encoding/json" + "fmt" + + abci "github.com/cometbft/cometbft/abci/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type ( + // VoteExtensionHandler defines a dummy vote extension handler for SimApp. + // + // NOTE: This implementation is solely used for testing purposes. DO NOT use + // in a production application! + VoteExtensionHandler struct{} + + // VoteExtension defines the structure used to create a dummy vote extension. + VoteExtension struct { + Hash []byte + Height int64 + Data []byte + } +) + +func NewVoteExtensionHandler() *VoteExtensionHandler { + return &VoteExtensionHandler{} +} + +func (h *VoteExtensionHandler) SetHandlers(bApp *baseapp.BaseApp) { + bApp.SetExtendVoteHandler(h.ExtendVote()) + bApp.SetVerifyVoteExtensionHandler(h.VerifyVoteExtension()) +} + +func (h *VoteExtensionHandler) ExtendVote() sdk.ExtendVoteHandler { + return func(_ sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + buf := make([]byte, 1024) + + _, err := rand.Read(buf) + if err != nil { + return nil, fmt.Errorf("failed to generate random vote extension data: %w", err) + } + + ve := VoteExtension{ + Hash: req.Hash, + Height: req.Height, + Data: buf, + } + + bz, err := json.Marshal(ve) + if err != nil { + return nil, fmt.Errorf("failed to encode vote extension: %w", err) + } + + return &abci.ResponseExtendVote{VoteExtension: bz}, nil + } +} + +func (h *VoteExtensionHandler) VerifyVoteExtension() sdk.VerifyVoteExtensionHandler { + return func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + var ve VoteExtension + + if err := json.Unmarshal(req.VoteExtension, &ve); err != nil { + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil + } + + switch { + case req.Height != ve.Height: + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil + + case !bytes.Equal(req.Hash, ve.Hash): + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil + + case len(ve.Data) != 1024: + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil + } + + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil + } +} diff --git a/app/consumer/app.go b/app/consumer/app.go index 937067ee7e..cdfcf17867 100644 --- a/app/consumer/app.go +++ b/app/consumer/app.go @@ -1,12 +1,19 @@ package app import ( + "context" "fmt" "io" stdlog "log" "os" "path/filepath" + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + "cosmossdk.io/client/v2/autocli" + "cosmossdk.io/core/appmodule" + "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" + "github.com/cosmos/ibc-go/v8/modules/apps/transfer" ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" @@ -15,14 +22,11 @@ import ( porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" ibchost "github.com/cosmos/ibc-go/v8/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" - tendermint "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" ibctesting "github.com/cosmos/ibc-go/v8/testing" ibctestingtypes "github.com/cosmos/ibc-go/v8/testing/types" "github.com/spf13/cast" - autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" - reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" - storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/evidence" evidencekeeper "cosmossdk.io/x/evidence/keeper" @@ -53,8 +57,8 @@ import ( "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" @@ -66,6 +70,7 @@ import ( bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" "github.com/cosmos/cosmos-sdk/x/crisis" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" @@ -83,10 +88,10 @@ import ( capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" "cosmossdk.io/log" - dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" tmjson "github.com/cometbft/cometbft/libs/json" tmos "github.com/cometbft/cometbft/libs/os" + dbm "github.com/cosmos/cosmos-db" appparams "github.com/cosmos/interchain-security/v3/app/params" testutil "github.com/cosmos/interchain-security/v3/testutil/integration" @@ -123,7 +128,7 @@ var ( evidence.AppModuleBasic{}, transfer.AppModuleBasic{}, vesting.AppModuleBasic{}, - tendermint.AppModuleBasic{}, + ibctm.AppModuleBasic{}, // router.AppModuleBasic{}, ibcconsumer.AppModuleBasic{}, ) @@ -150,12 +155,13 @@ type App struct { // nolint: golint *baseapp.BaseApp legacyAmino *codec.LegacyAmino appCodec codec.Codec - txConfig client.TxConfig interfaceRegistry types.InterfaceRegistry + txConfig client.TxConfig // keys to access the substores - keys map[string]*storetypes.KVStoreKey - tkeys map[string]*storetypes.TransientStoreKey + keys map[string]*storetypes.KVStoreKey + tkeys map[string]*storetypes.TransientStoreKey + memKeys map[string]*storetypes.MemoryStoreKey // keepers @@ -164,10 +170,6 @@ type App struct { // nolint: golint CapabilityKeeper *capabilitykeeper.Keeper SlashingKeeper slashingkeeper.Keeper - // NOTE the distribution keeper should either be removed - // from consumer chain or set to use an independent - // different fee-pool from the consumer chain ConsumerKeeper - CrisisKeeper crisiskeeper.Keeper UpgradeKeeper upgradekeeper.Keeper ParamsKeeper paramskeeper.Keeper @@ -217,20 +219,27 @@ func New( interfaceRegistry := encodingConfig.InterfaceRegistry txConfig := encodingConfig.TxConfig + // ABCI++, v50 + voteExtOp := func(bApp *baseapp.BaseApp) { + voteExtHandler := NewVoteExtensionHandler() + voteExtHandler.SetHandlers(bApp) + } + baseAppOptions = append(baseAppOptions, voteExtOp) + bApp := baseapp.NewBaseApp(AppName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) - keys := sdk.NewKVStoreKeys( + keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, slashingtypes.StoreKey, crisistypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, feegrant.StoreKey, authzkeeper.StoreKey, ibcconsumertypes.StoreKey, ) - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) + tkeys := storetypes.NewTransientStoreKeys(paramstypes.TStoreKey) + memKeys := storetypes.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) app := &App{ BaseApp: bApp, @@ -251,8 +260,8 @@ func New( ) // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[upgradetypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) - bApp.SetParamStore(&app.ConsensusParamsKeeper) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), authtypes.NewModuleAddress(govtypes.ModuleName).String(), runtime.EventService{}) + bApp.SetParamStore(&app.ConsensusParamsKeeper.ParamsStore) // add capability keeper and ScopeToModule for ibc module app.CapabilityKeeper = capabilitykeeper.NewKeeper( @@ -268,10 +277,11 @@ func New( // add keepers app.AccountKeeper = authkeeper.NewAccountKeeper( appCodec, - keys[authtypes.StoreKey], + runtime.NewKVStoreService(keys[authtypes.StoreKey]), authtypes.ProtoBaseAccount, maccPerms, - AccountAddressPrefix, + authcodec.NewBech32Codec(sdk.Bech32MainPrefix), + sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -284,20 +294,22 @@ func New( app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, - keys[banktypes.StoreKey], + runtime.NewKVStoreService(keys[banktypes.StoreKey]), app.AccountKeeper, bankBlockedAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + logger, ) app.AuthzKeeper = authzkeeper.NewKeeper( - keys[authzkeeper.StoreKey], + runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), appCodec, - app.BaseApp.MsgServiceRouter(), + app.MsgServiceRouter(), app.AccountKeeper, ) + app.FeeGrantKeeper = feegrantkeeper.NewKeeper( appCodec, - keys[feegrant.StoreKey], + runtime.NewKVStoreService(keys[feegrant.StoreKey]), app.AccountKeeper, ) @@ -306,7 +318,7 @@ func New( app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, - keys[slashingtypes.StoreKey], + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), &app.ConsumerKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -314,11 +326,12 @@ func New( invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) app.CrisisKeeper = *crisiskeeper.NewKeeper( appCodec, - keys[crisistypes.StoreKey], + runtime.NewKVStoreService(keys[crisistypes.StoreKey]), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + app.AccountKeeper.AddressCodec(), ) // get skipUpgradeHeights from the app options @@ -330,7 +343,7 @@ func New( // set the governance module account as the authority for conducting upgrades app.UpgradeKeeper = *upgradekeeper.NewKeeper( skipUpgradeHeights, - keys[upgradetypes.StoreKey], + runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, @@ -354,6 +367,7 @@ func New( app.ConsumerKeeper, app.UpgradeKeeper, scopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // initialize the actual consumer keeper @@ -363,7 +377,7 @@ func New( app.GetSubspace(ibcconsumertypes.ModuleName), scopedIBCConsumerKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, + app.IBCKeeper.PortKeeper, app.IBCKeeper.ConnectionKeeper, app.IBCKeeper.ClientKeeper, app.SlashingKeeper, @@ -372,6 +386,9 @@ func New( &app.TransferKeeper, app.IBCKeeper, authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), + authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) // register slashing module Slashing hooks to the consumer keeper @@ -384,10 +401,11 @@ func New( app.GetSubspace(ibctransfertypes.ModuleName), app.IBCKeeper.ChannelKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, + app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, scopedTransferKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) transferModule := transfer.NewAppModule(app.TransferKeeper) ibcmodule := transfer.NewIBCModule(app.TransferKeeper) @@ -401,9 +419,11 @@ func New( // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( appCodec, - keys[evidencetypes.StoreKey], + runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), &app.ConsumerKeeper, app.SlashingKeeper, + app.AccountKeeper.AddressCodec(), + runtime.ProvideCometInfoService(), ) app.EvidenceKeeper = *evidenceKeeper @@ -416,7 +436,7 @@ func New( genutil.NewAppModule( app.AccountKeeper, app.ConsumerKeeper, - app.BaseApp.DeliverTx, + app, encodingConfig.TxConfig, ), auth.NewAppModule(appCodec, app.AccountKeeper, nil, app.GetSubspace(authtypes.ModuleName)), @@ -424,8 +444,8 @@ func New( bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.ConsumerKeeper, app.GetSubspace(slashingtypes.ModuleName)), - upgrade.NewAppModule(&app.UpgradeKeeper), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.ConsumerKeeper, app.GetSubspace(slashingtypes.ModuleName), app.interfaceRegistry), + upgrade.NewAppModule(&app.UpgradeKeeper, app.AccountKeeper.AddressCodec()), evidence.NewAppModule(app.EvidenceKeeper), feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), @@ -435,6 +455,16 @@ func New( consumerModule, ) + ModuleBasics = module.NewBasicManagerFromManager( + app.MM, + map[string]module.AppModuleBasic{ + genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + }) + + app.MM.SetOrderPreBlockers( + upgradetypes.ModuleName, + ) + // 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. @@ -442,7 +472,6 @@ func New( // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) app.MM.SetOrderBeginBlockers( // upgrades should be run first - upgradetypes.ModuleName, capabilitytypes.ModuleName, crisistypes.ModuleName, ibctransfertypes.ModuleName, @@ -458,6 +487,8 @@ func New( vestingtypes.ModuleName, ibcconsumertypes.ModuleName, ) + app.SetPreBlocker(app.PreBlocker) + app.MM.SetOrderEndBlockers( crisistypes.ModuleName, ibctransfertypes.ModuleName, @@ -503,30 +534,32 @@ func New( app.MM.RegisterInvariants(&app.CrisisKeeper) app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) - app.MM.RegisterServices(app.configurator) - - // create the simulation manager and define the order of the modules for deterministic simulations - // - // NOTE: this is not required apps that don't use the simulator for fuzz testing - // transactions - app.sm = module.NewSimulationManager( - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), - capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - params.NewAppModule(app.ParamsKeeper), - evidence.NewAppModule(app.EvidenceKeeper), ibc.NewAppModule(app.IBCKeeper), - transferModule, - ) + err := app.MM.RegisterServices(app.configurator) + if err != nil { + panic(err) + } - app.sm.RegisterStoreDecoders() + autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.MM.Modules)) + + reflectionSvc, err := runtimeservices.NewReflectionService() + if err != nil { + panic(err) + } + reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) + + // add test gRPC service for testing gRPC queries in isolation + testpb.RegisterQueryServer(app.GRPCQueryRouter(), testpb.QueryImpl{}) // initialize stores app.MountKVStores(keys) app.MountTransientStores(tkeys) app.MountMemoryStores(memKeys) + app.SetInitChainer(app.InitChainer) + app.SetPreBlocker(app.PreBlocker) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + anteHandler, err := NewAnteHandler( HandlerOptions{ HandlerOptions: ante.HandlerOptions{ @@ -545,16 +578,13 @@ func New( } app.SetAnteHandler(anteHandler) - app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - // Note this upgrade handler is just an example and may not be exactly what you need to implement. // See https://docs.cosmos.network/v0.45/building-modules/upgrade.html app.UpgradeKeeper.SetUpgradeHandler( upgradeName, - func(ctx sdk.Context, _ upgradetypes.Plan, _ module.VersionMap) (module.VersionMap, error) { - app.IBCKeeper.ConnectionKeeper.SetParams(ctx, ibcconnectiontypes.DefaultParams()) + func(ctx context.Context, _ upgradetypes.Plan, _ module.VersionMap) (module.VersionMap, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + app.IBCKeeper.ConnectionKeeper.SetParams(sdkCtx, ibcconnectiontypes.DefaultParams()) fromVM := make(map[string]uint64) @@ -565,7 +595,7 @@ func New( } } - ctx.Logger().Info("start to run module migrations...") + app.Logger().Info("start to run module migrations...") return app.MM.RunMigrations(ctx, app.configurator, fromVM) }, @@ -593,32 +623,28 @@ func New( app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedIBCConsumerKeeper = scopedIBCConsumerKeeper - autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.MM.Modules)) - - reflectionSvc, err := runtimeservices.NewReflectionService() - if err != nil { - panic(err) - } - reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) - return app } // Name returns the name of the App func (app *App) Name() string { return app.BaseApp.Name() } +func (app *App) PreBlocker(ctx sdk.Context, _ *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { + return app.MM.PreBlock(ctx) +} + // BeginBlocker application updates every begin block -func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.MM.BeginBlock(ctx, req) +func (app *App) BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error) { + return app.MM.BeginBlock(ctx) } // EndBlocker application updates every end block -func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.MM.EndBlock(ctx, req) +func (app *App) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { + return app.MM.EndBlock(ctx) } // InitChainer application update at chain initialization -func (app *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { +func (app *App) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { var genesisState GenesisState if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil { panic(err) @@ -720,11 +746,6 @@ func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { return app.SlashingKeeper } -// GetTestEvidenceKeeper implements the ConsumerApp interface. -func (app *App) GetTestEvidenceKeeper() testutil.TestEvidenceKeeper { - return app.EvidenceKeeper -} - // TestingApp functions // GetBaseApp implements the TestingApp interface. @@ -757,6 +778,26 @@ func (app *App) TxConfig() client.TxConfig { return app.txConfig } +// AutoCliOpts returns the autocli options for the app. +func (app *App) AutoCliOpts() autocli.AppOptions { + modules := make(map[string]appmodule.AppModule, 0) + for _, m := range app.MM.Modules { + if moduleWithName, ok := m.(module.HasName); ok { + moduleName := moduleWithName.Name() + if appModule, ok := moduleWithName.(appmodule.AppModule); ok { + modules[moduleName] = appModule + } + } + } + + return autocli.AppOptions{ + Modules: modules, + AddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()), + ValidatorAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()), + ConsensusAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()), + } +} + // RegisterAPIRoutes registers all application module routes with the provided // API server. func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { @@ -776,8 +817,8 @@ func (app *App) RegisterTxService(clientCtx client.Context) { authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry) } -func (app *App) RegisterNodeService(clientCtx client.Context) { - nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) +func (app *App) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter(), cfg) } // RegisterTendermintService implements the Application.RegisterTendermintService method. diff --git a/app/consumer/export.go b/app/consumer/export.go index 4260efda92..c8fd545f05 100644 --- a/app/consumer/export.go +++ b/app/consumer/export.go @@ -8,7 +8,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmtypes "github.com/cometbft/cometbft/types" ) @@ -18,7 +17,7 @@ func (app *App) ExportAppStateAndValidators( forZeroHeight bool, jailAllowedAddrs, modulesToExport []string, ) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block - ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + ctx := app.NewContext(true) // We export at last height + 1, because that's the height at which // Tendermint will start InitChain. @@ -28,7 +27,10 @@ func (app *App) ExportAppStateAndValidators( app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState := app.MM.ExportGenesis(ctx, app.appCodec) + genState, err := app.MM.ExportGenesis(ctx, app.appCodec) + if err != nil { + return servertypes.ExportedApp{}, err + } appState, err := json.MarshalIndent(genState, "", " ") if err != nil { return servertypes.ExportedApp{}, err diff --git a/app/provider/app.go b/app/provider/app.go index dc38571179..b8098417c7 100644 --- a/app/provider/app.go +++ b/app/provider/app.go @@ -153,7 +153,6 @@ var ( evidence.AppModuleBasic{}, transfer.AppModuleBasic{}, vesting.AppModuleBasic{}, - // tendermint.AppModuleBasic{}, // router.AppModuleBasic{}, icsprovider.AppModuleBasic{}, ) diff --git a/cmd/interchain-security-cd/cmd/root.go b/cmd/interchain-security-cd/cmd/root.go index 6b7be48148..759a078a5a 100644 --- a/cmd/interchain-security-cd/cmd/root.go +++ b/cmd/interchain-security-cd/cmd/root.go @@ -8,8 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - rosettaCmd "cosmossdk.io/tools/rosetta/cmd" - + confixcmd "cosmossdk.io/tools/confix/cmd" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" @@ -28,8 +27,8 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" "cosmossdk.io/log" - dbm "github.com/cometbft/cometbft-db" tmcfg "github.com/cometbft/cometbft/config" + dbm "github.com/cosmos/cosmos-db" consumer "github.com/cosmos/interchain-security/v3/app/consumer" "github.com/cosmos/interchain-security/v3/app/params" @@ -87,6 +86,9 @@ func NewRootCmd() *cobra.Command { } initRootCmd(rootCmd, encodingConfig) + if err := tempApp.AutoCliOpts().EnhanceRootCommand(rootCmd); err != nil { + panic(err) + } return rootCmd } @@ -121,10 +123,10 @@ func txCommand() *cobra.Command { authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), - authcmd.GetAuxToFeeCommand(), ) - consumer.ModuleBasics.AddTxCommands(cmd) + // @MSalopek: deprecated by usage of autocli + // consumer.ModuleBasics.AddTxCommands(cmd) return cmd } @@ -193,23 +195,20 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { rootCmd.AddCommand( genutilcli.InitCmd(consumer.ModuleBasics, consumer.DefaultNodeHome), debug.Cmd(), - config.Cmd(), - pruning.PruningCmd(newApp), + pruning.Cmd(newApp, consumer.DefaultNodeHome), + confixcmd.ConfigCommand(), ) server.AddCommands(rootCmd, consumer.DefaultNodeHome, newApp, appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( - rpc.StatusCommand(), + server.StatusCommand(), genesisCommand(encodingConfig), queryCommand(), txCommand(), - keys.Commands(consumer.DefaultNodeHome), + keys.Commands(), ) - - // add rosetta - rootCmd.AddCommand(rosettaCmd.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Codec)) } // newApp is an appCreator @@ -296,15 +295,18 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetAccountCmd(), rpc.ValidatorCommand(), - rpc.BlockCommand(), + server.QueryBlockCmd(), + server.QueryBlocksCmd(), + server.QueryBlockResultsCmd(), authcmd.QueryTxsByEventsCmd(), authcmd.QueryTxCmd(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), + authcmd.GetSimulateCmd(), ) + // @MSalopek: deprecated by usage of autocli consumer.ModuleBasics.AddQueryCommands(cmd) return cmd diff --git a/cmd/interchain-security-cd/main.go b/cmd/interchain-security-cd/main.go index 12afc46e65..6f4e94a52c 100644 --- a/cmd/interchain-security-cd/main.go +++ b/cmd/interchain-security-cd/main.go @@ -1,9 +1,9 @@ package main import ( + "fmt" "os" - "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" app "github.com/cosmos/interchain-security/v3/app/consumer" @@ -14,12 +14,7 @@ func main() { rootCmd := cmd.NewRootCmd() if err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: - os.Exit(e.Code) - - default: - os.Exit(1) - } + fmt.Fprintln(rootCmd.OutOrStderr(), err) + os.Exit(1) } } diff --git a/cmd/interchain-security-pd/cmd/root.go b/cmd/interchain-security-pd/cmd/root.go index 829e9b2376..6e70145ee9 100644 --- a/cmd/interchain-security-pd/cmd/root.go +++ b/cmd/interchain-security-pd/cmd/root.go @@ -64,6 +64,7 @@ func NewRootCmd() *cobra.Command { cmd.SetOut(cmd.OutOrStdout()) cmd.SetErr(cmd.ErrOrStderr()) + initClientCtx = initClientCtx.WithCmdContext(cmd.Context()) initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags()) if err != nil { return err diff --git a/x/ccv/consumer/keeper/hooks.go b/x/ccv/consumer/keeper/hooks.go index 7f03896e55..11a10e0840 100644 --- a/x/ccv/consumer/keeper/hooks.go +++ b/x/ccv/consumer/keeper/hooks.go @@ -1,6 +1,8 @@ package keeper import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" ccv "github.com/cosmos/interchain-security/v3/x/ccv/types" @@ -18,7 +20,7 @@ func (k Keeper) Hooks() Hooks { return Hooks{k} } -func (k Keeper) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (k Keeper) AfterValidatorBonded(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { if k.hooks != nil { err := k.hooks.AfterValidatorBonded(ctx, consAddr, nil) return err diff --git a/x/ccv/consumer/keeper/keeper.go b/x/ccv/consumer/keeper/keeper.go index f508324241..84167e61f8 100644 --- a/x/ccv/consumer/keeper/keeper.go +++ b/x/ccv/consumer/keeper/keeper.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "encoding/binary" "fmt" "reflect" @@ -177,6 +178,16 @@ func (k *Keeper) SetHooks(sh ccv.ConsumerHooks) *Keeper { return k } +// ValidatorAddressCodec returns the app validator address codec. +func (k Keeper) ValidatorAddressCodec() addresscodec.Codec { + return k.validatorAddressCodec +} + +// ConsensusAddressCodec returns the app consensus address codec. +func (k Keeper) ConsensusAddressCodec() addresscodec.Codec { + return k.consensusAddressCodec +} + // ChanCloseInit defines a wrapper function for the channel Keeper's function // Following ICS 004: https://github.com/cosmos/ibc/tree/main/spec/core/ics-004-channel-and-packet-semantics#closing-handshake func (k Keeper) ChanCloseInit(ctx sdk.Context, portID, channelID string) error { @@ -600,8 +611,9 @@ func (k Keeper) GetAllCCValidator(ctx sdk.Context) (validators []types.CrossChai } // Implement from stakingkeeper interface -func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []stakingtypes.Validator) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllValidators(ctx context.Context) (validators []stakingtypes.Validator, err error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + store := sdkCtx.KVStore(k.storeKey) iterator := storetypes.KVStorePrefixIterator(store, stakingtypes.ValidatorsKey) defer iterator.Close() @@ -611,7 +623,7 @@ func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []stakingtypes.Val validators = append(validators, validator) } - return validators + return validators, err } // getAndIncrementPendingPacketsIdx returns the current pending packets index and increments it. diff --git a/x/ccv/consumer/keeper/params.go b/x/ccv/consumer/keeper/params.go index 770edf229e..9bd0d1fa10 100644 --- a/x/ccv/consumer/keeper/params.go +++ b/x/ccv/consumer/keeper/params.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -36,9 +37,9 @@ func (k Keeper) SetParams(ctx sdk.Context, params ccvtypes.Params) { // GetParams implements StakingKeeper GetParams interface method // it returns an a empty stakingtypes.Params struct // NOTE: this method must be implemented on the consumer keeper because the evidence module keeper -// in cosmos-sdk v0.47 requires this exact method with this exact signature to be available on the StakingKeepr -func (k Keeper) GetParams(ctx sdk.Context) stakingtypes.Params { - return stakingtypes.Params{} +// in cosmos-sdk v0.50 requires this exact method with this exact signature to be available on the StakingKeepr +func (k Keeper) GetParams(context.Context) (stakingtypes.Params, error) { + return stakingtypes.Params{}, nil } // GetEnabled returns the enabled flag for the consumer module diff --git a/x/ccv/consumer/keeper/validators.go b/x/ccv/consumer/keeper/validators.go index 22b1ed8caf..ce2d726ca2 100644 --- a/x/ccv/consumer/keeper/validators.go +++ b/x/ccv/consumer/keeper/validators.go @@ -1,6 +1,8 @@ package keeper import ( + "context" + "errors" "time" "cosmossdk.io/math" @@ -74,27 +76,29 @@ func (k Keeper) ApplyCCValidatorChanges(ctx sdk.Context, changes []abci.Validato // IterateValidators - unimplemented on CCV keeper but perform a no-op in order to pass the slashing module InitGenesis. // It is allowed since the condition verifying validator public keys in HandleValidatorSignature (x/slashing/keeper/infractions.go) is removed // therefore it isn't required to store any validator public keys to the slashing states during genesis. -func (k Keeper) IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) { +func (k Keeper) IterateValidators(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error { + return nil } // Validator - unimplemented on CCV keeper -func (k Keeper) Validator(ctx sdk.Context, addr sdk.ValAddress) stakingtypes.ValidatorI { +func (k Keeper) Validator(ctx context.Context, addr sdk.ValAddress) (stakingtypes.ValidatorI, error) { panic("unimplemented on CCV keeper") } // IsJailed returns the outstanding slashing flag for the given validator adddress -func (k Keeper) IsValidatorJailed(ctx sdk.Context, addr sdk.ConsAddress) (bool, error) { +func (k Keeper) IsValidatorJailed(ctx context.Context, addr sdk.ConsAddress) (bool, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // if the changeover is not complete for prev standalone chain, // return the standalone staking keeper's jailed status - if k.IsPrevStandaloneChain(ctx) && !k.ChangeoverIsComplete(ctx) { - return k.standaloneStakingKeeper.IsValidatorJailed(ctx, addr) + if k.IsPrevStandaloneChain(sdkCtx) && !k.ChangeoverIsComplete(sdkCtx) { + return k.standaloneStakingKeeper.IsValidatorJailed(sdkCtx, addr) } // Otherwise, return the ccv consumer keeper's notion of a validator being jailed - return k.OutstandingDowntime(ctx, addr), nil + return k.OutstandingDowntime(sdkCtx, addr), nil } // ValidatorByConsAddr returns an empty validator -func (k Keeper) ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI { +func (k Keeper) ValidatorByConsAddr(context.Context, sdk.ConsAddress) (stakingtypes.ValidatorI, error) { /* NOTE: @@ -105,27 +109,28 @@ func (k Keeper) ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.V Also, the slashing module will cal lthis function when it observes downtime. In that case the only requirement on the returned value is that it isn't null. */ - return stakingtypes.Validator{} + return stakingtypes.Validator{}, nil } // Calls SlashWithInfractionReason with Infraction_INFRACTION_UNSPECIFIED. // ConsumerKeeper must implement StakingKeeper interface. // This function should not be called anywhere -func (k Keeper) Slash(ctx sdk.Context, addr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) { +func (k Keeper) Slash(ctx context.Context, addr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) { return k.SlashWithInfractionReason(ctx, addr, infractionHeight, power, slashFactor, stakingtypes.Infraction_INFRACTION_UNSPECIFIED) } // Slash queues a slashing request for the the provider chain // All queued slashing requests will be cleared in EndBlock // Called by Slashing keeper in SlashWithInfractionReason -func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, addr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec, infraction stakingtypes.Infraction) (math.Int, error) { +func (k Keeper) SlashWithInfractionReason(ctx context.Context, addr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec, infraction stakingtypes.Infraction) (math.Int, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) if infraction == stakingtypes.Infraction_INFRACTION_UNSPECIFIED { return math.NewInt(0), nil } // If this is a previously standalone chain and infraction happened before the changeover was completed, // slash only on the standalone staking keeper. - if k.IsPrevStandaloneChain(ctx) && infractionHeight < k.FirstConsumerHeight(ctx) { + if k.IsPrevStandaloneChain(sdkCtx) && infractionHeight < k.FirstConsumerHeight(sdkCtx) { // Slash for a standalone chain does not require an infraction reason so we pass in Infraction_INFRACTION_UNSPECIFIED return k.standaloneStakingKeeper.SlashWithInfractionReason(ctx, addr, infractionHeight, power, slashFactor, stakingtypes.Infraction_INFRACTION_UNSPECIFIED) } @@ -135,9 +140,9 @@ func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, addr sdk.ConsAddress, // if this is a downtime infraction and the validator is allowed to // soft opt out, do not queue a slash packet if infraction == stakingtypes.Infraction_INFRACTION_DOWNTIME { - if power < k.GetSmallestNonOptOutPower(ctx) { + if power < k.GetSmallestNonOptOutPower(sdkCtx) { // soft opt out - k.Logger(ctx).Debug("soft opt out", + k.Logger(sdkCtx).Debug("soft opt out", "validator", addr, "power", power, ) @@ -145,9 +150,9 @@ func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, addr sdk.ConsAddress, } } // get VSC ID for infraction height - vscID := k.GetHeightValsetUpdateID(ctx, uint64(infractionHeight)) + vscID := k.GetHeightValsetUpdateID(sdkCtx, uint64(infractionHeight)) - k.Logger(ctx).Debug("vscID obtained from mapped infraction height", + k.Logger(sdkCtx).Debug("vscID obtained from mapped infraction height", "infraction height", infractionHeight, "vscID", vscID, ) @@ -156,7 +161,7 @@ func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, addr sdk.ConsAddress, // everything else is just here to implement StakingKeeper interface // IBC packets are created from slash data and sent to the provider during EndBlock k.QueueSlashPacket( - ctx, + sdkCtx, abci.Validator{ Address: addr.Bytes(), Power: power, @@ -174,46 +179,49 @@ func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, addr sdk.ConsAddress, // This method should be a no-op even during a standalone to consumer changeover. // Once the upgrade has happened as a part of the changeover, // the provider validator set will soon be in effect, and jailing is n/a. -func (k Keeper) Jail(ctx sdk.Context, addr sdk.ConsAddress) {} +func (k Keeper) Jail(context.Context, sdk.ConsAddress) error { return nil } // Unjail - unimplemented on CCV keeper // // This method should be a no-op even during a standalone to consumer changeover. // Once the upgrade has happened as a part of the changeover, // the provider validator set will soon be in effect, and jailing is n/a. -func (k Keeper) Unjail(sdk.Context, sdk.ConsAddress) {} +func (k Keeper) Unjail(context.Context, sdk.ConsAddress) error { return nil } // Delegation - unimplemented on CCV keeper -func (k Keeper) Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) stakingtypes.DelegationI { +func (k Keeper) Delegation(ctx context.Context, addr sdk.AccAddress, valAddr sdk.ValAddress) (stakingtypes.DelegationI, error) { panic("unimplemented on CCV keeper") } // MaxValidators - unimplemented on CCV keeper -func (k Keeper) MaxValidators(sdk.Context) uint32 { +func (k Keeper) MaxValidators(context.Context) (uint32, error) { panic("unimplemented on CCV keeper") } // UnbondingTime returns consumer unbonding period, satisfying the staking keeper interface -func (k Keeper) UnbondingTime(ctx sdk.Context) time.Duration { - return k.GetUnbondingPeriod(ctx) +func (k Keeper) UnbondingTime(ctx context.Context) (time.Duration, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return k.GetUnbondingPeriod(sdkCtx), nil } // GetHistoricalInfo gets the historical info at a given height -func (k Keeper) GetHistoricalInfo(ctx sdk.Context, height int64) (stakingtypes.HistoricalInfo, bool) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetHistoricalInfo(ctx context.Context, height int64) (stakingtypes.HistoricalInfo, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + store := sdkCtx.KVStore(k.storeKey) key := types.HistoricalInfoKey(height) value := store.Get(key) if value == nil { - return stakingtypes.HistoricalInfo{}, false + return stakingtypes.HistoricalInfo{}, stakingtypes.ErrNoHistoricalInfo } - return stakingtypes.MustUnmarshalHistoricalInfo(k.cdc, value), true + return stakingtypes.UnmarshalHistoricalInfo(k.cdc, value) } // SetHistoricalInfo sets the historical info at a given height -func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi *stakingtypes.HistoricalInfo) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) SetHistoricalInfo(ctx context.Context, height int64, hi *stakingtypes.HistoricalInfo) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + store := sdkCtx.KVStore(k.storeKey) key := types.HistoricalInfoKey(height) value := k.cdc.MustMarshal(hi) @@ -221,17 +229,20 @@ func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi *stakingtype } // DeleteHistoricalInfo deletes the historical info at a given height -func (k Keeper) DeleteHistoricalInfo(ctx sdk.Context, height int64) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) DeleteHistoricalInfo(ctx context.Context, height int64) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + store := sdkCtx.KVStore(k.storeKey) key := types.HistoricalInfoKey(height) store.Delete(key) + return nil } // TrackHistoricalInfo saves the latest historical-info and deletes the oldest // heights that are below pruning height -func (k Keeper) TrackHistoricalInfo(ctx sdk.Context) { - numHistoricalEntries := k.GetHistoricalEntries(ctx) +func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + numHistoricalEntries := k.GetHistoricalEntries(sdkCtx) // Prune store to ensure we only have parameter-defined historical entries. // In most cases, this will involve removing a single historical entry. @@ -240,23 +251,27 @@ func (k Keeper) TrackHistoricalInfo(ctx sdk.Context) { // Since the entries to be deleted are always in a continuous range, we can iterate // over the historical entries starting from the most recent version to be pruned // and then return at the first empty entry. - for i := ctx.BlockHeight() - numHistoricalEntries; i >= 0; i-- { - _, found := k.GetHistoricalInfo(ctx, i) - if found { - k.DeleteHistoricalInfo(ctx, i) - } else { - break + for i := sdkCtx.BlockHeight() - numHistoricalEntries; i >= 0; i-- { + _, err := k.GetHistoricalInfo(ctx, i) + if err != nil { + if errors.Is(err, stakingtypes.ErrNoHistoricalInfo) { + break + } + return err + } + if err = k.DeleteHistoricalInfo(ctx, i); err != nil { + return err } } // if there is no need to persist historicalInfo, return if numHistoricalEntries == 0 { - return + return nil } // Create HistoricalInfo struct lastVals := []stakingtypes.Validator{} - for _, v := range k.GetAllCCValidator(ctx) { + for _, v := range k.GetAllCCValidator(sdkCtx) { pk, err := v.ConsPubKey() if err != nil { // This should never happen as the pubkey is assumed @@ -279,10 +294,11 @@ func (k Keeper) TrackHistoricalInfo(ctx sdk.Context) { } // Create historical info entry which sorts the validator set by voting power - historicalEntry := stakingtypes.NewHistoricalInfo(ctx.BlockHeader(), stakingtypes.Validators{Validators: lastVals, ValidatorCodec: k.validatorAddressCodec}, sdk.DefaultPowerReduction) + historicalEntry := stakingtypes.NewHistoricalInfo(sdkCtx.BlockHeader(), stakingtypes.Validators{Validators: lastVals, ValidatorCodec: k.validatorAddressCodec}, sdk.DefaultPowerReduction) // Set latest HistoricalInfo at current height - k.SetHistoricalInfo(ctx, ctx.BlockHeight(), &historicalEntry) + k.SetHistoricalInfo(ctx, sdkCtx.BlockHeight(), &historicalEntry) + return nil } // MustGetCurrentValidatorsAsABCIUpdates gets all cross-chain validators converted @@ -310,6 +326,6 @@ func (k Keeper) MustGetCurrentValidatorsAsABCIUpdates(ctx sdk.Context) []abci.Va // implement interface method needed for x/genutil in sdk v47 // returns empty updates and err -func (k Keeper) ApplyAndReturnValidatorSetUpdates(sdk.Context) (updates []abci.ValidatorUpdate, err error) { +func (k Keeper) ApplyAndReturnValidatorSetUpdates(context.Context) (updates []abci.ValidatorUpdate, err error) { return } diff --git a/x/ccv/types/expected_keepers.go b/x/ccv/types/expected_keepers.go index ef6b60e116..181bfb5d01 100644 --- a/x/ccv/types/expected_keepers.go +++ b/x/ccv/types/expected_keepers.go @@ -109,7 +109,7 @@ type DistributionKeeper interface { // ConsumerHooks event hooks for newly bonded cross-chain validators type ConsumerHooks interface { - AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddresses sdk.ValAddress) error + AfterValidatorBonded(ctx context.Context, consAddr sdk.ConsAddress, valAddresses sdk.ValAddress) error } // BankKeeper defines the expected interface needed to retrieve account balances.