diff --git a/baseapp/abci.go b/baseapp/abci.go index b3e3f76d52..3bdef31bfb 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -630,7 +630,7 @@ func (app *BaseApp) createQueryContext(height int64, prove bool) (sdk.Context, e // branch the commit-multistore for safety ctx := sdk.NewContext( - cacheMS, app.checkState.ctx.BlockHeader(), true, app.logger, + cacheMS, app.checkState.ctx.BlockHeader(), true, app.upgradeChecker, app.logger, ).WithMinGasPrices(app.minGasPrices).WithBlockHeight(height) return ctx, nil diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 448ef792fd..5e54b98b7a 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -12,6 +12,7 @@ import ( dbm "github.com/tendermint/tm-db" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/store/rootmulti" @@ -59,6 +60,9 @@ type BaseApp struct { // nolint: maligned abciData moduleRouter + appConfig serverconfig.Config + chainID string + // volatile states: // // checkState is set on InitChain and reset on Commit @@ -111,6 +115,9 @@ type BaseApp struct { // nolint: maligned // abciListeners for hooking into the ABCI message processing of the BaseApp // and exposing the requests and responses to external consumers abciListeners []ABCIListener + + // upgradeChecker is a hook function from the upgrade module to check upgrade is executed or not. + upgradeChecker func(ctx sdk.Context, name string) bool } type appStore struct { @@ -390,6 +397,14 @@ func (app *BaseApp) setIndexEvents(ie []string) { } } +func (app *BaseApp) setAppConfig(config serverconfig.Config) { + app.appConfig = config +} + +func (app *BaseApp) setChainID(chainID string) { + app.chainID = chainID +} + // Router returns the legacy router of the BaseApp. func (app *BaseApp) Router() sdk.Router { if app.sealed { @@ -418,7 +433,7 @@ func (app *BaseApp) setCheckState(header tmproto.Header) { ms := app.cms.CacheMultiStore() app.checkState = &state{ ms: ms, - ctx: sdk.NewContext(ms, header, true, app.logger).WithMinGasPrices(app.minGasPrices), + ctx: sdk.NewContext(ms, header, true, app.upgradeChecker, app.logger).WithMinGasPrices(app.minGasPrices), } } @@ -430,7 +445,7 @@ func (app *BaseApp) setDeliverState(header tmproto.Header) { ms := app.cms.CacheMultiStore() app.deliverState = &state{ ms: ms, - ctx: sdk.NewContext(ms, header, false, app.logger), + ctx: sdk.NewContext(ms, header, false, app.upgradeChecker, app.logger), } } @@ -467,6 +482,16 @@ func (app *BaseApp) GetConsensusParams(ctx sdk.Context) *abci.ConsensusParams { return cp } +// AppConfig returns the AppConfig. +func (app *BaseApp) AppConfig() serverconfig.Config { + return app.appConfig +} + +// ChainID returns the chain id. +func (app *BaseApp) ChainID() string { + return app.chainID +} + // AddRunTxRecoveryHandler adds custom app.runTx method panic handlers. func (app *BaseApp) AddRunTxRecoveryHandler(handlers ...RecoveryHandler) { for _, h := range handlers { @@ -557,7 +582,7 @@ func validateBasicTxMsgs(msgs []sdk.Msg) error { return nil } -// Returns the applications's deliverState if app is in runTxModeDeliver, +// GetState returns the applications's deliverState if app is in runTxModeDeliver, // otherwise it returns the application's checkstate. func (app *BaseApp) getState(mode runTxMode) *state { if mode == runTxModeDeliver { diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go index a3fbe8773a..72715d3b7b 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -66,7 +66,7 @@ func TestBaseApp_BlockGas(t *testing.T) { encCfg.InterfaceRegistry.RegisterImplementations((*sdk.Msg)(nil), &testdata.TestMsg{}, ) - app = simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, map[int64]bool{}, "", 0, encCfg, simapp.EmptyAppOptions{}, routerOpt) + app = simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, "", 0, encCfg, simapp.EmptyAppOptions{}, routerOpt) genState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.MarshalIndent(genState, "", " ") require.NoError(t, err) diff --git a/baseapp/options.go b/baseapp/options.go index ad8b7f9d5e..a94fda5aa5 100644 --- a/baseapp/options.go +++ b/baseapp/options.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/types" pruningtypes "github.com/cosmos/cosmos-sdk/pruning/types" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/snapshots" snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" "github.com/cosmos/cosmos-sdk/store" @@ -80,6 +81,16 @@ func SetSnapshot(snapshotStore *snapshots.Store, opts snapshottypes.SnapshotOpti return func(app *BaseApp) { app.SetSnapshot(snapshotStore, opts) } } +// SetAppConfig sets the server/config.Config. +func SetAppConfig(config serverconfig.Config) func(*BaseApp) { + return func(app *BaseApp) { app.setAppConfig(config) } +} + +// SetAppConfig sets the chain id. +func SetChainID(chainID string) func(*BaseApp) { + return func(app *BaseApp) { app.setChainID(chainID) } +} + func (app *BaseApp) SetName(name string) { if app.sealed { panic("SetName() on sealed BaseApp") @@ -243,3 +254,8 @@ func (app *BaseApp) SetStreamingService(s StreamingService) { // BaseApp will pass BeginBlock, DeliverTx, and EndBlock requests and responses to the streaming services to update their ABCI context app.abciListeners = append(app.abciListeners, s) } + +// SetUpgradeChecker is used to set a upgrade checker from the upgrade module +func (app *BaseApp) SetUpgradeChecker(checker func(sdk.Context, string) bool) { + app.upgradeChecker = checker +} diff --git a/baseapp/test_helpers.go b/baseapp/test_helpers.go index 6489595bc8..8e836e1067 100644 --- a/baseapp/test_helpers.go +++ b/baseapp/test_helpers.go @@ -39,15 +39,15 @@ func (app *BaseApp) SimDeliver(txEncoder sdk.TxEncoder, tx sdk.Tx) (sdk.GasInfo, // Context with current {check, deliver}State of the app used by tests. func (app *BaseApp) NewContext(isCheckTx bool, header tmproto.Header) sdk.Context { if isCheckTx { - return sdk.NewContext(app.checkState.ms, header, true, app.logger). + return sdk.NewContext(app.checkState.ms, header, true, app.upgradeChecker, app.logger). WithMinGasPrices(app.minGasPrices) } - return sdk.NewContext(app.deliverState.ms, header, false, app.logger) + return sdk.NewContext(app.deliverState.ms, header, false, app.upgradeChecker, app.logger) } func (app *BaseApp) NewUncachedContext(isCheckTx bool, header tmproto.Header) sdk.Context { - return sdk.NewContext(app.cms, header, isCheckTx, app.logger) + return sdk.NewContext(app.cms, header, isCheckTx, app.upgradeChecker, app.logger) } func (app *BaseApp) GetContextForDeliverTx(txBytes []byte) sdk.Context { diff --git a/client/pruning/main.go b/client/pruning/main.go index fb62dd21a0..7bdf1f107a 100644 --- a/client/pruning/main.go +++ b/client/pruning/main.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" pruningtypes "github.com/cosmos/cosmos-sdk/pruning/types" "github.com/cosmos/cosmos-sdk/server" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/store/rootmulti" "github.com/tendermint/tendermint/libs/log" @@ -62,7 +63,13 @@ func PruningCmd(appCreator servertypes.AppCreator) *cobra.Command { } logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - app := appCreator(logger, db, nil, vp) + + config, err := serverconfig.GetConfig(vp) + if err != nil { + return err + } + + app := appCreator(logger, db, nil, config, "", vp) cms := app.CommitMultiStore() rootMultiStore, ok := cms.(*rootmulti.Store) diff --git a/proto/cosmos/upgrade/v1beta1/query.proto b/proto/cosmos/upgrade/v1beta1/query.proto index 870cf9ee6b..1b041ad428 100644 --- a/proto/cosmos/upgrade/v1beta1/query.proto +++ b/proto/cosmos/upgrade/v1beta1/query.proto @@ -35,13 +35,6 @@ service Query { rpc ModuleVersions(QueryModuleVersionsRequest) returns (QueryModuleVersionsResponse) { option (google.api.http).get = "/cosmos/upgrade/v1beta1/module_versions"; } - - // Returns the account with authority to conduct upgrades - // - // Since: cosmos-sdk 0.46 - rpc Authority(QueryAuthorityRequest) returns (QueryAuthorityResponse) { - option (google.api.http).get = "/cosmos/upgrade/v1beta1/authority"; - } } // QueryCurrentPlanRequest is the request type for the Query/CurrentPlan RPC @@ -52,7 +45,7 @@ message QueryCurrentPlanRequest {} // method. message QueryCurrentPlanResponse { // plan is the current upgrade plan. - Plan plan = 1; + repeated Plan plan = 1; } // QueryCurrentPlanRequest is the request type for the Query/AppliedPlan RPC diff --git a/proto/cosmos/upgrade/v1beta1/tx.proto b/proto/cosmos/upgrade/v1beta1/tx.proto deleted file mode 100644 index 7a2931da21..0000000000 --- a/proto/cosmos/upgrade/v1beta1/tx.proto +++ /dev/null @@ -1,56 +0,0 @@ -// Since: cosmos-sdk 0.46 -syntax = "proto3"; -package cosmos.upgrade.v1beta1; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "cosmos/upgrade/v1beta1/upgrade.proto"; -import "cosmos/msg/v1/msg.proto"; - -option go_package = "github.com/cosmos/cosmos-sdk/x/upgrade/types"; - -// Msg defines the upgrade Msg service. -service Msg { - // SoftwareUpgrade is a governance operation for initiating a software upgrade. - // - // Since: cosmos-sdk 0.46 - rpc SoftwareUpgrade(MsgSoftwareUpgrade) returns (MsgSoftwareUpgradeResponse); - // CancelUpgrade is a governance operation for cancelling a previously - // approvid software upgrade. - // - // Since: cosmos-sdk 0.46 - rpc CancelUpgrade(MsgCancelUpgrade) returns (MsgCancelUpgradeResponse); -} - -// MsgSoftwareUpgrade is the Msg/SoftwareUpgrade request type. -// -// Since: cosmos-sdk 0.46 -message MsgSoftwareUpgrade { - option (cosmos.msg.v1.signer) = "authority"; - - // authority is the address of the governance account. - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // plan is the upgrade plan. - Plan plan = 2 [(gogoproto.nullable) = false]; -} - -// MsgSoftwareUpgradeResponse is the Msg/SoftwareUpgrade response type. -// -// Since: cosmos-sdk 0.46 -message MsgSoftwareUpgradeResponse {} - -// MsgCancelUpgrade is the Msg/CancelUpgrade request type. -// -// Since: cosmos-sdk 0.46 -message MsgCancelUpgrade { - option (cosmos.msg.v1.signer) = "authority"; - - // authority is the address of the governance account. - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// MsgCancelUpgradeResponse is the Msg/CancelUpgrade response type. -// -// Since: cosmos-sdk 0.46 -message MsgCancelUpgradeResponse {} diff --git a/proto/cosmos/upgrade/v1beta1/upgrade.proto b/proto/cosmos/upgrade/v1beta1/upgrade.proto index 4d19a29998..ec021ac2a8 100644 --- a/proto/cosmos/upgrade/v1beta1/upgrade.proto +++ b/proto/cosmos/upgrade/v1beta1/upgrade.proto @@ -1,10 +1,7 @@ syntax = "proto3"; package cosmos.upgrade.v1beta1; -import "google/protobuf/any.proto"; import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "cosmos_proto/cosmos.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/upgrade/types"; option (gogoproto.goproto_getters_all) = false; @@ -23,52 +20,13 @@ message Plan { // reached and the software will exit. string name = 1; - // Deprecated: Time based upgrades have been deprecated. Time based upgrade logic - // has been removed from the SDK. - // If this field is not empty, an error will be thrown. - google.protobuf.Timestamp time = 2 [deprecated = true, (gogoproto.stdtime) = true, (gogoproto.nullable) = false]; - // The height at which the upgrade must be performed. // Only used if Time is not set. - int64 height = 3; + int64 height = 2; // Any application specific upgrade info to be included on-chain // such as a git commit that validators could automatically upgrade to - string info = 4; - - // Deprecated: UpgradedClientState field has been deprecated. IBC upgrade logic has been - // moved to the IBC module in the sub module 02-client. - // If this field is not empty, an error will be thrown. - google.protobuf.Any upgraded_client_state = 5 [deprecated = true]; -} - -// SoftwareUpgradeProposal is a gov Content type for initiating a software -// upgrade. -// Deprecated: This legacy proposal is deprecated in favor of Msg-based gov -// proposals, see MsgSoftwareUpgrade. -message SoftwareUpgradeProposal { - option deprecated = true; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - option (gogoproto.equal) = true; - option (gogoproto.goproto_stringer) = false; - - string title = 1; - string description = 2; - Plan plan = 3 [(gogoproto.nullable) = false]; -} - -// CancelSoftwareUpgradeProposal is a gov Content type for cancelling a software -// upgrade. -// Deprecated: This legacy proposal is deprecated in favor of Msg-based gov -// proposals, see MsgCancelUpgrade. -message CancelSoftwareUpgradeProposal { - option deprecated = true; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - option (gogoproto.equal) = true; - option (gogoproto.goproto_stringer) = false; - - string title = 1; - string description = 2; + string info = 3; } // ModuleVersion specifies a module and its consensus version. diff --git a/server/config/config.go b/server/config/config.go index eb56824688..549626ae18 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -196,10 +196,18 @@ type StateSyncConfig struct { SnapshotKeepRecent uint32 `mapstructure:"snapshot-keep-recent"` } +// UpgradeConfig defines the upgrading configuration. +type UpgradeConfig struct { + Name string `mapstructure:"name"` + Height int64 `mapstructure:"height"` + Info string `mapstructure:"info"` +} + // Config defines the server's top level configuration type Config struct { BaseConfig `mapstructure:",squash"` + Upgrade []UpgradeConfig `mapstructure:"upgrade"` // Telemetry defines the application telemetry configuration Telemetry telemetry.Config `mapstructure:"telemetry"` API APIConfig `mapstructure:"api"` @@ -309,6 +317,8 @@ func GetConfig(v *viper.Viper) (Config, error) { } } + var upgrade []UpgradeConfig + v.UnmarshalKey("upgrade", &upgrade) return Config{ BaseConfig: BaseConfig{ MinGasPrices: v.GetString("minimum-gas-prices"), @@ -324,6 +334,7 @@ func GetConfig(v *viper.Viper) (Config, error) { IAVLDisableFastNode: v.GetBool("iavl-disable-fastnode"), AppDBBackend: v.GetString("app-db-backend"), }, + Upgrade: upgrade, Telemetry: telemetry.Config{ ServiceName: v.GetString("telemetry.service-name"), Enabled: v.GetBool("telemetry.enabled"), diff --git a/server/config/toml.go b/server/config/toml.go index 275914f8f5..8c9bc64731 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -84,6 +84,21 @@ iavl-disable-fastnode = {{ .BaseConfig.IAVLDisableFastNode }} # Second fallback (if the types.DBBackend also isn't set), is the db-backend value set in Tendermint's config.toml. app-db-backend = "{{ .BaseConfig.AppDBBackend }}" +############################################################################### +### Upgrade Configuration ### +############################################################################### + +# Example: +# [[upgrade]] +# name = "BEP111" +# height = 100 +# info = "https://github.com/bnb-chain/BEPs/pull/111" + +# [[upgrade]] +# name = "BEP112" +# height = 120 +# info = "https://github.com/bnb-chain/BEPs/pull/112" + ############################################################################### ### Telemetry Configuration ### ############################################################################### diff --git a/server/export_test.go b/server/export_test.go index 0bf955a257..34374d7337 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -129,7 +129,7 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *t logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) db := dbm.NewMemDB() encCfg := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(logger, db, nil, true, map[int64]bool{}, tempDir, 0, encCfg, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(logger, db, nil, true, tempDir, 0, encCfg, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") @@ -160,13 +160,13 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *t var simApp *simapp.SimApp if height != -1 { - simApp = simapp.NewSimApp(logger, db, nil, false, map[int64]bool{}, "", 0, encCfg, appOptons) + simApp = simapp.NewSimApp(logger, db, nil, false, "", 0, encCfg, appOptons) if err := simApp.LoadHeight(height); err != nil { return types.ExportedApp{}, err } } else { - simApp = simapp.NewSimApp(logger, db, nil, true, map[int64]bool{}, "", 0, encCfg, appOptons) + simApp = simapp.NewSimApp(logger, db, nil, true, "", 0, encCfg, appOptons) } return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) diff --git a/server/rollback.go b/server/rollback.go index c3dba33546..c30e2f6f58 100644 --- a/server/rollback.go +++ b/server/rollback.go @@ -4,9 +4,11 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/client/flags" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/server/types" "github.com/spf13/cobra" tmcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + "github.com/tendermint/tendermint/node" ) // NewRollbackCmd creates a command to rollback tendermint and multistore state by one height. @@ -30,7 +32,16 @@ application. if err != nil { return err } - app := appCreator(ctx.Logger, db, nil, ctx.Viper) + config, err := serverconfig.GetConfig(ctx.Viper) + if err != nil { + return err + } + genDocProvider := node.DefaultGenesisDocProviderFunc(ctx.Config) + genDoc, err := genDocProvider() + if err != nil { + return err + } + app := appCreator(ctx.Logger, db, nil, config, genDoc.ChainID, ctx.Viper) // rollback tendermint state height, hash, err := tmcmd.RollbackState(ctx.Config) if err != nil { diff --git a/server/start.go b/server/start.go index e61b96204c..b0536138a0 100644 --- a/server/start.go +++ b/server/start.go @@ -38,18 +38,17 @@ import ( const ( // Tendermint full-node start flags - flagWithTendermint = "with-tendermint" - flagAddress = "address" - flagTransport = "transport" - flagTraceStore = "trace-store" - flagCPUProfile = "cpu-profile" - FlagMinGasPrices = "minimum-gas-prices" - FlagHaltHeight = "halt-height" - FlagHaltTime = "halt-time" - FlagInterBlockCache = "inter-block-cache" - FlagUnsafeSkipUpgrades = "unsafe-skip-upgrades" - FlagTrace = "trace" - FlagInvCheckPeriod = "inv-check-period" + flagWithTendermint = "with-tendermint" + flagAddress = "address" + flagTransport = "transport" + flagTraceStore = "trace-store" + flagCPUProfile = "cpu-profile" + FlagMinGasPrices = "minimum-gas-prices" + FlagHaltHeight = "halt-height" + FlagHaltTime = "halt-time" + FlagInterBlockCache = "inter-block-cache" + FlagTrace = "trace" + FlagInvCheckPeriod = "inv-check-period" FlagPruning = "pruning" FlagPruningKeepRecent = "pruning-keep-recent" @@ -157,7 +156,6 @@ is performed. Note, when enabled, gRPC will also be automatically enabled. cmd.Flags().String(flagTransport, "socket", "Transport protocol: socket, grpc") cmd.Flags().String(flagTraceStore, "", "Enable KVStore tracing to an output file") cmd.Flags().String(FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; Any fee in a tx must meet this minimum (e.g. 0.01photino;0.0001stake)") - cmd.Flags().IntSlice(FlagUnsafeSkipUpgrades, []int{}, "Skip a set of upgrade heights to continue the old binary") cmd.Flags().Uint64(FlagHaltHeight, 0, "Block height at which to gracefully halt the chain and shutdown the node") cmd.Flags().Uint64(FlagHaltTime, 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node") cmd.Flags().Bool(FlagInterBlockCache, true, "Enable inter-block caching") @@ -211,13 +209,19 @@ func startStandAlone(ctx *Context, appCreator types.AppCreator) error { return err } - app := appCreator(ctx.Logger, db, traceWriter, ctx.Viper) - config, err := serverconfig.GetConfig(ctx.Viper) if err != nil { return err } + genDocProvider := node.DefaultGenesisDocProviderFunc(ctx.Config) + genDoc, err := genDocProvider() + if err != nil { + return err + } + + app := appCreator(ctx.Logger, db, traceWriter, config, genDoc.ChainID, ctx.Viper) + _, err = startTelemetry(config) if err != nil { return err @@ -290,15 +294,19 @@ func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.App return err } - app := appCreator(ctx.Logger, db, traceWriter, ctx.Viper) + genDocProvider := node.DefaultGenesisDocProviderFunc(cfg) + genDoc, err := genDocProvider() + if err != nil { + return err + } + + app := appCreator(ctx.Logger, db, traceWriter, config, genDoc.ChainID, ctx.Viper) nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile()) if err != nil { return err } - genDocProvider := node.DefaultGenesisDocProviderFunc(cfg) - var ( tmNode *node.Node gRPCOnly = ctx.Viper.GetBool(flagGRPCOnly) @@ -349,11 +357,6 @@ func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.App var apiSrv *api.Server if config.API.Enable { - genDoc, err := genDocProvider() - if err != nil { - return err - } - clientCtx := clientCtx.WithHomeDir(home).WithChainID(genDoc.ChainID) if config.GRPC.Enable { diff --git a/server/types/app.go b/server/types/app.go index abc4c739e5..ec629c57bb 100644 --- a/server/types/app.go +++ b/server/types/app.go @@ -69,7 +69,7 @@ type ( // AppCreator is a function that allows us to lazily initialize an // application using various configurations. - AppCreator func(log.Logger, dbm.DB, io.Writer, AppOptions) Application + AppCreator func(log.Logger, dbm.DB, io.Writer, config.Config, string, AppOptions) Application // ModuleInitFlags takes a start command and adds modules specific init flags. ModuleInitFlags func(startCmd *cobra.Command) diff --git a/simapp/app.go b/simapp/app.go index a4faa53f00..9d848ef531 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -13,6 +13,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmos "github.com/tendermint/tendermint/libs/os" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" @@ -95,7 +96,6 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -118,7 +118,7 @@ var ( mint.AppModuleBasic{}, distr.AppModuleBasic{}, gov.NewAppModuleBasic( - []govclient.ProposalHandler{paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.LegacyProposalHandler, upgradeclient.LegacyCancelProposalHandler}, + []govclient.ProposalHandler{paramsclient.ProposalHandler, distrclient.ProposalHandler}, ), params.AppModuleBasic{}, crisis.AppModuleBasic{}, @@ -206,7 +206,7 @@ func init() { // NewSimApp returns a reference to an initialized SimApp. func NewSimApp( - logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool, + logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, homePath string, invCheckPeriod uint, encodingConfig simappparams.EncodingConfig, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *SimApp { @@ -301,9 +301,6 @@ func NewSimApp( */ app.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper, groupConfig) - // set the governance module account as the authority for conducting upgrades - app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, 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. @@ -311,8 +308,7 @@ func NewSimApp( govRouter := govv1beta1.NewRouter() govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)). - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)) + AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)) govConfig := govtypes.DefaultConfig() /* Example of setting gov params: @@ -340,6 +336,36 @@ func NewSimApp( app.GashubKeeper = gashubkeeper.NewGashubKeeper(appCodec, keys[gashubtypes.StoreKey], app.GetSubspace(gashubtypes.ModuleName)) + // Register the upgrade keeper + upgradeHandler := map[string]upgradetypes.UpgradeHandler{ + // Add specific actions when the upgrade happen + // ex. + // upgradetypes.BEP111: func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // app.Logger().Info("upgrade to ", plan.Name) + // return fromVM, nil + // }, + } + + upgradeInitlizier := map[string]upgradetypes.UpgradeInitializer{ + // Add specific actions when restart the program + // ex. + // upgradetypes.BEP111: func() error { + // app.Logger().Info("Init BEP111") + // return nil + // }, + } + + var err error + upgradeKeeperOpts := []upgradekeeper.KeeperOption{ + upgradekeeper.RegisterUpgradePlan(app.ChainID(), bApp.AppConfig().Upgrade), + upgradekeeper.RegisterUpgradeHandler(upgradeHandler), + upgradekeeper.RegisterUpgradeInitializer(upgradeInitlizier), + } + app.UpgradeKeeper, err = upgradekeeper.NewKeeper(keys[upgradetypes.StoreKey], appCodec, homePath, upgradeKeeperOpts...) + if err != nil { + panic(err) + } + /**** Module Options ****/ // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment @@ -444,6 +470,7 @@ func NewSimApp( app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.setAnteHandler(encodingConfig.TxConfig) + app.SetUpgradeChecker(app.UpgradeKeeper.IsUpgraded) // 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. @@ -463,6 +490,18 @@ func NewSimApp( if err := app.LoadLatestVersion(); err != nil { tmos.Exit(err.Error()) } + + // Execute the upgraded register, such as the newly added Msg type + // ex. + // app.GovKeeper.Router().RegisterService(...) + ms := app.CommitMultiStore() + ctx := sdk.NewContext(ms, tmproto.Header{ChainID: app.ChainID(), Height: app.LastBlockHeight()}, true, app.UpgradeKeeper.IsUpgraded, app.Logger()) + if loadLatest { + err = app.UpgradeKeeper.InitUpgraded(ctx) + if err != nil { + panic(err) + } + } } return app diff --git a/simapp/app_test.go b/simapp/app_test.go index babd35a9d5..738c2259cd 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -42,13 +42,12 @@ func TestSimAppExportAndBlockedAddrs(t *testing.T) { db := dbm.NewMemDB() logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) app := NewSimappWithCustomOptions(t, false, SetupOptions{ - Logger: logger, - DB: db, - InvCheckPeriod: 0, - EncConfig: encCfg, - HomePath: DefaultNodeHome, - SkipUpgradeHeights: map[int64]bool{}, - AppOpts: EmptyAppOptions{}, + Logger: logger, + DB: db, + InvCheckPeriod: 0, + EncConfig: encCfg, + HomePath: DefaultNodeHome, + AppOpts: EmptyAppOptions{}, }) for acc := range maccPerms { @@ -63,7 +62,7 @@ func TestSimAppExportAndBlockedAddrs(t *testing.T) { logger2 := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) // Making a new app object with the db, so that initchain hasn't been called - app2 := NewSimApp(logger2, db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) + app2 := NewSimApp(logger2, db, nil, true, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) _, err := app2.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } @@ -77,7 +76,7 @@ func TestRunMigrations(t *testing.T) { db := dbm.NewMemDB() encCfg := MakeTestEncodingConfig() logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) // Create a new baseapp and configurator for the purpose of this test. bApp := baseapp.NewBaseApp(appName, logger, db, encCfg.TxConfig.TxDecoder()) @@ -207,7 +206,8 @@ func TestInitGenesisOnMigration(t *testing.T) { db := dbm.NewMemDB() encCfg := MakeTestEncodingConfig() logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, 0, encCfg, EmptyAppOptions{}) + app.SetUpgradeChecker(app.UpgradeKeeper.IsUpgraded) ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) // Create a mock module. This module will serve as the new module we're @@ -217,7 +217,7 @@ func TestInitGenesisOnMigration(t *testing.T) { mockModule := mocks.NewMockAppModule(mockCtrl) mockDefaultGenesis := json.RawMessage(`{"key": "value"}`) mockModule.EXPECT().DefaultGenesis(gomock.Eq(app.appCodec)).Times(1).Return(mockDefaultGenesis) - mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(app.appCodec), gomock.Eq(mockDefaultGenesis)).Times(1).Return(nil) + mockModule.EXPECT().InitGenesis(gomock.Any(), gomock.Eq(app.appCodec), gomock.Eq(mockDefaultGenesis)).Times(1).Return(nil) mockModule.EXPECT().ConsensusVersion().Times(1).Return(uint64(0)) app.mm.Modules["mock"] = mockModule @@ -252,13 +252,12 @@ func TestUpgradeStateOnGenesis(t *testing.T) { db := dbm.NewMemDB() logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) app := NewSimappWithCustomOptions(t, false, SetupOptions{ - Logger: logger, - DB: db, - InvCheckPeriod: 0, - EncConfig: encCfg, - HomePath: DefaultNodeHome, - SkipUpgradeHeights: map[int64]bool{}, - AppOpts: EmptyAppOptions{}, + Logger: logger, + DB: db, + InvCheckPeriod: 0, + EncConfig: encCfg, + HomePath: DefaultNodeHome, + AppOpts: EmptyAppOptions{}, }) // make sure the upgrade keeper has version map in state diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index 788299dc11..f35210970e 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -30,7 +30,7 @@ func BenchmarkFullAppSimulation(b *testing.B) { require.NoError(b, os.RemoveAll(dir)) }() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( @@ -77,7 +77,7 @@ func BenchmarkInvariants(b *testing.B) { require.NoError(b, os.RemoveAll(dir)) }() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( diff --git a/simapp/sim_test.go b/simapp/sim_test.go index bde9aa5859..860d5b9ada 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -70,7 +70,7 @@ func TestFullAppSimulation(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) require.Equal(t, "SimApp", app.Name()) // run randomized simulation @@ -108,7 +108,7 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) require.Equal(t, "SimApp", app.Name()) // Run randomized simulation @@ -148,7 +148,7 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) + newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) require.Equal(t, "SimApp", newApp.Name()) var genesisState GenesisState @@ -217,7 +217,7 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) require.Equal(t, "SimApp", app.Name()) // Run randomized simulation @@ -262,7 +262,7 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) + newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, fauxMerkleModeOpt) require.Equal(t, "SimApp", newApp.Name()) newApp.InitChain(abci.RequestInitChain{ @@ -313,7 +313,7 @@ func TestAppStateDeterminism(t *testing.T) { } db := dbm.NewMemDB() - app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) + app := NewSimApp(logger, db, nil, true, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt()) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 8e6a4667b8..fada920dfd 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -247,18 +247,13 @@ type appCreator struct { } // newApp is an appCreator -func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { +func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appConfig serverconfig.Config, chainID string, appOpts servertypes.AppOptions) servertypes.Application { var cache sdk.MultiStorePersistentCache if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { cache = store.NewCommitKVStoreCacheManager() } - skipUpgradeHeights := make(map[int64]bool) - for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { - skipUpgradeHeights[int64(h)] = true - } - pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) if err != nil { panic(err) @@ -280,7 +275,7 @@ func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, a ) return simapp.NewSimApp( - logger, db, traceStore, true, skipUpgradeHeights, + logger, db, traceStore, true, cast.ToString(appOpts.Get(flags.FlagHome)), cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), a.encCfg, @@ -296,6 +291,8 @@ func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, a baseapp.SetSnapshot(snapshotStore, snapshotOptions), baseapp.SetIAVLCacheSize(cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))), baseapp.SetIAVLDisableFastNode(cast.ToBool(appOpts.Get(server.FlagDisableIAVLFastNode))), + baseapp.SetAppConfig(appConfig), + baseapp.SetChainID(chainID), ) } @@ -311,13 +308,13 @@ func (a appCreator) appExport( } if height != -1 { - simApp = simapp.NewSimApp(logger, db, traceStore, false, map[int64]bool{}, homePath, uint(1), a.encCfg, appOpts) + simApp = simapp.NewSimApp(logger, db, traceStore, false, homePath, uint(1), a.encCfg, appOpts) if err := simApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } } else { - simApp = simapp.NewSimApp(logger, db, traceStore, true, map[int64]bool{}, homePath, uint(1), a.encCfg, appOpts) + simApp = simapp.NewSimApp(logger, db, traceStore, true, homePath, uint(1), a.encCfg, appOpts) } return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index b043926a9d..ba9db29065 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -58,19 +58,18 @@ var DefaultConsensusParams = &abci.ConsensusParams{ // SetupOptions defines arguments that are passed into `Simapp` constructor. type SetupOptions struct { - Logger log.Logger - DB *dbm.MemDB - InvCheckPeriod uint - HomePath string - SkipUpgradeHeights map[int64]bool - EncConfig params.EncodingConfig - AppOpts types.AppOptions + Logger log.Logger + DB *dbm.MemDB + InvCheckPeriod uint + HomePath string + EncConfig params.EncodingConfig + AppOpts types.AppOptions } func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, GenesisState) { db := dbm.NewMemDB() encCdc := MakeTestEncodingConfig() - app := NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, invCheckPeriod, encCdc, EmptyAppOptions{}) + app := NewSimApp(log.NewNopLogger(), db, nil, true, DefaultNodeHome, invCheckPeriod, encCdc, EmptyAppOptions{}) if withGenesis { return app, NewDefaultGenesisState(encCdc.Codec) } @@ -96,7 +95,7 @@ func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptio Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), } - app := NewSimApp(options.Logger, options.DB, nil, true, options.SkipUpgradeHeights, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts) + app := NewSimApp(options.Logger, options.DB, nil, true, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts) genesisState := NewDefaultGenesisState(app.appCodec) genesisState = genesisStateWithValSet(t, app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) diff --git a/simapp/upgrades.go b/simapp/upgrades.go index d6bd283402..31a9060c4a 100644 --- a/simapp/upgrades.go +++ b/simapp/upgrades.go @@ -26,7 +26,7 @@ func (app SimApp) RegisterUpgradeHandlers() { panic(err) } - if upgradeInfo.Name == UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + if upgradeInfo.Name == UpgradeName { storeUpgrades := storetypes.StoreUpgrades{ Added: []string{ group.ModuleName, diff --git a/store/rootmulti/rollback_test.go b/store/rootmulti/rollback_test.go index 36fb13e636..673e442d46 100644 --- a/store/rootmulti/rollback_test.go +++ b/store/rootmulti/rollback_test.go @@ -15,13 +15,12 @@ import ( func TestRollback(t *testing.T) { db := dbm.NewMemDB() options := simapp.SetupOptions{ - Logger: log.NewNopLogger(), - DB: db, - InvCheckPeriod: 0, - EncConfig: simapp.MakeTestEncodingConfig(), - HomePath: simapp.DefaultNodeHome, - SkipUpgradeHeights: map[int64]bool{}, - AppOpts: simapp.EmptyAppOptions{}, + Logger: log.NewNopLogger(), + DB: db, + InvCheckPeriod: 0, + EncConfig: simapp.MakeTestEncodingConfig(), + HomePath: simapp.DefaultNodeHome, + AppOpts: simapp.EmptyAppOptions{}, } app := simapp.NewSimappWithCustomOptions(t, false, options) app.Commit() @@ -49,7 +48,7 @@ func TestRollback(t *testing.T) { require.Equal(t, target, app.LastBlockHeight()) // recreate app to have clean check state - app = simapp.NewSimApp(options.Logger, options.DB, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, options.InvCheckPeriod, options.EncConfig, options.AppOpts) + app = simapp.NewSimApp(options.Logger, options.DB, nil, true, simapp.DefaultNodeHome, options.InvCheckPeriod, options.EncConfig, options.AppOpts) store = app.NewContext(true, tmproto.Header{}).KVStore(app.GetKey("bank")) require.Equal(t, []byte("value5"), store.Get([]byte("key"))) diff --git a/testutil/context.go b/testutil/context.go index 1addf17c28..6a6aa24b65 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -20,7 +20,7 @@ func DefaultContext(key storetypes.StoreKey, tkey storetypes.StoreKey) sdk.Conte if err != nil { panic(err) } - ctx := sdk.NewContext(cms, tmproto.Header{}, false, log.NewNopLogger()) + ctx := sdk.NewContext(cms, tmproto.Header{}, false, nil, log.NewNopLogger()) return ctx } diff --git a/testutil/network/network.go b/testutil/network/network.go index 1d9fa9b927..5cea4706e3 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -60,7 +60,7 @@ type AppConstructor = func(val Validator) servertypes.Application func NewAppConstructor(encodingCfg params.EncodingConfig) AppConstructor { return func(val Validator) servertypes.Application { return simapp.NewSimApp( - val.Ctx.Logger, dbm.NewMemDB(), nil, true, make(map[int64]bool), val.Ctx.Config.RootDir, 0, + val.Ctx.Logger, dbm.NewMemDB(), nil, true, val.Ctx.Config.RootDir, 0, encodingCfg, simapp.EmptyAppOptions{}, baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), diff --git a/types/context.go b/types/context.go index 7479f15c1f..2add85e60c 100644 --- a/types/context.go +++ b/types/context.go @@ -22,23 +22,24 @@ but please do not over-use it. We try to keep all data structured and standard additions here would be better just to add to the Context struct */ type Context struct { - baseCtx context.Context - ms MultiStore - header tmproto.Header - headerHash tmbytes.HexBytes - chainID string - txBytes []byte - logger log.Logger - voteInfo []abci.VoteInfo - gasMeter GasMeter - blockGasMeter GasMeter - checkTx bool - recheckTx bool // if recheckTx == true, then checkTx must also be true - minGasPrice DecCoins - consParams *abci.ConsensusParams - eventManager *EventManager - priority int64 // The tx priority, only relevant in CheckTx - txSize uint64 // The tx bytes length + baseCtx context.Context + ms MultiStore + header tmproto.Header + headerHash tmbytes.HexBytes + chainID string + txBytes []byte + logger log.Logger + voteInfo []abci.VoteInfo + gasMeter GasMeter + blockGasMeter GasMeter + checkTx bool + recheckTx bool // if recheckTx == true, then checkTx must also be true + minGasPrice DecCoins + consParams *abci.ConsensusParams + eventManager *EventManager + priority int64 // The tx priority, only relevant in CheckTx + txSize uint64 // The tx bytes length + upgradeChecker func(ctx Context, name string) bool } // Proposed rename, not done to avoid API breakage @@ -61,6 +62,12 @@ func (c Context) MinGasPrices() DecCoins { return c.minGasPrice } func (c Context) EventManager() *EventManager { return c.eventManager } func (c Context) Priority() int64 { return c.priority } func (c Context) TxSize() uint64 { return c.txSize } +func (c Context) IsUpgraded(name string) bool { + if c.upgradeChecker == nil { + return false + } + return c.upgradeChecker(c, name) +} // clone the header before returning func (c Context) BlockHeader() tmproto.Header { @@ -92,19 +99,20 @@ func (c Context) Err() error { } // create a new context -func NewContext(ms MultiStore, header tmproto.Header, isCheckTx bool, logger log.Logger) Context { +func NewContext(ms MultiStore, header tmproto.Header, isCheckTx bool, upgradeChecker func(Context, string) bool, logger log.Logger) Context { // https://github.com/gogo/protobuf/issues/519 header.Time = header.Time.UTC() return Context{ - baseCtx: context.Background(), - ms: ms, - header: header, - chainID: header.ChainID, - checkTx: isCheckTx, - logger: logger, - gasMeter: storetypes.NewInfiniteGasMeter(), - minGasPrice: DecCoins{}, - eventManager: NewEventManager(), + baseCtx: context.Background(), + ms: ms, + header: header, + chainID: header.ChainID, + checkTx: isCheckTx, + logger: logger, + gasMeter: storetypes.NewInfiniteGasMeter(), + minGasPrice: DecCoins{}, + eventManager: NewEventManager(), + upgradeChecker: upgradeChecker, } } diff --git a/types/context_test.go b/types/context_test.go index f5c7cadeb5..c2e9dcae52 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -99,7 +99,7 @@ func (s *contextTestSuite) TestContextWithCustom() { minGasPrices := types.DecCoins{types.NewInt64DecCoin("feetoken", 1)} headerHash := []byte("headerHash") - ctx = types.NewContext(nil, header, ischeck, logger) + ctx = types.NewContext(nil, header, ischeck, nil, logger) s.Require().Equal(header, ctx.BlockHeader()) ctx = ctx. @@ -149,7 +149,7 @@ func (s *contextTestSuite) TestContextHeader() { addr := secp256k1.GenPrivKey().PubKey().Address() proposer := types.ConsAddress(addr) - ctx = types.NewContext(nil, tmproto.Header{}, false, nil) + ctx = types.NewContext(nil, tmproto.Header{}, false, nil, nil) ctx = ctx. WithBlockHeight(height). @@ -204,7 +204,7 @@ func (s *contextTestSuite) TestContextHeaderClone() { for name, tc := range cases { tc := tc s.T().Run(name, func(t *testing.T) { - ctx := types.NewContext(nil, tc.h, false, nil) + ctx := types.NewContext(nil, tc.h, false, nil, nil) s.Require().Equal(tc.h.Height, ctx.BlockHeight()) s.Require().Equal(tc.h.Time.UTC(), ctx.BlockTime()) @@ -218,7 +218,7 @@ func (s *contextTestSuite) TestContextHeaderClone() { } func (s *contextTestSuite) TestUnwrapSDKContext() { - sdkCtx := types.NewContext(nil, tmproto.Header{}, false, nil) + sdkCtx := types.NewContext(nil, tmproto.Header{}, false, nil, nil) ctx := types.WrapSDKContext(sdkCtx) sdkCtx2 := types.UnwrapSDKContext(ctx) s.Require().Equal(sdkCtx, sdkCtx2) diff --git a/types/module/module_test.go b/types/module/module_test.go index 926a4a4ab3..b98b72ca04 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -195,7 +195,7 @@ func TestManager_InitGenesis(t *testing.T) { require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) - ctx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, tmproto.Header{}, false, nil, log.NewNopLogger()) interfaceRegistry := types.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) genesisData := map[string]json.RawMessage{"module1": json.RawMessage(`{"key": "value"}`)} diff --git a/x/auth/migrations/legacytx/stdtx_test.go b/x/auth/migrations/legacytx/stdtx_test.go index 2e69427c5a..b734b62bf9 100644 --- a/x/auth/migrations/legacytx/stdtx_test.go +++ b/x/auth/migrations/legacytx/stdtx_test.go @@ -150,7 +150,7 @@ func TestStdSignBytes(t *testing.T) { } func TestTxValidateBasic(t *testing.T) { - ctx := sdk.NewContext(nil, tmproto.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, tmproto.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger()) // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() diff --git a/x/auth/module_test.go b/x/auth/module_test.go index 6f527c587e..d429f3c800 100644 --- a/x/auth/module_test.go +++ b/x/auth/module_test.go @@ -17,7 +17,7 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.Marshal(genesisState) diff --git a/x/capability/genesis_test.go b/x/capability/genesis_test.go index 34a09960e7..87533f99f0 100644 --- a/x/capability/genesis_test.go +++ b/x/capability/genesis_test.go @@ -35,7 +35,7 @@ func (suite *CapabilityTestSuite) TestGenesis() { // and initialize app from exported genesis state above. db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - newApp := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + newApp := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) newKeeper := keeper.NewKeeper(suite.cdc, newApp.GetKey(types.StoreKey), newApp.GetMemKey(types.MemStoreKey)) newSk1 := newKeeper.ScopeToModule(banktypes.ModuleName) diff --git a/x/distribution/module_test.go b/x/distribution/module_test.go index 70e2e50ea8..ba342e5d9a 100644 --- a/x/distribution/module_test.go +++ b/x/distribution/module_test.go @@ -18,7 +18,7 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.Marshal(genesisState) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 26d933e6ff..a592f0d7d8 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -73,7 +73,7 @@ func TestImportExportQueues(t *testing.T) { } db := dbm.NewMemDB() - app2 := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 0, simapp.MakeTestEncodingConfig(), simapp.EmptyAppOptions{}) + app2 := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 0, simapp.MakeTestEncodingConfig(), simapp.EmptyAppOptions{}) app2.InitChain( abci.RequestInitChain{ diff --git a/x/gov/migrations/v046/store_test.go b/x/gov/migrations/v046/store_test.go index a9318f9390..ff52409670 100644 --- a/x/gov/migrations/v046/store_test.go +++ b/x/gov/migrations/v046/store_test.go @@ -13,7 +13,7 @@ import ( v046gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v046" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + // upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) func TestMigrateStore(t *testing.T) { @@ -29,15 +29,15 @@ func TestMigrateStore(t *testing.T) { require.NoError(t, err) prop1Bz, err := cdc.Marshal(&prop1) require.NoError(t, err) - prop2, err := v1beta1.NewProposal(upgradetypes.NewSoftwareUpgradeProposal("my title 2", "my desc 2", upgradetypes.Plan{ - Name: "my plan 2", - }), 2, propTime, propTime) - require.NoError(t, err) - prop2Bz, err := cdc.Marshal(&prop2) - require.NoError(t, err) + // prop2, err := v1beta1.NewProposal(upgradetypes.NewSoftwareUpgradeProposal("my title 2", "my desc 2", upgradetypes.Plan{ + // Name: "my plan 2", + // }), 2, propTime, propTime) + // require.NoError(t, err) + // prop2Bz, err := cdc.Marshal(&prop2) + // require.NoError(t, err) store.Set(v042gov.ProposalKey(prop1.ProposalId), prop1Bz) - store.Set(v042gov.ProposalKey(prop2.ProposalId), prop2Bz) + // store.Set(v042gov.ProposalKey(prop2.ProposalId), prop2Bz) // Run migrations. err = v046gov.MigrateStore(ctx, govKey, cdc) @@ -48,10 +48,10 @@ func TestMigrateStore(t *testing.T) { require.NoError(t, err) compareProps(t, prop1, newProp1) - var newProp2 v1.Proposal - err = cdc.Unmarshal(store.Get(v042gov.ProposalKey(prop2.ProposalId)), &newProp2) - require.NoError(t, err) - compareProps(t, prop2, newProp2) + // var newProp2 v1.Proposal + // err = cdc.Unmarshal(store.Get(v042gov.ProposalKey(prop2.ProposalId)), &newProp2) + // require.NoError(t, err) + // compareProps(t, prop2, newProp2) } func compareProps(t *testing.T, oldProp v1beta1.Proposal, newProp v1.Proposal) { diff --git a/x/gov/module_test.go b/x/gov/module_test.go index c43f570dba..f3fb679aa0 100644 --- a/x/gov/module_test.go +++ b/x/gov/module_test.go @@ -18,7 +18,7 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.Marshal(genesisState) diff --git a/x/gov/simulation/proposals_test.go b/x/gov/simulation/proposals_test.go index dcd6f3c3f0..da226d793b 100644 --- a/x/gov/simulation/proposals_test.go +++ b/x/gov/simulation/proposals_test.go @@ -18,7 +18,7 @@ func TestProposalContents(t *testing.T) { s := rand.NewSource(1) r := rand.New(s) - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) + ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil, nil) accounts := simtypes.RandomAccounts(r, 3) // execute ProposalContents function diff --git a/x/group/keeper/genesis_test.go b/x/group/keeper/genesis_test.go index 59a101bf3c..b5d8731bb3 100644 --- a/x/group/keeper/genesis_test.go +++ b/x/group/keeper/genesis_test.go @@ -46,7 +46,7 @@ func (s *GenesisTestSuite) SetupSuite() { checkTx := false db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) s.app = app s.sdkCtx = app.BaseApp.NewUncachedContext(checkTx, tmproto.Header{}) diff --git a/x/group/keeper/invariants_test.go b/x/group/keeper/invariants_test.go index 013f5e3a65..e815238315 100644 --- a/x/group/keeper/invariants_test.go +++ b/x/group/keeper/invariants_test.go @@ -42,7 +42,7 @@ func (s *invariantTestSuite) SetupSuite() { cms := store.NewCommitMultiStore(db) cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) _ = cms.LoadLatestVersion() - sdkCtx := sdk.NewContext(cms, tmproto.Header{}, false, log.NewNopLogger()) + sdkCtx := sdk.NewContext(cms, tmproto.Header{}, false, nil, log.NewNopLogger()) s.ctx = sdkCtx s.cdc = cdc diff --git a/x/mint/module_test.go b/x/mint/module_test.go index ecf0a1511b..5c5df2261d 100644 --- a/x/mint/module_test.go +++ b/x/mint/module_test.go @@ -18,7 +18,7 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.Marshal(genesisState) diff --git a/x/params/simulation/operations_test.go b/x/params/simulation/operations_test.go index 5ed1ba8a50..a5a290c5c4 100644 --- a/x/params/simulation/operations_test.go +++ b/x/params/simulation/operations_test.go @@ -43,7 +43,7 @@ func TestSimulateParamChangeProposalContent(t *testing.T) { s := rand.NewSource(1) r := rand.New(s) - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) + ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil, nil) accounts := simtypes.RandomAccounts(r, 3) paramChangePool := []simtypes.ParamChange{MockParamChange{1}, MockParamChange{2}, MockParamChange{3}} diff --git a/x/params/simulation/proposals_test.go b/x/params/simulation/proposals_test.go index 2902cb08aa..70fa4fc506 100644 --- a/x/params/simulation/proposals_test.go +++ b/x/params/simulation/proposals_test.go @@ -19,7 +19,7 @@ func TestProposalContents(t *testing.T) { s := rand.NewSource(1) r := rand.New(s) - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) + ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil, nil) accounts := simtypes.RandomAccounts(r, 3) paramChangePool := []simtypes.ParamChange{MockParamChange{1}, MockParamChange{2}, MockParamChange{3}} diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index 2f57119d01..8da5e4b8cb 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -41,7 +41,7 @@ func (suite *SubspaceTestSuite) SetupTest() { suite.cdc = encCfg.Codec suite.amino = encCfg.Amino - suite.ctx = sdk.NewContext(ms, tmproto.Header{}, false, log.NewNopLogger()) + suite.ctx = sdk.NewContext(ms, tmproto.Header{}, false, nil, log.NewNopLogger()) suite.ss = ss.WithKeyTable(paramKeyTable()) } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index 90eb4f22a0..7c0fd2642d 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -39,7 +39,7 @@ func TestNewWeightedProposalContent(t *testing.T) { require.Equal(t, key, pContent.AppParamsKey()) require.Equal(t, weight, pContent.DefaultWeight()) - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) + ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil, nil) require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) } diff --git a/x/staking/module_test.go b/x/staking/module_test.go index 3f1e5d9168..2f2ed14989 100644 --- a/x/staking/module_test.go +++ b/x/staking/module_test.go @@ -18,7 +18,7 @@ import ( func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) genesisState := simapp.GenesisStateWithSingleValidator(t, app) stateBytes, err := tmjson.Marshal(genesisState) diff --git a/x/upgrade/abci.go b/x/upgrade/abci.go index f021475142..73ad4253cc 100644 --- a/x/upgrade/abci.go +++ b/x/upgrade/abci.go @@ -23,74 +23,26 @@ import ( func BeginBlocker(k keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - plan, found := k.GetUpgradePlan(ctx) + plans, found := k.GetUpgradePlan(ctx) if !found { return } - logger := ctx.Logger() // To make sure clear upgrade is executed at the same block - if plan.ShouldExecute(ctx) { - // If skip upgrade has been set for current height, we clear the upgrade plan - if k.IsSkipHeight(ctx.BlockHeight()) { - skipUpgradeMsg := fmt.Sprintf("UPGRADE \"%s\" SKIPPED at %d: %s", plan.Name, plan.Height, plan.Info) - logger.Info(skipUpgradeMsg) - - // Clear the upgrade plan at current height - k.ClearUpgradePlan(ctx) - return - } - - // Prepare shutdown if we don't have an upgrade handler for this upgrade name (meaning this software is out of date) - if !k.HasHandler(plan.Name) { - // Write the upgrade info to disk. The UpgradeStoreLoader uses this info to perform or skip - // store migrations. - err := k.DumpUpgradeInfoToDisk(ctx.BlockHeight(), plan) - if err != nil { - panic(fmt.Errorf("unable to write upgrade info to filesystem: %s", err.Error())) - } - - upgradeMsg := BuildUpgradeNeededMsg(plan) - logger.Error(upgradeMsg) - panic(upgradeMsg) + executed := false + for _, plan := range plans { + if plan.ShouldExecute(ctx) { + + // We have an upgrade handler for this upgrade name, so apply the upgrade + ctx.Logger().Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt())) + ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) + k.ApplyUpgrade(ctx, *plan) + executed = true } - - // We have an upgrade handler for this upgrade name, so apply the upgrade - ctx.Logger().Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt())) - ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - k.ApplyUpgrade(ctx, plan) - return } - - // if we have a pending upgrade, but it is not yet time, make sure we did not - // set the handler already - if k.HasHandler(plan.Name) { - downgradeMsg := fmt.Sprintf("BINARY UPDATED BEFORE TRIGGER! UPGRADE \"%s\" - in binary but not executed on chain. Downgrade your binary", plan.Name) - ctx.Logger().Error(downgradeMsg) - panic(downgradeMsg) - } - - if !k.DowngradeVerified() { - k.SetDowngradeVerified(true) - lastAppliedPlan, _ := k.GetLastCompletedUpgrade(ctx) - // This check will make sure that we are using a valid binary. - // It'll panic in these cases if there is no upgrade handler registered for the last applied upgrade. - // 1. If there is no scheduled upgrade. - // 2. If the plan is not ready. - // 3. If the plan is ready and skip upgrade height is set for current height. - if !found || !plan.ShouldExecute(ctx) || (plan.ShouldExecute(ctx) && k.IsSkipHeight(ctx.BlockHeight())) { - if lastAppliedPlan != "" && !k.HasHandler(lastAppliedPlan) { - var appVersion uint64 - - cp := ctx.ConsensusParams() - if cp != nil && cp.Version != nil { - appVersion = cp.Version.AppVersion - } - - panic(fmt.Sprintf("Wrong app version %d, upgrade handler is missing for %s upgrade plan", appVersion, lastAppliedPlan)) - } - } + if executed { + k.ClearUpgradePlan(ctx) } } diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index aa38e8ab5d..caf50ec12b 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -1,7 +1,6 @@ package upgrade_test import ( - "errors" "fmt" "os" "testing" @@ -15,9 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/module" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/cosmos/cosmos-sdk/x/upgrade" "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/x/upgrade/types" @@ -27,22 +24,20 @@ type TestSuite struct { module module.BeginBlockAppModule keeper keeper.Keeper querier sdk.Querier - handler govtypes.Handler ctx sdk.Context } var s TestSuite -func setupTest(t *testing.T, height int64, skip map[int64]bool) TestSuite { +func setupTest(t *testing.T, height int64) TestSuite { db := dbm.NewMemDB() app := simapp.NewSimappWithCustomOptions(t, false, simapp.SetupOptions{ - Logger: log.NewNopLogger(), - SkipUpgradeHeights: skip, - DB: db, - InvCheckPeriod: 0, - HomePath: simapp.DefaultNodeHome, - EncConfig: simapp.MakeTestEncodingConfig(), - AppOpts: simapp.EmptyAppOptions{}, + Logger: log.NewNopLogger(), + DB: db, + InvCheckPeriod: 0, + HomePath: simapp.DefaultNodeHome, + EncConfig: simapp.MakeTestEncodingConfig(), + AppOpts: simapp.EmptyAppOptions{}, }) s.keeper = app.UpgradeKeeper @@ -50,40 +45,37 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) TestSuite { s.module = upgrade.NewAppModule(s.keeper) s.querier = s.module.LegacyQuerierHandler(app.LegacyAmino()) - s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return s } func TestRequireName(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) - - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{}}) + s := setupTest(t, 10) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{}) require.Error(t, err) - require.True(t, errors.Is(sdkerrors.ErrInvalidRequest, err), err) } func TestRequireFutureBlock(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: s.ctx.BlockHeight() - 1}}) + s := setupTest(t, 10) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() - 1}) require.Error(t, err) - require.True(t, errors.Is(sdkerrors.ErrInvalidRequest, err), err) } func TestDoHeightUpgrade(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) + s := setupTest(t, 10) t.Log("Verify can schedule an upgrade") - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}}) + + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}) require.NoError(t, err) VerifyDoUpgrade(t) } func TestCanOverwriteScheduleUpgrade(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) + s := setupTest(t, 10) t.Log("Can overwrite plan") - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "bad_test", Height: s.ctx.BlockHeight() + 10}}) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 10}) require.NoError(t, err) - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}}) + err = s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}) require.NoError(t, err) VerifyDoUpgrade(t) @@ -94,7 +86,7 @@ func VerifyDoUpgrade(t *testing.T) { newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - require.Panics(t, func() { + require.NotPanics(t, func() { s.module.BeginBlock(newCtx, req) }) @@ -112,9 +104,6 @@ func VerifyDoUpgrade(t *testing.T) { func VerifyDoUpgradeWithCtx(t *testing.T, newCtx sdk.Context, proposalName string) { t.Log("Verify that a panic happens at the upgrade height") req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - require.Panics(t, func() { - s.module.BeginBlock(newCtx, req) - }) t.Log("Verify that the upgrade can be successfully applied with a handler") s.keeper.SetUpgradeHandler(proposalName, func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { @@ -128,13 +117,14 @@ func VerifyDoUpgradeWithCtx(t *testing.T, newCtx sdk.Context, proposalName strin } func TestHaltIfTooNew(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) + s := setupTest(t, 10) t.Log("Verify that we don't panic with registered plan not in database at all") var called int s.keeper.SetUpgradeHandler("future", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { called++ return vm, nil }) + s.keeper.SetUpgradeInitializer("future", func() error { return nil }) newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} @@ -144,9 +134,9 @@ func TestHaltIfTooNew(t *testing.T) { require.Equal(t, 0, called) t.Log("Verify we panic if we have a registered handler ahead of time") - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "future", Height: s.ctx.BlockHeight() + 3}}) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "future", Height: s.ctx.BlockHeight() + 3}) require.NoError(t, err) - require.Panics(t, func() { + require.NotPanics(t, func() { s.module.BeginBlock(newCtx, req) }) require.Equal(t, 0, called) @@ -171,38 +161,15 @@ func VerifyCleared(t *testing.T, newCtx sdk.Context) { } func TestCanClear(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) + s := setupTest(t, 10) t.Log("Verify upgrade is scheduled") - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 100}}) - require.NoError(t, err) - - err = s.handler(s.ctx, &types.CancelSoftwareUpgradeProposal{Title: "cancel"}) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 100}) require.NoError(t, err) + s.keeper.ClearUpgradePlan(s.ctx) VerifyCleared(t, s.ctx) } -func TestCantApplySameUpgradeTwice(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) - height := s.ctx.BlockHeader().Height + 1 - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: height}}) - require.NoError(t, err) - VerifyDoUpgrade(t) - t.Log("Verify an executed upgrade \"test\" can't be rescheduled") - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: height}}) - require.Error(t, err) - require.True(t, errors.Is(sdkerrors.ErrInvalidRequest, err), err) -} - -func TestNoSpuriousUpgrades(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) - t.Log("Verify that no upgrade panic is triggered in the BeginBlocker when we haven't scheduled an upgrade") - req := abci.RequestBeginBlock{Header: s.ctx.BlockHeader()} - require.NotPanics(t, func() { - s.module.BeginBlock(s.ctx, req) - }) -} - func TestPlanStringer(t *testing.T) { require.Equal(t, `Upgrade Plan Name: test @@ -227,149 +194,18 @@ func VerifyDone(t *testing.T, newCtx sdk.Context, name string) { require.NotZero(t, height) } -func VerifySet(t *testing.T, skipUpgradeHeights map[int64]bool) { - t.Log("Verify if the skip upgrade has been set") - - for k := range skipUpgradeHeights { - require.True(t, s.keeper.IsSkipHeight(k)) - } -} - -func TestContains(t *testing.T) { - var skipOne int64 = 11 - s := setupTest(t, 10, map[int64]bool{skipOne: true}) - - VerifySet(t, map[int64]bool{skipOne: true}) - t.Log("case where array contains the element") - require.True(t, s.keeper.IsSkipHeight(11)) - - t.Log("case where array doesn't contain the element") - require.False(t, s.keeper.IsSkipHeight(4)) -} - -func TestSkipUpgradeSkippingAll(t *testing.T) { - var ( - skipOne int64 = 11 - skipTwo int64 = 20 - ) - s := setupTest(t, 10, map[int64]bool{skipOne: true, skipTwo: true}) - - newCtx := s.ctx - - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: skipOne}}) - require.NoError(t, err) - - t.Log("Verify if skip upgrade flag clears upgrade plan in both cases") - VerifySet(t, map[int64]bool{skipOne: true, skipTwo: true}) - - newCtx = newCtx.WithBlockHeight(skipOne) - require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) - }) - - t.Log("Verify a second proposal also is being cleared") - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop2", Plan: types.Plan{Name: "test2", Height: skipTwo}}) - require.NoError(t, err) - - newCtx = newCtx.WithBlockHeight(skipTwo) - require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) - }) - - // To ensure verification is being done only after both upgrades are cleared - t.Log("Verify if both proposals are cleared") - VerifyCleared(t, s.ctx) - VerifyNotDone(t, s.ctx, "test") - VerifyNotDone(t, s.ctx, "test2") -} - -func TestUpgradeSkippingOne(t *testing.T) { - var ( - skipOne int64 = 11 - skipTwo int64 = 20 - ) - s := setupTest(t, 10, map[int64]bool{skipOne: true}) - - newCtx := s.ctx - - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: skipOne}}) - require.NoError(t, err) - - t.Log("Verify if skip upgrade flag clears upgrade plan in one case and does upgrade on another") - VerifySet(t, map[int64]bool{skipOne: true}) - - // Setting block height of proposal test - newCtx = newCtx.WithBlockHeight(skipOne) - require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) - }) - - t.Log("Verify the second proposal is not skipped") - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop2", Plan: types.Plan{Name: "test2", Height: skipTwo}}) - require.NoError(t, err) - // Setting block height of proposal test2 - newCtx = newCtx.WithBlockHeight(skipTwo) - VerifyDoUpgradeWithCtx(t, newCtx, "test2") - - t.Log("Verify first proposal is cleared and second is done") - VerifyNotDone(t, s.ctx, "test") - VerifyDone(t, s.ctx, "test2") -} - -func TestUpgradeSkippingOnlyTwo(t *testing.T) { - var ( - skipOne int64 = 11 - skipTwo int64 = 20 - skipThree int64 = 25 - ) - s := setupTest(t, 10, map[int64]bool{skipOne: true, skipTwo: true}) - - newCtx := s.ctx - - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: skipOne}}) - require.NoError(t, err) - - t.Log("Verify if skip upgrade flag clears upgrade plan in both cases and does third upgrade") - VerifySet(t, map[int64]bool{skipOne: true, skipTwo: true}) - - // Setting block height of proposal test - newCtx = newCtx.WithBlockHeight(skipOne) - require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) - }) - - // A new proposal with height in skipUpgradeHeights - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop2", Plan: types.Plan{Name: "test2", Height: skipTwo}}) - require.NoError(t, err) - // Setting block height of proposal test2 - newCtx = newCtx.WithBlockHeight(skipTwo) - require.NotPanics(t, func() { - s.module.BeginBlock(newCtx, req) - }) - - t.Log("Verify a new proposal is not skipped") - err = s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop3", Plan: types.Plan{Name: "test3", Height: skipThree}}) - require.NoError(t, err) - newCtx = newCtx.WithBlockHeight(skipThree) - VerifyDoUpgradeWithCtx(t, newCtx, "test3") - - t.Log("Verify two proposals are cleared and third is done") - VerifyNotDone(t, s.ctx, "test") - VerifyNotDone(t, s.ctx, "test2") - VerifyDone(t, s.ctx, "test3") -} - -func TestUpgradeWithoutSkip(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) +func TestUpgrade(t *testing.T) { + s := setupTest(t, 10) newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "prop", Plan: types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}}) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.BlockHeight() + 1}) + s.keeper.SetUpgradeHandler("test", func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { + return vm, nil + }) + s.keeper.SetUpgradeInitializer("test", func() error { return nil }) require.NoError(t, err) t.Log("Verify if upgrade happens without skip upgrade") - require.Panics(t, func() { + require.NotPanics(t, func() { s.module.BeginBlock(newCtx, req) }) @@ -378,7 +214,7 @@ func TestUpgradeWithoutSkip(t *testing.T) { } func TestDumpUpgradeInfoToFile(t *testing.T) { - s := setupTest(t, 10, map[int64]bool{}) + s := setupTest(t, 10) require := require.New(t) // require no error when the upgrade info file does not exist @@ -410,8 +246,7 @@ func TestDumpUpgradeInfoToFile(t *testing.T) { // TODO: add testcase to for `no upgrade handler is present for last applied upgrade`. func TestBinaryVersion(t *testing.T) { - var skipHeight int64 = 15 - s := setupTest(t, 10, map[int64]bool{skipHeight: true}) + s := setupTest(t, 10) testCases := []struct { name string @@ -433,7 +268,7 @@ func TestBinaryVersion(t *testing.T) { return vm, nil }) - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "Upgrade test", Plan: types.Plan{Name: "test0", Height: s.ctx.BlockHeight() + 2}}) + err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test0", Height: s.ctx.BlockHeight() + 2}) require.NoError(t, err) newCtx := s.ctx.WithBlockHeight(12) @@ -447,30 +282,13 @@ func TestBinaryVersion(t *testing.T) { }, false, }, - { - "test panic: upgrade needed", - func() (sdk.Context, abci.RequestBeginBlock) { - err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "Upgrade test", Plan: types.Plan{Name: "test2", Height: 13}}) - require.NoError(t, err) - - newCtx := s.ctx.WithBlockHeight(13) - req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()} - return newCtx, req - }, - true, - }, } for _, tc := range testCases { ctx, req := tc.preRun() - if tc.expectPanic { - require.Panics(t, func() { - s.module.BeginBlock(ctx, req) - }) - } else { - require.NotPanics(t, func() { - s.module.BeginBlock(ctx, req) - }) - } + + require.NotPanics(t, func() { + s.module.BeginBlock(ctx, req) + }) } } diff --git a/x/upgrade/client/cli/parse.go b/x/upgrade/client/cli/parse.go deleted file mode 100644 index 7ce70e4843..0000000000 --- a/x/upgrade/client/cli/parse.go +++ /dev/null @@ -1,34 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/spf13/pflag" -) - -func parseArgsToContent(fs *pflag.FlagSet, name string) (gov.Content, error) { - title, err := fs.GetString(cli.FlagTitle) //nolint:staticcheck - if err != nil { - return nil, err - } - - description, err := fs.GetString(cli.FlagDescription) //nolint:staticcheck - if err != nil { - return nil, err - } - - height, err := fs.GetInt64(FlagUpgradeHeight) - if err != nil { - return nil, err - } - - info, err := fs.GetString(FlagUpgradeInfo) - if err != nil { - return nil, err - } - - plan := types.Plan{Name: name, Height: height, Info: info} - content := types.NewSoftwareUpgradeProposal(title, description, plan) - return content, nil -} diff --git a/x/upgrade/client/cli/parse_test.go b/x/upgrade/client/cli/parse_test.go deleted file mode 100644 index b5ce54e4b1..0000000000 --- a/x/upgrade/client/cli/parse_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package cli - -import ( - "strconv" - "testing" - - "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/stretchr/testify/require" -) - -func TestParseArgsToContent(t *testing.T) { - fs := NewCmdSubmitLegacyUpgradeProposal().Flags() - - proposal := types.SoftwareUpgradeProposal{ - Title: "proposal title", - Description: "proposal description", - Plan: types.Plan{ - Name: "plan name", - Height: 123456, - Info: "plan info", - }, - } - - fs.Set(cli.FlagTitle, proposal.Title) - fs.Set(cli.FlagDescription, proposal.Description) - fs.Set(FlagUpgradeHeight, strconv.FormatInt(proposal.Plan.Height, 10)) - fs.Set(FlagUpgradeInfo, proposal.Plan.Info) - - content, err := parseArgsToContent(fs, proposal.Plan.Name) - require.NoError(t, err) - - p, ok := content.(*types.SoftwareUpgradeProposal) - require.Equal(t, ok, true) - require.Equal(t, p.Title, proposal.Title) - require.Equal(t, p.Description, proposal.Description) - require.Equal(t, p.Plan.Name, proposal.Plan.Name) - require.Equal(t, p.Plan.Height, proposal.Plan.Height) - require.Equal(t, p.Plan.Info, proposal.Plan.Info) -} diff --git a/x/upgrade/client/cli/query.go b/x/upgrade/client/cli/query.go index 8c8cb43cbe..19400a9177 100644 --- a/x/upgrade/client/cli/query.go +++ b/x/upgrade/client/cli/query.go @@ -51,7 +51,14 @@ func GetCurrentPlanCmd() *cobra.Command { return fmt.Errorf("no upgrade scheduled") } - return clientCtx.PrintProto(res.GetPlan()) + for _, plan := range res.GetPlan() { + err := clientCtx.PrintProto(plan) + if err != nil { + return err + } + } + + return nil }, } diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go deleted file mode 100644 index 2ac2582736..0000000000 --- a/x/upgrade/client/cli/tx.go +++ /dev/null @@ -1,172 +0,0 @@ -package cli - -import ( - "os" - "path/filepath" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/upgrade/plan" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -const ( - // Deprecated: only used for v1beta1 legacy proposals. - FlagUpgradeHeight = "upgrade-height" - // Deprecated: only used for v1beta1 legacy proposals. - FlagUpgradeInfo = "upgrade-info" - FlagNoValidate = "no-validate" - FlagDaemonName = "daemon-name" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Upgrade transaction subcommands", - } - - return cmd -} - -// NewCmdSubmitLegacyUpgradeProposal implements a command handler for submitting a software upgrade proposal transaction. -// Deprecated: please use NewCmdSubmitUpgradeProposal instead. -func NewCmdSubmitLegacyUpgradeProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "software-upgrade [name] (--upgrade-height [height]) (--upgrade-info [info]) [flags]", - Args: cobra.ExactArgs(1), - Short: "Submit a software upgrade proposal", - Long: "Submit a software upgrade along with an initial deposit.\n" + - "Please specify a unique name and height for the upgrade to take effect.\n" + - "You may include info to reference a binary download link, in a format compatible with: https://github.com/cosmos/cosmos-sdk/tree/main/cosmovisor", - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - name := args[0] - content, err := parseArgsToContent(cmd.Flags(), name) - if err != nil { - return err - } - noValidate, err := cmd.Flags().GetBool(FlagNoValidate) - if err != nil { - return err - } - if !noValidate { - prop := content.(*types.SoftwareUpgradeProposal) //nolint:staticcheck - var daemonName string - if daemonName, err = cmd.Flags().GetString(FlagDaemonName); err != nil { - return err - } - var planInfo *plan.Info - if planInfo, err = plan.ParseInfo(prop.Plan.Info); err != nil { - return err - } - if err = planInfo.ValidateFull(daemonName); err != nil { - return err - } - } - - from := clientCtx.GetFromAddress() - - depositStr, err := cmd.Flags().GetString(cli.FlagDeposit) - if err != nil { - return err - } - deposit, err := sdk.ParseCoinsNormalized(depositStr) - if err != nil { - return err - } - - msg, err := v1beta1.NewMsgSubmitProposal(content, deposit, from) - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(cli.FlagTitle, "", "title of proposal") //nolint:staticcheck - cmd.Flags().String(cli.FlagDescription, "", "description of proposal") //nolint:staticcheck - cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") - cmd.Flags().Int64(FlagUpgradeHeight, 0, "The height at which the upgrade must happen") - cmd.Flags().String(FlagUpgradeInfo, "", "Info for the upgrade plan such as new version download urls, etc.") - cmd.Flags().Bool(FlagNoValidate, false, "Skip validation of the upgrade info") - cmd.Flags().String(FlagDaemonName, getDefaultDaemonName(), "The name of the executable being upgraded (for upgrade-info validation). Default is the DAEMON_NAME env var if set, or else this executable") - - return cmd -} - -// NewCmdSubmitLegacyCancelUpgradeProposal implements a command handler for submitting a software upgrade cancel proposal transaction. -// Deprecated: please use NewCmdSubmitCancelUpgradeProposal instead. -func NewCmdSubmitLegacyCancelUpgradeProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "cancel-software-upgrade [flags]", - Args: cobra.ExactArgs(0), - Short: "Cancel the current software upgrade proposal", - Long: "Cancel a software upgrade along with an initial deposit.", - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - from := clientCtx.GetFromAddress() - - depositStr, err := cmd.Flags().GetString(cli.FlagDeposit) - if err != nil { - return err - } - - deposit, err := sdk.ParseCoinsNormalized(depositStr) - if err != nil { - return err - } - - title, err := cmd.Flags().GetString(cli.FlagTitle) //nolint:staticcheck - if err != nil { - return err - } - - description, err := cmd.Flags().GetString(cli.FlagDescription) //nolint:staticcheck - if err != nil { - return err - } - - content := types.NewCancelSoftwareUpgradeProposal(title, description) - - msg, err := v1beta1.NewMsgSubmitProposal(content, deposit, from) - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(cli.FlagTitle, "", "title of proposal") //nolint:staticcheck - cmd.Flags().String(cli.FlagDescription, "", "description of proposal") //nolint:staticcheck - cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") - cmd.MarkFlagRequired(cli.FlagTitle) //nolint:staticcheck - cmd.MarkFlagRequired(cli.FlagDescription) //nolint:staticcheck - - return cmd -} - -// getDefaultDaemonName gets the default name to use for the daemon. -// If a DAEMON_NAME env var is set, that is used. -// Otherwise, the last part of the currently running executable is used. -func getDefaultDaemonName() string { - // DAEMON_NAME is specifically used here to correspond with the Cosmovisor setup env vars. - name := os.Getenv("DAEMON_NAME") - if len(name) == 0 { - _, name = filepath.Split(os.Args[0]) - } - return name -} diff --git a/x/upgrade/client/client.go b/x/upgrade/client/client.go new file mode 100644 index 0000000000..da13c8ef3c --- /dev/null +++ b/x/upgrade/client/client.go @@ -0,0 +1 @@ +package client diff --git a/x/upgrade/client/proposal_handler.go b/x/upgrade/client/proposal_handler.go deleted file mode 100644 index fb4a879fff..0000000000 --- a/x/upgrade/client/proposal_handler.go +++ /dev/null @@ -1,11 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/cosmos/cosmos-sdk/x/upgrade/client/cli" -) - -var ( - LegacyProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyUpgradeProposal) - LegacyCancelProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyCancelUpgradeProposal) -) diff --git a/x/upgrade/handler.go b/x/upgrade/handler.go deleted file mode 100644 index eec03cca59..0000000000 --- a/x/upgrade/handler.go +++ /dev/null @@ -1,36 +0,0 @@ -package upgrade - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -// NewSoftwareUpgradeProposalHandler creates a governance handler to manage new proposal types. -// It enables SoftwareUpgradeProposal to propose an Upgrade, and CancelSoftwareUpgradeProposal -// to abort a previously voted upgrade. -func NewSoftwareUpgradeProposalHandler(k keeper.Keeper) govtypes.Handler { - return func(ctx sdk.Context, content govtypes.Content) error { - switch c := content.(type) { - case *types.SoftwareUpgradeProposal: //nolint:staticcheck - return handleSoftwareUpgradeProposal(ctx, k, c) - - case *types.CancelSoftwareUpgradeProposal: //nolint:staticcheck - return handleCancelSoftwareUpgradeProposal(ctx, k, c) - - default: - return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized software upgrade proposal content type: %T", c) - } - } -} - -func handleSoftwareUpgradeProposal(ctx sdk.Context, k keeper.Keeper, p *types.SoftwareUpgradeProposal) error { //nolint:staticcheck - return k.ScheduleUpgrade(ctx, p.Plan) -} - -func handleCancelSoftwareUpgradeProposal(ctx sdk.Context, k keeper.Keeper, _ *types.CancelSoftwareUpgradeProposal) error { //nolint:staticcheck - k.ClearUpgradePlan(ctx) - return nil -} diff --git a/x/upgrade/keeper/grpc_query.go b/x/upgrade/keeper/grpc_query.go index 3c9e667ac9..15be80b75e 100644 --- a/x/upgrade/keeper/grpc_query.go +++ b/x/upgrade/keeper/grpc_query.go @@ -19,7 +19,7 @@ func (k Keeper) CurrentPlan(c context.Context, req *types.QueryCurrentPlanReques return &types.QueryCurrentPlanResponse{}, nil } - return &types.QueryCurrentPlanResponse{Plan: &plan}, nil + return &types.QueryCurrentPlanResponse{Plan: plan}, nil } // AppliedPlan implements the Query/AppliedPlan gRPC method @@ -70,8 +70,3 @@ func (k Keeper) ModuleVersions(c context.Context, req *types.QueryModuleVersions ModuleVersions: mv, }, nil } - -// Authority implements the Query/Authority gRPC method, returning the account capable of performing upgrades -func (k Keeper) Authority(c context.Context, req *types.QueryAuthorityRequest) (*types.QueryAuthorityResponse, error) { - return &types.QueryAuthorityResponse{Address: k.authority}, nil -} diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index da54ae7fe4..dd0c8eb489 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -12,8 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -57,10 +55,13 @@ func (suite *UpgradeTestSuite) TestQueryCurrentPlan() { "with current upgrade plan", func() { plan := types.Plan{Name: "test-plan", Height: 5} - suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + err := suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + if err != nil { + suite.T().Fatal(err) + } req = &types.QueryCurrentPlanRequest{} - expResponse = types.QueryCurrentPlanResponse{Plan: &plan} + expResponse = types.QueryCurrentPlanResponse{Plan: []*types.Plan{&plan}} }, true, }, @@ -116,6 +117,9 @@ func (suite *UpgradeTestSuite) TestAppliedCurrentPlan() { suite.app.UpgradeKeeper.SetUpgradeHandler(planName, func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + suite.app.UpgradeKeeper.SetUpgradeInitializer(planName, func() error { + return nil + }) suite.app.UpgradeKeeper.ApplyUpgrade(suite.ctx, plan) req = &types.QueryAppliedPlanRequest{Name: planName} @@ -205,12 +209,6 @@ func (suite *UpgradeTestSuite) TestModuleVersions() { } } -func (suite *UpgradeTestSuite) TestAuthority() { - res, err := suite.queryClient.Authority(gocontext.Background(), &types.QueryAuthorityRequest{}) - suite.Require().NoError(err) - suite.Require().Equal(authtypes.NewModuleAddress(govtypes.ModuleName).String(), res.Address) -} - func TestUpgradeTestSuite(t *testing.T) { suite.Run(t, new(UpgradeTestSuite)) } diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index c8edaceeb6..b7d6c74457 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -16,44 +16,41 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/kv" "github.com/cosmos/cosmos-sdk/types/module" - xp "github.com/cosmos/cosmos-sdk/x/upgrade/exported" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) -// Deprecated: UpgradeInfoFileName file to store upgrade information -// use x/upgrade/types.UpgradeInfoFilename instead. -const UpgradeInfoFileName string = "upgrade-info.json" - type Keeper struct { - homePath string // root directory of app config - skipUpgradeHeights map[int64]bool // map of heights to skip for an upgrade - storeKey storetypes.StoreKey // key to access x/upgrade store - cdc codec.BinaryCodec // App-wide binary codec - upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler - versionSetter xp.ProtocolVersionSetter // implements setting the protocol version field on BaseApp - downgradeVerified bool // tells if we've already sanity checked that this binary version isn't being used against an old state. - authority string // the address capable of executing and cancelling an upgrade. Usually the gov module account + homePath string // root directory of app config + storeKey storetypes.StoreKey // key to access x/upgrade store + cdc codec.BinaryCodec // App-wide binary codec + upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler + upgradeInitializer map[string]types.UpgradeInitializer // map of plan name to upgrade initializer + upgradeConfig *types.UpgradeConfig } // NewKeeper constructs an upgrade Keeper which requires the following arguments: -// skipUpgradeHeights - map of heights to skip an upgrade // storeKey - a store key with which to access upgrade's store // cdc - the app-wide binary codec // homePath - root directory of the application's config -// vs - the interface implemented by baseapp which allows setting baseapp's protocol version field -func NewKeeper(skipUpgradeHeights map[int64]bool, storeKey storetypes.StoreKey, cdc codec.BinaryCodec, homePath string, vs xp.ProtocolVersionSetter, authority string) Keeper { - return Keeper{ +func NewKeeper(storeKey storetypes.StoreKey, cdc codec.BinaryCodec, homePath string, opts ...KeeperOption) (Keeper, error) { + keeper := Keeper{ homePath: homePath, - skipUpgradeHeights: skipUpgradeHeights, storeKey: storeKey, cdc: cdc, - upgradeHandlers: map[string]types.UpgradeHandler{}, - versionSetter: vs, - authority: authority, + upgradeHandlers: make(map[string]types.UpgradeHandler), + upgradeInitializer: make(map[string]types.UpgradeInitializer), + upgradeConfig: types.NewUpgradeConfig(), + } + + for _, opt := range opts { + if err := opt(&keeper); err != nil { + return keeper, err + } } + + return keeper, nil } // SetUpgradeHandler sets an UpgradeHandler for the upgrade specified by name. This handler will be called when the upgrade @@ -63,26 +60,11 @@ func (k Keeper) SetUpgradeHandler(name string, upgradeHandler types.UpgradeHandl k.upgradeHandlers[name] = upgradeHandler } -// setProtocolVersion sets the protocol version to state -func (k Keeper) setProtocolVersion(ctx sdk.Context, v uint64) { - store := ctx.KVStore(k.storeKey) - versionBytes := make([]byte, 8) - binary.BigEndian.PutUint64(versionBytes, v) - store.Set([]byte{types.ProtocolVersionByte}, versionBytes) -} - -// getProtocolVersion gets the protocol version from state -func (k Keeper) getProtocolVersion(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - ok := store.Has([]byte{types.ProtocolVersionByte}) - if ok { - pvBytes := store.Get([]byte{types.ProtocolVersionByte}) - protocolVersion := binary.BigEndian.Uint64(pvBytes) - - return protocolVersion - } - // default value - return 0 +// SetUpgradeInitializer sets an UpgradeInitializer for the upgrade specified by name. This initializer will be called when the program restart after upgrade +// with this name is applied. In order for an upgrade with the given name to proceed, a initializer for this upgrade +// must be set even if it is a no-op function. +func (k Keeper) SetUpgradeInitializer(name string, upgradeInitializer types.UpgradeInitializer) { + k.upgradeInitializer[name] = upgradeInitializer } // SetModuleVersionMap saves a given version map to state @@ -176,23 +158,22 @@ func (k Keeper) ScheduleUpgrade(ctx sdk.Context, plan types.Plan) error { // NOTE: allow for the possibility of chains to schedule upgrades in begin block of the same block // as a strategy for emergency hard fork recoveries if plan.Height < ctx.BlockHeight() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "upgrade cannot be scheduled in the past") + return types.ErrUpgradeScheduled } if k.GetDoneHeight(ctx, plan.Name) != 0 { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "upgrade with name %s has already been completed", plan.Name) + return types.ErrUpgradeCompleted } - store := ctx.KVStore(k.storeKey) - // clear any old IBC state stored by previous plan oldPlan, found := k.GetUpgradePlan(ctx) if found { - k.ClearIBCState(ctx, oldPlan.Height) + for _, plan := range oldPlan { + k.ClearIBCState(ctx, plan.Height) + } } - bz := k.cdc.MustMarshal(&plan) - store.Set(types.PlanKey(), bz) + k.upgradeConfig.SetPlan(&plan) return nil } @@ -288,13 +269,16 @@ func (k Keeper) ClearIBCState(ctx sdk.Context, lastHeight int64) { // ClearUpgradePlan clears any schedule upgrade and associated IBC states. func (k Keeper) ClearUpgradePlan(ctx sdk.Context) { // clear IBC states everytime upgrade plan is removed - oldPlan, found := k.GetUpgradePlan(ctx) + planHeight := ctx.BlockHeight() + oldPlans, found := k.GetUpgradePlan(ctx) if found { - k.ClearIBCState(ctx, oldPlan.Height) + for _, plan := range oldPlans { + planHeight = plan.Height + k.ClearIBCState(ctx, plan.Height) + } } - store := ctx.KVStore(k.storeKey) - store.Delete(types.PlanKey()) + k.upgradeConfig.Clear(planHeight) } // Logger returns a module-specific logger. @@ -304,15 +288,24 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { // GetUpgradePlan returns the currently scheduled Plan if any, setting havePlan to true if there is a scheduled // upgrade or false if there is none -func (k Keeper) GetUpgradePlan(ctx sdk.Context) (plan types.Plan, havePlan bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PlanKey()) - if bz == nil { - return plan, false +func (k Keeper) GetUpgradePlan(ctx sdk.Context) ([]*types.Plan, bool) { + plans := k.upgradeConfig.GetPlan(ctx.BlockHeight()) + if len(plans) == 0 { + return nil, false + } + + nonUpgraded := make([]*types.Plan, 0, len(plans)) + for i := 0; i < len(plans); i++ { + if !k.IsUpgraded(ctx, plans[i].Name) { + nonUpgraded = append(nonUpgraded, plans[i]) + } } - k.cdc.MustUnmarshal(bz, &plan) - return plan, true + if len(nonUpgraded) == 0 { + return nil, false + } + + return nonUpgraded, true } // setDone marks this upgrade name as being done so the name can't be reused accidentally @@ -329,38 +322,34 @@ func (k Keeper) HasHandler(name string) bool { // ApplyUpgrade will execute the handler associated with the Plan and mark the plan as done. func (k Keeper) ApplyUpgrade(ctx sdk.Context, plan types.Plan) { + initializer := k.upgradeInitializer[plan.Name] + + if initializer != nil { + err := initializer() + if err != nil { + ctx.Logger().Error("failed to init upgrade ["+plan.Name+"]", "err", err) + return + } + } + handler := k.upgradeHandlers[plan.Name] if handler == nil { - panic("ApplyUpgrade should never be called without first checking HasHandler") + ctx.Logger().Error("missing handler to upgrade [" + plan.Name + "]") + return } updatedVM, err := handler(ctx, plan, k.GetModuleVersionMap(ctx)) if err != nil { - panic(err) + ctx.Logger().Error("failed to upgrade ["+plan.Name+"]", "err", err) + return } - k.SetModuleVersionMap(ctx, updatedVM) - // incremement the protocol version and set it in state and baseapp - nextProtocolVersion := k.getProtocolVersion(ctx) + 1 - k.setProtocolVersion(ctx, nextProtocolVersion) - if k.versionSetter != nil { - // set protocol version on BaseApp - k.versionSetter.SetProtocolVersion(nextProtocolVersion) - } - // Must clear IBC state after upgrade is applied as it is stored separately from the upgrade plan. // This will prevent resubmission of upgrade msg after upgrade is already completed. - k.ClearIBCState(ctx, plan.Height) - k.ClearUpgradePlan(ctx) k.setDone(ctx, plan.Name) } -// IsSkipHeight checks if the given height is part of skipUpgradeHeights -func (k Keeper) IsSkipHeight(height int64) bool { - return k.skipUpgradeHeights[height] -} - // DumpUpgradeInfoToDisk writes upgrade information to UpgradeInfoFileName. func (k Keeper) DumpUpgradeInfoToDisk(height int64, p types.Plan) error { upgradeInfoFilePath, err := k.GetUpgradeInfoPath() @@ -426,12 +415,35 @@ func (k Keeper) ReadUpgradeInfoFromDisk() (types.Plan, error) { return upgradeInfo, nil } -// SetDowngradeVerified updates downgradeVerified. -func (k *Keeper) SetDowngradeVerified(v bool) { - k.downgradeVerified = v +// IsUpgraded returns the bool which the given upgrade was executed +func (k Keeper) IsUpgraded(ctx sdk.Context, name string) bool { + height := k.GetDoneHeight(ctx, name) + if height == 0 { + return false + } + + return height <= ctx.BlockHeight() } -// DowngradeVerified returns downgradeVerified. -func (k Keeper) DowngradeVerified() bool { - return k.downgradeVerified +// InitUpgraded execute the upgrade initializer that the upgrade is already applied. +func (k Keeper) InitUpgraded(ctx sdk.Context) error { + iter := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), []byte{types.DoneByte}) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + upgradeName, height := parseDoneKey(iter.Key()) + if height < ctx.BlockHeight() { + f := k.upgradeInitializer[upgradeName] + if f == nil { + continue + } + + err := f() + if err != nil { + return err + } + } + } + + return nil } diff --git a/x/upgrade/keeper/keeper_option.go b/x/upgrade/keeper/keeper_option.go new file mode 100644 index 0000000000..0ea1088e0a --- /dev/null +++ b/x/upgrade/keeper/keeper_option.go @@ -0,0 +1,65 @@ +package keeper + +import ( + serverconfig "github.com/cosmos/cosmos-sdk/server/config" + "github.com/cosmos/cosmos-sdk/x/upgrade/types" +) + +func convertUpgradeConfig(chainID string, plans []serverconfig.UpgradeConfig) (*types.UpgradeConfig, error) { + upgradeConfig := types.NewUpgradeConfig() + if chainID == types.MainnetChainID { + upgradeConfig = types.MainnetConfig + } + + // override by app config + for _, plan := range plans { + nPlan := &types.Plan{ + Name: plan.Name, + Height: plan.Height, + Info: plan.Info, + } + if err := nPlan.ValidateBasic(); err != nil { + return nil, err + } + upgradeConfig.SetPlan(nPlan) + } + + return upgradeConfig, nil +} + +// Option function for Keeper +type KeeperOption func(k *Keeper) error + +// RegisterUpgradePlan returns a KeeperOption to set the upgrade plan into the upgrade keeper +func RegisterUpgradePlan(chianID string, + plans []serverconfig.UpgradeConfig, +) KeeperOption { + return func(k *Keeper) error { + c, err := convertUpgradeConfig(chianID, plans) + if err != nil { + return err + } + k.upgradeConfig = c + return nil + } +} + +// RegisterUpgradeHandler returns a KeeperOption to set the upgrade handler into the upgrade keeper +func RegisterUpgradeHandler(handlers map[string]types.UpgradeHandler) KeeperOption { + return func(k *Keeper) error { + for name, handler := range handlers { + k.SetUpgradeHandler(name, handler) + } + return nil + } +} + +// RegisterUpgradeInitializer returns a KeeperOption to set the upgrade initializer into the upgrade keeper +func RegisterUpgradeInitializer(handlers map[string]types.UpgradeInitializer) KeeperOption { + return func(k *Keeper) error { + for name, handler := range handlers { + k.SetUpgradeInitializer(name, handler) + } + return nil + } +} diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index 19fee1054e..ee91bf1c31 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -11,8 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -23,17 +21,19 @@ type KeeperTestSuite struct { homeDir string app *simapp.SimApp ctx sdk.Context - msgSrvr types.MsgServer addrs []sdk.AccAddress } func (s *KeeperTestSuite) SetupTest() { + var err error app := simapp.Setup(s.T(), false) homeDir := filepath.Join(s.T().TempDir(), "x_upgrade_keeper_test") - app.UpgradeKeeper = keeper.NewKeeper( // recreate keeper in order to use a custom home path - make(map[int64]bool), app.GetKey(types.StoreKey), app.AppCodec(), homeDir, app.BaseApp, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + app.UpgradeKeeper, err = keeper.NewKeeper( // recreate keeper in order to use a custom home Path + app.GetKey(types.StoreKey), app.AppCodec(), homeDir, ) + if err != nil { + s.T().Fatal(err) + } s.T().Log("home dir:", homeDir) s.homeDir = homeDir s.app = app @@ -41,7 +41,6 @@ func (s *KeeperTestSuite) SetupTest() { Time: time.Now(), Height: 10, }) - s.msgSrvr = keeper.NewMsgServerImpl(s.app.UpgradeKeeper) s.addrs = simapp.AddTestAddrsIncremental(app, s.ctx, 1, sdk.NewInt(30000000)) } @@ -126,6 +125,7 @@ func (s *KeeperTestSuite) TestScheduleUpgrade() { s.app.UpgradeKeeper.SetUpgradeHandler("all-good", func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + s.app.UpgradeKeeper.SetUpgradeInitializer("all-good", func() error { return nil }) s.app.UpgradeKeeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "all-good", Info: "some text here", @@ -200,22 +200,6 @@ func (s *KeeperTestSuite) TestSetUpgradedClient() { } } -// Test that the protocol version successfully increments after an -// upgrade and is successfully set on BaseApp's appVersion. -func (s *KeeperTestSuite) TestIncrementProtocolVersion() { - oldProtocolVersion := s.app.BaseApp.AppVersion() - s.app.UpgradeKeeper.SetUpgradeHandler("dummy", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) - dummyPlan := types.Plan{ - Name: "dummy", - Info: "some text here", - Height: 100, - } - s.app.UpgradeKeeper.ApplyUpgrade(s.ctx, dummyPlan) - upgradedProtocolVersion := s.app.BaseApp.AppVersion() - - s.Require().Equal(oldProtocolVersion+1, upgradedProtocolVersion) -} - // Tests that the underlying state of x/upgrade is set correctly after // an upgrade. func (s *KeeperTestSuite) TestMigrations() { @@ -227,6 +211,7 @@ func (s *KeeperTestSuite) TestMigrations() { vm["bank"] = vm["bank"] + 1 return vm, nil }) + s.app.UpgradeKeeper.SetUpgradeInitializer("dummy", func() error { return nil }) dummyPlan := types.Plan{ Name: "dummy", Info: "some text here", @@ -250,6 +235,7 @@ func (s *KeeperTestSuite) TestLastCompletedUpgrade() { keeper.SetUpgradeHandler("test0", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + keeper.SetUpgradeInitializer("test0", func() error { return nil }) keeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "test0", @@ -264,6 +250,7 @@ func (s *KeeperTestSuite) TestLastCompletedUpgrade() { keeper.SetUpgradeHandler("test1", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + keeper.SetUpgradeInitializer("test1", func() error { return nil }) newCtx := s.ctx.WithBlockHeight(15) keeper.ApplyUpgrade(newCtx, types.Plan{ @@ -287,6 +274,7 @@ func (s *KeeperTestSuite) TestLastCompletedUpgradeOrdering() { keeper.SetUpgradeHandler("test-v0.9", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + keeper.SetUpgradeInitializer("test-v0.9", func() error { return nil }) keeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "test-v0.9", @@ -301,6 +289,7 @@ func (s *KeeperTestSuite) TestLastCompletedUpgradeOrdering() { keeper.SetUpgradeHandler("test-v0.10", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) + keeper.SetUpgradeInitializer("test-v0.10", func() error { return nil }) newCtx := s.ctx.WithBlockHeight(15) keeper.ApplyUpgrade(newCtx, types.Plan{ diff --git a/x/upgrade/keeper/msg_server.go b/x/upgrade/keeper/msg_server.go deleted file mode 100644 index 1e1249f5e8..0000000000 --- a/x/upgrade/keeper/msg_server.go +++ /dev/null @@ -1,51 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - gov "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -type msgServer struct { - Keeper -} - -// NewMsgServerImpl returns an implementation of the upgrade MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(k Keeper) types.MsgServer { - return &msgServer{ - Keeper: k, - } -} - -var _ types.MsgServer = msgServer{} - -// SoftwareUpgrade implements the Msg/SoftwareUpgrade Msg service. -func (k msgServer) SoftwareUpgrade(goCtx context.Context, req *types.MsgSoftwareUpgrade) (*types.MsgSoftwareUpgradeResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - err := k.ScheduleUpgrade(ctx, req.Plan) - if err != nil { - return nil, err - } - - return &types.MsgSoftwareUpgradeResponse{}, nil -} - -// CancelUpgrade implements the Msg/CancelUpgrade Msg service. -func (k msgServer) CancelUpgrade(goCtx context.Context, req *types.MsgCancelUpgrade) (*types.MsgCancelUpgradeResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - k.ClearUpgradePlan(ctx) - - return &types.MsgCancelUpgradeResponse{}, nil -} diff --git a/x/upgrade/keeper/msg_server_test.go b/x/upgrade/keeper/msg_server_test.go deleted file mode 100644 index a83cdc09b7..0000000000 --- a/x/upgrade/keeper/msg_server_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper_test - -import ( - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -func (s *KeeperTestSuite) TestSoftwareUpgrade() { - govAccAddr := s.app.GovKeeper.GetGovernanceAccount(s.ctx).GetAddress().String() - - testCases := []struct { - name string - req *types.MsgSoftwareUpgrade - expectErr bool - errMsg string - }{ - { - "unauthorized authority address", - &types.MsgSoftwareUpgrade{ - Authority: s.addrs[0].String(), - Plan: types.Plan{ - Name: "all-good", - Info: "some text here", - Height: 123450000, - }, - }, - true, - "expected gov account as only signer for proposal message", - }, - { - "invalid plan", - &types.MsgSoftwareUpgrade{ - Authority: govAccAddr, - Plan: types.Plan{ - Height: 123450000, - }, - }, - true, - "name cannot be empty: invalid request", - }, - { - "successful upgrade scheduled", - &types.MsgSoftwareUpgrade{ - Authority: govAccAddr, - Plan: types.Plan{ - Name: "all-good", - Info: "some text here", - Height: 123450000, - }, - }, - false, - "", - }, - } - for _, tc := range testCases { - s.Run(tc.name, func() { - _, err := s.msgSrvr.SoftwareUpgrade(s.ctx, tc.req) - if tc.expectErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), tc.errMsg) - } else { - s.Require().NoError(err) - plan, found := s.app.UpgradeKeeper.GetUpgradePlan(s.ctx) - s.Require().Equal(true, found) - s.Require().Equal(tc.req.Plan, plan) - } - }) - } -} - -func (s *KeeperTestSuite) TestCancelUpgrade() { - govAccAddr := s.app.GovKeeper.GetGovernanceAccount(s.ctx).GetAddress().String() - err := s.app.UpgradeKeeper.ScheduleUpgrade(s.ctx, types.Plan{ - Name: "some name", - Info: "some info", - Height: 123450000, - }) - s.Require().NoError(err) - - testCases := []struct { - name string - req *types.MsgCancelUpgrade - expectErr bool - errMsg string - }{ - { - "unauthorized authority address", - &types.MsgCancelUpgrade{ - Authority: s.addrs[0].String(), - }, - true, - "expected gov account as only signer for proposal message", - }, - { - "upgrade cancelled successfully", - &types.MsgCancelUpgrade{ - Authority: govAccAddr, - }, - false, - "", - }, - } - for _, tc := range testCases { - s.Run(tc.name, func() { - _, err := s.msgSrvr.CancelUpgrade(s.ctx, tc.req) - if tc.expectErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), tc.errMsg) - } else { - s.Require().NoError(err) - _, found := s.app.UpgradeKeeper.GetUpgradePlan(s.ctx) - s.Require().Equal(false, found) - } - }) - } -} diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 9a31d21241..f5c33f0df4 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -18,10 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) -func init() { - types.RegisterLegacyAminoCodec(codec.NewLegacyAmino()) -} - const ( consensusVersion uint64 = 2 ) @@ -40,9 +36,7 @@ func (AppModuleBasic) Name() string { } // RegisterLegacyAminoCodec registers the upgrade types on the LegacyAmino codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the upgrade module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { @@ -58,12 +52,10 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { // GetTxCmd returns the transaction commands for this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() + return nil } -func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} +func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {} // AppModule implements the sdk.AppModule interface type AppModule struct { @@ -97,7 +89,6 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) m := keeper.NewMigrator(am.keeper) diff --git a/x/upgrade/plan/downloader.go b/x/upgrade/plan/downloader.go deleted file mode 100644 index d09d4725b8..0000000000 --- a/x/upgrade/plan/downloader.go +++ /dev/null @@ -1,143 +0,0 @@ -package plan - -import ( - "errors" - "fmt" - neturl "net/url" - "os" - "path/filepath" - "strings" - - "github.com/hashicorp/go-getter" -) - -// DownloadUpgrade downloads the given url into the provided directory and ensures it's valid. -// The provided url must contain a checksum parameter that matches the file being downloaded. -// If this returns nil, the download was successful, and {dstRoot}/bin/{daemonName} is a regular executable file. -// This is an opinionated directory structure that corresponds with Cosmovisor requirements. -// If the url is not an archive, it is downloaded and saved to {dstRoot}/bin/{daemonName}. -// If the url is an archive, it is downloaded and unpacked to {dstRoot}. -// -// If the archive does not contain a /bin/{daemonName} file, then this will attempt to move /{daemonName} to /bin/{daemonName}. -// If the archive does not contain either /bin/{daemonName} or /{daemonName}, an error is returned. -// -// Note: Because a checksum is required, this function cannot be used to download non-archive directories. -// If dstRoot already exists, some or all of its contents might be updated. -func DownloadUpgrade(dstRoot, url, daemonName string) error { - if err := ValidateIsURLWithChecksum(url); err != nil { - return err - } - target := filepath.Join(dstRoot, "bin", daemonName) - // First try to download it as a single file. If there's no error, it's okay and we're done. - if err := getter.GetFile(target, url); err != nil { - // If it was a checksum error, no need to try as directory. - if _, ok := err.(*getter.ChecksumError); ok { - return err - } - // File download didn't work, try it as an archive. - if err = downloadUpgradeAsArchive(dstRoot, url, daemonName); err != nil { - // Out of options, send back the error. - return err - } - } - return EnsureBinary(target) -} - -// downloadUpgradeAsArchive tries to download the given url as an archive. -// The archive is unpacked and saved in dstDir. -// If the archive contains /{daemonName} and not /bin/{daemonName}, then /{daemonName} will be moved to /bin/{daemonName}. -// If this returns nil, the download was successful, and {dstDir}/bin/{daemonName} is a regular executable file. -func downloadUpgradeAsArchive(dstDir, url, daemonName string) error { - err := getter.Get(dstDir, url) - if err != nil { - return err - } - - // If bin/{daemonName} exists, we're done. - dstDirBinFile := filepath.Join(dstDir, "bin", daemonName) - err = EnsureBinary(dstDirBinFile) - if err == nil { - return nil - } - - // Otherwise, check for a root {daemonName} file and move it to the bin/ directory if found. - dstDirFile := filepath.Join(dstDir, daemonName) - err = EnsureBinary(dstDirFile) - if err == nil { - err = os.Rename(dstDirFile, dstDirBinFile) - if err != nil { - return fmt.Errorf("could not move %s to the bin directory: %w", daemonName, err) - } - return nil - } - - return fmt.Errorf("url \"%s\" result does not contain a bin/%s or %s file", url, daemonName, daemonName) -} - -// EnsureBinary checks that the given file exists as a regular file and is executable. -// An error is returned if: -// - The file does not exist. -// - The path exists, but is one of: Dir, Symlink, NamedPipe, Socket, Device, CharDevice, or Irregular. -// - The file exists, is not executable by all three of User, Group, and Other, and cannot be made executable. -func EnsureBinary(path string) error { - info, err := os.Stat(path) - if err != nil { - return err - } - if !info.Mode().IsRegular() { - _, f := filepath.Split(path) - return fmt.Errorf("%s is not a regular file", f) - } - // Make sure all executable bits are set. - oldMode := info.Mode().Perm() - newMode := oldMode | 0o111 // Set the three execute bits to on (a+x). - if oldMode != newMode { - return os.Chmod(path, newMode) - } - return nil -} - -// DownloadURLWithChecksum gets the contents of the given url, ensuring the checksum is correct. -// The provided url must contain a checksum parameter that matches the file being downloaded. -// If there isn't an error, the content returned by the url will be returned as a string. -// Returns an error if: -// - The url is not a URL or does not contain a checksum parameter. -// - Downloading the URL fails. -// - The checksum does not match what is returned by the URL. -// - The URL does not return a regular file. -// - The downloaded file is empty or only whitespace. -func DownloadURLWithChecksum(url string) (string, error) { - if err := ValidateIsURLWithChecksum(url); err != nil { - return "", err - } - tempDir, err := os.MkdirTemp("", "reference") - if err != nil { - return "", fmt.Errorf("could not create temp directory: %w", err) - } - defer os.RemoveAll(tempDir) - tempFile := filepath.Join(tempDir, "content") - if err = getter.GetFile(tempFile, url); err != nil { - return "", fmt.Errorf("could not download url \"%s\": %w", url, err) - } - tempFileBz, rerr := os.ReadFile(tempFile) - if rerr != nil { - return "", fmt.Errorf("could not read downloaded temporary file: %w", rerr) - } - tempFileStr := strings.TrimSpace(string(tempFileBz)) - if len(tempFileStr) == 0 { - return "", fmt.Errorf("no content returned by \"%s\"", url) - } - return tempFileStr, nil -} - -// ValidateIsURLWithChecksum checks that the given string is a url and contains a checksum query parameter. -func ValidateIsURLWithChecksum(urlStr string) error { - url, err := neturl.Parse(urlStr) - if err != nil { - return err - } - if len(url.Query().Get("checksum")) == 0 { - return errors.New("missing checksum query parameter") - } - return nil -} diff --git a/x/upgrade/plan/downloader_test.go b/x/upgrade/plan/downloader_test.go deleted file mode 100644 index 3d50e9f13a..0000000000 --- a/x/upgrade/plan/downloader_test.go +++ /dev/null @@ -1,299 +0,0 @@ -package plan - -import ( - "archive/zip" - "crypto/sha256" - "fmt" - "io" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" -) - -type DownloaderTestSuite struct { - suite.Suite - - // Home is a temporary directory for use in these tests. - // It will have a src/ for things to download. - Home string -} - -func (s *DownloaderTestSuite) SetupTest() { - s.Home = s.T().TempDir() - s.Assert().NoError(os.MkdirAll(filepath.Join(s.Home, "src"), 0o777), "creating src/ dir") - s.T().Logf("Home: [%s]", s.Home) -} - -func TestDownloaderTestSuite(t *testing.T) { - suite.Run(t, new(DownloaderTestSuite)) -} - -// TestFile represents a file that will be used for a test. -type TestFile struct { - // Name is the relative path and name of the file. - Name string - // Contents is the contents of the file. - Contents []byte -} - -func NewTestFile(name, contents string) *TestFile { - return &TestFile{ - Name: name, - Contents: []byte(contents), - } -} - -// SaveIn saves this TestFile in the given path. -// The full path to the file is returned. -func (f TestFile) SaveIn(path string) (string, error) { - name := filepath.Join(path, f.Name) - file, err := os.Create(name) - if err != nil { - return name, err - } - defer file.Close() - _, err = file.Write(f.Contents) - return name, err -} - -// TestZip represents a collection of TestFile objects to be zipped into an archive. -type TestZip []*TestFile - -func NewTestZip(testFiles ...*TestFile) TestZip { - tz := make([]*TestFile, len(testFiles)) - for i, tf := range testFiles { - tz[i] = tf - } - return tz -} - -// SaveAs saves this TestZip at the given path. -func (z TestZip) SaveAs(path string) error { - archive, err := os.Create(path) - if err != nil { - return err - } - defer archive.Close() - zipper := zip.NewWriter(archive) - for _, tf := range z { - zfw, zfwerr := zipper.Create(tf.Name) - if zfwerr != nil { - return zfwerr - } - _, err = zfw.Write(tf.Contents) - if err != nil { - return err - } - } - return zipper.Close() -} - -// saveTestZip saves a TestZip in this test's Home/src directory with the given name. -// The full path to the saved archive is returned. -func (s DownloaderTestSuite) saveSrcTestZip(name string, z TestZip) string { - fullName := filepath.Join(s.Home, "src", name) - s.Require().NoError(z.SaveAs(fullName), "saving test zip %s", name) - return fullName -} - -// saveSrcTestFile saves a TestFile in this test's Home/src directory. -// The full path to the saved file is returned. -func (s DownloaderTestSuite) saveSrcTestFile(f *TestFile) string { - path := filepath.Join(s.Home, "src") - fullName, err := f.SaveIn(path) - s.Require().NoError(err, "saving test file %s", f.Name) - return fullName -} - -// requireFileExistsAndIsExecutable requires that the given file exists and is executable. -func requireFileExistsAndIsExecutable(t *testing.T, path string) { - info, err := os.Stat(path) - require.NoError(t, err, "stat error") - perm := info.Mode().Perm() - // Checks if at least one executable bit is set (user, group, or other) - isExe := perm&0o111 != 0 - require.True(t, isExe, "is executable: permissions = %s", perm) -} - -// requireFileEquals requires that the contents of the file at the given path -// is equal to the contents of the given TestFile. -func requireFileEquals(t *testing.T, path string, tf *TestFile) { - file, err := os.ReadFile(path) - require.NoError(t, err, "reading file") - require.Equal(t, string(tf.Contents), string(file), "file contents") -} - -// makeFileUrl converts the given path to a URL with the correct checksum query parameter. -func makeFileURL(t *testing.T, path string) string { - f, err := os.Open(path) - require.NoError(t, err, "opening file") - defer f.Close() - hasher := sha256.New() - _, err = io.Copy(hasher, f) - require.NoError(t, err, "copying file to hasher") - return fmt.Sprintf("file://%s?checksum=sha256:%x", path, hasher.Sum(nil)) -} - -func (s *DownloaderTestSuite) TestDownloadUpgrade() { - justAFile := NewTestFile("just-a-file", "#!/usr/bin\necho 'I am just a file'\n") - someFileName := "some-file" - someFileInBin := NewTestFile("bin"+someFileName, "#!/usr/bin\necho 'I am some file in bin'\n") - anotherFile := NewTestFile("another-file", "#!/usr/bin\necho 'I am just another file'\n") - justAFilePath := s.saveSrcTestFile(justAFile) - justAFileZip := s.saveSrcTestZip(justAFile.Name+".zip", NewTestZip(justAFile)) - someFileInBinZip := s.saveSrcTestZip(someFileInBin.Name+".zip", NewTestZip(someFileInBin)) - allFilesZip := s.saveSrcTestZip(anotherFile.Name+".zip", NewTestZip(justAFile, someFileInBin, anotherFile)) - getDstDir := func(testName string) string { - _, tName := filepath.Split(testName) - return s.Home + "/dst/" + tName - } - - s.T().Run("url does not exist", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := "file:///never/gonna/be/a/thing.zip?checksum=sha256:2c22e34510bd1d4ad2343cdc54f7165bccf30caef73f39af7dd1db2795a3da48" - err := DownloadUpgrade(dstRoot, url, "nothing") - require.Error(t, err) - assert.Contains(t, err.Error(), "no such file or directory") - }) - - s.T().Run("url does not have checksum", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := "file://" + justAFilePath - err := DownloadUpgrade(dstRoot, url, justAFile.Name) - require.Error(t, err) - require.Contains(t, err.Error(), "missing checksum query parameter") - }) - - s.T().Run("url has incorrect checksum", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - badChecksum := "2c22e34510bd1d4ad2343cdc54f7165bccf30caef73f39af7dd1db2795a3da48" - url := "file://" + justAFilePath + "?checksum=sha256:" + badChecksum - err := DownloadUpgrade(dstRoot, url, justAFile.Name) - require.Error(t, err) - assert.Contains(t, err.Error(), "Checksums did not match") - assert.Contains(t, err.Error(), "Expected: "+badChecksum) - }) - - s.T().Run("url returns single file", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := makeFileURL(t, justAFilePath) - err := DownloadUpgrade(dstRoot, url, justAFile.Name) - require.NoError(t, err) - expectedFile := filepath.Join(dstRoot, "bin", justAFile.Name) - requireFileExistsAndIsExecutable(t, expectedFile) - requireFileEquals(t, expectedFile, justAFile) - }) - - s.T().Run("url returns archive with file in bin", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := makeFileURL(t, someFileInBinZip) - err := DownloadUpgrade(dstRoot, url, someFileName) - require.NoError(t, err) - expectedFile := filepath.Join(dstRoot, "bin", someFileName) - requireFileExistsAndIsExecutable(t, expectedFile) - requireFileEquals(t, expectedFile, someFileInBin) - }) - - s.T().Run("url returns archive with just expected file", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := makeFileURL(t, justAFileZip) - err := DownloadUpgrade(dstRoot, url, justAFile.Name) - require.NoError(t, err) - expectedFile := filepath.Join(dstRoot, "bin", justAFile.Name) - requireFileExistsAndIsExecutable(t, expectedFile) - requireFileEquals(t, expectedFile, justAFile) - }) - - s.T().Run("url returns archive without expected file", func(t *testing.T) { - dstRoot := getDstDir(t.Name()) - url := makeFileURL(t, allFilesZip) - err := DownloadUpgrade(dstRoot, url, "not-expected") - require.Error(t, err) - require.Contains(t, err.Error(), "result does not contain a bin/not-expected or not-expected file") - }) -} - -func (s *DownloaderTestSuite) TestEnsureBinary() { - nonExeName := s.saveSrcTestFile(NewTestFile("non-exe.txt", "Not executable")) - s.Require().NoError(os.Chmod(nonExeName, 0o600), "chmod error nonExeName") - isExeName := s.saveSrcTestFile(NewTestFile("is-exe.sh", "#!/bin/bash\necho 'executing'\n")) - s.Require().NoError(os.Chmod(isExeName, 0o777), "chmod error isExeName") - - s.T().Run("file does not exist", func(t *testing.T) { - name := filepath.Join(s.Home, "does-not-exist.txt") - actual := EnsureBinary(name) - require.Error(t, actual) - }) - - s.T().Run("file is a directory", func(t *testing.T) { - name := filepath.Join(s.Home, "src") - actual := EnsureBinary(name) - require.EqualError(t, actual, fmt.Sprintf("%s is not a regular file", "src")) - }) - - s.T().Run("file exists and becomes executable", func(t *testing.T) { - name := nonExeName - actual := EnsureBinary(name) - require.NoError(t, actual, "EnsureBinary error") - requireFileExistsAndIsExecutable(t, name) - }) - - s.T().Run("file is already executable", func(t *testing.T) { - name := isExeName - actual := EnsureBinary(name) - require.NoError(t, actual, "EnsureBinary error") - requireFileExistsAndIsExecutable(t, name) - }) -} - -func (s *DownloaderTestSuite) TestDownloadURLWithChecksum() { - planContents := `{"binaries":{"xxx/yyy":"url"}}` - planFile := NewTestFile("plan-info.json", planContents) - planPath := s.saveSrcTestFile(planFile) - planChecksum := fmt.Sprintf("%x", sha256.Sum256(planFile.Contents)) - emptyFile := NewTestFile("empty-plan-info.json", "") - emptyPlanPath := s.saveSrcTestFile(emptyFile) - emptyChecksum := fmt.Sprintf("%x", sha256.Sum256(emptyFile.Contents)) - - s.T().Run("url does not exist", func(t *testing.T) { - url := "file:///never-gonna-be-a-thing?checksum=sha256:2c22e34510bd1d4ad2343cdc54f7165bccf30caef73f39af7dd1db2795a3da48" - _, err := DownloadURLWithChecksum(url) - require.Error(t, err) - assert.Contains(t, err.Error(), "could not download url") - }) - - s.T().Run("without checksum", func(t *testing.T) { - url := "file://" + planPath - _, err := DownloadURLWithChecksum(url) - require.Error(t, err) - assert.Contains(t, err.Error(), "missing checksum query parameter") - }) - - s.T().Run("with correct checksum", func(t *testing.T) { - url := "file://" + planPath + "?checksum=sha256:" + planChecksum - actual, err := DownloadURLWithChecksum(url) - require.NoError(t, err) - require.Equal(t, planContents, actual) - }) - - s.T().Run("with incorrect checksum", func(t *testing.T) { - badChecksum := "2c22e34510bd1d4ad2343cdc54f7165bccf30caef73f39af7dd1db2795a3da48" - url := "file://" + planPath + "?checksum=sha256:" + badChecksum - _, err := DownloadURLWithChecksum(url) - require.Error(t, err) - assert.Contains(t, err.Error(), "Checksums did not match") - assert.Contains(t, err.Error(), "Expected: "+badChecksum) - assert.Contains(t, err.Error(), "Got: "+planChecksum) - }) - - s.T().Run("plan is empty", func(t *testing.T) { - url := "file://" + emptyPlanPath + "?checksum=sha256:" + emptyChecksum - _, err := DownloadURLWithChecksum(url) - require.Error(t, err) - assert.Contains(t, err.Error(), "no content returned") - }) -} diff --git a/x/upgrade/plan/info.go b/x/upgrade/plan/info.go deleted file mode 100644 index c29ec2ab5a..0000000000 --- a/x/upgrade/plan/info.go +++ /dev/null @@ -1,109 +0,0 @@ -package plan - -import ( - "encoding/json" - "errors" - "fmt" - neturl "net/url" - "os" - "path/filepath" - "regexp" - "strings" - - "github.com/cosmos/cosmos-sdk/internal/conv" -) - -// Info is the special structure that the Plan.Info string can be (as json). -type Info struct { - Binaries BinaryDownloadURLMap `json:"binaries"` -} - -// BinaryDownloadURLMap is a map of os/architecture stings to a URL where the binary can be downloaded. -type BinaryDownloadURLMap map[string]string - -// ParseInfo parses an info string into a map of os/arch strings to URL string. -// If the infoStr is a url, an GET request will be made to it, and its response will be parsed instead. -func ParseInfo(infoStr string) (*Info, error) { - infoStr = strings.TrimSpace(infoStr) - - if len(infoStr) == 0 { - return nil, errors.New("plan info must not be blank") - } - - // If it's a url, download it and treat the result as the real info. - if _, err := neturl.Parse(infoStr); err == nil { - infoStr, err = DownloadURLWithChecksum(infoStr) - if err != nil { - return nil, err - } - } - - // Now, try to parse it into the expected structure. - var planInfo Info - if err := json.Unmarshal(conv.UnsafeStrToBytes(infoStr), &planInfo); err != nil { - return nil, fmt.Errorf("could not parse plan info: %v", err) - } - - return &planInfo, nil -} - -// ValidateFull does all possible validation of this Info. -// The provided daemonName is the name of the executable file expected in all downloaded directories. -// It checks that: -// - Binaries.ValidateBasic() doesn't return an error -// - Binaries.CheckURLs(daemonName) doesn't return an error. -// -// Warning: This is an expensive process. See BinaryDownloadURLMap.CheckURLs for more info. -func (m Info) ValidateFull(daemonName string) error { - if err := m.Binaries.ValidateBasic(); err != nil { - return err - } - if err := m.Binaries.CheckURLs(daemonName); err != nil { - return err - } - return nil -} - -// ValidateBasic does stateless validation of this BinaryDownloadURLMap. -// It validates that: -// - This has at least one entry. -// - All entry keys have the format "os/arch" or are "any". -// - All entry values are valid URLs. -// - All URLs contain a checksum query parameter. -func (m BinaryDownloadURLMap) ValidateBasic() error { - // Make sure there's at least one. - if len(m) == 0 { - return errors.New("no \"binaries\" entries found") - } - - osArchRx := regexp.MustCompile(`[a-zA-Z0-9]+/[a-zA-Z0-9]+`) - for key, val := range m { - if key != "any" && !osArchRx.MatchString(key) { - return fmt.Errorf("invalid os/arch format in key \"%s\"", key) - } - if err := ValidateIsURLWithChecksum(val); err != nil { - return fmt.Errorf("invalid url \"%s\" in binaries[%s]: %v", val, key, err) - } - } - - return nil -} - -// CheckURLs checks that all entries have valid URLs that return expected data. -// The provided daemonName is the name of the executable file expected in all downloaded directories. -// Warning: This is an expensive process. -// It will make an HTTP GET request to each URL and download the response. -func (m BinaryDownloadURLMap) CheckURLs(daemonName string) error { - tempDir, err := os.MkdirTemp("", "os-arch-downloads") - if err != nil { - return fmt.Errorf("could not create temp directory: %w", err) - } - defer os.RemoveAll(tempDir) - for osArch, url := range m { - dstRoot := filepath.Join(tempDir, strings.ReplaceAll(osArch, "/", "-")) - if err = DownloadUpgrade(dstRoot, url, daemonName); err != nil { - return fmt.Errorf("error downloading binary for os/arch %s: %v", osArch, err) - } - } - return nil -} diff --git a/x/upgrade/plan/info_test.go b/x/upgrade/plan/info_test.go deleted file mode 100644 index 65736a5e67..0000000000 --- a/x/upgrade/plan/info_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package plan - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" -) - -type InfoTestSuite struct { - suite.Suite - - // Home is a temporary directory for use in these tests. - Home string -} - -func (s *InfoTestSuite) SetupTest() { - s.Home = s.T().TempDir() - s.T().Logf("Home: [%s]", s.Home) -} - -func TestInfoTestSuite(t *testing.T) { - suite.Run(t, new(InfoTestSuite)) -} - -// saveSrcTestFile saves a TestFile in this test's Home/src directory. -// The full path to the saved file is returned. -func (s InfoTestSuite) saveTestFile(f *TestFile) string { - fullName, err := f.SaveIn(s.Home) - s.Require().NoError(err, "saving test file %s", f.Name) - return fullName -} - -func (s InfoTestSuite) TestParseInfo() { - goodJSON := `{"binaries":{"os1/arch1":"url1","os2/arch2":"url2"}}` - binariesWrongJSON := `{"binaries":["foo","bar"]}` - binariesWrongValueJSON := `{"binaries":{"os1/arch1":1,"os2/arch2":2}}` - goodJSONPath := s.saveTestFile(NewTestFile("good.json", goodJSON)) - binariesWrongJSONPath := s.saveTestFile(NewTestFile("binaries-wrong.json", binariesWrongJSON)) - binariesWrongValueJSONPath := s.saveTestFile(NewTestFile("binaries-wrong-value.json", binariesWrongValueJSON)) - goodJSONAsInfo := &Info{ - Binaries: BinaryDownloadURLMap{ - "os1/arch1": "url1", - "os2/arch2": "url2", - }, - } - makeInfoStrFuncString := func(val string) func(t *testing.T) string { - return func(t *testing.T) string { - return val - } - } - makeInfoStrFuncURL := func(file string) func(t *testing.T) string { - return func(t *testing.T) string { - return makeFileURL(t, file) - } - } - - tests := []struct { - name string - infoStrMaker func(t *testing.T) string - expectedInfo *Info - expectedInError []string - }{ - { - name: "json good", - infoStrMaker: makeInfoStrFuncString(goodJSON), - expectedInfo: goodJSONAsInfo, - expectedInError: nil, - }, - { - name: "blank string", - infoStrMaker: makeInfoStrFuncString(" "), - expectedInfo: nil, - expectedInError: []string{"plan info must not be blank"}, - }, - { - name: "json binaries is wrong data type", - infoStrMaker: makeInfoStrFuncString(binariesWrongJSON), - expectedInfo: nil, - expectedInError: []string{"could not parse plan info", "cannot unmarshal array into Go struct field Info.binaries"}, - }, - { - name: "json wrong data type in binaries value", - infoStrMaker: makeInfoStrFuncString(binariesWrongValueJSON), - expectedInfo: nil, - expectedInError: []string{"could not parse plan info", "cannot unmarshal number into Go struct field Info.binaries"}, - }, - { - name: "url does not exist", - infoStrMaker: makeInfoStrFuncString("file:///this/file/does/not/exist?checksum=sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), - expectedInfo: nil, - expectedInError: []string{"could not download url", "file:///this/file/does/not/exist"}, - }, - { - name: "url good", - infoStrMaker: makeInfoStrFuncURL(goodJSONPath), - expectedInfo: goodJSONAsInfo, - expectedInError: nil, - }, - { - name: "url binaries is wrong data type", - infoStrMaker: makeInfoStrFuncURL(binariesWrongJSONPath), - expectedInfo: nil, - expectedInError: []string{"could not parse plan info", "cannot unmarshal array into Go struct field Info.binaries"}, - }, - { - name: "url wrong data type in binaries value", - infoStrMaker: makeInfoStrFuncURL(binariesWrongValueJSONPath), - expectedInfo: nil, - expectedInError: []string{"could not parse plan info", "cannot unmarshal number into Go struct field Info.binaries"}, - }, - } - - for _, tc := range tests { - s.T().Run(tc.name, func(t *testing.T) { - infoStr := tc.infoStrMaker(t) - actualInfo, actualErr := ParseInfo(infoStr) - if len(tc.expectedInError) > 0 { - require.Error(t, actualErr) - for _, expectedErr := range tc.expectedInError { - assert.Contains(t, actualErr.Error(), expectedErr) - } - } else { - require.NoError(t, actualErr) - } - assert.Equal(t, tc.expectedInfo, actualInfo) - }) - } -} - -func (s InfoTestSuite) TestInfoValidateFull() { - darwinAMD64File := NewTestFile("darwin_amd64", "#!/usr/bin\necho 'darwin/amd64'\n") - linux386File := NewTestFile("linux_386", "#!/usr/bin\necho 'darwin/amd64'\n") - darwinAMD64Path := s.saveTestFile(darwinAMD64File) - linux386Path := s.saveTestFile(linux386File) - darwinAMD64URL := makeFileURL(s.T(), darwinAMD64Path) - linux386URL := makeFileURL(s.T(), linux386Path) - - tests := []struct { - name string - planInfo *Info - errs []string - }{ - // Positive test case - { - name: "two good entries", - planInfo: &Info{ - Binaries: BinaryDownloadURLMap{ - "darwin/amd64": darwinAMD64URL, - "linux/386": linux386URL, - }, - }, - errs: nil, - }, - // a failure from BinaryDownloadURLMap.ValidateBasic - { - name: "empty binaries", - planInfo: &Info{Binaries: BinaryDownloadURLMap{}}, - errs: []string{"no \"binaries\" entries found"}, - }, - // a failure from BinaryDownloadURLMap.CheckURLS - { - name: "url does not exist", - planInfo: &Info{ - Binaries: BinaryDownloadURLMap{ - "darwin/arm64": "file:///no/such/file/exists/hopefully.zip?checksum=sha256:b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259", - }, - }, - errs: []string{"error downloading binary", "darwin/arm64", "no such file or directory"}, - }, - } - - for _, tc := range tests { - s.T().Run(tc.name, func(t *testing.T) { - actualErr := tc.planInfo.ValidateFull("daemon") - if len(tc.errs) > 0 { - require.Error(t, actualErr) - for _, expectedErr := range tc.errs { - assert.Contains(t, actualErr.Error(), expectedErr) - } - } else { - require.NoError(t, actualErr) - } - }) - } -} - -func (s InfoTestSuite) TestBinaryDownloadURLMapValidateBasic() { - addDummyChecksum := func(url string) string { - return url + "?checksum=sha256:b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259" - } - tests := []struct { - name string - urlMap BinaryDownloadURLMap - errs []string - }{ - { - name: "empty map", - urlMap: BinaryDownloadURLMap{}, - errs: []string{"no \"binaries\" entries found"}, - }, - { - name: "key with empty string", - urlMap: BinaryDownloadURLMap{ - "": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: []string{"invalid os/arch", `""`}, - }, - { - name: "invalid key format", - urlMap: BinaryDownloadURLMap{ - "badkey": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: []string{"invalid os/arch", "badkey"}, - }, - { - name: "any key is valid", - urlMap: BinaryDownloadURLMap{ - "any": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: nil, - }, - { - name: "os arch key is valid", - urlMap: BinaryDownloadURLMap{ - "darwin/amd64": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: nil, - }, - { - name: "not a url", - urlMap: BinaryDownloadURLMap{ - "isa/url": addDummyChecksum("https://v1.cosmos.network/sdk"), - "nota/url": addDummyChecksum("https://v1.cosmos.network:not-a-port/sdk"), - }, - errs: []string{"invalid url", "nota/url", "invalid port"}, - }, - { - name: "url without checksum", - urlMap: BinaryDownloadURLMap{ - "darwin/amd64": "https://v1.cosmos.network/sdk", - }, - errs: []string{"invalid url", "darwin/amd64", "missing checksum query parameter"}, - }, - { - name: "multiple valid entries but one bad url", - urlMap: BinaryDownloadURLMap{ - "any": addDummyChecksum("https://v1.cosmos.network/sdk"), - "darwin/amd64": addDummyChecksum("https://v1.cosmos.network/sdk"), - "darwin/arm64": addDummyChecksum("https://v1.cosmos.network/sdk"), - "windows/bad": addDummyChecksum("https://v1.cosmos.network:not-a-port/sdk"), - "linux/386": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: []string{"invalid url", "windows/bad", "invalid port"}, - }, - { - name: "multiple valid entries but one bad key", - urlMap: BinaryDownloadURLMap{ - "any": addDummyChecksum("https://v1.cosmos.network/sdk"), - "darwin/amd64": addDummyChecksum("https://v1.cosmos.network/sdk"), - "badkey": addDummyChecksum("https://v1.cosmos.network/sdk"), - "darwin/arm64": addDummyChecksum("https://v1.cosmos.network/sdk"), - "linux/386": addDummyChecksum("https://v1.cosmos.network/sdk"), - }, - errs: []string{"invalid os/arch", "badkey"}, - }, - } - - for _, tc := range tests { - s.T().Run(tc.name, func(t *testing.T) { - actualErr := tc.urlMap.ValidateBasic() - if len(tc.errs) > 0 { - require.Error(t, actualErr) - for _, expectedErr := range tc.errs { - assert.Contains(t, actualErr.Error(), expectedErr) - } - } else { - require.NoError(t, actualErr) - } - }) - } -} - -func (s InfoTestSuite) TestBinaryDownloadURLMapCheckURLs() { - darwinAMD64File := NewTestFile("darwin_amd64", "#!/usr/bin\necho 'darwin/amd64'\n") - linux386File := NewTestFile("linux_386", "#!/usr/bin\necho 'darwin/amd64'\n") - darwinAMD64Path := s.saveTestFile(darwinAMD64File) - linux386Path := s.saveTestFile(linux386File) - darwinAMD64URL := makeFileURL(s.T(), darwinAMD64Path) - linux386URL := makeFileURL(s.T(), linux386Path) - - tests := []struct { - name string - urlMap BinaryDownloadURLMap - errs []string - }{ - { - name: "two good entries", - urlMap: BinaryDownloadURLMap{ - "darwin/amd64": darwinAMD64URL, - "linux/386": linux386URL, - }, - errs: nil, - }, - { - name: "url does not exist", - urlMap: BinaryDownloadURLMap{ - "darwin/arm64": "file:///no/such/file/exists/hopefully.zip?checksum=sha256:b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259", - }, - errs: []string{"error downloading binary", "darwin/arm64", "no such file or directory"}, - }, - { - name: "bad checksum", - urlMap: BinaryDownloadURLMap{ - "darwin/amd64": "file://" + darwinAMD64Path + "?checksum=sha256:b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259", - }, - errs: []string{"error downloading binary", "darwin/amd64", "Checksums did not match", "b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259"}, - }, - } - - for _, tc := range tests { - s.T().Run(tc.name, func(t *testing.T) { - actualErr := tc.urlMap.CheckURLs("daemon") - if len(tc.errs) > 0 { - require.Error(t, actualErr) - for _, expectedErr := range tc.errs { - assert.Contains(t, actualErr.Error(), expectedErr) - } - } else { - require.NoError(t, actualErr) - } - }) - } -} diff --git a/x/upgrade/types/codec.go b/x/upgrade/types/codec.go deleted file mode 100644 index 0f852cc9a2..0000000000 --- a/x/upgrade/types/codec.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers concrete types on the LegacyAmino codec -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(Plan{}, "cosmos-sdk/Plan", nil) - cdc.RegisterConcrete(&SoftwareUpgradeProposal{}, "cosmos-sdk/SoftwareUpgradeProposal", nil) - cdc.RegisterConcrete(&CancelSoftwareUpgradeProposal{}, "cosmos-sdk/CancelSoftwareUpgradeProposal", nil) - legacy.RegisterAminoMsg(cdc, &MsgSoftwareUpgrade{}, "cosmos-sdk/MsgSoftwareUpgrade") - legacy.RegisterAminoMsg(cdc, &MsgCancelUpgrade{}, "cosmos-sdk/MsgCancelUpgrade") -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations( - (*govtypes.Content)(nil), - &SoftwareUpgradeProposal{}, - &CancelSoftwareUpgradeProposal{}, - ) - - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgSoftwareUpgrade{}, - &MsgCancelUpgrade{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - sdk.RegisterLegacyAminoCodec(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/upgrade/types/errors.go b/x/upgrade/types/errors.go new file mode 100644 index 0000000000..ddc2797138 --- /dev/null +++ b/x/upgrade/types/errors.go @@ -0,0 +1,13 @@ +package types + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/upgrade module sentinel errors +var ( + // ErrUpgradeScheduled error if the upgrade scheduled in the past + ErrUpgradeScheduled = sdkerrors.Register(ModuleName, 2, "upgrade cannot be scheduled in the past") + // ErrUpgradeCompleted error if the upgrade has already been completed + ErrUpgradeCompleted = sdkerrors.Register(ModuleName, 3, "upgrade has already been completed") +) diff --git a/x/upgrade/types/handler.go b/x/upgrade/types/handler.go index 0543b6bbeb..87bc8f3c5d 100644 --- a/x/upgrade/types/handler.go +++ b/x/upgrade/types/handler.go @@ -7,6 +7,7 @@ import ( // UpgradeHandler specifies the type of function that is called when an upgrade // is applied. +// ex. Setting a new store in Keeper // // `fromVM` is a VersionMap of moduleName to fromVersion (unit64), where // fromVersion denotes the version from which we should migrate the module, the @@ -21,6 +22,9 @@ import ( // modified inside the upgrade handler, e.g. to skip running InitGenesis or // migrations for certain modules when calling the `module.Manager#RunMigrations` // function. -// -// Please also refer to docs/core/upgrade.md for more information. type UpgradeHandler func(ctx sdk.Context, plan Plan, fromVM module.VersionMap) (module.VersionMap, error) + +// UpgradeInitializer specifies the function type to be called +// when the app is restarted after an upgrade. +// ex. RegisterInterface for module +type UpgradeInitializer func() error diff --git a/x/upgrade/types/keys.go b/x/upgrade/types/keys.go index 45128fc704..e1a30c77ae 100644 --- a/x/upgrade/types/keys.go +++ b/x/upgrade/types/keys.go @@ -17,17 +17,12 @@ const ( ) const ( - // PlanByte specifies the Byte under which a pending upgrade plan is stored in the store - PlanByte = 0x0 // DoneByte is a prefix for to look up completed upgrade plan by name DoneByte = 0x1 // VersionMapByte is a prefix to look up module names (key) and versions (value) VersionMapByte = 0x2 - // ProtocolVersionByte is a prefix to look up Protocol Version - ProtocolVersionByte = 0x3 - // KeyUpgradedIBCState is the key under which upgraded ibc state is stored in the upgrade store KeyUpgradedIBCState = "upgradedIBCState" @@ -38,12 +33,6 @@ const ( KeyUpgradedConsState = "upgradedConsState" ) -// PlanKey is the key under which the current plan is saved -// We store PlanByte as a const to keep it immutable (unlike a []byte) -func PlanKey() []byte { - return []byte{PlanByte} -} - // UpgradedClientKey is the key under which the upgraded client state is saved // Connecting IBC chains can verify against the upgraded client in this path before // upgrading their clients diff --git a/x/upgrade/types/msgs.go b/x/upgrade/types/msgs.go deleted file mode 100644 index 4caf508af9..0000000000 --- a/x/upgrade/types/msgs.go +++ /dev/null @@ -1,68 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -var ( - _, _ sdk.Msg = &MsgSoftwareUpgrade{}, &MsgCancelUpgrade{} - _, _ legacytx.LegacyMsg = &MsgSoftwareUpgrade{}, &MsgCancelUpgrade{} -) - -// Route implements the LegacyMsg interface. -func (m MsgSoftwareUpgrade) Route() string { return sdk.MsgTypeURL(&m) } - -// Type implements the LegacyMsg interface. -func (m MsgSoftwareUpgrade) Type() string { return sdk.MsgTypeURL(&m) } - -// GetSignBytes implements the LegacyMsg interface. -func (m MsgSoftwareUpgrade) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ValidateBasic does a sanity check on the provided data. -func (m *MsgSoftwareUpgrade) ValidateBasic() error { - if _, err := sdk.AccAddressFromHexUnsafe(m.Authority); err != nil { - return sdkerrors.Wrap(err, "authority") - } - - if err := m.Plan.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "plan") - } - - return nil -} - -// GetSigners returns the expected signers for MsgSoftwareUpgrade. -func (m *MsgSoftwareUpgrade) GetSigners() []sdk.AccAddress { - addr, _ := sdk.AccAddressFromHexUnsafe(m.Authority) - return []sdk.AccAddress{addr} -} - -// Route implements the LegacyMsg interface. -func (m MsgCancelUpgrade) Route() string { return sdk.MsgTypeURL(&m) } - -// Type implements the LegacyMsg interface. -func (m MsgCancelUpgrade) Type() string { return sdk.MsgTypeURL(&m) } - -// GetSignBytes implements the LegacyMsg interface. -func (m MsgCancelUpgrade) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ValidateBasic does a sanity check on the provided data. -func (m *MsgCancelUpgrade) ValidateBasic() error { - if _, err := sdk.AccAddressFromHexUnsafe(m.Authority); err != nil { - return sdkerrors.Wrap(err, "authority") - } - - return nil -} - -// GetSigners returns the expected signers for MsgCancelUpgrade. -func (m *MsgCancelUpgrade) GetSigners() []sdk.AccAddress { - addr, _ := sdk.AccAddressFromHexUnsafe(m.Authority) - return []sdk.AccAddress{addr} -} diff --git a/x/upgrade/types/msgs_test.go b/x/upgrade/types/msgs_test.go deleted file mode 100644 index 53253a7c29..0000000000 --- a/x/upgrade/types/msgs_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -var authority = sdk.AccAddress("authority") - -func TestMsgSoftwareUpgrade(t *testing.T) { - testCases := []struct { - name string - msg *types.MsgSoftwareUpgrade - expErr bool - errMsg string - }{ - { - "invalid authority address", - &types.MsgSoftwareUpgrade{ - Authority: "authority", - Plan: types.Plan{ - Name: "all-good", - Height: 123450000, - }, - }, - true, - "authority: invalid address hex length", - }, - { - "invalid plan", - &types.MsgSoftwareUpgrade{ - Authority: authority.String(), - Plan: types.Plan{ - Height: 123450000, - }, - }, - true, - "plan", - }, - { - "all good", - &types.MsgSoftwareUpgrade{ - Authority: authority.String(), - Plan: types.Plan{ - Name: "all-good", - Height: 123450000, - }, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, tc.msg.Type(), sdk.MsgTypeURL(&types.MsgSoftwareUpgrade{})) - } - }) - } -} - -func TestMsgCancelUpgrade(t *testing.T) { - testCases := []struct { - name string - msg *types.MsgCancelUpgrade - expErr bool - errMsg string - }{ - { - "invalid authority address", - &types.MsgCancelUpgrade{ - Authority: "authority", - }, - true, - "authority: invalid address hex length", - }, - { - "all good", - &types.MsgCancelUpgrade{ - Authority: authority.String(), - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, tc.msg.Type(), sdk.MsgTypeURL(&types.MsgCancelUpgrade{})) - } - }) - } -} diff --git a/x/upgrade/types/plan.go b/x/upgrade/types/plan.go index 81c754caae..02d8919d61 100644 --- a/x/upgrade/types/plan.go +++ b/x/upgrade/types/plan.go @@ -20,12 +20,6 @@ func (p Plan) String() string { // ValidateBasic does basic validation of a Plan func (p Plan) ValidateBasic() error { - if !p.Time.IsZero() { - return sdkerrors.ErrInvalidRequest.Wrap("time-based upgrades have been deprecated in the SDK") - } - if p.UpgradedClientState != nil { - return sdkerrors.ErrInvalidRequest.Wrap("upgrade logic for IBC has been moved to the IBC module") - } if len(p.Name) == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "name cannot be empty") } diff --git a/x/upgrade/types/plan_test.go b/x/upgrade/types/plan_test.go index 724f68bf05..817d4295f2 100644 --- a/x/upgrade/types/plan_test.go +++ b/x/upgrade/types/plan_test.go @@ -9,7 +9,6 @@ import ( "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -69,15 +68,9 @@ func TestPlanValid(t *testing.T) { Height: 123450000, }, }, - "time-base upgrade": { - p: types.Plan{ - Time: time.Now(), - }, - }, "IBC upgrade": { p: types.Plan{ - Height: 123450000, - UpgradedClientState: &codectypes.Any{}, + Height: 123450000, }, }, "no due at": { @@ -146,7 +139,7 @@ func TestShouldExecute(t *testing.T) { for name, tc := range cases { tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { - ctx := sdk.NewContext(nil, tmproto.Header{Height: tc.ctxHeight, Time: tc.ctxTime}, false, log.NewNopLogger()) + ctx := sdk.NewContext(nil, tmproto.Header{Height: tc.ctxHeight, Time: tc.ctxTime}, false, nil, log.NewNopLogger()) should := tc.p.ShouldExecute(ctx) assert.Equal(t, tc.expected, should) }) diff --git a/x/upgrade/types/proposal.go b/x/upgrade/types/proposal.go deleted file mode 100644 index 60a11fe7e8..0000000000 --- a/x/upgrade/types/proposal.go +++ /dev/null @@ -1,67 +0,0 @@ -package types - -import ( - "fmt" - - gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - ProposalTypeSoftwareUpgrade string = "SoftwareUpgrade" - ProposalTypeCancelSoftwareUpgrade string = "CancelSoftwareUpgrade" -) - -func NewSoftwareUpgradeProposal(title, description string, plan Plan) gov.Content { - return &SoftwareUpgradeProposal{title, description, plan} -} - -// Implements Proposal Interface -var _ gov.Content = &SoftwareUpgradeProposal{} - -func init() { - gov.RegisterProposalType(ProposalTypeSoftwareUpgrade) - gov.RegisterProposalType(ProposalTypeCancelSoftwareUpgrade) -} - -func (sup *SoftwareUpgradeProposal) GetTitle() string { return sup.Title } -func (sup *SoftwareUpgradeProposal) GetDescription() string { return sup.Description } -func (sup *SoftwareUpgradeProposal) ProposalRoute() string { return RouterKey } -func (sup *SoftwareUpgradeProposal) ProposalType() string { return ProposalTypeSoftwareUpgrade } -func (sup *SoftwareUpgradeProposal) ValidateBasic() error { - if err := sup.Plan.ValidateBasic(); err != nil { - return err - } - return gov.ValidateAbstract(sup) -} - -func (sup SoftwareUpgradeProposal) String() string { - return fmt.Sprintf(`Software Upgrade Proposal: - Title: %s - Description: %s -`, sup.Title, sup.Description) -} - -func NewCancelSoftwareUpgradeProposal(title, description string) gov.Content { - return &CancelSoftwareUpgradeProposal{title, description} -} - -// Implements Proposal Interface -var _ gov.Content = &CancelSoftwareUpgradeProposal{} - -func (csup *CancelSoftwareUpgradeProposal) GetTitle() string { return csup.Title } -func (csup *CancelSoftwareUpgradeProposal) GetDescription() string { return csup.Description } -func (csup *CancelSoftwareUpgradeProposal) ProposalRoute() string { return RouterKey } -func (csup *CancelSoftwareUpgradeProposal) ProposalType() string { - return ProposalTypeCancelSoftwareUpgrade -} - -func (csup *CancelSoftwareUpgradeProposal) ValidateBasic() error { - return gov.ValidateAbstract(csup) -} - -func (csup CancelSoftwareUpgradeProposal) String() string { - return fmt.Sprintf(`Cancel Software Upgrade Proposal: - Title: %s - Description: %s -`, csup.Title, csup.Description) -} diff --git a/x/upgrade/types/proposal_test.go b/x/upgrade/types/proposal_test.go deleted file mode 100644 index 4e6233a2d3..0000000000 --- a/x/upgrade/types/proposal_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/upgrade/types" -) - -type ProposalWrapper struct { - Prop gov.Content -} - -func TestContentAccessors(t *testing.T) { - cases := map[string]struct { - p gov.Content - title string - desc string - typ string - str string - }{ - "upgrade": { - p: types.NewSoftwareUpgradeProposal("Title", "desc", types.Plan{ - Name: "due_height", - Info: "https://foo.bar", - Height: 99999999999, - }), - title: "Title", - desc: "desc", - typ: "SoftwareUpgrade", - str: "Software Upgrade Proposal:\n Title: Title\n Description: desc\n", - }, - "cancel": { - p: types.NewCancelSoftwareUpgradeProposal("Cancel", "bad idea"), - title: "Cancel", - desc: "bad idea", - typ: "CancelSoftwareUpgrade", - str: "Cancel Software Upgrade Proposal:\n Title: Cancel\n Description: bad idea\n", - }, - } - - cdc := codec.NewLegacyAmino() - gov.RegisterLegacyAminoCodec(cdc) - types.RegisterLegacyAminoCodec(cdc) - - for name, tc := range cases { - tc := tc // copy to local variable for scopelint - t.Run(name, func(t *testing.T) { - assert.Equal(t, tc.title, tc.p.GetTitle()) - assert.Equal(t, tc.desc, tc.p.GetDescription()) - assert.Equal(t, tc.typ, tc.p.ProposalType()) - assert.Equal(t, "upgrade", tc.p.ProposalRoute()) - assert.Equal(t, tc.str, tc.p.String()) - - // try to encode and decode type to ensure codec works - wrap := ProposalWrapper{tc.p} - bz, err := cdc.Marshal(&wrap) - require.NoError(t, err) - unwrap := ProposalWrapper{} - err = cdc.Unmarshal(bz, &unwrap) - require.NoError(t, err) - - // all methods should look the same - assert.Equal(t, tc.title, unwrap.Prop.GetTitle()) - assert.Equal(t, tc.desc, unwrap.Prop.GetDescription()) - assert.Equal(t, tc.typ, unwrap.Prop.ProposalType()) - assert.Equal(t, "upgrade", unwrap.Prop.ProposalRoute()) - assert.Equal(t, tc.str, unwrap.Prop.String()) - }) - - } -} - -// tests a software update proposal can be marshaled and unmarshaled -func TestMarshalSoftwareUpdateProposal(t *testing.T) { - // create proposal - plan := types.Plan{ - Name: "upgrade", - Height: 1000, - } - content := types.NewSoftwareUpgradeProposal("title", "description", plan) - sup, ok := content.(*types.SoftwareUpgradeProposal) - require.True(t, ok) - - // create codec - ir := codectypes.NewInterfaceRegistry() - types.RegisterInterfaces(ir) - gov.RegisterInterfaces(ir) - cdc := codec.NewProtoCodec(ir) - - // marshal message - bz, err := cdc.MarshalJSON(sup) - require.NoError(t, err) - - // unmarshal proposal - newSup := &types.SoftwareUpgradeProposal{} - err = cdc.UnmarshalJSON(bz, newSup) - require.NoError(t, err) -} diff --git a/x/upgrade/types/query.pb.go b/x/upgrade/types/query.pb.go index e84c333051..95407043db 100644 --- a/x/upgrade/types/query.pb.go +++ b/x/upgrade/types/query.pb.go @@ -70,7 +70,7 @@ var xxx_messageInfo_QueryCurrentPlanRequest proto.InternalMessageInfo // method. type QueryCurrentPlanResponse struct { // plan is the current upgrade plan. - Plan *Plan `protobuf:"bytes,1,opt,name=plan,proto3" json:"plan,omitempty"` + Plan []*Plan `protobuf:"bytes,1,rep,name=plan,proto3" json:"plan,omitempty"` } func (m *QueryCurrentPlanResponse) Reset() { *m = QueryCurrentPlanResponse{} } @@ -106,7 +106,7 @@ func (m *QueryCurrentPlanResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryCurrentPlanResponse proto.InternalMessageInfo -func (m *QueryCurrentPlanResponse) GetPlan() *Plan { +func (m *QueryCurrentPlanResponse) GetPlan() []*Plan { if m != nil { return m.Plan } @@ -510,48 +510,46 @@ func init() { } var fileDescriptor_4a334d07ad8374f0 = []byte{ - // 644 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xc1, 0x4f, 0x13, 0x4f, - 0x14, 0x66, 0x0a, 0x3f, 0x7e, 0xf2, 0x6a, 0xd0, 0x4c, 0x62, 0x59, 0x57, 0x52, 0x71, 0x40, 0x85, - 0x48, 0x77, 0xa0, 0x5c, 0x0c, 0x46, 0xa3, 0x92, 0x18, 0x31, 0x4a, 0xb4, 0x46, 0x0f, 0x5e, 0x9a, - 0xa1, 0x3b, 0x69, 0x37, 0xb6, 0x3b, 0xcb, 0xce, 0x2c, 0x91, 0x10, 0x2e, 0x9e, 0x3c, 0x9a, 0x18, - 0xaf, 0xde, 0xbc, 0xf8, 0x97, 0x78, 0x24, 0xf1, 0xe2, 0xc1, 0x83, 0x01, 0xff, 0x04, 0xff, 0x00, - 0xb3, 0xb3, 0xb3, 0xa4, 0xa5, 0xbb, 0x0b, 0x7a, 0x6a, 0x77, 0xde, 0xf7, 0x7d, 0xef, 0x7b, 0x3b, - 0xdf, 0x6b, 0x81, 0xb4, 0x84, 0xec, 0x09, 0x49, 0xa3, 0xa0, 0x1d, 0x32, 0x97, 0xd3, 0xed, 0xe5, - 0x4d, 0xae, 0xd8, 0x32, 0xdd, 0x8a, 0x78, 0xb8, 0xe3, 0x04, 0xa1, 0x50, 0x02, 0x57, 0x12, 0x8c, - 0x63, 0x30, 0x8e, 0xc1, 0xd8, 0xd3, 0x6d, 0x21, 0xda, 0x5d, 0x4e, 0x59, 0xe0, 0x51, 0xe6, 0xfb, - 0x42, 0x31, 0xe5, 0x09, 0x5f, 0x26, 0x2c, 0x7b, 0x2e, 0x47, 0x39, 0x55, 0xd1, 0x28, 0x72, 0x11, - 0xa6, 0x9e, 0xc5, 0xad, 0xd6, 0xa2, 0x30, 0xe4, 0xbe, 0x7a, 0xda, 0x65, 0x7e, 0x83, 0x6f, 0x45, - 0x5c, 0x2a, 0xf2, 0x18, 0xac, 0xe1, 0x92, 0x0c, 0x84, 0x2f, 0x39, 0x5e, 0x82, 0xb1, 0xa0, 0xcb, - 0x7c, 0x0b, 0xcd, 0xa0, 0xf9, 0x72, 0x7d, 0xda, 0xc9, 0x76, 0xe8, 0x68, 0x8e, 0x46, 0x92, 0x9a, - 0x69, 0x74, 0x2f, 0x08, 0xba, 0x1e, 0x77, 0xfb, 0x1a, 0x61, 0x0c, 0x63, 0x3e, 0xeb, 0x71, 0x2d, - 0x36, 0xd1, 0xd0, 0xdf, 0x49, 0xdd, 0x34, 0x1f, 0x80, 0x9b, 0xe6, 0x15, 0x18, 0xef, 0x70, 0xaf, - 0xdd, 0x51, 0x9a, 0x31, 0xda, 0x30, 0x4f, 0x64, 0x1d, 0x88, 0xe6, 0xbc, 0x48, 0x5c, 0xb8, 0x6b, - 0x31, 0xda, 0x97, 0x91, 0x7c, 0xae, 0x98, 0xe2, 0x69, 0xb7, 0xcb, 0x50, 0xee, 0x32, 0xa9, 0x9a, - 0x03, 0x12, 0x10, 0x1f, 0x3d, 0xd4, 0x27, 0xab, 0x25, 0x0b, 0x11, 0x0f, 0x66, 0x0b, 0xa5, 0x8c, - 0x93, 0x9b, 0x60, 0x99, 0x91, 0xdd, 0x66, 0x2b, 0x85, 0x34, 0x65, 0x8c, 0xb1, 0x4a, 0x33, 0x68, - 0xfe, 0x6c, 0xa3, 0x12, 0x65, 0x2a, 0xc4, 0x4d, 0x1e, 0x8d, 0x9d, 0x41, 0xe7, 0x4b, 0xe4, 0x36, - 0xd8, 0xba, 0xd5, 0x13, 0xe1, 0x46, 0x5d, 0xfe, 0x92, 0x87, 0x32, 0xbe, 0xc4, 0x3e, 0xb7, 0x3d, - 0x5d, 0x68, 0xf6, 0xbd, 0x22, 0x48, 0x8e, 0x36, 0xe2, 0x17, 0xd5, 0x83, 0x4b, 0x99, 0x74, 0xe3, - 0x70, 0x03, 0xce, 0x19, 0xfe, 0xb6, 0x29, 0x59, 0x68, 0x66, 0x74, 0xbe, 0x5c, 0xbf, 0x9a, 0x77, - 0x67, 0x03, 0x42, 0x8d, 0xc9, 0xde, 0x80, 0x2e, 0x99, 0x82, 0x0b, 0xc9, 0xbd, 0x44, 0xaa, 0x23, - 0x42, 0x4f, 0xed, 0xa4, 0x69, 0xa9, 0x43, 0xe5, 0x78, 0xc1, 0x58, 0xb0, 0xe0, 0x7f, 0xe6, 0xba, - 0x21, 0x97, 0xd2, 0xd8, 0x4f, 0x1f, 0xeb, 0xbf, 0xc7, 0xe1, 0x3f, 0x4d, 0xc2, 0x9f, 0x10, 0x94, - 0xfb, 0x72, 0x86, 0x69, 0x9e, 0xbb, 0x9c, 0xb0, 0xda, 0x4b, 0xa7, 0x27, 0x24, 0xb6, 0xc8, 0xe2, - 0xdb, 0x6f, 0xbf, 0x3e, 0x94, 0xae, 0xe1, 0x39, 0x9a, 0xb3, 0x28, 0xad, 0x84, 0xd4, 0x8c, 0xe3, - 0x8b, 0x3f, 0x23, 0x28, 0xf7, 0x65, 0xf1, 0x04, 0x83, 0xc3, 0x21, 0x3f, 0xc1, 0x60, 0x46, 0xcc, - 0xc9, 0x8a, 0x36, 0x58, 0xc3, 0x37, 0xf2, 0x0c, 0xb2, 0x84, 0xa4, 0x0d, 0xd2, 0xdd, 0x38, 0x1f, - 0x7b, 0xf8, 0x07, 0x82, 0x4a, 0x76, 0x68, 0xf1, 0x6a, 0xa1, 0x83, 0xc2, 0xa5, 0xb1, 0x6f, 0xfd, - 0x13, 0xd7, 0x0c, 0xb2, 0xae, 0x07, 0xb9, 0x8b, 0xef, 0xd0, 0xe2, 0x9f, 0xa4, 0xa1, 0x1d, 0xa2, - 0xbb, 0x7d, 0x9b, 0xba, 0xf7, 0xae, 0x84, 0xf0, 0x17, 0x04, 0x93, 0x83, 0x49, 0xc7, 0xf5, 0x42, - 0x6b, 0x99, 0x5b, 0x65, 0xaf, 0xfc, 0x15, 0xc7, 0x8c, 0x41, 0xf5, 0x18, 0x0b, 0xf8, 0x7a, 0xde, - 0x18, 0xc7, 0x16, 0x0d, 0x7f, 0x44, 0x30, 0x71, 0xb4, 0x0e, 0xb8, 0x56, 0x1c, 0x80, 0x63, 0xfb, - 0x64, 0x3b, 0xa7, 0x85, 0x1b, 0x77, 0x0b, 0xda, 0xdd, 0x2c, 0xbe, 0x92, 0x9b, 0x96, 0x94, 0x72, - 0xff, 0xc1, 0xd7, 0x83, 0x2a, 0xda, 0x3f, 0xa8, 0xa2, 0x9f, 0x07, 0x55, 0xf4, 0xfe, 0xb0, 0x3a, - 0xb2, 0x7f, 0x58, 0x1d, 0xf9, 0x7e, 0x58, 0x1d, 0x79, 0xb5, 0xd8, 0xf6, 0x54, 0x27, 0xda, 0x74, - 0x5a, 0xa2, 0x97, 0xca, 0x24, 0x1f, 0x35, 0xe9, 0xbe, 0xa6, 0x6f, 0x8e, 0x34, 0xd5, 0x4e, 0xc0, - 0xe5, 0xe6, 0xb8, 0xfe, 0x0b, 0x59, 0xf9, 0x13, 0x00, 0x00, 0xff, 0xff, 0x18, 0x7f, 0x99, 0xff, - 0xc4, 0x06, 0x00, 0x00, + // 611 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x3f, 0x6f, 0xd3, 0x4e, + 0x18, 0xee, 0xa5, 0x7f, 0x7e, 0x3f, 0x2e, 0xa8, 0xa0, 0x93, 0x48, 0x8d, 0xa9, 0x4c, 0x75, 0x14, + 0x28, 0xa2, 0xf1, 0xb5, 0xc9, 0x82, 0x8a, 0x40, 0x40, 0x25, 0x44, 0x11, 0x54, 0x10, 0x04, 0x03, + 0x4b, 0x74, 0x89, 0x4f, 0x89, 0x85, 0xed, 0x73, 0x7d, 0xe7, 0x8a, 0xa8, 0xea, 0xc2, 0xc4, 0x88, + 0xc4, 0xce, 0xc6, 0xc2, 0x27, 0x61, 0xac, 0xc4, 0xc2, 0xd0, 0x01, 0x25, 0x7c, 0x10, 0xe4, 0xf3, + 0x19, 0x39, 0x8d, 0x9d, 0x02, 0x53, 0xe2, 0xbb, 0xe7, 0x79, 0xde, 0xe7, 0xf5, 0xfb, 0xbc, 0x86, + 0xb8, 0xcb, 0x85, 0xcf, 0x05, 0x89, 0xc3, 0x5e, 0x44, 0x1d, 0x46, 0xf6, 0x37, 0x3b, 0x4c, 0xd2, + 0x4d, 0xb2, 0x17, 0xb3, 0x68, 0x60, 0x87, 0x11, 0x97, 0x1c, 0xd5, 0x52, 0x8c, 0xad, 0x31, 0xb6, + 0xc6, 0x98, 0xcb, 0x3d, 0xce, 0x7b, 0x1e, 0x23, 0x34, 0x74, 0x09, 0x0d, 0x02, 0x2e, 0xa9, 0x74, + 0x79, 0x20, 0x52, 0x96, 0xb9, 0x5a, 0xa2, 0x9c, 0xa9, 0x28, 0x14, 0xbe, 0x08, 0x97, 0x9e, 0x27, + 0xa5, 0xb6, 0xe3, 0x28, 0x62, 0x81, 0x7c, 0xe6, 0xd1, 0xa0, 0xc5, 0xf6, 0x62, 0x26, 0x24, 0x7e, + 0x02, 0x8d, 0xc9, 0x2b, 0x11, 0xf2, 0x40, 0x30, 0xb4, 0x01, 0xe7, 0x42, 0x8f, 0x06, 0x06, 0x58, + 0x99, 0x5d, 0xab, 0x36, 0x96, 0xed, 0x62, 0x87, 0xb6, 0xe2, 0x28, 0x24, 0xae, 0xeb, 0x42, 0xf7, + 0xc3, 0xd0, 0x73, 0x99, 0x93, 0x2b, 0x84, 0x10, 0x9c, 0x0b, 0xa8, 0xcf, 0x0c, 0xb0, 0x02, 0xd6, + 0xce, 0xb4, 0xd4, 0x7f, 0xdc, 0xd0, 0xc5, 0xc7, 0xe0, 0xba, 0x78, 0x0d, 0x2e, 0xf4, 0x99, 0xdb, + 0xeb, 0x4b, 0xc5, 0x98, 0x6d, 0xe9, 0x27, 0xbc, 0x03, 0xb1, 0xe2, 0xbc, 0x4c, 0x5d, 0x38, 0xdb, + 0x09, 0x3a, 0x10, 0xb1, 0x78, 0x21, 0xa9, 0x64, 0x59, 0xb5, 0xcb, 0xb0, 0xea, 0x51, 0x21, 0xdb, + 0x63, 0x12, 0x30, 0x39, 0x7a, 0xa4, 0x4e, 0xb6, 0x2a, 0x06, 0xc0, 0x2e, 0xbc, 0x32, 0x55, 0x4a, + 0x3b, 0xb9, 0x05, 0x0d, 0xdd, 0xb2, 0xd3, 0xee, 0x66, 0x90, 0xb6, 0x48, 0x30, 0x46, 0x65, 0x05, + 0xac, 0x9d, 0x6d, 0xd5, 0xe2, 0x42, 0x85, 0xa4, 0xc8, 0xe3, 0xb9, 0xff, 0xc1, 0xf9, 0x0a, 0xbe, + 0x03, 0x4d, 0x55, 0xea, 0x29, 0x77, 0x62, 0x8f, 0xbd, 0x62, 0x91, 0x48, 0x86, 0x98, 0x73, 0xeb, + 0xab, 0x8b, 0x76, 0xee, 0x15, 0xc1, 0xf4, 0x68, 0x37, 0x79, 0x51, 0x3e, 0xbc, 0x54, 0x48, 0xd7, + 0x0e, 0x77, 0xe1, 0x39, 0xcd, 0xdf, 0xd7, 0x57, 0x7a, 0x66, 0x57, 0xcb, 0x66, 0x36, 0x26, 0xd4, + 0x5a, 0xf4, 0xc7, 0x74, 0xf1, 0x12, 0xbc, 0x90, 0xce, 0x25, 0x96, 0x7d, 0x1e, 0xb9, 0x72, 0x90, + 0xa5, 0xa5, 0x01, 0x6b, 0x27, 0x2f, 0xb4, 0x05, 0x03, 0xfe, 0x47, 0x1d, 0x27, 0x62, 0x42, 0x68, + 0xfb, 0xd9, 0x63, 0xe3, 0x78, 0x1e, 0xce, 0x2b, 0x12, 0xfa, 0x04, 0x60, 0x35, 0x97, 0x33, 0x44, + 0xca, 0xdc, 0x95, 0x84, 0xd5, 0xdc, 0xf8, 0x73, 0x42, 0x6a, 0x0b, 0xaf, 0xbf, 0xfb, 0xf6, 0xf3, + 0x63, 0xe5, 0x1a, 0x5a, 0x25, 0x25, 0x8b, 0xd2, 0x4d, 0x49, 0xed, 0x24, 0xbe, 0xe8, 0x33, 0x80, + 0xd5, 0x5c, 0x16, 0x4f, 0x31, 0x38, 0x19, 0xf2, 0x53, 0x0c, 0x16, 0xc4, 0x1c, 0x37, 0x95, 0xc1, + 0x3a, 0xba, 0x59, 0x66, 0x90, 0xa6, 0x24, 0x65, 0x90, 0x1c, 0x24, 0xf9, 0x38, 0x44, 0xc7, 0x00, + 0xd6, 0x8a, 0x43, 0x8b, 0xb6, 0xa6, 0x3a, 0x98, 0xba, 0x34, 0xe6, 0xed, 0x7f, 0xe2, 0xea, 0x46, + 0x76, 0x54, 0x23, 0xf7, 0xd0, 0x5d, 0x32, 0xfd, 0x93, 0x34, 0xb1, 0x43, 0xe4, 0x20, 0xb7, 0xa9, + 0x87, 0xef, 0x2b, 0x00, 0x7d, 0x01, 0x70, 0x71, 0x3c, 0xe9, 0xa8, 0x31, 0xd5, 0x5a, 0xe1, 0x56, + 0x99, 0xcd, 0xbf, 0xe2, 0xe8, 0x36, 0x88, 0x6a, 0xe3, 0x06, 0xba, 0x5e, 0xd6, 0xc6, 0x89, 0x45, + 0x7b, 0xf0, 0xf0, 0xeb, 0xd0, 0x02, 0x47, 0x43, 0x0b, 0xfc, 0x18, 0x5a, 0xe0, 0xc3, 0xc8, 0x9a, + 0x39, 0x1a, 0x59, 0x33, 0xdf, 0x47, 0xd6, 0xcc, 0xeb, 0xf5, 0x9e, 0x2b, 0xfb, 0x71, 0xc7, 0xee, + 0x72, 0x3f, 0x13, 0x4b, 0x7f, 0xea, 0xc2, 0x79, 0x43, 0xde, 0xfe, 0x56, 0x96, 0x83, 0x90, 0x89, + 0xce, 0x82, 0xfa, 0x54, 0x37, 0x7f, 0x05, 0x00, 0x00, 0xff, 0xff, 0x46, 0x87, 0x09, 0xdc, 0x2c, + 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -581,10 +579,6 @@ type QueryClient interface { // // Since: cosmos-sdk 0.43 ModuleVersions(ctx context.Context, in *QueryModuleVersionsRequest, opts ...grpc.CallOption) (*QueryModuleVersionsResponse, error) - // Returns the account with authority to conduct upgrades - // - // Since: cosmos-sdk 0.46 - Authority(ctx context.Context, in *QueryAuthorityRequest, opts ...grpc.CallOption) (*QueryAuthorityResponse, error) } type queryClient struct { @@ -632,15 +626,6 @@ func (c *queryClient) ModuleVersions(ctx context.Context, in *QueryModuleVersion return out, nil } -func (c *queryClient) Authority(ctx context.Context, in *QueryAuthorityRequest, opts ...grpc.CallOption) (*QueryAuthorityResponse, error) { - out := new(QueryAuthorityResponse) - err := c.cc.Invoke(ctx, "/cosmos.upgrade.v1beta1.Query/Authority", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - // QueryServer is the server API for Query service. type QueryServer interface { // CurrentPlan queries the current upgrade plan. @@ -658,10 +643,6 @@ type QueryServer interface { // // Since: cosmos-sdk 0.43 ModuleVersions(context.Context, *QueryModuleVersionsRequest) (*QueryModuleVersionsResponse, error) - // Returns the account with authority to conduct upgrades - // - // Since: cosmos-sdk 0.46 - Authority(context.Context, *QueryAuthorityRequest) (*QueryAuthorityResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -680,9 +661,6 @@ func (*UnimplementedQueryServer) UpgradedConsensusState(ctx context.Context, req func (*UnimplementedQueryServer) ModuleVersions(ctx context.Context, req *QueryModuleVersionsRequest) (*QueryModuleVersionsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ModuleVersions not implemented") } -func (*UnimplementedQueryServer) Authority(ctx context.Context, req *QueryAuthorityRequest) (*QueryAuthorityResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Authority not implemented") -} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -760,24 +738,6 @@ func _Query_ModuleVersions_Handler(srv interface{}, ctx context.Context, dec fun return interceptor(ctx, in, info, handler) } -func _Query_Authority_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAuthorityRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Authority(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.upgrade.v1beta1.Query/Authority", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Authority(ctx, req.(*QueryAuthorityRequest)) - } - return interceptor(ctx, in, info, handler) -} - var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "cosmos.upgrade.v1beta1.Query", HandlerType: (*QueryServer)(nil), @@ -798,10 +758,6 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "ModuleVersions", Handler: _Query_ModuleVersions_Handler, }, - { - MethodName: "Authority", - Handler: _Query_Authority_Handler, - }, }, Streams: []grpc.StreamDesc{}, Metadata: "cosmos/upgrade/v1beta1/query.proto", @@ -850,17 +806,19 @@ func (m *QueryCurrentPlanResponse) MarshalToSizedBuffer(dAtA []byte) (int, error _ = i var l int _ = l - if m.Plan != nil { - { - size, err := m.Plan.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if len(m.Plan) > 0 { + for iNdEx := len(m.Plan) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Plan[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0xa } - i-- - dAtA[i] = 0xa } return len(dAtA) - i, nil } @@ -1127,9 +1085,11 @@ func (m *QueryCurrentPlanResponse) Size() (n int) { } var l int _ = l - if m.Plan != nil { - l = m.Plan.Size() - n += 1 + l + sovQuery(uint64(l)) + if len(m.Plan) > 0 { + for _, e := range m.Plan { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } } return n } @@ -1348,10 +1308,8 @@ func (m *QueryCurrentPlanResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Plan == nil { - m.Plan = &Plan{} - } - if err := m.Plan.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Plan = append(m.Plan, &Plan{}) + if err := m.Plan[len(m.Plan)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/upgrade/types/query.pb.gw.go b/x/upgrade/types/query.pb.gw.go index 036a84c11e..951ddc24b5 100644 --- a/x/upgrade/types/query.pb.gw.go +++ b/x/upgrade/types/query.pb.gw.go @@ -195,24 +195,6 @@ func local_request_Query_ModuleVersions_0(ctx context.Context, marshaler runtime } -func request_Query_Authority_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuthorityRequest - var metadata runtime.ServerMetadata - - msg, err := client.Authority(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Authority_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuthorityRequest - var metadata runtime.ServerMetadata - - msg, err := server.Authority(ctx, &protoReq) - return msg, metadata, err - -} - // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -311,29 +293,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) - mux.Handle("GET", pattern_Query_Authority_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Authority_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Authority_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - return nil } @@ -455,26 +414,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) - mux.Handle("GET", pattern_Query_Authority_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Authority_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Authority_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - return nil } @@ -486,8 +425,6 @@ var ( pattern_Query_UpgradedConsensusState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "upgrade", "v1beta1", "upgraded_consensus_state", "last_height"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_ModuleVersions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "upgrade", "v1beta1", "module_versions"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Authority_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "upgrade", "v1beta1", "authority"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( @@ -498,6 +435,4 @@ var ( forward_Query_UpgradedConsensusState_0 = runtime.ForwardResponseMessage forward_Query_ModuleVersions_0 = runtime.ForwardResponseMessage - - forward_Query_Authority_0 = runtime.ForwardResponseMessage ) diff --git a/x/upgrade/types/tx.pb.go b/x/upgrade/types/tx.pb.go deleted file mode 100644 index 47d9edbfd7..0000000000 --- a/x/upgrade/types/tx.pb.go +++ /dev/null @@ -1,941 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/upgrade/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgSoftwareUpgrade is the Msg/SoftwareUpgrade request type. -// -// Since: cosmos-sdk 0.46 -type MsgSoftwareUpgrade struct { - // authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // plan is the upgrade plan. - Plan Plan `protobuf:"bytes,2,opt,name=plan,proto3" json:"plan"` -} - -func (m *MsgSoftwareUpgrade) Reset() { *m = MsgSoftwareUpgrade{} } -func (m *MsgSoftwareUpgrade) String() string { return proto.CompactTextString(m) } -func (*MsgSoftwareUpgrade) ProtoMessage() {} -func (*MsgSoftwareUpgrade) Descriptor() ([]byte, []int) { - return fileDescriptor_2852c16e3ab79fef, []int{0} -} -func (m *MsgSoftwareUpgrade) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSoftwareUpgrade) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSoftwareUpgrade.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSoftwareUpgrade) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSoftwareUpgrade.Merge(m, src) -} -func (m *MsgSoftwareUpgrade) XXX_Size() int { - return m.Size() -} -func (m *MsgSoftwareUpgrade) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSoftwareUpgrade.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSoftwareUpgrade proto.InternalMessageInfo - -func (m *MsgSoftwareUpgrade) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgSoftwareUpgrade) GetPlan() Plan { - if m != nil { - return m.Plan - } - return Plan{} -} - -// MsgSoftwareUpgradeResponse is the Msg/SoftwareUpgrade response type. -// -// Since: cosmos-sdk 0.46 -type MsgSoftwareUpgradeResponse struct { -} - -func (m *MsgSoftwareUpgradeResponse) Reset() { *m = MsgSoftwareUpgradeResponse{} } -func (m *MsgSoftwareUpgradeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSoftwareUpgradeResponse) ProtoMessage() {} -func (*MsgSoftwareUpgradeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2852c16e3ab79fef, []int{1} -} -func (m *MsgSoftwareUpgradeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSoftwareUpgradeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSoftwareUpgradeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSoftwareUpgradeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSoftwareUpgradeResponse.Merge(m, src) -} -func (m *MsgSoftwareUpgradeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSoftwareUpgradeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSoftwareUpgradeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSoftwareUpgradeResponse proto.InternalMessageInfo - -// MsgCancelUpgrade is the Msg/CancelUpgrade request type. -// -// Since: cosmos-sdk 0.46 -type MsgCancelUpgrade struct { - // authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` -} - -func (m *MsgCancelUpgrade) Reset() { *m = MsgCancelUpgrade{} } -func (m *MsgCancelUpgrade) String() string { return proto.CompactTextString(m) } -func (*MsgCancelUpgrade) ProtoMessage() {} -func (*MsgCancelUpgrade) Descriptor() ([]byte, []int) { - return fileDescriptor_2852c16e3ab79fef, []int{2} -} -func (m *MsgCancelUpgrade) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCancelUpgrade) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCancelUpgrade.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCancelUpgrade) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCancelUpgrade.Merge(m, src) -} -func (m *MsgCancelUpgrade) XXX_Size() int { - return m.Size() -} -func (m *MsgCancelUpgrade) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCancelUpgrade.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCancelUpgrade proto.InternalMessageInfo - -func (m *MsgCancelUpgrade) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -// MsgCancelUpgradeResponse is the Msg/CancelUpgrade response type. -// -// Since: cosmos-sdk 0.46 -type MsgCancelUpgradeResponse struct { -} - -func (m *MsgCancelUpgradeResponse) Reset() { *m = MsgCancelUpgradeResponse{} } -func (m *MsgCancelUpgradeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCancelUpgradeResponse) ProtoMessage() {} -func (*MsgCancelUpgradeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2852c16e3ab79fef, []int{3} -} -func (m *MsgCancelUpgradeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCancelUpgradeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCancelUpgradeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCancelUpgradeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCancelUpgradeResponse.Merge(m, src) -} -func (m *MsgCancelUpgradeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCancelUpgradeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCancelUpgradeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCancelUpgradeResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgSoftwareUpgrade)(nil), "cosmos.upgrade.v1beta1.MsgSoftwareUpgrade") - proto.RegisterType((*MsgSoftwareUpgradeResponse)(nil), "cosmos.upgrade.v1beta1.MsgSoftwareUpgradeResponse") - proto.RegisterType((*MsgCancelUpgrade)(nil), "cosmos.upgrade.v1beta1.MsgCancelUpgrade") - proto.RegisterType((*MsgCancelUpgradeResponse)(nil), "cosmos.upgrade.v1beta1.MsgCancelUpgradeResponse") -} - -func init() { proto.RegisterFile("cosmos/upgrade/v1beta1/tx.proto", fileDescriptor_2852c16e3ab79fef) } - -var fileDescriptor_2852c16e3ab79fef = []byte{ - // 363 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x2f, 0x2d, 0x48, 0x2f, 0x4a, 0x4c, 0x49, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x83, 0x28, 0xd0, - 0x83, 0x2a, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, 0xd1, 0x07, 0xb1, - 0x20, 0xaa, 0xa5, 0x24, 0x21, 0xaa, 0xe3, 0x21, 0x12, 0x50, 0xad, 0x10, 0x29, 0x15, 0x1c, 0x36, - 0xc1, 0x0c, 0x86, 0xa8, 0x12, 0x87, 0xaa, 0xca, 0x2d, 0x4e, 0xd7, 0x2f, 0x33, 0x04, 0x51, 0x10, - 0x09, 0xa5, 0x29, 0x8c, 0x5c, 0x42, 0xbe, 0xc5, 0xe9, 0xc1, 0xf9, 0x69, 0x25, 0xe5, 0x89, 0x45, - 0xa9, 0xa1, 0x10, 0x5d, 0x42, 0x66, 0x5c, 0x9c, 0x89, 0xa5, 0x25, 0x19, 0xf9, 0x45, 0x99, 0x25, - 0x95, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x4e, 0x12, 0x97, 0xb6, 0xe8, 0x8a, 0x40, 0xad, 0x76, - 0x4c, 0x49, 0x29, 0x4a, 0x2d, 0x2e, 0x0e, 0x2e, 0x29, 0xca, 0xcc, 0x4b, 0x0f, 0x42, 0x28, 0x15, - 0x32, 0xe3, 0x62, 0x29, 0xc8, 0x49, 0xcc, 0x93, 0x60, 0x52, 0x60, 0xd4, 0xe0, 0x36, 0x92, 0xd1, - 0xc3, 0xee, 0x4b, 0xbd, 0x80, 0x9c, 0xc4, 0x3c, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xc0, - 0xea, 0xad, 0xf8, 0x9a, 0x9e, 0x6f, 0xd0, 0x42, 0x98, 0xa3, 0x24, 0xc3, 0x25, 0x85, 0xe9, 0xaa, - 0xa0, 0xd4, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0xa5, 0x28, 0x2e, 0x01, 0xdf, 0xe2, 0x74, 0xe7, - 0xc4, 0xbc, 0xe4, 0xd4, 0x1c, 0x0a, 0x5d, 0x8c, 0x61, 0xb3, 0x14, 0x97, 0x04, 0xba, 0xd9, 0x30, - 0x7b, 0x8d, 0x9e, 0x32, 0x72, 0x31, 0xfb, 0x16, 0xa7, 0x0b, 0x15, 0x72, 0xf1, 0xa3, 0x07, 0x98, - 0x16, 0x2e, 0xaf, 0x62, 0x7a, 0x43, 0xca, 0x88, 0x78, 0xb5, 0x30, 0xab, 0x85, 0xb2, 0xb9, 0x78, - 0x51, 0xfd, 0xab, 0x81, 0xc7, 0x10, 0x14, 0x95, 0x52, 0x06, 0xc4, 0xaa, 0x84, 0x59, 0xe6, 0xe4, - 0x76, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, - 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x3a, 0xe9, 0x99, 0x25, 0x19, - 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xd0, 0x64, 0x08, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x2b, - 0xe0, 0xa9, 0xb0, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x9c, 0xc6, 0x8c, 0x01, 0x01, 0x00, - 0x00, 0xff, 0xff, 0x11, 0x7e, 0xae, 0x0d, 0x0e, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // SoftwareUpgrade is a governance operation for initiating a software upgrade. - // - // Since: cosmos-sdk 0.46 - SoftwareUpgrade(ctx context.Context, in *MsgSoftwareUpgrade, opts ...grpc.CallOption) (*MsgSoftwareUpgradeResponse, error) - // CancelUpgrade is a governance operation for cancelling a previously - // approvid software upgrade. - // - // Since: cosmos-sdk 0.46 - CancelUpgrade(ctx context.Context, in *MsgCancelUpgrade, opts ...grpc.CallOption) (*MsgCancelUpgradeResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) SoftwareUpgrade(ctx context.Context, in *MsgSoftwareUpgrade, opts ...grpc.CallOption) (*MsgSoftwareUpgradeResponse, error) { - out := new(MsgSoftwareUpgradeResponse) - err := c.cc.Invoke(ctx, "/cosmos.upgrade.v1beta1.Msg/SoftwareUpgrade", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) CancelUpgrade(ctx context.Context, in *MsgCancelUpgrade, opts ...grpc.CallOption) (*MsgCancelUpgradeResponse, error) { - out := new(MsgCancelUpgradeResponse) - err := c.cc.Invoke(ctx, "/cosmos.upgrade.v1beta1.Msg/CancelUpgrade", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // SoftwareUpgrade is a governance operation for initiating a software upgrade. - // - // Since: cosmos-sdk 0.46 - SoftwareUpgrade(context.Context, *MsgSoftwareUpgrade) (*MsgSoftwareUpgradeResponse, error) - // CancelUpgrade is a governance operation for cancelling a previously - // approvid software upgrade. - // - // Since: cosmos-sdk 0.46 - CancelUpgrade(context.Context, *MsgCancelUpgrade) (*MsgCancelUpgradeResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) SoftwareUpgrade(ctx context.Context, req *MsgSoftwareUpgrade) (*MsgSoftwareUpgradeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SoftwareUpgrade not implemented") -} -func (*UnimplementedMsgServer) CancelUpgrade(ctx context.Context, req *MsgCancelUpgrade) (*MsgCancelUpgradeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CancelUpgrade not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_SoftwareUpgrade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSoftwareUpgrade) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SoftwareUpgrade(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.upgrade.v1beta1.Msg/SoftwareUpgrade", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SoftwareUpgrade(ctx, req.(*MsgSoftwareUpgrade)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_CancelUpgrade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCancelUpgrade) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CancelUpgrade(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.upgrade.v1beta1.Msg/CancelUpgrade", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CancelUpgrade(ctx, req.(*MsgCancelUpgrade)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.upgrade.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SoftwareUpgrade", - Handler: _Msg_SoftwareUpgrade_Handler, - }, - { - MethodName: "CancelUpgrade", - Handler: _Msg_CancelUpgrade_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/upgrade/v1beta1/tx.proto", -} - -func (m *MsgSoftwareUpgrade) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSoftwareUpgrade) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSoftwareUpgrade) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Plan.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSoftwareUpgradeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSoftwareUpgradeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSoftwareUpgradeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgCancelUpgrade) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCancelUpgrade) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCancelUpgrade) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCancelUpgradeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCancelUpgradeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCancelUpgradeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgSoftwareUpgrade) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Plan.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgSoftwareUpgradeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgCancelUpgrade) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgCancelUpgradeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgSoftwareUpgrade) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSoftwareUpgrade: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSoftwareUpgrade: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Plan", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Plan.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSoftwareUpgradeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSoftwareUpgradeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSoftwareUpgradeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCancelUpgrade) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCancelUpgrade: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCancelUpgrade: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCancelUpgradeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCancelUpgradeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCancelUpgradeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/upgrade/types/upgrade.pb.go b/x/upgrade/types/upgrade.pb.go index 1c4167f9fd..f9e8398376 100644 --- a/x/upgrade/types/upgrade.pb.go +++ b/x/upgrade/types/upgrade.pb.go @@ -5,23 +5,17 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" - github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" - time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. @@ -39,20 +33,12 @@ type Plan struct { // assumed that the software is out-of-date when the upgrade Time or Height is // reached and the software will exit. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Deprecated: Time based upgrades have been deprecated. Time based upgrade logic - // has been removed from the SDK. - // If this field is not empty, an error will be thrown. - Time time.Time `protobuf:"bytes,2,opt,name=time,proto3,stdtime" json:"time"` // Deprecated: Do not use. // The height at which the upgrade must be performed. // Only used if Time is not set. - Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` + Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` // Any application specific upgrade info to be included on-chain // such as a git commit that validators could automatically upgrade to - Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"` - // Deprecated: UpgradedClientState field has been deprecated. IBC upgrade logic has been - // moved to the IBC module in the sub module 02-client. - // If this field is not empty, an error will be thrown. - UpgradedClientState *types.Any `protobuf:"bytes,5,opt,name=upgraded_client_state,json=upgradedClientState,proto3" json:"upgraded_client_state,omitempty"` // Deprecated: Do not use. + Info string `protobuf:"bytes,3,opt,name=info,proto3" json:"info,omitempty"` } func (m *Plan) Reset() { *m = Plan{} } @@ -87,93 +73,6 @@ func (m *Plan) XXX_DiscardUnknown() { var xxx_messageInfo_Plan proto.InternalMessageInfo -// SoftwareUpgradeProposal is a gov Content type for initiating a software -// upgrade. -// Deprecated: This legacy proposal is deprecated in favor of Msg-based gov -// proposals, see MsgSoftwareUpgrade. -// -// Deprecated: Do not use. -type SoftwareUpgradeProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Plan Plan `protobuf:"bytes,3,opt,name=plan,proto3" json:"plan"` -} - -func (m *SoftwareUpgradeProposal) Reset() { *m = SoftwareUpgradeProposal{} } -func (*SoftwareUpgradeProposal) ProtoMessage() {} -func (*SoftwareUpgradeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_ccf2a7d4d7b48dca, []int{1} -} -func (m *SoftwareUpgradeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SoftwareUpgradeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SoftwareUpgradeProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SoftwareUpgradeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_SoftwareUpgradeProposal.Merge(m, src) -} -func (m *SoftwareUpgradeProposal) XXX_Size() int { - return m.Size() -} -func (m *SoftwareUpgradeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_SoftwareUpgradeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_SoftwareUpgradeProposal proto.InternalMessageInfo - -// CancelSoftwareUpgradeProposal is a gov Content type for cancelling a software -// upgrade. -// Deprecated: This legacy proposal is deprecated in favor of Msg-based gov -// proposals, see MsgCancelUpgrade. -// -// Deprecated: Do not use. -type CancelSoftwareUpgradeProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` -} - -func (m *CancelSoftwareUpgradeProposal) Reset() { *m = CancelSoftwareUpgradeProposal{} } -func (*CancelSoftwareUpgradeProposal) ProtoMessage() {} -func (*CancelSoftwareUpgradeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_ccf2a7d4d7b48dca, []int{2} -} -func (m *CancelSoftwareUpgradeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CancelSoftwareUpgradeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CancelSoftwareUpgradeProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CancelSoftwareUpgradeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CancelSoftwareUpgradeProposal.Merge(m, src) -} -func (m *CancelSoftwareUpgradeProposal) XXX_Size() int { - return m.Size() -} -func (m *CancelSoftwareUpgradeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CancelSoftwareUpgradeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CancelSoftwareUpgradeProposal proto.InternalMessageInfo - // ModuleVersion specifies a module and its consensus version. // // Since: cosmos-sdk 0.43 @@ -188,7 +87,7 @@ func (m *ModuleVersion) Reset() { *m = ModuleVersion{} } func (m *ModuleVersion) String() string { return proto.CompactTextString(m) } func (*ModuleVersion) ProtoMessage() {} func (*ModuleVersion) Descriptor() ([]byte, []int) { - return fileDescriptor_ccf2a7d4d7b48dca, []int{3} + return fileDescriptor_ccf2a7d4d7b48dca, []int{1} } func (m *ModuleVersion) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -219,8 +118,6 @@ var xxx_messageInfo_ModuleVersion proto.InternalMessageInfo func init() { proto.RegisterType((*Plan)(nil), "cosmos.upgrade.v1beta1.Plan") - proto.RegisterType((*SoftwareUpgradeProposal)(nil), "cosmos.upgrade.v1beta1.SoftwareUpgradeProposal") - proto.RegisterType((*CancelSoftwareUpgradeProposal)(nil), "cosmos.upgrade.v1beta1.CancelSoftwareUpgradeProposal") proto.RegisterType((*ModuleVersion)(nil), "cosmos.upgrade.v1beta1.ModuleVersion") } @@ -229,38 +126,23 @@ func init() { } var fileDescriptor_ccf2a7d4d7b48dca = []byte{ - // 483 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0x3d, 0x6f, 0xd3, 0x40, - 0x18, 0xc7, 0x7d, 0xad, 0x5b, 0xe8, 0x45, 0x2c, 0x26, 0x94, 0x6b, 0x04, 0x76, 0x14, 0x31, 0x64, - 0xa0, 0xb6, 0x5a, 0x24, 0x86, 0x6c, 0x24, 0x03, 0x12, 0x02, 0xa9, 0x72, 0x81, 0x81, 0x25, 0xba, - 0xd8, 0x17, 0xc7, 0xc2, 0xbe, 0xc7, 0xf2, 0x5d, 0x02, 0x19, 0xf9, 0x06, 0x1d, 0x19, 0xfb, 0x1d, - 0xe0, 0x43, 0x44, 0x4c, 0x1d, 0x11, 0x03, 0x2f, 0xc9, 0xc2, 0xc7, 0x40, 0xf7, 0xe2, 0x0a, 0x41, - 0x17, 0x24, 0x26, 0x3f, 0xcf, 0xf9, 0xff, 0xf7, 0xef, 0x79, 0x39, 0xe3, 0x7b, 0x09, 0x88, 0x12, - 0x44, 0x34, 0xaf, 0xb2, 0x9a, 0xa6, 0x2c, 0x5a, 0x1c, 0x4d, 0x98, 0xa4, 0x47, 0x4d, 0x1e, 0x56, - 0x35, 0x48, 0xf0, 0xf6, 0x8d, 0x2a, 0x6c, 0x4e, 0xad, 0xaa, 0x73, 0x90, 0x01, 0x64, 0x05, 0x8b, - 0xb4, 0x6a, 0x32, 0x9f, 0x46, 0x94, 0x2f, 0x8d, 0xa5, 0xd3, 0xce, 0x20, 0x03, 0x1d, 0x46, 0x2a, - 0xb2, 0xa7, 0xc1, 0x9f, 0x06, 0x99, 0x97, 0x4c, 0x48, 0x5a, 0x56, 0x56, 0x70, 0x60, 0x48, 0x63, - 0xe3, 0xb4, 0x58, 0x9d, 0xf4, 0xbe, 0x20, 0xec, 0x9e, 0x14, 0x94, 0x7b, 0x1e, 0x76, 0x39, 0x2d, - 0x19, 0x41, 0x5d, 0xd4, 0xdf, 0x8b, 0x75, 0xec, 0x0d, 0xb0, 0xab, 0x3e, 0x45, 0xb6, 0xba, 0xa8, - 0xdf, 0x3a, 0xee, 0x84, 0x86, 0x13, 0x36, 0x9c, 0xf0, 0x79, 0xc3, 0x19, 0xe2, 0xd5, 0xd7, 0xc0, - 0x39, 0xfb, 0x16, 0x20, 0x82, 0x62, 0xed, 0xf1, 0xf6, 0xf1, 0xee, 0x8c, 0xe5, 0xd9, 0x4c, 0x92, - 0xed, 0x2e, 0xea, 0x6f, 0xc7, 0x36, 0x53, 0x9c, 0x9c, 0x4f, 0x81, 0xb8, 0x86, 0xa3, 0x62, 0xef, - 0x29, 0xbe, 0x65, 0x87, 0x90, 0x8e, 0x93, 0x22, 0x67, 0x5c, 0x8e, 0x85, 0xa4, 0x92, 0x91, 0x1d, - 0x0d, 0x6e, 0xff, 0x05, 0x7e, 0xc4, 0x97, 0xc3, 0x2d, 0x82, 0xe2, 0x9b, 0x8d, 0x6d, 0xa4, 0x5d, - 0xa7, 0xca, 0x34, 0xb8, 0xfe, 0xfe, 0x3c, 0x70, 0x7e, 0x9e, 0x07, 0xa8, 0xf7, 0x01, 0xe1, 0xdb, - 0xa7, 0x30, 0x95, 0x6f, 0x68, 0xcd, 0x5e, 0x18, 0xe5, 0x49, 0x0d, 0x15, 0x08, 0x5a, 0x78, 0x6d, - 0xbc, 0x23, 0x73, 0x59, 0x34, 0x0d, 0x9b, 0xc4, 0xeb, 0xe2, 0x56, 0xca, 0x44, 0x52, 0xe7, 0x95, - 0xcc, 0x81, 0xeb, 0xc6, 0xf7, 0xe2, 0xdf, 0x8f, 0xbc, 0x87, 0xd8, 0xad, 0x0a, 0xca, 0x75, 0x57, - 0xad, 0xe3, 0x3b, 0xe1, 0xd5, 0x4b, 0x0c, 0xd5, 0x4c, 0x87, 0xae, 0x9a, 0x4a, 0xac, 0xf5, 0x83, - 0x7e, 0x53, 0xd5, 0xa7, 0x8f, 0x87, 0x1d, 0x6b, 0xca, 0x60, 0x71, 0x69, 0x18, 0x01, 0x97, 0x8c, - 0x4b, 0x82, 0x7a, 0xef, 0x10, 0xbe, 0x3b, 0xa2, 0x3c, 0x61, 0xc5, 0x7f, 0xae, 0xfd, 0x1f, 0x6a, - 0x78, 0x8c, 0x6f, 0x3c, 0x83, 0x74, 0x5e, 0xb0, 0x97, 0xac, 0x16, 0xaa, 0xed, 0xab, 0xae, 0x07, - 0xc1, 0xd7, 0x16, 0xe6, 0xb5, 0x86, 0xb9, 0x71, 0x93, 0xea, 0x15, 0x20, 0x05, 0x1a, 0x3e, 0x59, - 0xfd, 0xf0, 0x9d, 0xd5, 0xda, 0x47, 0x17, 0x6b, 0x1f, 0x7d, 0x5f, 0xfb, 0xe8, 0x6c, 0xe3, 0x3b, - 0x17, 0x1b, 0xdf, 0xf9, 0xbc, 0xf1, 0x9d, 0x57, 0xf7, 0xb3, 0x5c, 0xce, 0xe6, 0x93, 0x30, 0x81, - 0xd2, 0x5e, 0x4b, 0xfb, 0x38, 0x14, 0xe9, 0xeb, 0xe8, 0xed, 0xe5, 0x0f, 0x24, 0x97, 0x15, 0x13, - 0x93, 0x5d, 0xbd, 0xff, 0x07, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0x06, 0xec, 0xeb, 0xea, 0x5f, - 0x03, 0x00, 0x00, + // 246 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x49, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x2f, 0x2d, 0x48, 0x2f, 0x4a, 0x4c, 0x49, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, + 0x49, 0x34, 0x84, 0xf1, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xc4, 0x20, 0xaa, 0xf4, 0x60, + 0xa2, 0x50, 0x55, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x25, 0xfa, 0x20, 0x16, 0x44, 0xb5, + 0x52, 0x00, 0x17, 0x4b, 0x40, 0x4e, 0x62, 0x9e, 0x90, 0x10, 0x17, 0x4b, 0x5e, 0x62, 0x6e, 0xaa, + 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x98, 0x2d, 0x24, 0xc6, 0xc5, 0x96, 0x91, 0x9a, 0x99, + 0x9e, 0x51, 0x22, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x1c, 0x04, 0xe5, 0x81, 0xd4, 0x66, 0xe6, 0xa5, + 0xe5, 0x4b, 0x30, 0x43, 0xd4, 0x82, 0xd8, 0x56, 0x1c, 0x33, 0x16, 0xc8, 0x33, 0xbc, 0x58, 0x20, + 0xcf, 0xa8, 0xe4, 0xce, 0xc5, 0xeb, 0x9b, 0x9f, 0x52, 0x9a, 0x93, 0x1a, 0x96, 0x5a, 0x54, 0x9c, + 0x99, 0x8f, 0xdd, 0x68, 0x09, 0x2e, 0xf6, 0x32, 0x88, 0x34, 0xd8, 0x6c, 0x96, 0x20, 0x18, 0x17, + 0x6c, 0x10, 0x23, 0xc8, 0x20, 0x27, 0xaf, 0x13, 0x0f, 0xe5, 0x18, 0x4e, 0x3c, 0x92, 0x63, 0xbc, + 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, + 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x27, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, + 0x57, 0x1f, 0x1a, 0x2e, 0x10, 0x4a, 0xb7, 0x38, 0x25, 0x5b, 0xbf, 0x02, 0x1e, 0x48, 0x25, 0x95, + 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0xdf, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf3, 0xc1, + 0x6c, 0x0b, 0x43, 0x01, 0x00, 0x00, } func (this *Plan) Equal(that interface{}) bool { @@ -285,75 +167,12 @@ func (this *Plan) Equal(that interface{}) bool { if this.Name != that1.Name { return false } - if !this.Time.Equal(that1.Time) { - return false - } if this.Height != that1.Height { return false } if this.Info != that1.Info { return false } - if !this.UpgradedClientState.Equal(that1.UpgradedClientState) { - return false - } - return true -} -func (this *SoftwareUpgradeProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*SoftwareUpgradeProposal) - if !ok { - that2, ok := that.(SoftwareUpgradeProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if !this.Plan.Equal(&that1.Plan) { - return false - } - return true -} -func (this *CancelSoftwareUpgradeProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CancelSoftwareUpgradeProposal) - if !ok { - that2, ok := that.(CancelSoftwareUpgradeProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } return true } func (this *ModuleVersion) Equal(that interface{}) bool { @@ -403,38 +222,18 @@ func (m *Plan) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.UpgradedClientState != nil { - { - size, err := m.UpgradedClientState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintUpgrade(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } if len(m.Info) > 0 { i -= len(m.Info) copy(dAtA[i:], m.Info) i = encodeVarintUpgrade(dAtA, i, uint64(len(m.Info))) i-- - dAtA[i] = 0x22 + dAtA[i] = 0x1a } if m.Height != 0 { i = encodeVarintUpgrade(dAtA, i, uint64(m.Height)) i-- - dAtA[i] = 0x18 - } - n2, err2 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Time):]) - if err2 != nil { - return 0, err2 + dAtA[i] = 0x10 } - i -= n2 - i = encodeVarintUpgrade(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x12 if len(m.Name) > 0 { i -= len(m.Name) copy(dAtA[i:], m.Name) @@ -445,90 +244,6 @@ func (m *Plan) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *SoftwareUpgradeProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SoftwareUpgradeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SoftwareUpgradeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Plan.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintUpgrade(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintUpgrade(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintUpgrade(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CancelSoftwareUpgradeProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CancelSoftwareUpgradeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CancelSoftwareUpgradeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintUpgrade(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintUpgrade(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - func (m *ModuleVersion) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -585,8 +300,6 @@ func (m *Plan) Size() (n int) { if l > 0 { n += 1 + l + sovUpgrade(uint64(l)) } - l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Time) - n += 1 + l + sovUpgrade(uint64(l)) if m.Height != 0 { n += 1 + sovUpgrade(uint64(m.Height)) } @@ -594,46 +307,6 @@ func (m *Plan) Size() (n int) { if l > 0 { n += 1 + l + sovUpgrade(uint64(l)) } - if m.UpgradedClientState != nil { - l = m.UpgradedClientState.Size() - n += 1 + l + sovUpgrade(uint64(l)) - } - return n -} - -func (m *SoftwareUpgradeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovUpgrade(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovUpgrade(uint64(l)) - } - l = m.Plan.Size() - n += 1 + l + sovUpgrade(uint64(l)) - return n -} - -func (m *CancelSoftwareUpgradeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovUpgrade(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovUpgrade(uint64(l)) - } return n } @@ -721,39 +394,6 @@ func (m *Plan) Unmarshal(dAtA []byte) error { m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } @@ -772,7 +412,7 @@ func (m *Plan) Unmarshal(dAtA []byte) error { break } } - case 4: + case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) } @@ -804,303 +444,6 @@ func (m *Plan) Unmarshal(dAtA []byte) error { } m.Info = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UpgradedClientState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.UpgradedClientState == nil { - m.UpgradedClientState = &types.Any{} - } - if err := m.UpgradedClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipUpgrade(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthUpgrade - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SoftwareUpgradeProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SoftwareUpgradeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SoftwareUpgradeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Plan", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Plan.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipUpgrade(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthUpgrade - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CancelSoftwareUpgradeProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CancelSoftwareUpgradeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CancelSoftwareUpgradeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUpgrade - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUpgrade - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthUpgrade - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipUpgrade(dAtA[iNdEx:]) diff --git a/x/upgrade/types/upgrade_config.go b/x/upgrade/types/upgrade_config.go new file mode 100644 index 0000000000..fc9612069a --- /dev/null +++ b/x/upgrade/types/upgrade_config.go @@ -0,0 +1,79 @@ +package types + +import ( + "math" +) + +// ex. +// const ( +// BEP111 = "BEP111" +// ) + +var ( + MainnetChainID = "inscription_9000-1" + MainnetConfig = NewUpgradeConfig() + // .SetPlan(&Plan{ + // Name: BEP111, + // Height: 100, + // Info: "https://github.com/bnb-chain/BEPs/pull/111", + // }) +) + +func NewUpgradeConfig() *UpgradeConfig { + return &UpgradeConfig{ + keys: make(map[string]*key), + elements: make(map[int64][]*Plan), + } +} + +type key struct { + index int + height int64 +} + +type UpgradeConfig struct { + keys map[string]*key + elements map[int64][]*Plan +} + +func (c *UpgradeConfig) SetPlan(plan *Plan) *UpgradeConfig { + if key, ok := c.keys[plan.Name]; ok { + if c.elements[key.height][key.index].Height == plan.Height { + *c.elements[key.height][key.index] = *plan + return c + } + + c.elements[key.height] = append(c.elements[key.height][:key.index], c.elements[key.height][key.index+1:]...) + } + + c.elements[plan.Height] = append(c.elements[plan.Height], plan) + c.keys[plan.Name] = &key{height: plan.Height, index: len(c.elements[plan.Height]) - 1} + + return c +} + +func (c *UpgradeConfig) Clear(height int64) { + for _, plan := range c.elements[height] { + delete(c.keys, plan.Name) + } + c.elements[height] = nil +} + +func (c *UpgradeConfig) GetPlan(height int64) []*Plan { + plans, exist := c.elements[height] + if exist && len(plans) != 0 { + return plans + } + + // get recent upgrade plan + recentHeight := int64(math.MaxInt64) + for vHeight, vPlans := range c.elements { + if vHeight > height { + if vHeight < recentHeight { + plans = vPlans + recentHeight = vHeight + } + } + } + return plans +} diff --git a/x/upgrade/types/upgrade_config_test.go b/x/upgrade/types/upgrade_config_test.go new file mode 100644 index 0000000000..779447f2ab --- /dev/null +++ b/x/upgrade/types/upgrade_config_test.go @@ -0,0 +1,114 @@ +package types + +import ( + "reflect" + "testing" +) + +func TestUpgradeConfig(t *testing.T) { + type args struct { + height int64 + } + tests := []struct { + name string + c *UpgradeConfig + args args + want []*Plan + }{ + { + name: "TestUpgradeConfig_GetPlan Case 1", + c: NewUpgradeConfig().SetPlan(&Plan{ + Name: "Upgrade-1", + Height: 1, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 11, + }).SetPlan(&Plan{ + Name: "Upgrade-3", + Height: 20, + }), + args: args{ + height: 10, + }, + want: []*Plan{{ + Name: "Upgrade-2", + Height: 11, + }}, + }, + { + name: "TestUpgradeConfig_GetPlan Case 2", + c: NewUpgradeConfig().SetPlan(&Plan{ + Name: "Upgrade-1", + Height: 1, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 11, + }).SetPlan(&Plan{ + Name: "Upgrade-3", + Height: 20, + }), + args: args{ + height: 20, + }, + want: []*Plan{{ + Name: "Upgrade-3", + Height: 20, + }}, + }, + { + name: "TestUpgradeConfig_SetPlan Override 1", + c: NewUpgradeConfig().SetPlan(&Plan{ + Name: "Upgrade-1", + Height: 1, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 11, + }).SetPlan(&Plan{ + Name: "Upgrade-3", + Height: 20, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 19, + }), + args: args{ + height: 11, + }, + want: []*Plan{{ + Name: "Upgrade-2", + Height: 19, + }}, + }, + { + name: "TestUpgradeConfig_SetPlan Override 2", + c: NewUpgradeConfig().SetPlan(&Plan{ + Name: "Upgrade-1", + Height: 1, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 11, + }).SetPlan(&Plan{ + Name: "Upgrade-3", + Height: 20, + }).SetPlan(&Plan{ + Name: "Upgrade-2", + Height: 11, + Info: "override", + }), + args: args{ + height: 10, + }, + want: []*Plan{{ + Name: "Upgrade-2", + Height: 11, + Info: "override", + }}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.c.GetPlan(tt.args.height); !reflect.DeepEqual(got, tt.want) { + t.Errorf("UpgradeConfig.GetPlan() = %v, want %v", got, tt.want) + } + }) + } +}