From 58d803764e13cb3c4f8c3eaead58ff4265cb28e2 Mon Sep 17 00:00:00 2001 From: MSalopek Date: Sat, 11 Nov 2023 17:21:09 +0100 Subject: [PATCH] [fixed] slashing unjail works; dont know why --- app/provider/ante_handler.go | 36 +- app/provider/app.go | 971 +++++++++----------- app/provider/cp_app.gold | 1040 ++++++++++++++++++++++ app/provider/export.go | 116 +-- app/provider/genesis.go | 9 +- cmd/interchain-security-pd/cmd/root.go | 133 ++- cmd/interchain-security-pd/cmd/root.gold | 374 ++++++++ 7 files changed, 1982 insertions(+), 697 deletions(-) create mode 100644 app/provider/cp_app.gold create mode 100644 cmd/interchain-security-pd/cmd/root.gold diff --git a/app/provider/ante_handler.go b/app/provider/ante_handler.go index 564f96284d..57f9e2854d 100644 --- a/app/provider/ante_handler.go +++ b/app/provider/ante_handler.go @@ -1,55 +1,49 @@ package app import ( - ibcante "github.com/cosmos/ibc-go/v8/modules/core/ante" - ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" - - errorsmod "cosmossdk.io/errors" + "errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/ante" + ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" ) -// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC -// channel keeper. +// HandlerOptions are the options required for constructing a default SDK AnteHandler. type HandlerOptions struct { ante.HandlerOptions IBCKeeper *ibckeeper.Keeper } +// NewAnteHandler returns an AnteHandler that checks and increments sequence +// numbers, checks signatures & account numbers, and deducts fees from the first +// signer. func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { if options.AccountKeeper == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler") + return nil, errors.New("account keeper is required for ante builder") } + if options.BankKeeper == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler") - } - if options.SignModeHandler == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder") + return nil, errors.New("bank keeper is required for ante builder") } - sigGasConsumer := options.SigGasConsumer - if sigGasConsumer == nil { - sigGasConsumer = ante.DefaultSigVerificationGasConsumer + if options.SignModeHandler == nil { + return nil, errors.New("sign mode handler is required for ante builder") } anteDecorators := []sdk.AnteDecorator{ - ante.NewSetUpContextDecorator(), - ante.NewExtensionOptionsDecorator(nil), + ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first + ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker), ante.NewValidateBasicDecorator(), ante.NewTxTimeoutHeightDecorator(), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), - // SetPubKeyDecorator must be called before all signature verification decorators - ante.NewSetPubKeyDecorator(options.AccountKeeper), + ante.NewSetPubKeyDecorator(options.AccountKeeper), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewValidateSigCountDecorator(options.AccountKeeper), - ante.NewSigGasConsumeDecorator(options.AccountKeeper, sigGasConsumer), + ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler), ante.NewIncrementSequenceDecorator(options.AccountKeeper), - ibcante.NewRedundantRelayDecorator(options.IBCKeeper), } return sdk.ChainAnteDecorators(anteDecorators...), nil diff --git a/app/provider/app.go b/app/provider/app.go index 08e1368f57..e6991b24b7 100644 --- a/app/provider/app.go +++ b/app/provider/app.go @@ -2,44 +2,57 @@ package app import ( "context" + "encoding/json" "fmt" "io" "os" "path/filepath" - "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" - "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" - ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" - porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" - 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" - 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" "cosmossdk.io/client/v2/autocli" "cosmossdk.io/core/appmodule" - + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" + "cosmossdk.io/x/circuit" + circuitkeeper "cosmossdk.io/x/circuit/keeper" + circuittypes "cosmossdk.io/x/circuit/types" "cosmossdk.io/x/evidence" evidencekeeper "cosmossdk.io/x/evidence/keeper" evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/feegrant" + feegrantkeeper "cosmossdk.io/x/feegrant/keeper" + feegrantmodule "cosmossdk.io/x/feegrant/module" + + 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" + porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + + "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/x/tx/signing" "cosmossdk.io/x/upgrade" upgradekeeper "cosmossdk.io/x/upgrade/keeper" upgradetypes "cosmossdk.io/x/upgrade/types" + abci "github.com/cometbft/cometbft/abci/types" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/gogoproto/proto" + "github.com/cosmos/ibc-go/v8/modules/apps/transfer" + ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" + "github.com/spf13/cast" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "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,24 +61,31 @@ import ( "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/std" + testdata_pulsar "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/msgservice" + sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" "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" "github.com/cosmos/cosmos-sdk/x/auth/posthandler" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/tx" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "github.com/cosmos/cosmos-sdk/x/authz" + authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" + authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" "github.com/cosmos/cosmos-sdk/x/bank" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + consensus "github.com/cosmos/cosmos-sdk/x/consensus" 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" @@ -81,6 +101,9 @@ import ( govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/group" + groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" + groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" "github.com/cosmos/cosmos-sdk/x/mint" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -95,68 +118,19 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "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" - 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" - sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" - - appparams "github.com/cosmos/interchain-security/v3/app/params" - testutil "github.com/cosmos/interchain-security/v3/testutil/integration" icsprovider "github.com/cosmos/interchain-security/v3/x/ccv/provider" - icsproviderclient "github.com/cosmos/interchain-security/v3/x/ccv/provider/client" icsproviderkeeper "github.com/cosmos/interchain-security/v3/x/ccv/provider/keeper" providertypes "github.com/cosmos/interchain-security/v3/x/ccv/provider/types" ) -const ( - AppName = "interchain-security-p" - upgradeName = "ics-v1-to-v2" -) - -// this line is used by starport scaffolding # stargate/wasm/app/enabledProposals +const appName = "intechain-security-p" +const upgradeName = "upgrade" var ( // DefaultNodeHome default home directories for the application daemon DefaultNodeHome string - // ModuleBasics defines the module BasicManager is in charge of setting up basic, - // non-dependant module elements, such as codec registration - // and genesis verification. - ModuleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distr.AppModuleBasic{}, - gov.NewAppModuleBasic( - []govclient.ProposalHandler{ - paramsclient.ProposalHandler, - icsproviderclient.ConsumerAdditionProposalHandler, - icsproviderclient.ConsumerRemovalProposalHandler, - icsproviderclient.ChangeRewardDenomsProposalHandler, - }, - ), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - ibctm.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, - // router.AppModuleBasic{}, - icsprovider.AppModuleBasic{}, - ) - // module account permissions maccPerms = map[string][]string{ authtypes.FeeCollectorName: nil, @@ -164,80 +138,80 @@ var ( minttypes.ModuleName: {authtypes.Minter}, stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + govtypes.ModuleName: {authtypes.Burner}, providertypes.ConsumerRewardsPool: nil, } ) var ( - _ runtime.AppI = (*App)(nil) - _ servertypes.Application = (*App)(nil) - _ ibctesting.TestingApp = (*App)(nil) + _ runtime.AppI = (*SimApp)(nil) + _ servertypes.Application = (*SimApp)(nil) ) -// App extends an ABCI application, but with most of its parameters exported. +// SimApp extends an ABCI application, but with most of its parameters exported. // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. -type App struct { // nolint: golint +type SimApp struct { *baseapp.BaseApp legacyAmino *codec.LegacyAmino appCodec codec.Codec - interfaceRegistry types.InterfaceRegistry txConfig client.TxConfig + interfaceRegistry types.InterfaceRegistry // 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 - AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.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 - DistrKeeper distrkeeper.Keeper - + AccountKeeper authkeeper.AccountKeeper + BankKeeper bankkeeper.BaseKeeper + StakingKeeper *stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.Keeper + DistrKeeper distrkeeper.Keeper GovKeeper govkeeper.Keeper - CrisisKeeper crisiskeeper.Keeper - UpgradeKeeper upgradekeeper.Keeper + CrisisKeeper *crisiskeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper ParamsKeeper paramskeeper.Keeper - IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + AuthzKeeper authzkeeper.Keeper EvidenceKeeper evidencekeeper.Keeper - TransferKeeper ibctransferkeeper.Keeper - ProviderKeeper icsproviderkeeper.Keeper + FeeGrantKeeper feegrantkeeper.Keeper + GroupKeeper groupkeeper.Keeper ConsensusParamsKeeper consensusparamkeeper.Keeper + CircuitKeeper circuitkeeper.Keeper + + CapabilityKeeper *capabilitykeeper.Keeper + IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + TransferKeeper ibctransferkeeper.Keeper + ProviderKeeper icsproviderkeeper.Keeper - // make scoped keepers public for test purposes ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedTransferKeeper capabilitykeeper.ScopedKeeper ScopedIBCProviderKeeper capabilitykeeper.ScopedKeeper // the module manager - MM *module.Manager + ModuleManager *module.Manager + BasicModuleManager module.BasicManager // simulation manager - sm *module.SimulationManager + sm *module.SimulationManager + + // module configurator configurator module.Configurator } func init() { userHomeDir, err := os.UserHomeDir() if err != nil { - panic(fmt.Sprintf("Failed to get home dir %v", err)) + panic(err) } - DefaultNodeHome = filepath.Join(userHomeDir, "."+AppName) + DefaultNodeHome = filepath.Join(userHomeDir, ".simapp") } -// New returns a reference to an initialized App. +// NewSimApp returns a reference to an initialized SimApp. func New( logger log.Logger, db dbm.DB, @@ -245,24 +219,59 @@ func New( loadLatest bool, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), -) *App { - encodingConfig := makeEncodingConfig() +) *SimApp { + 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 := tx.NewTxConfig(appCodec, tx.DefaultSignModes) - interfaceRegistry := encodingConfig.InterfaceRegistry - appCodec := encodingConfig.Codec - legacyAmino := encodingConfig.Amino - txConfig := encodingConfig.TxConfig std.RegisterLegacyAminoCodec(legacyAmino) std.RegisterInterfaces(interfaceRegistry) - // ABCI++, v50 + // Below we could construct and set an application specific mempool and + // ABCI 1.0 PrepareProposal and ProcessProposal handlers. These defaults are + // already set in the SDK's BaseApp, this shows an example of how to override + // them. + // + // Example: + // + // bApp := baseapp.NewBaseApp(...) + // nonceMempool := mempool.NewSenderNonceMempool() + // abciPropHandler := NewDefaultProposalHandler(nonceMempool, bApp) + // + // bApp.SetMempool(nonceMempool) + // bApp.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) + // bApp.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) + // + // Alternatively, you can construct BaseApp options, append those to + // baseAppOptions and pass them to NewBaseApp. + // + // Example: + // + // prepareOpt = func(app *baseapp.BaseApp) { + // abciPropHandler := baseapp.NewDefaultProposalHandler(nonceMempool, app) + // app.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) + // } + // baseAppOptions = append(baseAppOptions, prepareOpt) + + // create and set dummy vote extension handler voteExtOp := func(bApp *baseapp.BaseApp) { voteExtHandler := NewVoteExtensionHandler() voteExtHandler.SetHandlers(bApp) } - baseAppOptions = append(baseAppOptions, voteExtOp) + baseAppOptions = append(baseAppOptions, voteExtOp, baseapp.SetOptimisticExecution()) - bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...) + bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) @@ -271,11 +280,12 @@ func New( keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, crisistypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, + govtypes.StoreKey, paramstypes.StoreKey, consensusparamtypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, + evidencetypes.StoreKey, circuittypes.StoreKey, + authzkeeper.StoreKey, group.StoreKey, capabilitytypes.StoreKey, + ibcexported.StoreKey, ibctransfertypes.StoreKey, providertypes.StoreKey, - consensusparamtypes.StoreKey, ) // register streaming services @@ -286,34 +296,22 @@ func New( tkeys := storetypes.NewTransientStoreKeys(paramstypes.TStoreKey) memKeys := storetypes.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - app := &App{ + app := &SimApp{ BaseApp: bApp, legacyAmino: legacyAmino, appCodec: appCodec, + txConfig: txConfig, interfaceRegistry: interfaceRegistry, keys: keys, tkeys: tkeys, memKeys: memKeys, - txConfig: txConfig, } - app.ParamsKeeper = initParamsKeeper( - appCodec, - legacyAmino, - keys[paramstypes.StoreKey], - tkeys[paramstypes.TStoreKey], - ) + app.ParamsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey]) // 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, - runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - runtime.EventService{}, - ) - - bApp.SetParamStore(&app.ConsensusParamsKeeper.ParamsStore) + 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( @@ -327,28 +325,13 @@ func New( app.CapabilityKeeper.Seal() // add keepers - app.AccountKeeper = authkeeper.NewAccountKeeper( - appCodec, - runtime.NewKVStoreService(keys[authtypes.StoreKey]), - authtypes.ProtoBaseAccount, - maccPerms, - authcodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - // Remove the ConsumerRewardsPool from the group of blocked recipient addresses in bank - // this is required for the provider chain to be able to receive tokens from - // the consumer chain - bankBlockedAddrs := app.ModuleAccountAddrs() - delete(bankBlockedAddrs, authtypes.NewModuleAddress( - providertypes.ConsumerRewardsPool).String()) + app.AccountKeeper = authkeeper.NewAccountKeeper(appCodec, runtime.NewKVStoreService(keys[authtypes.StoreKey]), authtypes.ProtoBaseAccount, maccPerms, authcodec.NewBech32Codec(sdk.Bech32MainPrefix), sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, runtime.NewKVStoreService(keys[banktypes.StoreKey]), app.AccountKeeper, - bankBlockedAddrs, + BlockedAddresses(), authtypes.NewModuleAddress(govtypes.ModuleName).String(), logger, ) @@ -369,50 +352,33 @@ func New( app.txConfig = txConfig app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, - 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, - runtime.NewKVStoreService(keys[minttypes.StoreKey]), - app.StakingKeeper, - app.AccountKeeper, - app.BankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - app.DistrKeeper = distrkeeper.NewKeeper( - appCodec, - runtime.NewKVStoreService(keys[distrtypes.StoreKey]), - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, 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, runtime.NewKVStoreService(keys[minttypes.StoreKey]), app.StakingKeeper, app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + + app.DistrKeeper = distrkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[distrtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.SlashingKeeper = slashingkeeper.NewKeeper( - appCodec, - legacyAmino, - runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), - app.StakingKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, legacyAmino, runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) - app.CrisisKeeper = *crisiskeeper.NewKeeper( - appCodec, - runtime.NewKVStoreService(keys[crisistypes.StoreKey]), - invCheckPeriod, - app.BankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - app.AccountKeeper.AddressCodec(), - ) + app.CrisisKeeper = crisiskeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[crisistypes.StoreKey]), invCheckPeriod, + app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AccountKeeper.AddressCodec()) + + app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[feegrant.StoreKey]), app.AccountKeeper) + + app.CircuitKeeper = circuitkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[circuittypes.StoreKey]), authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AccountKeeper.AddressCodec()) + app.BaseApp.SetCircuitBreaker(&app.CircuitKeeper) + + app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), appCodec, app.MsgServiceRouter(), app.AccountKeeper) + + groupConfig := group.DefaultConfig() + /* + Example of setting group params: + groupConfig.MaxMetadataLen = 1000 + */ + app.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper, groupConfig) // get skipUpgradeHeights from the app options skipUpgradeHeights := map[int64]bool{} @@ -421,25 +387,41 @@ func New( } homePath := cast.ToString(appOpts.Get(flags.FlagHome)) // set the governance module account as the authority for conducting upgrades - app.UpgradeKeeper = *upgradekeeper.NewKeeper( - skipUpgradeHeights, - runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), - appCodec, - homePath, - app.BaseApp, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + + // Register the proposal types + // Deprecated: Avoid adding new handlers, instead use the new proposal flow + // by granting the governance module the right to execute the message. + // See: https://docs.cosmos.network/main/modules/gov#proposal-messages + govRouter := govv1beta1.NewRouter() + govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)) + govConfig := govtypes.DefaultConfig() + /* + Example of setting gov params: + govConfig.MaxMetadataLen = 10000 + */ + govKeeper := govkeeper.NewKeeper( + appCodec, runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, + app.StakingKeeper, app.DistrKeeper, app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks( - app.DistrKeeper.Hooks(), - app.SlashingKeeper.Hooks(), - app.ProviderKeeper.Hooks(), + // Set legacy router for backwards compatibility with gov v1beta1 + govKeeper.SetLegacyRouter(govRouter) + + app.GovKeeper = *govKeeper.SetHooks( + govtypes.NewMultiGovHooks( + // register the governance hooks ), ) + // create evidence keeper with router + evidenceKeeper := evidencekeeper.NewKeeper( + appCodec, runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), app.StakingKeeper, app.SlashingKeeper, app.AccountKeeper.AddressCodec(), runtime.ProvideCometInfoService(), + ) + // If evidence needs to be handled for the app, set routes in router here and seal + app.EvidenceKeeper = *evidenceKeeper + app.IBCKeeper = ibckeeper.NewKeeper( appCodec, keys[ibcexported.StoreKey], @@ -450,6 +432,22 @@ func New( authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.TransferKeeper = ibctransferkeeper.NewKeeper( + appCodec, + keys[ibctransfertypes.StoreKey], + app.GetSubspace(ibctransfertypes.ModuleName), + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + scopedTransferKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + transferModule := transfer.NewAppModule(app.TransferKeeper) + ibcmodule := transfer.NewIBCModule(app.TransferKeeper) + providerModule := icsprovider.NewAppModule(&app.ProviderKeeper, app.GetSubspace(providertypes.ModuleName)) + app.ProviderKeeper = icsproviderkeeper.NewKeeper( appCodec, keys[providertypes.StoreKey], @@ -470,231 +468,140 @@ func New( authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) - providerModule := icsprovider.NewAppModule(&app.ProviderKeeper, app.GetSubspace(providertypes.ModuleName)) - - // create evidence keeper with router - app.EvidenceKeeper = *evidencekeeper.NewKeeper( - appCodec, - runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), - app.StakingKeeper, - app.SlashingKeeper, - app.AccountKeeper.AddressCodec(), - runtime.ProvideCometInfoService(), - ) - - // register the proposal types - govRouter := govv1beta1.NewRouter() - govRouter. - AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - // NOTE: @MSalopek -> remove NewSoftwareUpgradeProposalHandler - // AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.UpgradeKeeper)). - AddRoute(providertypes.RouterKey, icsprovider.NewProviderProposalHandler(app.ProviderKeeper)) - govConfig := govtypes.DefaultConfig() - - app.GovKeeper = *govkeeper.NewKeeper( - appCodec, - runtime.NewKVStoreService(keys[govtypes.StoreKey]), - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.DistrKeeper, - app.MsgServiceRouter(), - govConfig, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - // Set legacy router for backwards compatibility with gov v1beta1 - app.GovKeeper.SetLegacyRouter(govRouter) - - app.TransferKeeper = ibctransferkeeper.NewKeeper( - appCodec, - keys[ibctransfertypes.StoreKey], - app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - scopedTransferKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - transferModule := transfer.NewAppModule(app.TransferKeeper) - ibcmodule := transfer.NewIBCModule(app.TransferKeeper) - // create static IBC router, add transfer route, then set and seal it ibcRouter := porttypes.NewRouter() ibcRouter.AddRoute(ibctransfertypes.ModuleName, ibcmodule) ibcRouter.AddRoute(providertypes.ModuleName, providerModule) app.IBCKeeper.SetRouter(ibcRouter) + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.StakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks(), app.ProviderKeeper.Hooks()), + ) + + /**** Module Options ****/ + + // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment + // we prefer to be more strict in what arguments the modules expect. skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. - app.MM = module.NewManager( + app.ModuleManager = module.NewManager( genutil.NewAppModule( - app.AccountKeeper, - app.StakingKeeper, - app, + app.AccountKeeper, app.StakingKeeper, app, txConfig, ), - auth.NewAppModule(appCodec, app.AccountKeeper, nil, app.GetSubspace(authtypes.ModuleName)), + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), 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)), + crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), + feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), 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), 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, app.AccountKeeper.AddressCodec()), + 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), + groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), + circuit.NewAppModule(appCodec, app.CircuitKeeper), ibc.NewAppModule(app.IBCKeeper), ibctm.NewAppModule(), params.NewAppModule(app.ParamsKeeper), + capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), transferModule, providerModule, ) - // NOTE: @Msalopek -> ModuleBasic override is happening because Tx commands don't work without it - // NOTE: @MSalopek -> this may affect testing - ModuleBasics = module.NewBasicManagerFromManager( - app.MM, + // BasicModuleManager defines the module BasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration and genesis verification. + // By default it is composed of all the module from the module manager. + // Additionally, app module basics can be overwritten by passing them as argument. + app.BasicModuleManager = module.NewBasicManagerFromManager( + app.ModuleManager, map[string]module.AppModuleBasic{ genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), govtypes.ModuleName: gov.NewAppModuleBasic( []govclient.ProposalHandler{ paramsclient.ProposalHandler, - icsproviderclient.ConsumerAdditionProposalHandler, - icsproviderclient.ConsumerRemovalProposalHandler, - icsproviderclient.ChangeRewardDenomsProposalHandler, }, ), }) - ModuleBasics.RegisterLegacyAminoCodec(legacyAmino) - ModuleBasics.RegisterInterfaces(interfaceRegistry) + app.BasicModuleManager.RegisterLegacyAminoCodec(legacyAmino) + app.BasicModuleManager.RegisterInterfaces(interfaceRegistry) - app.MM.SetOrderPreBlockers( + // NOTE: upgrade module is required to be prioritized + app.ModuleManager.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. // NOTE: staking module is required if HistoricalEntries param > 0 - // 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, + app.ModuleManager.SetOrderBeginBlockers( capabilitytypes.ModuleName, - crisistypes.ModuleName, - govtypes.ModuleName, + minttypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + evidencetypes.ModuleName, stakingtypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - minttypes.ModuleName, genutiltypes.ModuleName, - evidencetypes.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, + authz.ModuleName, providertypes.ModuleName, ) - - app.MM.SetOrderEndBlockers( + app.ModuleManager.SetOrderEndBlockers( crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName, + capabilitytypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - minttypes.ModuleName, genutiltypes.ModuleName, - evidencetypes.ModuleName, - paramstypes.ModuleName, - upgradetypes.ModuleName, - vestingtypes.ModuleName, + feegrant.ModuleName, + group.ModuleName, providertypes.ModuleName, ) // NOTE: The genutils module must occur after staking so that pools are // properly initialized with tokens from genesis accounts. // NOTE: The genutils module must also occur after auth so that it can access the params from auth. - // NOTE: Capability module must occur first so that it can initialize any capabilities - // so that other modules that want to create or claim capabilities afterwards in InitChain - // can do so safely. - app.MM.SetOrderInitGenesis( + genesisModuleOrder := []string{ + authtypes.ModuleName, banktypes.ModuleName, + distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, + minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, + feegrant.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, + vestingtypes.ModuleName, consensusparamtypes.ModuleName, circuittypes.ModuleName, capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - govtypes.ModuleName, - minttypes.ModuleName, - crisistypes.ModuleName, ibcexported.ModuleName, - evidencetypes.ModuleName, ibctransfertypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - upgradetypes.ModuleName, - vestingtypes.ModuleName, providertypes.ModuleName, - ) - - app.MM.RegisterInvariants(&app.CrisisKeeper) - app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) - err = app.MM.RegisterServices(app.configurator) - if err != nil { - panic(err) } + app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) + app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) - // 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 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) - - for moduleName := range app.MM.Modules { - m := app.MM.Modules[moduleName] - if module, ok := m.(module.HasConsensusVersion); ok { - fromVM[moduleName] = module.ConsensusVersion() - } - } - - app.Logger().Info("start to run module migrations...") - - return app.MM.RunMigrations(ctx, app.configurator, fromVM) - }, - ) + // Uncomment if you want to set a custom migration order here. + // app.ModuleManager.SetOrderMigrations(custom order) - upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + app.ModuleManager.RegisterInvariants(app.CrisisKeeper) + app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) + err = app.ModuleManager.RegisterServices(app.configurator) if err != nil { - panic(fmt.Sprintf("failed to read upgrade info from disk %s", err)) + panic(err) } - if upgradeInfo.Name == upgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := storetypes.StoreUpgrades{} - - // configure store loader that checks if version == upgradeHeight and applies store upgrades - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) - } + // RegisterUpgradeHandlers is used for registering any on-chain upgrades. + // Make sure it's called after `app.ModuleManager` and `app.configurator` are set. + app.RegisterUpgradeHandlers() - autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.MM.Modules)) + autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.ModuleManager.Modules)) reflectionSvc, err := runtimeservices.NewReflectionService() if err != nil { @@ -703,34 +610,44 @@ func New( reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) // add test gRPC service for testing gRPC queries in isolation - testpb.RegisterQueryServer(app.GRPCQueryRouter(), testpb.QueryImpl{}) + testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{}) + + // 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 + overrideModules := map[string]module.AppModuleSimulation{ + authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + } + app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) + + 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, - }, - ) - if err != nil { - panic(fmt.Errorf("failed to create AnteHandler: %s", err)) - } - + // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetPreBlocker(app.PreBlocker) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(anteHandler) - + app.setAnteHandler(txConfig) + + // In v0.46, the SDK introduces _postHandlers_. PostHandlers are like + // antehandlers, but are run _after_ the `runMsgs` execution. They are also + // defined as a chain, and have the same signature as antehandlers. + // + // In baseapp, postHandlers are run in the same store branch as `runMsgs`, + // meaning that both `runMsgs` and `postHandler` state will be committed if + // both are successful, and both will be reverted if any of the two fails. + // + // The SDK exposes a default postHandlers chain + // + // Please note that changing any of the anteHandler or postHandler chain is + // likely to be a state-machine breaking change, which needs a coordinated + // upgrade. app.setPostHandler() // At startup, after all modules have been registered, check that all prot @@ -748,57 +665,62 @@ func New( if loadLatest { if err := app.LoadLatestVersion(); err != nil { - tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) + panic(fmt.Errorf("error loading last version: %w", err)) } } - app.ScopedIBCKeeper = scopedIBCKeeper app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedIBCProviderKeeper = scopedIBCProviderKeeper - 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) (sdk.BeginBlock, error) { - return app.MM.BeginBlock(ctx) -} +func (app *SimApp) setAnteHandler(txConfig client.TxConfig) { + anteHandler, err := NewAnteHandler( + HandlerOptions{ + ante.HandlerOptions{ + AccountKeeper: app.AccountKeeper, + BankKeeper: app.BankKeeper, + SignModeHandler: txConfig.SignModeHandler(), + FeegrantKeeper: app.FeeGrantKeeper, + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + app.IBCKeeper, + }, + ) + if err != nil { + panic(err) + } -// EndBlocker application updates every end block -func (app *App) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { - return app.MM.EndBlock(ctx) + // Set the AnteHandler for the app + app.SetAnteHandler(anteHandler) } -// Configurator returns the configurator for the app -func (app *App) Configurator() module.Configurator { - return app.configurator -} +func (app SimApp) RegisterUpgradeHandlers() { + app.UpgradeKeeper.SetUpgradeHandler( + upgradeName, + func(ctx context.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + return app.ModuleManager.RunMigrations(ctx, app.Configurator(), fromVM) + }, + ) -// InitChainer application update at chain initialization -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 { + upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { panic(err) } - app.UpgradeKeeper.SetModuleVersionMap(ctx, app.MM.GetVersionMap()) - - return app.MM.InitGenesis(ctx, app.appCodec, genesisState) -} + if upgradeInfo.Name == upgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + storeUpgrades := storetypes.StoreUpgrades{ + Added: []string{ + circuittypes.ModuleName, + }, + } -// LoadHeight loads a particular height -func (app *App) LoadHeight(height int64) error { - return app.LoadVersion(height) + // configure store loader that checks if version == upgradeHeight and applies store upgrades + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) + } } -func (app *App) setPostHandler() { +func (app *SimApp) setPostHandler() { postHandler, err := posthandler.NewPostHandler( posthandler.HandlerOptions{}, ) @@ -809,139 +731,73 @@ func (app *App) setPostHandler() { app.SetPostHandler(postHandler) } -// ModuleAccountAddrs returns all the app's module account addresses. -func (app *App) ModuleAccountAddrs() map[string]bool { - modAccAddrs := make(map[string]bool) - for acc := range maccPerms { - modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true - } +// Name returns the name of the App +func (app *SimApp) Name() string { return app.BaseApp.Name() } - return modAccAddrs +// PreBlocker application updates every pre block +func (app *SimApp) PreBlocker(ctx sdk.Context, _ *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { + return app.ModuleManager.PreBlock(ctx) } -// LegacyAmino returns App's amino codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *App) LegacyAmino() *codec.LegacyAmino { - return app.legacyAmino +// BeginBlocker application updates every begin block +func (app *SimApp) BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error) { + return app.ModuleManager.BeginBlock(ctx) } -// AppCodec returns the app codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *App) AppCodec() codec.Codec { - return app.appCodec +// EndBlocker application updates every end block +func (app *SimApp) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { + return app.ModuleManager.EndBlock(ctx) } -// InterfaceRegistry returns the InterfaceRegistry -func (app *App) InterfaceRegistry() types.InterfaceRegistry { - return app.interfaceRegistry +func (a *SimApp) Configurator() module.Configurator { + return a.configurator } -// GetKey returns the KVStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *App) GetKey(storeKey string) *storetypes.KVStoreKey { - return app.keys[storeKey] +// InitChainer application update at chain initialization +func (app *SimApp) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { + var genesisState GenesisState + if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { + panic(err) + } + app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) + return app.ModuleManager.InitGenesis(ctx, app.appCodec, genesisState) } -// GetTKey returns the TransientStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *App) GetTKey(storeKey string) *storetypes.TransientStoreKey { - return app.tkeys[storeKey] +// LoadHeight loads a particular height +func (app *SimApp) LoadHeight(height int64) error { + return app.LoadVersion(height) } -// GetMemKey returns the MemStoreKey for the provided mem key. +// LegacyAmino returns SimApp's amino codec. // -// NOTE: This is solely used for testing purposes. -func (app *App) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { - return app.memKeys[storeKey] +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *SimApp) LegacyAmino() *codec.LegacyAmino { + return app.legacyAmino } -// GetSubspace returns a param subspace for a given module name. +// AppCodec returns SimApp's app codec. // -// NOTE: This is solely to be used for testing purposes. -func (app *App) GetSubspace(moduleName string) paramstypes.Subspace { - subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) - return subspace -} - -// SimulationManager implements the SimulationApp interface -func (app *App) SimulationManager() *module.SimulationManager { - return app.sm -} - -// ProviderApp interface implementations for integration tests - -// GetProviderKeeper implements the ProviderApp interface. -func (app *App) GetProviderKeeper() icsproviderkeeper.Keeper { - return app.ProviderKeeper -} - -// GetTestStakingKeeper implements the ProviderApp interface. -func (app *App) GetTestStakingKeeper() testutil.TestStakingKeeper { - return app.StakingKeeper -} - -// GetTestBankKeeper implements the ProviderApp interface. -func (app *App) GetTestBankKeeper() testutil.TestBankKeeper { - return app.BankKeeper -} - -// GetTestSlashingKeeper implements the ProviderApp interface. -func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { - return app.SlashingKeeper -} - -// GetTestDistributionKeeper implements the ProviderApp interface. -func (app *App) GetTestDistributionKeeper() testutil.TestDistributionKeeper { - return app.DistrKeeper -} - -// GetTestAccountKeeper implements the ProviderApp interface. -func (app *App) GetTestAccountKeeper() testutil.TestAccountKeeper { - return app.AccountKeeper -} - -// TestingApp functions - -// GetBaseApp implements the TestingApp interface. -func (app *App) GetBaseApp() *baseapp.BaseApp { - return app.BaseApp -} - -// GetStakingKeeper implements the TestingApp interface. -func (app *App) GetStakingKeeper() ibctestingtypes.StakingKeeper { - return app.StakingKeeper -} - -// GetIBCKeeper implements the TestingApp interface. -func (app *App) GetIBCKeeper() *ibckeeper.Keeper { - return app.IBCKeeper -} - -// GetScopedIBCKeeper implements the TestingApp interface. -func (app *App) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { - return app.ScopedIBCKeeper +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *SimApp) AppCodec() codec.Codec { + return app.appCodec } -// GetTxConfig implements the TestingApp interface. -func (app *App) GetTxConfig() client.TxConfig { - return app.txConfig +// InterfaceRegistry returns SimApp's InterfaceRegistry +func (app *SimApp) InterfaceRegistry() types.InterfaceRegistry { + return app.interfaceRegistry } // TxConfig returns SimApp's TxConfig -func (app *App) TxConfig() client.TxConfig { +func (app *SimApp) TxConfig() client.TxConfig { return app.txConfig } // AutoCliOpts returns the autocli options for the app. -func (app *App) AutoCliOpts() autocli.AppOptions { +func (app *SimApp) AutoCliOpts() autocli.AppOptions { modules := make(map[string]appmodule.AppModule, 0) - for _, m := range app.MM.Modules { + for _, m := range app.ModuleManager.Modules { if moduleWithName, ok := m.(module.HasName); ok { moduleName := moduleWithName.Name() if appModule, ok := moduleWithName.(appmodule.AppModule); ok { @@ -952,27 +808,63 @@ func (app *App) AutoCliOpts() autocli.AppOptions { return autocli.AppOptions{ Modules: modules, - ModuleOptions: runtimeservices.ExtractAutoCLIOptions(app.MM.Modules), + ModuleOptions: runtimeservices.ExtractAutoCLIOptions(app.ModuleManager.Modules), AddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()), ValidatorAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()), ConsensusAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()), } } +// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. +func (a *SimApp) DefaultGenesis() map[string]json.RawMessage { + return a.BasicModuleManager.DefaultGenesis(a.appCodec) +} + +// GetKey returns the KVStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *SimApp) GetKey(storeKey string) *storetypes.KVStoreKey { + return app.keys[storeKey] +} + +// GetStoreKeys returns all the stored store keys. +func (app *SimApp) GetStoreKeys() []storetypes.StoreKey { + keys := make([]storetypes.StoreKey, len(app.keys)) + for _, key := range app.keys { + keys = append(keys, key) + } + + return keys +} + +// GetSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *SimApp) GetSubspace(moduleName string) paramstypes.Subspace { + subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + return subspace +} + +// SimulationManager implements the SimulationApp interface +func (app *SimApp) SimulationManager() *module.SimulationManager { + return app.sm +} + // RegisterAPIRoutes registers all application module routes with the provided // API server. -func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { +func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { clientCtx := apiSvr.ClientCtx // Register new tx routes from grpc-gateway. authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - // Register new tendermint queries routes from grpc-gateway. + + // Register new CometBFT queries routes from grpc-gateway. cmtservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register node gRPC service for grpc-gateway. nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - // Register legacy and grpc-gateway routes for all modules. - ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register grpc-gateway routes for all modules. + app.BasicModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // register swagger API from root so that other applications can override easily if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { @@ -981,29 +873,50 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig } // RegisterTxService implements the Application.RegisterTxService method. -func (app *App) RegisterTxService(clientCtx client.Context) { +func (app *SimApp) RegisterTxService(clientCtx client.Context) { authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry) } -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) { +func (app *SimApp) RegisterTendermintService(clientCtx client.Context) { cmtApp := server.NewCometABCIWrapper(app) - cmtservice.RegisterTendermintService(clientCtx, app.BaseApp.GRPCQueryRouter(), app.interfaceRegistry, cmtApp.Query) + cmtservice.RegisterTendermintService( + clientCtx, + app.BaseApp.GRPCQueryRouter(), + app.interfaceRegistry, + cmtApp.Query, + ) +} + +func (app *SimApp) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter(), cfg) } // GetMaccPerms returns a copy of the module account permissions +// +// NOTE: This is solely to be used for testing purposes. func GetMaccPerms() map[string][]string { dupMaccPerms := make(map[string][]string) for k, v := range maccPerms { dupMaccPerms[k] = v } + return dupMaccPerms } +// BlockedAddresses returns all the app's blocked account addresses. +func BlockedAddresses() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range GetMaccPerms() { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + // allow the following addresses to receive funds + delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + + return modAccAddrs +} + // initParamsKeeper init params keeper and its subspaces func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) @@ -1014,27 +927,9 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(minttypes.ModuleName) paramsKeeper.Subspace(distrtypes.ModuleName) paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(gov.ProvideKeyTable()) + paramsKeeper.Subspace(govtypes.ModuleName) paramsKeeper.Subspace(crisistypes.ModuleName) - paramsKeeper.Subspace(ibctransfertypes.ModuleName) - paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(providertypes.ModuleName) return paramsKeeper } - -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 makeEncodingConfig() appparams.EncodingConfig { - encodingConfig := appparams.MakeTestEncodingConfig() - // std.RegisterLegacyAminoCodec(encodingConfig.Amino) - // std.RegisterInterfaces(encodingConfig.InterfaceRegistry) - return encodingConfig -} diff --git a/app/provider/cp_app.gold b/app/provider/cp_app.gold new file mode 100644 index 0000000000..08e1368f57 --- /dev/null +++ b/app/provider/cp_app.gold @@ -0,0 +1,1040 @@ +package app + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" + "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" + ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" + porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" + 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" + 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" + "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/upgrade" + upgradekeeper "cosmossdk.io/x/upgrade/keeper" + upgradetypes "cosmossdk.io/x/upgrade/types" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "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/types" + "github.com/cosmos/cosmos-sdk/runtime" + runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/api" + "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + "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" + "github.com/cosmos/cosmos-sdk/x/auth/posthandler" + "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "github.com/cosmos/cosmos-sdk/x/bank" + 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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/cosmos/cosmos-sdk/x/gov" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/mint" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "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" + 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" + sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + + appparams "github.com/cosmos/interchain-security/v3/app/params" + testutil "github.com/cosmos/interchain-security/v3/testutil/integration" + icsprovider "github.com/cosmos/interchain-security/v3/x/ccv/provider" + icsproviderclient "github.com/cosmos/interchain-security/v3/x/ccv/provider/client" + icsproviderkeeper "github.com/cosmos/interchain-security/v3/x/ccv/provider/keeper" + providertypes "github.com/cosmos/interchain-security/v3/x/ccv/provider/types" +) + +const ( + AppName = "interchain-security-p" + upgradeName = "ics-v1-to-v2" +) + +// this line is used by starport scaffolding # stargate/wasm/app/enabledProposals + +var ( + // DefaultNodeHome default home directories for the application daemon + DefaultNodeHome string + + // ModuleBasics defines the module BasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration + // and genesis verification. + ModuleBasics = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distr.AppModuleBasic{}, + gov.NewAppModuleBasic( + []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + icsproviderclient.ConsumerAdditionProposalHandler, + icsproviderclient.ConsumerRemovalProposalHandler, + icsproviderclient.ChangeRewardDenomsProposalHandler, + }, + ), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + ibc.AppModuleBasic{}, + ibctm.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, + vesting.AppModuleBasic{}, + // router.AppModuleBasic{}, + icsprovider.AppModuleBasic{}, + ) + + // module account permissions + maccPerms = map[string][]string{ + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + providertypes.ConsumerRewardsPool: nil, + } +) + +var ( + _ runtime.AppI = (*App)(nil) + _ servertypes.Application = (*App)(nil) + _ ibctesting.TestingApp = (*App)(nil) +) + +// App extends an ABCI application, but with most of its parameters exported. +// They are exported for convenience in creating helper functions, as object +// capabilities aren't needed for testing. +type App struct { // nolint: golint + *baseapp.BaseApp + legacyAmino *codec.LegacyAmino + appCodec codec.Codec + interfaceRegistry types.InterfaceRegistry + txConfig client.TxConfig + + // keys to access the substores + keys map[string]*storetypes.KVStoreKey + tkeys map[string]*storetypes.TransientStoreKey + + memKeys map[string]*storetypes.MemoryStoreKey + + // keepers + AccountKeeper authkeeper.AccountKeeper + BankKeeper bankkeeper.Keeper + CapabilityKeeper *capabilitykeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.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 + DistrKeeper distrkeeper.Keeper + + GovKeeper govkeeper.Keeper + CrisisKeeper crisiskeeper.Keeper + UpgradeKeeper upgradekeeper.Keeper + ParamsKeeper paramskeeper.Keeper + IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + EvidenceKeeper evidencekeeper.Keeper + TransferKeeper ibctransferkeeper.Keeper + ProviderKeeper icsproviderkeeper.Keeper + ConsensusParamsKeeper consensusparamkeeper.Keeper + + // make scoped keepers public for test purposes + ScopedIBCKeeper capabilitykeeper.ScopedKeeper + ScopedTransferKeeper capabilitykeeper.ScopedKeeper + ScopedIBCProviderKeeper capabilitykeeper.ScopedKeeper + + // the module manager + MM *module.Manager + + // simulation manager + sm *module.SimulationManager + configurator module.Configurator +} + +func init() { + userHomeDir, err := os.UserHomeDir() + if err != nil { + panic(fmt.Sprintf("Failed to get home dir %v", err)) + } + + DefaultNodeHome = filepath.Join(userHomeDir, "."+AppName) +} + +// New returns a reference to an initialized App. +func New( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + loadLatest bool, + appOpts servertypes.AppOptions, + baseAppOptions ...func(*baseapp.BaseApp), +) *App { + encodingConfig := makeEncodingConfig() + + interfaceRegistry := encodingConfig.InterfaceRegistry + appCodec := encodingConfig.Codec + legacyAmino := encodingConfig.Amino + txConfig := encodingConfig.TxConfig + 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, txConfig.TxDecoder(), baseAppOptions...) + bApp.SetCommitMultiStoreTracer(traceStore) + bApp.SetVersion(version.Version) + bApp.SetInterfaceRegistry(interfaceRegistry) + bApp.SetTxEncoder(txConfig.TxEncoder()) + + keys := storetypes.NewKVStoreKeys( + authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, crisistypes.StoreKey, + minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, + govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, + evidencetypes.StoreKey, ibctransfertypes.StoreKey, + capabilitytypes.StoreKey, + providertypes.StoreKey, + consensusparamtypes.StoreKey, + ) + + // 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, + legacyAmino: legacyAmino, + appCodec: appCodec, + interfaceRegistry: interfaceRegistry, + keys: keys, + tkeys: tkeys, + memKeys: memKeys, + txConfig: txConfig, + } + + app.ParamsKeeper = initParamsKeeper( + appCodec, + legacyAmino, + keys[paramstypes.StoreKey], + tkeys[paramstypes.TStoreKey], + ) + + // 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, + 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( + appCodec, + keys[capabilitytypes.StoreKey], + memKeys[capabilitytypes.MemStoreKey], + ) + scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) + scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + scopedIBCProviderKeeper := app.CapabilityKeeper.ScopeToModule(providertypes.ModuleName) + app.CapabilityKeeper.Seal() + + // add keepers + app.AccountKeeper = authkeeper.NewAccountKeeper( + appCodec, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + maccPerms, + authcodec.NewBech32Codec(sdk.Bech32MainPrefix), + sdk.Bech32MainPrefix, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // Remove the ConsumerRewardsPool from the group of blocked recipient addresses in bank + // this is required for the provider chain to be able to receive tokens from + // the consumer chain + bankBlockedAddrs := app.ModuleAccountAddrs() + delete(bankBlockedAddrs, authtypes.NewModuleAddress( + providertypes.ConsumerRewardsPool).String()) + + app.BankKeeper = bankkeeper.NewBaseKeeper( + appCodec, + runtime.NewKVStoreService(keys[banktypes.StoreKey]), + app.AccountKeeper, + bankBlockedAddrs, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + logger, + ) + + // optional: enable sign mode textual by overwriting the default tx config (after setting the bank keeper) + enabledSignModes := append(tx.DefaultSignModes, sigtypes.SignMode_SIGN_MODE_TEXTUAL) + txConfigOpts := tx.ConfigOptions{ + EnabledSignModes: enabledSignModes, + TextualCoinMetadataQueryFn: txmodule.NewBankKeeperCoinMetadataQueryFn(app.BankKeeper), + } + txConfig, err := tx.NewTxConfigWithOptions( + appCodec, + txConfigOpts, + ) + if err != nil { + panic(err) + } + app.txConfig = txConfig + + app.StakingKeeper = stakingkeeper.NewKeeper( + appCodec, + 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, + runtime.NewKVStoreService(keys[minttypes.StoreKey]), + app.StakingKeeper, + app.AccountKeeper, + app.BankKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + app.DistrKeeper = distrkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[distrtypes.StoreKey]), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + app.SlashingKeeper = slashingkeeper.NewKeeper( + appCodec, + legacyAmino, + runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), + app.StakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) + app.CrisisKeeper = *crisiskeeper.NewKeeper( + appCodec, + 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)) { + skipUpgradeHeights[int64(h)] = true + } + homePath := cast.ToString(appOpts.Get(flags.FlagHome)) + // set the governance module account as the authority for conducting upgrades + app.UpgradeKeeper = *upgradekeeper.NewKeeper( + skipUpgradeHeights, + runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), + appCodec, + homePath, + app.BaseApp, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.StakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks( + app.DistrKeeper.Hooks(), + app.SlashingKeeper.Hooks(), + app.ProviderKeeper.Hooks(), + ), + ) + + app.IBCKeeper = ibckeeper.NewKeeper( + appCodec, + keys[ibcexported.StoreKey], + app.GetSubspace(ibcexported.ModuleName), + app.StakingKeeper, + app.UpgradeKeeper, + scopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + app.ProviderKeeper = icsproviderkeeper.NewKeeper( + appCodec, + keys[providertypes.StoreKey], + app.GetSubspace(providertypes.ModuleName), + scopedIBCProviderKeeper, + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.PortKeeper, + app.IBCKeeper.ConnectionKeeper, + app.IBCKeeper.ClientKeeper, + app.StakingKeeper, + app.SlashingKeeper, + app.AccountKeeper, + app.DistrKeeper, + app.BankKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), + authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), + ) + + providerModule := icsprovider.NewAppModule(&app.ProviderKeeper, app.GetSubspace(providertypes.ModuleName)) + + // create evidence keeper with router + app.EvidenceKeeper = *evidencekeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), + app.StakingKeeper, + app.SlashingKeeper, + app.AccountKeeper.AddressCodec(), + runtime.ProvideCometInfoService(), + ) + + // register the proposal types + govRouter := govv1beta1.NewRouter() + govRouter. + AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). + // NOTE: @MSalopek -> remove NewSoftwareUpgradeProposalHandler + // AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.UpgradeKeeper)). + AddRoute(providertypes.RouterKey, icsprovider.NewProviderProposalHandler(app.ProviderKeeper)) + govConfig := govtypes.DefaultConfig() + + app.GovKeeper = *govkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[govtypes.StoreKey]), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.DistrKeeper, + app.MsgServiceRouter(), + govConfig, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // Set legacy router for backwards compatibility with gov v1beta1 + app.GovKeeper.SetLegacyRouter(govRouter) + + app.TransferKeeper = ibctransferkeeper.NewKeeper( + appCodec, + keys[ibctransfertypes.StoreKey], + app.GetSubspace(ibctransfertypes.ModuleName), + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.ChannelKeeper, + app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + scopedTransferKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + transferModule := transfer.NewAppModule(app.TransferKeeper) + ibcmodule := transfer.NewIBCModule(app.TransferKeeper) + + // create static IBC router, add transfer route, then set and seal it + ibcRouter := porttypes.NewRouter() + ibcRouter.AddRoute(ibctransfertypes.ModuleName, ibcmodule) + ibcRouter.AddRoute(providertypes.ModuleName, providerModule) + app.IBCKeeper.SetRouter(ibcRouter) + + skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) + + // NOTE: Any module instantiated in the module manager that is later modified + // must be passed by reference here. + app.MM = module.NewManager( + genutil.NewAppModule( + app.AccountKeeper, + app.StakingKeeper, + app, + txConfig, + ), + auth.NewAppModule(appCodec, app.AccountKeeper, nil, app.GetSubspace(authtypes.ModuleName)), + vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), + 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)), + 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), 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, 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 + // NOTE: @MSalopek -> this may affect testing + ModuleBasics = module.NewBasicManagerFromManager( + app.MM, + map[string]module.AppModuleBasic{ + genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + govtypes.ModuleName: gov.NewAppModuleBasic( + []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + icsproviderclient.ConsumerAdditionProposalHandler, + icsproviderclient.ConsumerRemovalProposalHandler, + icsproviderclient.ChangeRewardDenomsProposalHandler, + }, + ), + }) + ModuleBasics.RegisterLegacyAminoCodec(legacyAmino) + ModuleBasics.RegisterInterfaces(interfaceRegistry) + + 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. + // NOTE: staking module is required if HistoricalEntries param > 0 + // 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, + govtypes.ModuleName, + stakingtypes.ModuleName, + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + paramstypes.ModuleName, + vestingtypes.ModuleName, + providertypes.ModuleName, + ) + + app.MM.SetOrderEndBlockers( + crisistypes.ModuleName, + govtypes.ModuleName, + stakingtypes.ModuleName, + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + providertypes.ModuleName, + ) + + // NOTE: The genutils module must occur after staking so that pools are + // properly initialized with tokens from genesis accounts. + // NOTE: The genutils module must also occur after auth so that it can access the params from auth. + // NOTE: Capability module must occur first so that it can initialize any capabilities + // so that other modules that want to create or claim capabilities afterwards in InitChain + // can do so safely. + app.MM.SetOrderInitGenesis( + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + stakingtypes.ModuleName, + slashingtypes.ModuleName, + govtypes.ModuleName, + minttypes.ModuleName, + crisistypes.ModuleName, + ibcexported.ModuleName, + evidencetypes.ModuleName, + ibctransfertypes.ModuleName, + genutiltypes.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + providertypes.ModuleName, + ) + + app.MM.RegisterInvariants(&app.CrisisKeeper) + app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) + err = app.MM.RegisterServices(app.configurator) + if err != nil { + panic(err) + } + + // 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 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) + + for moduleName := range app.MM.Modules { + m := app.MM.Modules[moduleName] + if module, ok := m.(module.HasConsensusVersion); ok { + fromVM[moduleName] = module.ConsensusVersion() + } + } + + app.Logger().Info("start to run module migrations...") + + return app.MM.RunMigrations(ctx, app.configurator, fromVM) + }, + ) + + upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { + panic(fmt.Sprintf("failed to read upgrade info from disk %s", err)) + } + + if upgradeInfo.Name == upgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + storeUpgrades := storetypes.StoreUpgrades{} + + // configure store loader that checks if version == upgradeHeight and applies store upgrades + 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: encodingConfig.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)) + } + } + + app.ScopedIBCKeeper = scopedIBCKeeper + app.ScopedTransferKeeper = scopedTransferKeeper + app.ScopedIBCProviderKeeper = scopedIBCProviderKeeper + + 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) (sdk.BeginBlock, error) { + return app.MM.BeginBlock(ctx) +} + +// EndBlocker application updates every end block +func (app *App) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { + return app.MM.EndBlock(ctx) +} + +// Configurator returns the configurator for the app +func (app *App) Configurator() module.Configurator { + return app.configurator +} + +// InitChainer application update at chain initialization +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) + } + + app.UpgradeKeeper.SetModuleVersionMap(ctx, app.MM.GetVersionMap()) + + return app.MM.InitGenesis(ctx, app.appCodec, genesisState) +} + +// LoadHeight loads a particular height +func (app *App) LoadHeight(height int64) error { + return app.LoadVersion(height) +} + +func (app *App) setPostHandler() { + postHandler, err := posthandler.NewPostHandler( + posthandler.HandlerOptions{}, + ) + if err != nil { + panic(err) + } + + app.SetPostHandler(postHandler) +} + +// ModuleAccountAddrs returns all the app's module account addresses. +func (app *App) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range maccPerms { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + +// LegacyAmino returns App's amino codec. +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *App) LegacyAmino() *codec.LegacyAmino { + return app.legacyAmino +} + +// AppCodec returns the app codec. +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *App) AppCodec() codec.Codec { + return app.appCodec +} + +// InterfaceRegistry returns the InterfaceRegistry +func (app *App) InterfaceRegistry() types.InterfaceRegistry { + return app.interfaceRegistry +} + +// GetKey returns the KVStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *App) GetKey(storeKey string) *storetypes.KVStoreKey { + return app.keys[storeKey] +} + +// GetTKey returns the TransientStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *App) GetTKey(storeKey string) *storetypes.TransientStoreKey { + return app.tkeys[storeKey] +} + +// GetMemKey returns the MemStoreKey for the provided mem key. +// +// NOTE: This is solely used for testing purposes. +func (app *App) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { + return app.memKeys[storeKey] +} + +// GetSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *App) GetSubspace(moduleName string) paramstypes.Subspace { + subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + return subspace +} + +// SimulationManager implements the SimulationApp interface +func (app *App) SimulationManager() *module.SimulationManager { + return app.sm +} + +// ProviderApp interface implementations for integration tests + +// GetProviderKeeper implements the ProviderApp interface. +func (app *App) GetProviderKeeper() icsproviderkeeper.Keeper { + return app.ProviderKeeper +} + +// GetTestStakingKeeper implements the ProviderApp interface. +func (app *App) GetTestStakingKeeper() testutil.TestStakingKeeper { + return app.StakingKeeper +} + +// GetTestBankKeeper implements the ProviderApp interface. +func (app *App) GetTestBankKeeper() testutil.TestBankKeeper { + return app.BankKeeper +} + +// GetTestSlashingKeeper implements the ProviderApp interface. +func (app *App) GetTestSlashingKeeper() testutil.TestSlashingKeeper { + return app.SlashingKeeper +} + +// GetTestDistributionKeeper implements the ProviderApp interface. +func (app *App) GetTestDistributionKeeper() testutil.TestDistributionKeeper { + return app.DistrKeeper +} + +// GetTestAccountKeeper implements the ProviderApp interface. +func (app *App) GetTestAccountKeeper() testutil.TestAccountKeeper { + return app.AccountKeeper +} + +// TestingApp functions + +// GetBaseApp implements the TestingApp interface. +func (app *App) GetBaseApp() *baseapp.BaseApp { + return app.BaseApp +} + +// GetStakingKeeper implements the TestingApp interface. +func (app *App) GetStakingKeeper() ibctestingtypes.StakingKeeper { + return app.StakingKeeper +} + +// GetIBCKeeper implements the TestingApp interface. +func (app *App) GetIBCKeeper() *ibckeeper.Keeper { + return app.IBCKeeper +} + +// GetScopedIBCKeeper implements the TestingApp interface. +func (app *App) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { + return app.ScopedIBCKeeper +} + +// GetTxConfig implements the TestingApp interface. +func (app *App) GetTxConfig() client.TxConfig { + return app.txConfig +} + +// TxConfig returns SimApp's TxConfig +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) { + clientCtx := apiSvr.ClientCtx + // Register new tx routes from grpc-gateway. + authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register new tendermint queries routes from grpc-gateway. + cmtservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register node gRPC service for grpc-gateway. + nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register legacy and grpc-gateway routes for all modules. + ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // register swagger API from root so that other applications can override easily + if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { + panic(err) + } +} + +// RegisterTxService implements the Application.RegisterTxService method. +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, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter(), cfg) +} + +// RegisterTendermintService implements the Application.RegisterTendermintService method. +func (app *App) RegisterTendermintService(clientCtx client.Context) { + cmtApp := server.NewCometABCIWrapper(app) + cmtservice.RegisterTendermintService(clientCtx, app.BaseApp.GRPCQueryRouter(), app.interfaceRegistry, cmtApp.Query) +} + +// GetMaccPerms returns a copy of the module account permissions +func GetMaccPerms() map[string][]string { + dupMaccPerms := make(map[string][]string) + for k, v := range maccPerms { + dupMaccPerms[k] = v + } + return dupMaccPerms +} + +// initParamsKeeper init params keeper and its subspaces +func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { + paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) + + paramsKeeper.Subspace(authtypes.ModuleName) + paramsKeeper.Subspace(banktypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName) + paramsKeeper.Subspace(minttypes.ModuleName) + paramsKeeper.Subspace(distrtypes.ModuleName) + paramsKeeper.Subspace(slashingtypes.ModuleName) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(gov.ProvideKeyTable()) + paramsKeeper.Subspace(crisistypes.ModuleName) + paramsKeeper.Subspace(ibctransfertypes.ModuleName) + paramsKeeper.Subspace(ibcexported.ModuleName) + paramsKeeper.Subspace(providertypes.ModuleName) + + return paramsKeeper +} + +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 makeEncodingConfig() appparams.EncodingConfig { + encodingConfig := appparams.MakeTestEncodingConfig() + // std.RegisterLegacyAminoCodec(encodingConfig.Amino) + // std.RegisterInterfaces(encodingConfig.InterfaceRegistry) + return encodingConfig +} diff --git a/app/provider/export.go b/app/provider/export.go index e58a86a4bf..eb4465d279 100644 --- a/app/provider/export.go +++ b/app/provider/export.go @@ -2,9 +2,13 @@ package app import ( "encoding/json" + "fmt" "log" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + 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" @@ -14,46 +18,42 @@ import ( // ExportAppStateAndValidators exports the state of the application for a genesis // file. -func (app *App) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs, modulesToExport []string, -) (servertypes.ExportedApp, error) { +func (app *SimApp) 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) + ctx := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()}) // We export at last height + 1, because that's the height at which - // Tendermint will start InitChain. + // CometBFT will start InitChain. height := app.LastBlockHeight() + 1 if forZeroHeight { height = 0 app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState, err := app.MM.ExportGenesis(ctx, app.appCodec) + genState, err := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) if err != nil { return servertypes.ExportedApp{}, err } + appState, err := json.MarshalIndent(genState, "", " ") if err != nil { return servertypes.ExportedApp{}, err } validators, err := staking.WriteValidators(ctx, app.StakingKeeper) - if err != nil { - return servertypes.ExportedApp{}, err - } return servertypes.ExportedApp{ AppState: appState, Validators: validators, Height: height, ConsensusParams: app.BaseApp.GetConsensusParams(ctx), - }, nil + }, err } // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // -// in favour of export at a block height -func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { +// in favor of export at a block height +func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false // check if there is a allowed address list @@ -77,18 +77,17 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str /* Handle fee distribution state. */ // withdraw all validator commission - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valAddrBech32, err := sdk.ValAddressFromHex(val.GetOperator()) - if err != nil { - panic(err) - } - - _, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrBech32) + err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) if err != nil { panic(err) } + _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, valBz) return false }) + if err != nil { + panic(err) + } // withdraw all delegator rewards dels, err := app.StakingKeeper.GetAllDelegations(ctx) @@ -97,20 +96,14 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str } for _, delegation := range dels { - // NOTE: @MSalopek this may be wrong - 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) + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { panic(err) } + + delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + + _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) } // clear validator slash events @@ -124,22 +117,26 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str ctx = ctx.WithBlockHeight(0) // reinitialize all validators - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + err = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) if err != nil { panic(err) } // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valAddr) + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz) + if err != nil { + panic(err) + } feePool, err := app.DistrKeeper.FeePool.Get(ctx) if err != nil { panic(err) } feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.FeePool.Set(ctx, feePool) + if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil { + panic(err) + } - err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valAddr) - if err != nil { + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil { panic(err) } return false @@ -147,23 +144,20 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // reinitialize all delegations for _, del := range dels { - // NOTE: @MSalopek this may be wrong - delAddr, err := app.AccountKeeper.AddressCodec().StringToBytes(del.GetDelegatorAddr()) + valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) if err != nil { panic(err) } - // NOTE: @MSalopek this may be wrong -> need validator addr codec - 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) + delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) + + if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + // never called as BeforeDelegationCreated always returns nil + panic(fmt.Errorf("error while incrementing period: %w", err)) } - err = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) - if err != nil { - panic(err) + + if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + // never called as AfterDelegationModified always returns nil + panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) } } @@ -177,7 +171,10 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for i := range red.Entries { red.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetRedelegation(ctx, red) + err = app.StakingKeeper.SetRedelegation(ctx, red) + if err != nil { + panic(err) + } return false }) @@ -186,18 +183,21 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + err = app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + if err != nil { + panic(err) + } return false }) // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. - store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) - iter := storetypes.KVStorePrefixIterator(store, stakingtypes.ValidatorsKey) + store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey)) + iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) counter := int16(0) for ; iter.Valid(); iter.Next() { - addr := sdk.ValAddress(iter.Key()[1:]) + addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) validator, err := app.StakingKeeper.GetValidator(ctx, addr) if err != nil { panic("expected validator, not found") @@ -213,11 +213,13 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str } if err := iter.Close(); err != nil { - panic(err) + app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err) + return } - if _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx); err != nil { - panic(err) + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + if err != nil { + log.Fatal(err) } /* Handle slashing state. */ diff --git a/app/provider/genesis.go b/app/provider/genesis.go index 5bf0c1da80..e4e849fc27 100644 --- a/app/provider/genesis.go +++ b/app/provider/genesis.go @@ -2,11 +2,9 @@ package app import ( "encoding/json" - - "github.com/cosmos/cosmos-sdk/codec" ) -// The genesis state of the blockchain is represented here as a map of raw json +// GenesisState of the blockchain is represented here as a map of raw json // messages key'd by a identifier string. // The identifier is used to determine which module genesis information belongs // to so it may be appropriately routed during init chain. @@ -14,8 +12,3 @@ import ( // the ModuleBasicManager which populates json from each BasicModule // object provided to it during init. type GenesisState map[string]json.RawMessage - -// NewDefaultGenesisState generates the default state for the application. -func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { - return ModuleBasics.DefaultGenesis(cdc) -} diff --git a/cmd/interchain-security-pd/cmd/root.go b/cmd/interchain-security-pd/cmd/root.go index f781b445ce..f64fa623c9 100644 --- a/cmd/interchain-security-pd/cmd/root.go +++ b/cmd/interchain-security-pd/cmd/root.go @@ -2,15 +2,25 @@ package cmd import ( "errors" - "fmt" "io" "os" + "cosmossdk.io/log" + confixcmd "cosmossdk.io/tools/confix/cmd" + + "github.com/cosmos/interchain-security/v3/app/params" + + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" "github.com/spf13/viper" - "cosmossdk.io/client/v2/autocli" - confixcmd "cosmossdk.io/tools/confix/cmd" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" @@ -18,27 +28,20 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/pruning" "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/codec" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/client/snapshot" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" - serverconfig "github.com/cosmos/cosmos-sdk/server/config" - servertypes "github.com/cosmos/cosmos-sdk/server/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/tx/signing" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/crisis" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "cosmossdk.io/log" cmtcfg "github.com/cometbft/cometbft/config" - dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/interchain-security/v3/app/params" providerApp "github.com/cosmos/interchain-security/v3/app/provider" ) @@ -46,6 +49,7 @@ import ( // main function. func NewRootCmd() *cobra.Command { // we "pre"-instantiate the application for getting the injected/configured encoding configuration + // note, this is not necessary when using app wiring, as depinject can be directly used (see root_v2.go) tempApp := providerApp.New(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(tempDir())) encodingConfig := params.EncodingConfig{ InterfaceRegistry: tempApp.InterfaceRegistry(), @@ -57,6 +61,7 @@ func NewRootCmd() *cobra.Command { initClientCtx := client.Context{}. WithCodec(encodingConfig.Codec). WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithTxConfig(encodingConfig.TxConfig). WithLegacyAmino(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). @@ -73,35 +78,34 @@ func NewRootCmd() *cobra.Command { cmd.SetErr(cmd.ErrOrStderr()) initClientCtx = initClientCtx.WithCmdContext(cmd.Context()) - fmt.Println("## INIT ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags()) if err != nil { return err } - fmt.Println("## AFTER ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) + initClientCtx, err = config.ReadFromClientConfig(initClientCtx) if err != nil { return err } - fmt.Println("## AFTER 2 ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) - fmt.Println("TX CONFIG", initClientCtx) // This needs to go after ReadFromClientConfig, as that function // sets the RPC client needed for SIGN_MODE_TEXTUAL. This sign mode // is only available if the client is online. if !initClientCtx.Offline { + enabledSignModes := append(tx.DefaultSignModes, signing.SignMode_SIGN_MODE_TEXTUAL) txConfigOpts := tx.ConfigOptions{ - EnabledSignModes: append(tx.DefaultSignModes, signing.SignMode_SIGN_MODE_TEXTUAL), + EnabledSignModes: enabledSignModes, TextualCoinMetadataQueryFn: txmodule.NewGRPCCoinMetadataQueryFn(initClientCtx), } - txConfigWithTextual, err := tx.NewTxConfigWithOptions( - codec.NewProtoCodec(encodingConfig.InterfaceRegistry), + txConfig, err := tx.NewTxConfigWithOptions( + initClientCtx.Codec, txConfigOpts, ) if err != nil { return err } - initClientCtx = initClientCtx.WithTxConfig(txConfigWithTextual) + + initClientCtx = initClientCtx.WithTxConfig(txConfig) } if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { @@ -115,11 +119,13 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, encodingConfig) - autoCliOpts, err := enrichAutoCliOpts(tempApp.AutoCliOpts(), initClientCtx) - if err != nil { - panic(err) - } + initRootCmd(rootCmd, encodingConfig.TxConfig, encodingConfig.InterfaceRegistry, encodingConfig.Codec, tempApp.BasicModuleManager) + + // add keyring to autocli opts + autoCliOpts := tempApp.AutoCliOpts() + initClientCtx, _ = config.ReadFromClientConfig(initClientCtx) + autoCliOpts.Keyring, _ = keyring.NewAutoCLIKeyring(initClientCtx.Keyring) + autoCliOpts.ClientCtx = initClientCtx if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) @@ -128,29 +134,6 @@ func NewRootCmd() *cobra.Command { return rootCmd } -func enrichAutoCliOpts(autoCliOpts autocli.AppOptions, clientCtx client.Context) (autocli.AppOptions, error) { - autoCliOpts.AddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()) - autoCliOpts.ValidatorAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()) - autoCliOpts.ConsensusAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()) - - var err error - clientCtx, err = config.ReadFromClientConfig(clientCtx) - if err != nil { - return autocli.AppOptions{}, err - } - - autoCliOpts.ClientCtx = clientCtx - autoCliOpts.Keyring, err = keyring.NewAutoCLIKeyring(clientCtx.Keyring) - s, err := autoCliOpts.Keyring.List() - d, err := clientCtx.Keyring.List() - fmt.Println("# USING KEYRING #", s, err, "D", d, err) - if err != nil { - return autocli.AppOptions{}, err - } - - return autoCliOpts, nil -} - // initCometBFTConfig helps to override default CometBFT Config values. // return cmtcfg.DefaultConfig if no custom configuration is required for the application. func initCometBFTConfig() *cmtcfg.Config { @@ -178,7 +161,7 @@ func initAppConfig() (string, interface{}) { } type CustomAppConfig struct { - serverconfig.Config + serverconfig.Config `mapstructure:",squash"` WASM WASMConfig `mapstructure:"wasm"` } @@ -212,24 +195,30 @@ func initAppConfig() (string, interface{}) { customAppTemplate := serverconfig.DefaultConfigTemplate + ` [wasm] # This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries -query_gas_limit = 300000 +query_gas_limit = {{ .WASM.QueryGasLimit }} # This is the number of wasm vm instances we keep cached in memory for speed-up # Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally -lru_size = 0` +lru_size = {{ .WASM.LruSize }}` return customAppTemplate, customAppConfig } -func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { +func initRootCmd( + rootCmd *cobra.Command, + txConfig client.TxConfig, + interfaceRegistry codectypes.InterfaceRegistry, + appCodec codec.Codec, + basicManager module.BasicManager, +) { cfg := sdk.GetConfig() cfg.Seal() rootCmd.AddCommand( - genutilcli.InitCmd(providerApp.ModuleBasics, providerApp.DefaultNodeHome), + genutilcli.InitCmd(basicManager, providerApp.DefaultNodeHome), debug.Cmd(), - pruning.Cmd(newApp, providerApp.DefaultNodeHome), confixcmd.ConfigCommand(), - server.QueryBlockResultsCmd(), + pruning.Cmd(newApp, providerApp.DefaultNodeHome), + snapshot.Cmd(newApp), ) server.AddCommands(rootCmd, providerApp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) @@ -237,9 +226,9 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( server.StatusCommand(), - genesisCommand(encodingConfig), - txCommand(), + genesisCommand(txConfig, basicManager), queryCommand(), + txCommand(), keys.Commands(), ) } @@ -248,6 +237,16 @@ func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) } +// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter +func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.Commands(txConfig, basicManager, providerApp.DefaultNodeHome) + + for _, subCmd := range cmds { + cmd.AddCommand(subCmd) + } + return cmd +} + func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", @@ -259,12 +258,12 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - rpc.ValidatorCommand(), + rpc.QueryEventForTxCmd(), server.QueryBlockCmd(), authcmd.QueryTxsByEventsCmd(), server.QueryBlocksCmd(), authcmd.QueryTxCmd(), - authcmd.GetSimulateCmd(), + server.QueryBlockResultsCmd(), ) return cmd @@ -294,16 +293,6 @@ func txCommand() *cobra.Command { return cmd } -// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(encodingConfig params.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, providerApp.ModuleBasics, providerApp.DefaultNodeHome) - for _, sub_cmd := range cmds { - cmd.AddCommand(sub_cmd) - } - return cmd -} - -// newApp is an appCreator // newApp creates the application func newApp( logger log.Logger, @@ -331,8 +320,6 @@ func appExport( appOpts servertypes.AppOptions, modulesToExport []string, ) (servertypes.ExportedApp, error) { - var simApp *providerApp.App - // this check is necessary as we use the flag in x/upgrade. // we can exit more gracefully by checking the flag here. homePath, ok := appOpts.Get(flags.FlagHome).(string) @@ -349,6 +336,7 @@ func appExport( viperAppOpts.Set(server.FlagInvCheckPeriod, 1) appOpts = viperAppOpts + var simApp *providerApp.SimApp if height != -1 { simApp = providerApp.New(logger, db, traceStore, false, appOpts) @@ -363,8 +351,7 @@ func appExport( } var tempDir = func() string { - fmt.Println("## CALLED ##") - dir, err := os.MkdirTemp("", "."+providerApp.AppName) + dir, err := os.MkdirTemp("", "simapp") if err != nil { dir = providerApp.DefaultNodeHome } diff --git a/cmd/interchain-security-pd/cmd/root.gold b/cmd/interchain-security-pd/cmd/root.gold new file mode 100644 index 0000000000..f781b445ce --- /dev/null +++ b/cmd/interchain-security-pd/cmd/root.gold @@ -0,0 +1,374 @@ +package cmd + +import ( + "errors" + "fmt" + "io" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "cosmossdk.io/client/v2/autocli" + 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" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/pruning" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/codec" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/server" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/x/auth/tx" + txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" + "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/crisis" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + + "cosmossdk.io/log" + cmtcfg "github.com/cometbft/cometbft/config" + dbm "github.com/cosmos/cosmos-db" + + "github.com/cosmos/interchain-security/v3/app/params" + providerApp "github.com/cosmos/interchain-security/v3/app/provider" +) + +// NewRootCmd creates a new root command for simd. It is called once in the +// main function. +func NewRootCmd() *cobra.Command { + // we "pre"-instantiate the application for getting the injected/configured encoding configuration + tempApp := providerApp.New(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(tempDir())) + encodingConfig := params.EncodingConfig{ + InterfaceRegistry: tempApp.InterfaceRegistry(), + Codec: tempApp.AppCodec(), + TxConfig: tempApp.TxConfig(), + Amino: tempApp.LegacyAmino(), + } + + initClientCtx := client.Context{}. + WithCodec(encodingConfig.Codec). + WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithLegacyAmino(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}). + WithHomeDir(providerApp.DefaultNodeHome). + WithViper("") // In simapp, we don't use any prefix for env variables. + + rootCmd := &cobra.Command{ + Use: "simd", + Short: "simulation app", + SilenceErrors: true, + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + // set the default command outputs + cmd.SetOut(cmd.OutOrStdout()) + cmd.SetErr(cmd.ErrOrStderr()) + + initClientCtx = initClientCtx.WithCmdContext(cmd.Context()) + fmt.Println("## INIT ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) + initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags()) + if err != nil { + return err + } + fmt.Println("## AFTER ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) + initClientCtx, err = config.ReadFromClientConfig(initClientCtx) + if err != nil { + return err + } + fmt.Println("## AFTER 2 ##", initClientCtx.KeyringDir, initClientCtx.HomeDir) + fmt.Println("TX CONFIG", initClientCtx) + + // This needs to go after ReadFromClientConfig, as that function + // sets the RPC client needed for SIGN_MODE_TEXTUAL. This sign mode + // is only available if the client is online. + if !initClientCtx.Offline { + txConfigOpts := tx.ConfigOptions{ + EnabledSignModes: append(tx.DefaultSignModes, signing.SignMode_SIGN_MODE_TEXTUAL), + TextualCoinMetadataQueryFn: txmodule.NewGRPCCoinMetadataQueryFn(initClientCtx), + } + txConfigWithTextual, err := tx.NewTxConfigWithOptions( + codec.NewProtoCodec(encodingConfig.InterfaceRegistry), + txConfigOpts, + ) + if err != nil { + return err + } + initClientCtx = initClientCtx.WithTxConfig(txConfigWithTextual) + } + + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { + return err + } + + customAppTemplate, customAppConfig := initAppConfig() + customCMTConfig := initCometBFTConfig() + + return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig) + }, + } + + initRootCmd(rootCmd, encodingConfig) + autoCliOpts, err := enrichAutoCliOpts(tempApp.AutoCliOpts(), initClientCtx) + if err != nil { + panic(err) + } + + if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { + panic(err) + } + + return rootCmd +} + +func enrichAutoCliOpts(autoCliOpts autocli.AppOptions, clientCtx client.Context) (autocli.AppOptions, error) { + autoCliOpts.AddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()) + autoCliOpts.ValidatorAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()) + autoCliOpts.ConsensusAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()) + + var err error + clientCtx, err = config.ReadFromClientConfig(clientCtx) + if err != nil { + return autocli.AppOptions{}, err + } + + autoCliOpts.ClientCtx = clientCtx + autoCliOpts.Keyring, err = keyring.NewAutoCLIKeyring(clientCtx.Keyring) + s, err := autoCliOpts.Keyring.List() + d, err := clientCtx.Keyring.List() + fmt.Println("# USING KEYRING #", s, err, "D", d, err) + if err != nil { + return autocli.AppOptions{}, err + } + + return autoCliOpts, nil +} + +// initCometBFTConfig helps to override default CometBFT Config values. +// return cmtcfg.DefaultConfig if no custom configuration is required for the application. +func initCometBFTConfig() *cmtcfg.Config { + cfg := cmtcfg.DefaultConfig() + + // these values put a higher strain on node memory + // cfg.P2P.MaxNumInboundPeers = 100 + // cfg.P2P.MaxNumOutboundPeers = 40 + + return cfg +} + +// initAppConfig helps to override default appConfig template and configs. +// return "", nil if no custom configuration is required for the application. +func initAppConfig() (string, interface{}) { + // The following code snippet is just for reference. + + // WASMConfig defines configuration for the wasm module. + type WASMConfig struct { + // This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries + QueryGasLimit uint64 `mapstructure:"query_gas_limit"` + + // Address defines the gRPC-web server to listen on + LruSize uint64 `mapstructure:"lru_size"` + } + + type CustomAppConfig struct { + serverconfig.Config + + WASM WASMConfig `mapstructure:"wasm"` + } + + // Optionally allow the chain developer to overwrite the SDK's default + // server config. + srvCfg := serverconfig.DefaultConfig() + // The SDK's default minimum gas price is set to "" (empty value) inside + // app.toml. If left empty by validators, the node will halt on startup. + // However, the chain developer can set a default app.toml value for their + // validators here. + // + // In summary: + // - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their + // own app.toml config, + // - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their + // own app.toml to override, or use this default value. + // + // In simapp, we set the min gas prices to 0. + srvCfg.MinGasPrices = "0stake" + // srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default + + customAppConfig := CustomAppConfig{ + Config: *srvCfg, + WASM: WASMConfig{ + LruSize: 1, + QueryGasLimit: 300000, + }, + } + + customAppTemplate := serverconfig.DefaultConfigTemplate + ` +[wasm] +# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries +query_gas_limit = 300000 +# This is the number of wasm vm instances we keep cached in memory for speed-up +# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally +lru_size = 0` + + return customAppTemplate, customAppConfig +} + +func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { + cfg := sdk.GetConfig() + cfg.Seal() + + rootCmd.AddCommand( + genutilcli.InitCmd(providerApp.ModuleBasics, providerApp.DefaultNodeHome), + debug.Cmd(), + pruning.Cmd(newApp, providerApp.DefaultNodeHome), + confixcmd.ConfigCommand(), + server.QueryBlockResultsCmd(), + ) + + server.AddCommands(rootCmd, providerApp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) + + // add keybase, auxiliary RPC, query, genesis, and tx child commands + rootCmd.AddCommand( + server.StatusCommand(), + genesisCommand(encodingConfig), + txCommand(), + queryCommand(), + keys.Commands(), + ) +} + +func addModuleInitFlags(startCmd *cobra.Command) { + crisis.AddModuleInitFlags(startCmd) +} + +func queryCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: false, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + rpc.ValidatorCommand(), + server.QueryBlockCmd(), + authcmd.QueryTxsByEventsCmd(), + server.QueryBlocksCmd(), + authcmd.QueryTxCmd(), + authcmd.GetSimulateCmd(), + ) + + return cmd +} + +func txCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: false, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + authcmd.GetSimulateCmd(), + ) + + return cmd +} + +// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter +func genesisCommand(encodingConfig params.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, providerApp.ModuleBasics, providerApp.DefaultNodeHome) + for _, sub_cmd := range cmds { + cmd.AddCommand(sub_cmd) + } + return cmd +} + +// newApp is an appCreator +// newApp creates the application +func newApp( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + appOpts servertypes.AppOptions, +) servertypes.Application { + baseappOptions := server.DefaultBaseappOptions(appOpts) + + return providerApp.New( + logger, db, traceStore, true, + appOpts, + baseappOptions..., + ) +} + +// appExport creates a new simapp (optionally at a given height) and exports state. +func appExport( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + height int64, + forZeroHeight bool, + jailAllowedAddrs []string, + appOpts servertypes.AppOptions, + modulesToExport []string, +) (servertypes.ExportedApp, error) { + var simApp *providerApp.App + + // this check is necessary as we use the flag in x/upgrade. + // we can exit more gracefully by checking the flag here. + homePath, ok := appOpts.Get(flags.FlagHome).(string) + if !ok || homePath == "" { + return servertypes.ExportedApp{}, errors.New("application home not set") + } + + viperAppOpts, ok := appOpts.(*viper.Viper) + if !ok { + return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") + } + + // overwrite the FlagInvCheckPeriod + viperAppOpts.Set(server.FlagInvCheckPeriod, 1) + appOpts = viperAppOpts + + if height != -1 { + simApp = providerApp.New(logger, db, traceStore, false, appOpts) + + if err := simApp.LoadHeight(height); err != nil { + return servertypes.ExportedApp{}, err + } + } else { + simApp = providerApp.New(logger, db, traceStore, true, appOpts) + } + + return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) +} + +var tempDir = func() string { + fmt.Println("## CALLED ##") + dir, err := os.MkdirTemp("", "."+providerApp.AppName) + if err != nil { + dir = providerApp.DefaultNodeHome + } + defer os.RemoveAll(dir) + + return dir +}