From c71521c700362d376c511f82cd8d18854987223e Mon Sep 17 00:00:00 2001 From: MSalopek Date: Fri, 13 Oct 2023 22:02:30 +0200 Subject: [PATCH] democracy: update democracy consumer v50 (#1358) * democracy: update x/staking * democracy: update x/governance forbidden prop deletions * democracy: update app.go, cmd * app: fix app dir wrong references --- app/consumer-democracy/abci.go | 84 ++++++++ .../ante/forbidden_proposals_ante_test.go | 4 +- app/consumer-democracy/app.go | 192 ++++++++++-------- app/consumer-democracy/export.go | 8 +- app/provider/app.go | 8 + cmd/interchain-security-cd/cmd/root.go | 2 +- cmd/interchain-security-cdd/cmd/root.go | 28 +-- cmd/interchain-security-cdd/main.go | 11 +- cmd/interchain-security-sd/main.go | 4 +- x/ccv/democracy/governance/module.go | 178 ++-------------- x/ccv/democracy/staking/module.go | 10 +- 11 files changed, 250 insertions(+), 279 deletions(-) create mode 100644 app/consumer-democracy/abci.go diff --git a/app/consumer-democracy/abci.go b/app/consumer-democracy/abci.go new file mode 100644 index 0000000000..94b34cc3bb --- /dev/null +++ b/app/consumer-democracy/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-democracy/ante/forbidden_proposals_ante_test.go b/app/consumer-democracy/ante/forbidden_proposals_ante_test.go index beecc710f1..3e3f05cb78 100644 --- a/app/consumer-democracy/ante/forbidden_proposals_ante_test.go +++ b/app/consumer-democracy/ante/forbidden_proposals_ante_test.go @@ -187,11 +187,11 @@ func newLegacyParamChangeProposalMsg(changes []proposal.ParamChange) *govv1.MsgS if err != nil { return nil } - msg, _ := govv1.NewMsgSubmitProposal([]sdk.Msg{msgContent}, sdk.NewCoins(), sdk.AccAddress{}.String(), "", "", "") + msg, _ := govv1.NewMsgSubmitProposal([]sdk.Msg{msgContent}, sdk.NewCoins(), sdk.AccAddress{}.String(), "", "", "", false) return msg } func newParamChangeProposalMsg(msgs []sdk.Msg) *govv1.MsgSubmitProposal { - msg, _ := govv1.NewMsgSubmitProposal(msgs, sdk.NewCoins(), sdk.AccAddress{}.String(), "", "", "") + msg, _ := govv1.NewMsgSubmitProposal(msgs, sdk.NewCoins(), sdk.AccAddress{}.String(), "", "", "", false) return msg } diff --git a/app/consumer-democracy/app.go b/app/consumer-democracy/app.go index 757cf9c22f..f954ddd03a 100644 --- a/app/consumer-democracy/app.go +++ b/app/consumer-democracy/app.go @@ -1,6 +1,7 @@ package app import ( + "context" "fmt" "io" stdlog "log" @@ -22,6 +23,8 @@ import ( autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + "cosmossdk.io/client/v2/autocli" + "cosmossdk.io/core/appmodule" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/evidence" @@ -49,8 +52,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" @@ -99,10 +102,10 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/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" @@ -256,7 +259,7 @@ func New( bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) - keys := sdk.NewKVStoreKeys( + keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, crisistypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, @@ -264,8 +267,8 @@ func New( capabilitytypes.StoreKey, authzkeeper.StoreKey, consensusparamtypes.StoreKey, consumertypes.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, @@ -286,8 +289,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( @@ -303,10 +306,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(), ) @@ -319,34 +323,37 @@ 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, ) app.StakingKeeper = stakingkeeper.NewKeeper( appCodec, - keys[stakingtypes.StoreKey], + runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), + authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) app.MintKeeper = mintkeeper.NewKeeper( appCodec, - keys[minttypes.StoreKey], + runtime.NewKVStoreService(keys[minttypes.StoreKey]), app.StakingKeeper, app.AccountKeeper, app.BankKeeper, @@ -357,13 +364,13 @@ func New( app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, - keys[slashingtypes.StoreKey], - &app.ConsumerKeeper, + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), + app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.DistrKeeper = distrkeeper.NewKeeper( appCodec, - keys[distrtypes.StoreKey], + runtime.NewKVStoreService(keys[distrtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, @@ -374,13 +381,13 @@ 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 skipUpgradeHeights := map[int64]bool{} for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { @@ -390,7 +397,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, @@ -407,14 +414,11 @@ func New( // register the proposal types ccvgovRouter := govv1beta1.NewRouter() ccvgovRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - // TODO: remove upgrade handler from gov once admin module or decision for only signaling proposal is made. - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.UpgradeKeeper)) - + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)) govConfig := govtypes.DefaultConfig() govKeeper := govkeeper.NewKeeper( - appCodec, keys[govtypes.StoreKey], app.AccountKeeper, app.BankKeeper, - app.StakingKeeper, app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, + app.StakingKeeper, app.DistrKeeper, app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) govKeeper.SetLegacyRouter(ccvgovRouter) @@ -431,15 +435,6 @@ func New( app.GetSubspace(consumertypes.ModuleName), ) - app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, - keys[ibchost.StoreKey], - app.GetSubspace(ibchost.ModuleName), - app.ConsumerKeeper, - app.UpgradeKeeper, - scopedIBCKeeper, - ) - app.IBCKeeper = ibckeeper.NewKeeper( appCodec, keys[ibchost.StoreKey], @@ -447,6 +442,7 @@ func New( &app.ConsumerKeeper, app.UpgradeKeeper, scopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // Create CCV consumer and modules @@ -456,7 +452,7 @@ func New( app.GetSubspace(consumertypes.ModuleName), scopedIBCConsumerKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, + app.IBCKeeper.PortKeeper, app.IBCKeeper.ConnectionKeeper, app.IBCKeeper.ClientKeeper, app.SlashingKeeper, @@ -465,6 +461,9 @@ func New( &app.TransferKeeper, app.IBCKeeper, authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), + authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) // Setting the standalone staking keeper is only needed for standalone to consumer changeover chains @@ -475,7 +474,7 @@ func New( app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, - keys[slashingtypes.StoreKey], + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), &app.ConsumerKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -490,10 +489,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) @@ -507,9 +507,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 @@ -522,7 +524,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)), @@ -533,10 +535,10 @@ func New( feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), ccvgov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper, IsProposalWhitelisted, app.GetSubspace(govtypes.ModuleName), IsModuleWhiteList), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.ConsumerKeeper, app.GetSubspace(slashingtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.ConsumerKeeper, app.GetSubspace(slashingtypes.ModuleName), app.interfaceRegistry), ccvdistr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, *app.StakingKeeper, authtypes.FeeCollectorName, app.GetSubspace(distrtypes.ModuleName)), ccvstaking.NewAppModule(appCodec, *app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), - upgrade.NewAppModule(&app.UpgradeKeeper), + upgrade.NewAppModule(&app.UpgradeKeeper, app.AccountKeeper.AddressCodec()), evidence.NewAppModule(app.EvidenceKeeper), params.NewAppModule(app.ParamsKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), @@ -546,6 +548,16 @@ func New( consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), ) + 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. @@ -631,28 +643,6 @@ func New( 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), - ccvgov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper, IsProposalWhitelisted, app.GetSubspace(govtypes.ModuleName), IsModuleWhiteList), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - ccvstaking.NewAppModule(appCodec, *app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), - ccvdistr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, *app.StakingKeeper, authtypes.FeeCollectorName, app.GetSubspace(distrtypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, *app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), - params.NewAppModule(app.ParamsKeeper), - evidence.NewAppModule(app.EvidenceKeeper), ibc.NewAppModule(app.IBCKeeper), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - transferModule, - ) - - app.sm.RegisterStoreDecoders() - // initialize stores app.MountKVStores(keys) app.MountTransientStores(tkeys) @@ -677,6 +667,7 @@ func New( app.SetAnteHandler(anteHandler) app.SetInitChainer(app.InitChainer) + app.SetPreBlocker(app.PreBlocker) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) @@ -684,8 +675,9 @@ func New( // 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) @@ -715,9 +707,9 @@ func New( appCodec.MustUnmarshalJSON(appState[consumertypes.ModuleName], &consumerGenesis) consumerGenesis.PreCCV = true - app.ConsumerKeeper.InitGenesis(ctx, &consumerGenesis) + app.ConsumerKeeper.InitGenesis(sdkCtx, &consumerGenesis) - ctx.Logger().Info("start to run module migrations...") + app.Logger().Info("start to run module migrations...") // Note: consumer ccv module is added to app.MM.Modules constructor above, // meaning the consumer ccv module will have an entry in fromVM. @@ -768,18 +760,22 @@ func New( // 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) @@ -881,10 +877,10 @@ func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { return app.SlashingKeeper } -// GetTestEvidenceKeeper implements the ConsumerApp interface. -func (app *App) GetTestEvidenceKeeper() testutil.TestEvidenceKeeper { - return app.EvidenceKeeper -} +// // GetTestEvidenceKeeper implements the ConsumerApp interface. +// func (app *App) GetTestEvidenceKeeper() testutil.TestEvidenceKeeper { +// return app.EvidenceKeeper +// } // GetTestStakingKeeper implements the ConsumerApp interface. func (app *App) GetTestStakingKeeper() testutil.TestStakingKeeper { @@ -896,15 +892,15 @@ func (app *App) GetTestDistributionKeeper() testutil.TestDistributionKeeper { return app.DistrKeeper } -// GetTestMintKeeper implements the ConsumerApp interface. -func (app *App) GetTestMintKeeper() testutil.TestMintKeeper { - return app.MintKeeper -} +// // GetTestMintKeeper implements the ConsumerApp interface. +// func (app *App) GetTestMintKeeper() testutil.TestMintKeeper { +// return app.MintKeeper +// } -// GetTestGovKeeper implements the ConsumerApp interface. -func (app *App) GetTestGovKeeper() testutil.TestGovKeeper { - return app.GovKeeper -} +// // GetTestGovKeeper implements the ConsumerApp interface. +// func (app *App) GetTestGovKeeper() testutil.TestGovKeeper { +// return app.GovKeeper +// } // TestingApp functions @@ -938,6 +934,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) { @@ -964,8 +980,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-democracy/export.go b/app/consumer-democracy/export.go index bb710da1c4..9f73ae654d 100644 --- a/app/consumer-democracy/export.go +++ b/app/consumer-democracy/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 4052e6ccce..398d3fc215 100644 --- a/app/provider/app.go +++ b/app/provider/app.go @@ -555,6 +555,9 @@ func New( }, ), }) + 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 @@ -702,6 +705,7 @@ func New( } app.SetInitChainer(app.InitChainer) + app.SetPreBlocker(app.PreBlocker) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(anteHandler) @@ -737,6 +741,10 @@ func New( // 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) (sdk.BeginBlock, error) { return app.MM.BeginBlock(ctx) diff --git a/cmd/interchain-security-cd/cmd/root.go b/cmd/interchain-security-cd/cmd/root.go index 759a078a5a..dffb480cfa 100644 --- a/cmd/interchain-security-cd/cmd/root.go +++ b/cmd/interchain-security-cd/cmd/root.go @@ -306,7 +306,7 @@ func queryCommand() *cobra.Command { authcmd.GetSimulateCmd(), ) - // @MSalopek: deprecated by usage of autocli + // @MSalopek: should be deprecated by usage of autocli? consumer.ModuleBasics.AddQueryCommands(cmd) return cmd diff --git a/cmd/interchain-security-cdd/cmd/root.go b/cmd/interchain-security-cdd/cmd/root.go index 76af498214..a2cfd0f514 100644 --- a/cmd/interchain-security-cdd/cmd/root.go +++ b/cmd/interchain-security-cdd/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" cdd "github.com/cosmos/interchain-security/v3/app/consumer-democracy" "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,7 +123,6 @@ func txCommand() *cobra.Command { authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), - authcmd.GetAuxToFeeCommand(), ) cdd.ModuleBasics.AddTxCommands(cmd) @@ -193,23 +194,20 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { rootCmd.AddCommand( genutilcli.InitCmd(cdd.ModuleBasics, cdd.DefaultNodeHome), debug.Cmd(), - config.Cmd(), - pruning.PruningCmd(newApp), + pruning.Cmd(newApp, cdd.DefaultNodeHome), + confixcmd.ConfigCommand(), ) server.AddCommands(rootCmd, cdd.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(cdd.DefaultNodeHome), + keys.Commands(), ) - - // add rosetta - rootCmd.AddCommand(rosettaCmd.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Codec)) } // newApp is an appCreator @@ -296,11 +294,15 @@ 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(), ) cdd.ModuleBasics.AddQueryCommands(cmd) diff --git a/cmd/interchain-security-cdd/main.go b/cmd/interchain-security-cdd/main.go index 085903425e..5b2b6b84e5 100644 --- a/cmd/interchain-security-cdd/main.go +++ b/cmd/interchain-security-cdd/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-democracy" @@ -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-sd/main.go b/cmd/interchain-security-sd/main.go index 748a83144f..7ee946441e 100644 --- a/cmd/interchain-security-sd/main.go +++ b/cmd/interchain-security-sd/main.go @@ -6,8 +6,8 @@ import ( svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - app "github.com/cosmos/interchain-security/v3/app/provider" - "github.com/cosmos/interchain-security/v3/cmd/interchain-security-pd/cmd" + app "github.com/cosmos/interchain-security/v3/app/sovereign" + "github.com/cosmos/interchain-security/v3/cmd/interchain-security-sd/cmd" ) func main() { diff --git a/x/ccv/democracy/governance/module.go b/x/ccv/democracy/governance/module.go index 63fcf7aeed..74d200dbf4 100644 --- a/x/ccv/democracy/governance/module.go +++ b/x/ccv/democracy/governance/module.go @@ -1,8 +1,11 @@ package governance import ( + "context" "fmt" + "time" + "cosmossdk.io/collections" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -54,164 +57,23 @@ func NewAppModule(cdc codec.Codec, } } -// @MSalopek this returns an error and not validators -func (am AppModule) EndBlocker(ctx sdk.Context) error { - // am.keeper.IterateActiveProposalsQueue(ctx, ctx.BlockHeader().Time, func(proposal govv1.Proposal) bool { - // // if there are forbidden proposals in active proposals queue, refund deposit, delete votes for that proposal - // // and delete proposal from all storages - // deleteForbiddenProposal(ctx, am, proposal) - // return false - // }) - - // TODO: @MSalopek use new approach for handling props - // https://github.com/cosmos/cosmos-sdk/blob/87ba5a6a1368726cf0d19e2ffe1c835c4c5c5753/x/gov/abci.go#L77 - // err = keeper.ActiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) { - // proposal, err := keeper.Proposals.Get(ctx, key.K2()) - // if err != nil { - // return false, err - // } - - // var tagValue, logMsg string - - // passes, burnDeposits, tallyResults, err := keeper.Tally(ctx, proposal) - // if err != nil { - // return false, err - // } - - // // If an expedited proposal fails, we do not want to update - // // the deposit at this point since the proposal is converted to regular. - // // As a result, the deposits are either deleted or refunded in all cases - // // EXCEPT when an expedited proposal fails. - // if !(proposal.Expedited && !passes) { - // if burnDeposits { - // err = keeper.DeleteAndBurnDeposits(ctx, proposal.Id) - // } else { - // err = keeper.RefundAndDeleteDeposits(ctx, proposal.Id) - // } - - // if err != nil { - // return false, err - // } - // } - - // err = keeper.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)) - // if err != nil { - // return false, err - // } - - // switch { - // case passes: - // var ( - // idx int - // events sdk.Events - // msg sdk.Msg - // ) - - // // attempt to execute all messages within the passed proposal - // // Messages may mutate state thus we use a cached context. If one of - // // the handlers fails, no state mutation is written and the error - // // message is logged. - // cacheCtx, writeCache := ctx.CacheContext() - // messages, err := proposal.GetMsgs() - // if err != nil { - // proposal.Status = v1.StatusFailed - // proposal.FailedReason = err.Error() - // tagValue = types.AttributeValueProposalFailed - // logMsg = fmt.Sprintf("passed proposal (%v) failed to execute; msgs: %s", proposal, err) - - // break - // } - - // // execute all messages - // for idx, msg = range messages { - // handler := keeper.Router().Handler(msg) - // var res *sdk.Result - // res, err = safeExecuteHandler(cacheCtx, msg, handler) - // if err != nil { - // break - // } - - // events = append(events, res.GetEvents()...) - // } - - // // `err == nil` when all handlers passed. - // // Or else, `idx` and `err` are populated with the msg index and error. - // if err == nil { - // proposal.Status = v1.StatusPassed - // tagValue = types.AttributeValueProposalPassed - // logMsg = "passed" - - // // write state to the underlying multi-store - // writeCache() - - // // propagate the msg events to the current context - // ctx.EventManager().EmitEvents(events) - // } else { - // proposal.Status = v1.StatusFailed - // proposal.FailedReason = err.Error() - // tagValue = types.AttributeValueProposalFailed - // logMsg = fmt.Sprintf("passed, but msg %d (%s) failed on execution: %s", idx, sdk.MsgTypeURL(msg), err) - // } - // case proposal.Expedited: - // // When expedited proposal fails, it is converted - // // to a regular proposal. As a result, the voting period is extended, and, - // // once the regular voting period expires again, the tally is repeated - // // according to the regular proposal rules. - // proposal.Expedited = false - // params, err := keeper.Params.Get(ctx) - // if err != nil { - // return false, err - // } - // endTime := proposal.VotingStartTime.Add(*params.VotingPeriod) - // proposal.VotingEndTime = &endTime - - // err = keeper.ActiveProposalsQueue.Set(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id), proposal.Id) - // if err != nil { - // return false, err - // } - - // tagValue = types.AttributeValueExpeditedProposalRejected - // logMsg = "expedited proposal converted to regular" - // default: - // proposal.Status = v1.StatusRejected - // proposal.FailedReason = "proposal did not get enough votes to pass" - // tagValue = types.AttributeValueProposalRejected - // logMsg = "rejected" - // } - - // proposal.FinalTallyResult = &tallyResults - - // err = keeper.SetProposal(ctx, proposal) - // if err != nil { - // return false, err - // } - - // // when proposal become active - // keeper.Hooks().AfterProposalVotingPeriodEnded(ctx, proposal.Id) - - // logger.Info( - // "proposal tallied", - // "proposal", proposal.Id, - // "status", proposal.Status.String(), - // "expedited", proposal.Expedited, - // "title", proposal.Title, - // "results", logMsg, - // ) - - // ctx.EventManager().EmitEvent( - // sdk.NewEvent( - // types.EventTypeActiveProposal, - // sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), - // sdk.NewAttribute(types.AttributeKeyProposalResult, tagValue), - // sdk.NewAttribute(types.AttributeKeyProposalLog, logMsg), - // ), - // ) - - // return false, nil - // }) - // if err != nil { - // return err - // } +func (am AppModule) EndBlock(c context.Context) error { + ctx := sdk.UnwrapSDKContext(c) + rng := collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()) + keeper := am.keeper + // if there are forbidden proposals in active proposals queue, refund deposit, delete votes for that proposal + // and delete proposal from all storages + err := am.keeper.ActiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) { + proposal, err := keeper.Proposals.Get(ctx, key.K2()) + if err != nil { + return false, err + } + deleteForbiddenProposal(ctx, am, proposal) + return false, nil + }) + if err != nil { + return err + } return am.AppModule.EndBlock(ctx) } diff --git a/x/ccv/democracy/staking/module.go b/x/ccv/democracy/staking/module.go index 48fed76666..8f5ee86ea8 100644 --- a/x/ccv/democracy/staking/module.go +++ b/x/ccv/democracy/staking/module.go @@ -1,10 +1,10 @@ package staking import ( + "context" "encoding/json" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/exported" @@ -59,7 +59,7 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, // Note: InitGenesis is not called during the soft upgrade of a module // (as a part of a changeover from standalone -> consumer chain), // so there is no special handling needed in this method for a consumer being in the pre-CCV state. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -78,6 +78,8 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json. // The ccv consumer Endblocker is ordered to run before the staking Endblocker, // so if PreCCV is true during one block, the ccv consumer Enblocker will return the proper validator updates, // the PreCCV flag will be toggled to false, and no validator updates should be returned by this method. -func (am AppModule) EndBlocker(ctx sdk.Context) ([]abci.ValidatorUpdate, error) { - return am.keeper.EndBlocker(ctx) +// EndBlocker called at every block, update validator set +func (am AppModule) EndBlocker(ctx context.Context) ([]abci.ValidatorUpdate, error) { + _, _ = am.keeper.BlockValidatorUpdates(ctx) + return []abci.ValidatorUpdate{}, nil }