From 47e3b2370e3acd08419ae21d7f3732c4a67820c5 Mon Sep 17 00:00:00 2001 From: MSalopek Date: Mon, 4 Mar 2024 11:08:52 +0100 Subject: [PATCH] provider: update app --- app/provider/abci.go | 84 +++++++++ app/provider/app.go | 414 ++++++++++++++++++++++++++--------------- app/provider/export.go | 69 +++++-- 3 files changed, 401 insertions(+), 166 deletions(-) create mode 100644 app/provider/abci.go diff --git a/app/provider/abci.go b/app/provider/abci.go new file mode 100644 index 0000000000..94b34cc3bb --- /dev/null +++ b/app/provider/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/provider/app.go b/app/provider/app.go index 558870cf14..e2d7320122 100644 --- a/app/provider/app.go +++ b/app/provider/app.go @@ -1,22 +1,23 @@ package app import ( + "context" "fmt" "io" stdlog "log" "os" "path/filepath" + "github.com/cosmos/gogoproto/proto" "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" ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibcclient "github.com/cosmos/ibc-go/v8/modules/core/02-client" - ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" - ibchost "github.com/cosmos/ibc-go/v8/modules/core/exported" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" tendermint "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" @@ -24,11 +25,14 @@ 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" evidencekeeper "cosmossdk.io/x/evidence/keeper" evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/tx/signing" "cosmossdk.io/x/upgrade" upgradekeeper "cosmossdk.io/x/upgrade/keeper" upgradetypes "cosmossdk.io/x/upgrade/types" @@ -38,6 +42,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services" @@ -48,11 +53,13 @@ import ( "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/msgservice" "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" + "github.com/cosmos/cosmos-sdk/x/auth/posthandler" 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" @@ -61,6 +68,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" @@ -89,14 +97,14 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/ibc-go/modules/capability" - capabilitykeeper "github.com/cosmos/ibc-go/modules/capability" + capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" 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" appencoding "github.com/cosmos/interchain-security/v4/app/encoding" testutil "github.com/cosmos/interchain-security/v4/testutil/integration" @@ -104,6 +112,10 @@ import ( ibcproviderclient "github.com/cosmos/interchain-security/v4/x/ccv/provider/client" ibcproviderkeeper "github.com/cosmos/interchain-security/v4/x/ccv/provider/keeper" providertypes "github.com/cosmos/interchain-security/v4/x/ccv/provider/types" + + "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" + sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" ) const ( @@ -141,6 +153,7 @@ var ( crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, ibc.AppModuleBasic{}, + ibctm.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, transfer.AppModuleBasic{}, @@ -238,27 +251,51 @@ func New( appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *App { - encodingConfig := makeEncodingConfig() - - appCodec := encodingConfig.Codec - legacyAmino := encodingConfig.Amino - interfaceRegistry := encodingConfig.InterfaceRegistry + interfaceRegistry, _ := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ + ProtoFiles: proto.HybridResolver, + SigningOptions: signing.Options{ + AddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32AccountAddrPrefix(), + }, + ValidatorAddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), + }, + }, + }) + appCodec := codec.NewProtoCodec(interfaceRegistry) + legacyAmino := codec.NewLegacyAmino() + txConfig := authtx.NewTxConfig(appCodec, authtx.DefaultSignModes) + + std.RegisterLegacyAminoCodec(legacyAmino) + std.RegisterInterfaces(interfaceRegistry) + // 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 := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) 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, + govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, providertypes.StoreKey, ) - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) + + // register streaming services + if err := bApp.RegisterStreamingServices(appOpts, keys); err != nil { + panic(err) + } + + tkeys := storetypes.NewTransientStoreKeys(paramstypes.TStoreKey) + memKeys := storetypes.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) app := &App{ BaseApp: bApp, @@ -268,7 +305,7 @@ func New( keys: keys, tkeys: tkeys, memKeys: memKeys, - txConfig: encodingConfig.TxConfig, + txConfig: txConfig, } app.ParamsKeeper = initParamsKeeper( @@ -280,8 +317,14 @@ func New( // set the BaseApp's parameter store // upgradetypes.StoreKey -> maybe consensusparamtypes.StoreKey (package consensusparamtypes ("github.com/cosmos/cosmos-sdk/x/consensus/types") - 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( @@ -289,7 +332,7 @@ func New( keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey], ) - scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName) + scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) scopedIBCProviderKeeper := app.CapabilityKeeper.ScopeToModule(providertypes.ModuleName) app.CapabilityKeeper.Seal() @@ -297,10 +340,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(), ) @@ -313,22 +357,25 @@ 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.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, @@ -337,7 +384,7 @@ func New( ) app.DistrKeeper = distrkeeper.NewKeeper( appCodec, - keys[distrtypes.StoreKey], + runtime.NewKVStoreService(keys[distrtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, @@ -347,7 +394,7 @@ func New( app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, - keys[slashingtypes.StoreKey], + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -355,11 +402,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 @@ -371,7 +419,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, @@ -390,39 +438,58 @@ func New( app.IBCKeeper = ibckeeper.NewKeeper( appCodec, - keys[ibchost.StoreKey], - app.GetSubspace(ibchost.ModuleName), + keys[ibcexported.StoreKey], + app.GetSubspace(ibcexported.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // create evidence keeper with router app.EvidenceKeeper = *evidencekeeper.NewKeeper( appCodec, - keys[evidencetypes.StoreKey], + runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), app.StakingKeeper, app.SlashingKeeper, + app.AccountKeeper.AddressCodec(), + runtime.ProvideCometInfoService(), ) + govConfig := govtypes.DefaultConfig() + // register the proposal types + govRouter := govv1beta1.NewRouter() + govRouter. + AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). + AddRoute(providertypes.RouterKey, ibcprovider.NewProviderProposalHandler(app.ProviderKeeper)) + app.GovKeeper = govkeeper.NewKeeper( appCodec, - keys[govtypes.StoreKey], + runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, + app.DistrKeeper, app.MsgServiceRouter(), - govtypes.DefaultConfig(), + govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + // Set legacy router for backwards compatibility with gov v1beta1 + app.GovKeeper.SetLegacyRouter(govRouter) + + app.GovKeeper = app.GovKeeper.SetHooks( + govtypes.NewMultiGovHooks(app.ProviderKeeper.Hooks()), + ) + app.ProviderKeeper = ibcproviderkeeper.NewKeeper( appCodec, keys[providertypes.StoreKey], app.GetSubspace(providertypes.ModuleName), scopedIBCProviderKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, + app.IBCKeeper.PortKeeper, app.IBCKeeper.ConnectionKeeper, app.IBCKeeper.ClientKeeper, app.StakingKeeper, @@ -430,40 +497,28 @@ func New( app.AccountKeeper, app.DistrKeeper, app.BankKeeper, - app.GovKeeper, + *app.GovKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), + authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), authtypes.FeeCollectorName, ) providerModule := ibcprovider.NewAppModule(&app.ProviderKeeper, app.GetSubspace(providertypes.ModuleName)) - // register the proposal types - govRouter := govv1beta1.NewRouter() - govRouter. - AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.UpgradeKeeper)). - AddRoute(ibchost.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)). - AddRoute(providertypes.RouterKey, ibcprovider.NewProviderProposalHandler(app.ProviderKeeper)). - AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)) - - // Set legacy router for backwards compatibility with gov v1beta1 - app.GovKeeper.SetLegacyRouter(govRouter) - - app.GovKeeper = app.GovKeeper.SetHooks( - govtypes.NewMultiGovHooks(app.ProviderKeeper.Hooks()), - ) - app.TransferKeeper = ibctransferkeeper.NewKeeper( appCodec, keys[ibctransfertypes.StoreKey], 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) @@ -473,16 +528,6 @@ func New( ibcRouter.AddRoute(providertypes.ModuleName, providerModule) app.IBCKeeper.SetRouter(ibcRouter) - // create evidence keeper with router - evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, - keys[evidencetypes.StoreKey], - app.StakingKeeper, - app.SlashingKeeper, - ) - - app.EvidenceKeeper = *evidenceKeeper - skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) // NOTE: Any module instantiated in the module manager that is later modified @@ -491,8 +536,8 @@ func New( genutil.NewAppModule( app.AccountKeeper, app.StakingKeeper, - app.BaseApp.DeliverTx, - encodingConfig.TxConfig, + app, + txConfig, ), auth.NewAppModule(appCodec, app.AccountKeeper, nil, app.GetSubspace(authtypes.ModuleName)), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), @@ -501,17 +546,55 @@ func New( crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName), app.interfaceRegistry), distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), staking.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), ibc.NewAppModule(app.IBCKeeper), + ibctm.NewAppModule(), params.NewAppModule(app.ParamsKeeper), transferModule, providerModule, ) + // NOTE: @Msalopek -> ModuleBasic override is happening because Tx commands don't work without it + // TODO: double-check + ModuleBasics = module.NewBasicManagerFromManager( + app.MM, + map[string]module.AppModuleBasic{ + genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + govtypes.ModuleName: gov.NewAppModuleBasic( + []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + ibcproviderclient.ConsumerAdditionProposalHandler, + ibcproviderclient.ConsumerRemovalProposalHandler, + ibcproviderclient.ChangeRewardDenomsProposalHandler, + }, + ), + }) + ModuleBasics.RegisterLegacyAminoCodec(app.legacyAmino) + ModuleBasics.RegisterInterfaces(app.interfaceRegistry) + + enabledSignModes := append(authtx.DefaultSignModes, + sigtypes.SignMode_SIGN_MODE_TEXTUAL) + txConfigOpts := authtx.ConfigOptions{ + EnabledSignModes: enabledSignModes, + TextualCoinMetadataQueryFn: txmodule.NewBankKeeperCoinMetadataQueryFn(app.BankKeeper), + } + txConfig, err := authtx.NewTxConfigWithOptions( + appCodec, + txConfigOpts, + ) + if err != nil { + panic(err) + } + app.txConfig = txConfig + + 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. @@ -525,7 +608,7 @@ func New( govtypes.ModuleName, stakingtypes.ModuleName, ibctransfertypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, @@ -543,7 +626,7 @@ func New( govtypes.ModuleName, stakingtypes.ModuleName, ibctransfertypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, @@ -574,7 +657,7 @@ func New( govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName, genutiltypes.ModuleName, @@ -586,60 +669,20 @@ 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), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, 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), - transferModule, - ) - - app.sm.RegisterStoreDecoders() - - // initialize stores - app.MountKVStores(keys) - app.MountTransientStores(tkeys) - app.MountMemoryStores(memKeys) - - anteHandler, err := NewAnteHandler( - HandlerOptions{ - HandlerOptions: ante.HandlerOptions{ - AccountKeeper: app.AccountKeeper, - BankKeeper: app.BankKeeper, - SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), - SigGasConsumer: ante.DefaultSigVerificationGasConsumer, - }, - IBCKeeper: app.IBCKeeper, - }, - ) + err = app.MM.RegisterServices(app.configurator) if err != nil { - panic(fmt.Errorf("failed to create AnteHandler: %s", err)) + panic(err) } - app.SetAnteHandler(anteHandler) - app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) + // create the simulation manager and define the order of the modules for deterministic simulations // 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) @@ -650,7 +693,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) }, @@ -668,6 +711,58 @@ func New( app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) } + 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) + + anteHandler, err := NewAnteHandler( + HandlerOptions{ + HandlerOptions: ante.HandlerOptions{ + AccountKeeper: app.AccountKeeper, + BankKeeper: app.BankKeeper, + SignModeHandler: txConfig.SignModeHandler(), + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + IBCKeeper: app.IBCKeeper, + }, + ) + if err != nil { + panic(fmt.Errorf("failed to create AnteHandler: %s", err)) + } + + app.SetInitChainer(app.InitChainer) + app.SetPreBlocker(app.PreBlocker) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + app.SetAnteHandler(anteHandler) + + app.setPostHandler() + + // At startup, after all modules have been registered, check that all prot + // annotations are correct. + protoFiles, err := proto.MergedRegistry() + if err != nil { + panic(err) + } + err = msgservice.ValidateProtoAnnotations(protoFiles) + if err != nil { + // Once we switch to using protoreflect-based antehandlers, we might + // want to panic here instead of logging a warning. + fmt.Fprintln(os.Stderr, err.Error()) + } + if loadLatest { if err := app.LoadLatestVersion(); err != nil { tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) @@ -678,32 +773,44 @@ func New( app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedIBCProviderKeeper = scopedIBCProviderKeeper - autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.MM.Modules)) + return app +} - reflectionSvc, err := runtimeservices.NewReflectionService() +// Name returns the name of the App +func (app *App) Name() string { return app.BaseApp.Name() } + +// Configurator returns the configurator for the app +func (app *App) Configurator() module.Configurator { + return app.configurator +} + +func (app *App) setPostHandler() { + postHandler, err := posthandler.NewPostHandler( + posthandler.HandlerOptions{}, + ) if err != nil { panic(err) } - reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) - return app + app.SetPostHandler(postHandler) } -// 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) @@ -848,6 +955,27 @@ 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, + ModuleOptions: runtimeservices.ExtractAutoCLIOptions(app.MM.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) { @@ -874,13 +1002,14 @@ 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. func (app *App) RegisterTendermintService(clientCtx client.Context) { - cmtservice.RegisterTendermintService(clientCtx, app.BaseApp.GRPCQueryRouter(), app.interfaceRegistry, app.Query) + cmtApp := server.NewCometABCIWrapper(app) + cmtservice.RegisterTendermintService(clientCtx, app.BaseApp.GRPCQueryRouter(), app.interfaceRegistry, cmtApp.Query) } // GetMaccPerms returns a copy of the module account permissions @@ -905,25 +1034,12 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(gov.ProvideKeyTable()) paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(ibctransfertypes.ModuleName) - paramsKeeper.Subspace(ibchost.ModuleName) + paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(providertypes.ModuleName) return paramsKeeper } -// MakeTestEncodingConfig creates an EncodingConfig for testing. This function -// should be used only in tests or when creating a new app instance (NewApp*()). -// App user shouldn't create new codecs - use the app.AppCodec instead. -// [DEPRECATED] -// func MakeTestEncodingConfig() appparams.EncodingConfig { -// encodingConfig := appparams.MakeTestEncodingConfig() -// std.RegisterLegacyAminoCodec(encodingConfig.Amino) -// std.RegisterInterfaces(encodingConfig.InterfaceRegistry) -// ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) -// ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) -// return encodingConfig -// } - func MakeTestEncodingConfig() appencoding.EncodingConfig { encodingConfig := appencoding.MakeTestEncodingConfig() std.RegisterLegacyAminoCodec(encodingConfig.Amino) @@ -935,9 +1051,7 @@ func MakeTestEncodingConfig() appencoding.EncodingConfig { func makeEncodingConfig() appencoding.EncodingConfig { encodingConfig := appencoding.MakeTestEncodingConfig() - std.RegisterLegacyAminoCodec(encodingConfig.Amino) - std.RegisterInterfaces(encodingConfig.InterfaceRegistry) - ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) - ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // std.RegisterLegacyAminoCodec(encodingConfig.Amino) + // std.RegisterInterfaces(encodingConfig.InterfaceRegistry) return encodingConfig } diff --git a/app/provider/export.go b/app/provider/export.go index 74faed0657..ce7158634c 100644 --- a/app/provider/export.go +++ b/app/provider/export.go @@ -4,13 +4,12 @@ import ( "encoding/json" "log" + storetypes "cosmossdk.io/store/types" servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" ) // ExportAppStateAndValidators exports the state of the application for a genesis @@ -19,7 +18,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. @@ -29,7 +28,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 @@ -76,7 +78,12 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // withdraw all validator commission app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, err := app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + valAddr, err := sdk.ValAddressFromHex(val.GetOperator()) + if err != nil { + panic(err) + } + + _, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddr) if err != nil { panic(err) } @@ -84,9 +91,23 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str }) // withdraw all delegator rewards - dels := app.StakingKeeper.GetAllDelegations(ctx) + dels, err := app.StakingKeeper.GetAllDelegations(ctx) + if err != nil { + panic(err) + } for _, delegation := range dels { - _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr()) + // NOTE: @MSalopek this may be wrong + // TODO: add tests to figure this out (it's low impact since this is just a test app) + delAddr, err := app.AccountKeeper.AddressCodec().StringToBytes(delegation.GetDelegatorAddr()) + if err != nil { + panic(err) + } + // NOTE: @MSalopek this may be wrong -> need validator addr codec + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(delegation.GetValidatorAddr()) + if err != nil { + panic(err) + } + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) if err != nil { panic(err) } @@ -105,12 +126,20 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all validators app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - feePool := app.DistrKeeper.GetFeePool(ctx) + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err) + } + + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valAddr) + feePool, err := app.DistrKeeper.FeePool.Get(ctx) + if err != nil { + panic(err) + } feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.SetFeePool(ctx, feePool) + app.DistrKeeper.FeePool.Set(ctx, feePool) - err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valAddr) if err != nil { panic(err) } @@ -119,11 +148,19 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all delegations for _, del := range dels { - err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) + delAddr, err := app.AccountKeeper.AddressCodec().StringToBytes(del.GetDelegatorAddr()) if err != nil { panic(err) } - err = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(del.GetValidatorAddr()) + if err != nil { + panic(err) + } + err = app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) + if err != nil { + panic(err) + } + err = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) if err != nil { panic(err) } @@ -155,13 +192,13 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) - iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) + iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) counter := int16(0) for ; iter.Valid(); iter.Next() { addr := sdk.ValAddress(iter.Key()[1:]) - validator, found := app.StakingKeeper.GetValidator(ctx, addr) - if !found { + validator, err := app.StakingKeeper.GetValidator(ctx, addr) + if err != nil { panic("expected validator, not found") }