From 66c3ffc9e4a38b693573ace021c2ba94c25af59f Mon Sep 17 00:00:00 2001 From: zakir <80246097+zakir-code@users.noreply.github.com> Date: Mon, 31 Jul 2023 11:18:00 +0800 Subject: [PATCH] refactor(cli): remove duplicate `--home` flag --- client/pruning/main.go | 18 ++------ server/export.go | 6 +-- server/export_test.go | 4 +- server/rollback.go | 9 ++-- server/start.go | 8 ++-- server/util.go | 8 ++-- server/util_test.go | 56 ++++++++++++++----------- simapp/simd/cmd/root.go | 8 ++-- simapp/simd/cmd/root_v2.go | 8 ++-- tests/e2e/server/export_test.go | 23 +++++----- x/genutil/client/cli/collect.go | 6 +-- x/genutil/client/cli/commands.go | 16 +++---- x/genutil/client/cli/genaccount.go | 5 +-- x/genutil/client/cli/genaccount_test.go | 5 +-- x/genutil/client/cli/gentx.go | 7 +--- x/genutil/client/cli/gentx_test.go | 8 +--- x/genutil/client/cli/init.go | 4 +- x/genutil/client/cli/init_test.go | 23 +++++----- x/genutil/client/testutil/helpers.go | 6 +-- 19 files changed, 97 insertions(+), 131 deletions(-) diff --git a/client/pruning/main.go b/client/pruning/main.go index 51dc5f9c216..9e86c96dc69 100644 --- a/client/pruning/main.go +++ b/client/pruning/main.go @@ -6,13 +6,11 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" - "github.com/spf13/viper" "cosmossdk.io/log" pruningtypes "cosmossdk.io/store/pruning/types" "cosmossdk.io/store/rootmulti" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" ) @@ -21,7 +19,7 @@ const FlagAppDBBackend = "app-db-backend" // Cmd prunes the sdk root multi store history versions based on the pruning options // specified by command flags. -func Cmd(appCreator servertypes.AppCreator, defaultNodeHome string) *cobra.Command { +func Cmd(appCreator servertypes.AppCreator) *cobra.Command { cmd := &cobra.Command{ Use: "prune [pruning-method]", Short: "Prune app history states by keeping the recent heights and deleting old heights", @@ -38,11 +36,8 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, Example: "prune custom --pruning-keep-recent 100 --app-db-backend 'goleveldb'", Args: cobra.RangeArgs(0, 1), RunE: func(cmd *cobra.Command, args []string) error { - // bind flags to the Context's Viper so we can get pruning options. - vp := viper.New() - if err := vp.BindPFlags(cmd.Flags()); err != nil { - return err - } + serverCtx := server.GetServerContextFromCmd(cmd) + vp := serverCtx.Viper // use the first argument if present to set the pruning method if len(args) > 0 { @@ -60,11 +55,7 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, pruningOptions.KeepRecent, ) - home := vp.GetString(flags.FlagHome) - if home == "" { - home = defaultNodeHome - } - + home := serverCtx.Config.RootDir db, err := openDB(home, server.GetAppDBBackend(vp)) if err != nil { return err @@ -97,7 +88,6 @@ Supported app-db-backend types include 'goleveldb', 'rocksdb', 'pebbledb'.`, }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(FlagAppDBBackend, "", "The type of database for application and snapshots databases") cmd.Flags().Uint64(server.FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") cmd.Flags().Uint64(server.FlagPruningInterval, 10, diff --git a/server/export.go b/server/export.go index 9b43da0c854..3c4175315e4 100644 --- a/server/export.go +++ b/server/export.go @@ -23,7 +23,7 @@ const ( ) // ExportCmd dumps app state to JSON. -func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Command { +func ExportCmd(appExporter types.AppExporter) *cobra.Command { cmd := &cobra.Command{ Use: "export", Short: "Export state to JSON", @@ -32,9 +32,6 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com serverCtx := GetServerContextFromCmd(cmd) config := serverCtx.Config - homeDir, _ := cmd.Flags().GetString(flags.FlagHome) - config.SetRoot(homeDir) - if _, err := os.Stat(config.GenesisFile()); os.IsNotExist(err) { return err } @@ -115,7 +112,6 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().Int64(FlagHeight, -1, "Export state from a particular height (-1 means latest height)") cmd.Flags().Bool(FlagForZeroHeight, false, "Export state to start at height zero (perform preproccessing)") cmd.Flags().StringSlice(FlagJailAllowedAddrs, []string{}, "Comma-separated list of operator addresses of jailed validators to unjail") diff --git a/server/export_test.go b/server/export_test.go index f7c0124f900..dc400f9c9ed 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -58,8 +58,8 @@ func NewExportSystem(t *testing.T, exporter types.AppExporter) *ExportSystem { sys := cmdtest.NewSystem() sys.AddCommands( - server.ExportCmd(exporter, homeDir), - genutilcli.InitCmd(module.NewBasicManager(), homeDir), + server.ExportCmd(exporter), + genutilcli.InitCmd(module.NewBasicManager()), ) tw := zerolog.NewTestWriter(t) diff --git a/server/rollback.go b/server/rollback.go index ccd7e321390..c273a0492b7 100644 --- a/server/rollback.go +++ b/server/rollback.go @@ -6,12 +6,11 @@ import ( cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server/types" ) // NewRollbackCmd creates a command to rollback CometBFT and multistore state by one height. -func NewRollbackCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command { +func NewRollbackCmd(appCreator types.AppCreator) *cobra.Command { var removeBlock bool cmd := &cobra.Command{ @@ -27,9 +26,8 @@ application. `, RunE: func(cmd *cobra.Command, args []string) error { ctx := GetServerContextFromCmd(cmd) - cfg := ctx.Config - home := cfg.RootDir - db, err := openDB(home, GetAppDBBackend(ctx.Viper)) + + db, err := openDB(ctx.Config.RootDir, GetAppDBBackend(ctx.Viper)) if err != nil { return err } @@ -50,7 +48,6 @@ application. }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().BoolVar(&removeBlock, "hard", false, "remove last block as well as state") return cmd } diff --git a/server/start.go b/server/start.go index e5f89ac4691..b968ca90fd1 100644 --- a/server/start.go +++ b/server/start.go @@ -29,7 +29,6 @@ import ( pruningtypes "cosmossdk.io/store/pruning/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" @@ -103,13 +102,13 @@ type StartCmdOptions struct { // StartCmd runs the service passed in, either stand-alone or in-process with // CometBFT. -func StartCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command { - return StartCmdWithOptions(appCreator, defaultNodeHome, StartCmdOptions{}) +func StartCmd(appCreator types.AppCreator) *cobra.Command { + return StartCmdWithOptions(appCreator, StartCmdOptions{}) } // StartCmdWithOptions runs the service passed in, either stand-alone or in-process with // CometBFT. -func StartCmdWithOptions(appCreator types.AppCreator, defaultNodeHome string, opts StartCmdOptions) *cobra.Command { +func StartCmdWithOptions(appCreator types.AppCreator, opts StartCmdOptions) *cobra.Command { if opts.DBOpener == nil { opts.DBOpener = openDB } @@ -174,7 +173,6 @@ is performed. Note, when enabled, gRPC will also be automatically enabled. }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().Bool(flagWithComet, true, "Run abci app embedded in-process with CometBFT") cmd.Flags().String(flagAddress, "tcp://0.0.0.0:26658", "Listen address") cmd.Flags().String(flagTransport, "socket", "Transport protocol: socket, grpc") diff --git a/server/util.go b/server/util.go index 40842f4b2c3..fbaf6d0be1d 100644 --- a/server/util.go +++ b/server/util.go @@ -311,7 +311,7 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo } // add server commands -func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator types.AppCreator, appExport types.AppExporter, addStartFlags types.ModuleInitFlags) { +func AddCommands(rootCmd *cobra.Command, appCreator types.AppCreator, appExport types.AppExporter, addStartFlags types.ModuleInitFlags) { cometCmd := &cobra.Command{ Use: "comet", Aliases: []string{"cometbft", "tendermint"}, @@ -328,15 +328,15 @@ func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator type BootstrapStateCmd(appCreator), ) - startCmd := StartCmd(appCreator, defaultNodeHome) + startCmd := StartCmd(appCreator) addStartFlags(startCmd) rootCmd.AddCommand( startCmd, cometCmd, - ExportCmd(appExport, defaultNodeHome), + ExportCmd(appExport), version.NewVersionCommand(), - NewRollbackCmd(appCreator, defaultNodeHome), + NewRollbackCmd(appCreator), ) } diff --git a/server/util_test.go b/server/util_test.go index 6f9a91ceed2..e1a01cdfeec 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -39,8 +39,9 @@ func preRunETestImpl(cmd *cobra.Command, args []string) error { func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T) { tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -48,7 +49,7 @@ func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -115,8 +116,9 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { t.Fatalf("Failed closing config.toml: %v", err) } - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foober", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -125,7 +127,7 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -155,14 +157,15 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { if err := writer.Close(); err != nil { t.Fatalf("Failed closing app.toml: %v", err) } - cmd := server.StartCmd(nil, tempDir) + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") cmd.PreRunE = preRunETestImpl serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -174,9 +177,9 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { const testAddr = "tcp://127.1.2.3:12345" tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -190,7 +193,7 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -202,8 +205,9 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { const testAddr = "tcp://127.1.2.3:12345" tempDir := t.TempDir() - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, tempDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -225,7 +229,7 @@ func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -289,7 +293,8 @@ func newPrecedenceCommon(t *testing.T) precedenceCommon { }) // Set up the command object that is used in this test - retval.cmd = server.StartCmd(nil, tempDir) + retval.cmd = server.StartCmd(nil) + retval.cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") retval.cmd.PreRunE = preRunETestImpl return retval @@ -331,7 +336,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceFlag(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -347,7 +352,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceEnvVar(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -363,7 +368,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigFile(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -379,7 +384,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -397,8 +402,9 @@ func TestInterceptConfigsWithBadPermissions(t *testing.T) { if err := os.Mkdir(subDir, 0o600); err != nil { t.Fatalf("Failed to create sub directory: %v", err) } - cmd := server.StartCmd(nil, "/foobar") - if err := cmd.Flags().Set(flags.FlagHome, subDir); err != nil { + cmd := server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, "/foobar", "") + if err := cmd.PersistentFlags().Set(flags.FlagHome, subDir); err != nil { t.Fatalf("Could not set home flag [%T] %v", err, err) } @@ -420,9 +426,10 @@ func TestEmptyMinGasPrices(t *testing.T) { // Run InitCmd to create necessary config files. clientCtx := client.Context{}.WithHomeDir(tempDir).WithCodec(encCfg.Codec) serverCtx := server.NewDefaultContext() + serverCtx.Config.SetRoot(tempDir) ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := genutilcli.InitCmd(module.NewBasicManager(), tempDir) + cmd := genutilcli.InitCmd(module.NewBasicManager()) cmd.SetArgs([]string{"appnode-test"}) err = cmd.ExecuteContext(ctx) require.NoError(t, err) @@ -434,7 +441,8 @@ func TestEmptyMinGasPrices(t *testing.T) { config.WriteConfigFile(appCfgTempFilePath, appConf) // Run StartCmd. - cmd = server.StartCmd(nil, tempDir) + cmd = server.StartCmd(nil) + cmd.PersistentFlags().String(flags.FlagHome, tempDir, "") cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { ctx, err := server.InterceptConfigsAndCreateContext(cmd, "", nil, cmtcfg.DefaultConfig()) if err != nil { diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index a392ec87216..23914f7be46 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -193,15 +193,15 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, b cfg.Seal() rootCmd.AddCommand( - genutilcli.InitCmd(basicManager, simapp.DefaultNodeHome), + genutilcli.InitCmd(basicManager), NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), debug.Cmd(), confixcmd.ConfigCommand(), - pruning.Cmd(newApp, simapp.DefaultNodeHome), + pruning.Cmd(newApp), snapshot.Cmd(newApp), ) - server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) + server.AddCommands(rootCmd, newApp, appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( @@ -219,7 +219,7 @@ func addModuleInitFlags(startCmd *cobra.Command) { // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter func genesisCommand(encodingConfig params.EncodingConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(encodingConfig.TxConfig, basicManager, simapp.DefaultNodeHome) + cmd := genutilcli.Commands(encodingConfig.TxConfig, basicManager) for _, subCmd := range cmds { cmd.AddCommand(subCmd) diff --git a/simapp/simd/cmd/root_v2.go b/simapp/simd/cmd/root_v2.go index 72f5dff29d7..fe25126b315 100644 --- a/simapp/simd/cmd/root_v2.go +++ b/simapp/simd/cmd/root_v2.go @@ -209,15 +209,15 @@ func initRootCmd( cfg.Seal() rootCmd.AddCommand( - genutilcli.InitCmd(basicManager, simapp.DefaultNodeHome), + genutilcli.InitCmd(basicManager), NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), debug.Cmd(), confixcmd.ConfigCommand(), - pruning.Cmd(newApp, simapp.DefaultNodeHome), + pruning.Cmd(newApp), snapshot.Cmd(newApp), ) - server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, appExport, addModuleInitFlags) + server.AddCommands(rootCmd, newApp, appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( @@ -235,7 +235,7 @@ func addModuleInitFlags(startCmd *cobra.Command) { // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(txConfig, basicManager, simapp.DefaultNodeHome) + cmd := genutilcli.Commands(txConfig, basicManager) for _, subCmd := range cmds { cmd.AddCommand(subCmd) diff --git a/tests/e2e/server/export_test.go b/tests/e2e/server/export_test.go index 45616e7029b..773d3005a0e 100644 --- a/tests/e2e/server/export_test.go +++ b/tests/e2e/server/export_test.go @@ -193,20 +193,19 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge }) app.Commit() - cmd := server.ExportCmd( - func(_ log.Logger, _ dbm.DB, _ io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOptions types.AppOptions, modulesToExport []string) (types.ExportedApp, error) { - var simApp *simapp.SimApp - if height != -1 { - simApp = simapp.NewSimApp(logger, db, nil, false, appOptions) - if err := simApp.LoadHeight(height); err != nil { - return types.ExportedApp{}, err - } - } else { - simApp = simapp.NewSimApp(logger, db, nil, true, appOptions) + cmd := server.ExportCmd(func(_ log.Logger, _ dbm.DB, _ io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOptions types.AppOptions, modulesToExport []string) (types.ExportedApp, error) { + var simApp *simapp.SimApp + if height != -1 { + simApp = simapp.NewSimApp(logger, db, nil, false, appOptions) + if err := simApp.LoadHeight(height); err != nil { + return types.ExportedApp{}, err } + } else { + simApp = simapp.NewSimApp(logger, db, nil, true, appOptions) + } - return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) - }, tempDir) + return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) + }) ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index 5502445960d..f164c1ccd92 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -9,7 +9,6 @@ import ( "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/x/genutil" @@ -19,7 +18,7 @@ import ( const flagGenTxDir = "gentx-dir" // CollectGenTxsCmd - return the cobra command to collect genesis transactions -func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeHome string, validator types.MessageValidator, valAddrCodec runtime.ValidatorAddressCodec) *cobra.Command { +func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, validator types.MessageValidator, valAddrCodec runtime.ValidatorAddressCodec) *cobra.Command { cmd := &cobra.Command{ Use: "collect-gentxs", Short: "Collect genesis txs and output a genesis.json file", @@ -30,8 +29,6 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.Codec - config.SetRoot(clientCtx.HomeDir) - nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") @@ -62,7 +59,6 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeH }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flagGenTxDir, "", "override default \"gentx\" directory from which collect and execute genesis transactions; default [--home]/config/gentx/") return cmd diff --git a/x/genutil/client/cli/commands.go b/x/genutil/client/cli/commands.go index 0db6b39bfba..bc737886b13 100644 --- a/x/genutil/client/cli/commands.go +++ b/x/genutil/client/cli/commands.go @@ -12,18 +12,18 @@ import ( // GenesisCoreCommand adds core sdk's sub-commands into genesis command. // Deprecated: use Commands instead. -func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { - return Commands(txConfig, moduleBasics, defaultNodeHome) +func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManager) *cobra.Command { + return Commands(txConfig, moduleBasics) } // Commands adds core sdk's sub-commands into genesis command. -func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { - return CommandsWithCustomMigrationMap(txConfig, moduleBasics, defaultNodeHome, MigrationMap) +func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager) *cobra.Command { + return CommandsWithCustomMigrationMap(txConfig, moduleBasics, MigrationMap) } // CommandsWithCustomMigrationMap adds core sdk's sub-commands into genesis command with custom migration map. // This custom migration map can be used by the application to add its own migration map. -func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string, migrationMap genutiltypes.MigrationMap) *cobra.Command { +func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, migrationMap genutiltypes.MigrationMap) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -34,11 +34,11 @@ func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics modul gentxModule := moduleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) cmd.AddCommand( - GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome, txConfig.SigningContext().ValidatorAddressCodec()), + GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, txConfig.SigningContext().ValidatorAddressCodec()), MigrateGenesisCmd(migrationMap), - CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), + CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), ValidateGenesisCmd(moduleBasics), - AddGenesisAccountCmd(defaultNodeHome, txConfig.SigningContext().AddressCodec()), + AddGenesisAccountCmd(txConfig.SigningContext().AddressCodec()), ) return cmd diff --git a/x/genutil/client/cli/genaccount.go b/x/genutil/client/cli/genaccount.go index 100048751be..2dfe5e7c7d0 100644 --- a/x/genutil/client/cli/genaccount.go +++ b/x/genutil/client/cli/genaccount.go @@ -26,7 +26,7 @@ const ( // AddGenesisAccountCmd returns add-genesis-account cobra Command. // This command is provided as a default, applications are expected to provide their own command if custom genesis accounts are needed. -func AddGenesisAccountCmd(defaultNodeHome string, addressCodec address.Codec) *cobra.Command { +func AddGenesisAccountCmd(addressCodec address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -41,8 +41,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) - var kr keyring.Keyring addr, err := addressCodec.StringToBytes(args[0]) if err != nil { @@ -80,7 +78,6 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index 573d9a41bbf..7bc1a60702e 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -2,7 +2,6 @@ package cli_test import ( "context" - "fmt" "testing" "github.com/spf13/viper" @@ -11,7 +10,6 @@ import ( "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -91,11 +89,10 @@ func TestAddGenesisAccountCmd(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.AddGenesisAccountCmd(home, addresscodec.NewBech32Codec("cosmos")) + cmd := genutilcli.AddGenesisAccountCmd(addresscodec.NewBech32Codec("cosmos")) cmd.SetArgs([]string{ tc.addr, tc.denom, - fmt.Sprintf("--%s=home", flags.FlagHome), }) if tc.expectErr { diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 7c5ee6f7f9a..41410e9cd99 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" - address "cosmossdk.io/core/address" + "cosmossdk.io/core/address" "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" @@ -29,7 +29,7 @@ import ( ) // GenTxCmd builds the application's gentx command. -func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string, valAdddressCodec address.Codec) *cobra.Command { +func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, valAdddressCodec address.Codec) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -61,9 +61,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o return err } cdc := clientCtx.Codec - config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(serverCtx.Config) if err != nil { @@ -212,7 +210,6 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flags.FlagOutputDocument, "", "Write the genesis transaction JSON document to the given file instead of the default location") cmd.Flags().AddFlagSet(fsCreateValidator) flags.AddTxFlagsToCmd(cmd) diff --git a/x/genutil/client/cli/gentx_test.go b/x/genutil/client/cli/gentx_test.go index 1f7ffeabce5..478a536994f 100644 --- a/x/genutil/client/cli/gentx_test.go +++ b/x/genutil/client/cli/gentx_test.go @@ -123,13 +123,7 @@ func (s *CLITestSuite) TestGenTxCmd() { clientCtx := s.clientCtx ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd := cli.GenTxCmd( - module.NewBasicManager(), - clientCtx.TxConfig, - banktypes.GenesisBalancesIterator{}, - clientCtx.HomeDir, - address.NewBech32Codec("cosmosvaloper"), - ) + cmd := cli.GenTxCmd(module.NewBasicManager(), clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, address.NewBech32Codec("cosmosvaloper")) cmd.SetContext(ctx) cmd.SetArgs(tc.args) diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 0461713a0e1..999a3dbb0e8 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -68,7 +68,7 @@ func displayInfo(info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { +func InitCmd(mbm module.BasicManager) *cobra.Command { cmd := &cobra.Command{ Use: "init [moniker]", Short: "Initialize private validator, p2p, genesis, and application configuration files", @@ -80,7 +80,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config - config.SetRoot(clientCtx.HomeDir) chainID, _ := cmd.Flags().GetString(flags.FlagChainID) switch { @@ -173,7 +172,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file") cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 15df1571b89..c73f7d44fb3 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -78,7 +78,7 @@ func TestInitCmd(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs( tt.flags(home), ) @@ -111,7 +111,7 @@ func TestInitRecover(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) mockIn := testutil.ApplyMockIODiscardOutErr(cmd) cmd.SetArgs([]string{ @@ -142,11 +142,10 @@ func TestInitDefaultBondDenom(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{ "appnode-test", - fmt.Sprintf("--%s=%s", flags.FlagHome, home), fmt.Sprintf("--%s=testtoken", genutilcli.FlagDefaultBondDenom), }) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -159,6 +158,7 @@ func TestEmptyState(t *testing.T) { require.NoError(t, err) serverCtx := server.NewContext(viper.New(), cfg, logger) + serverCtx.Config.SetRoot(home) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -170,8 +170,8 @@ func TestEmptyState(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd := genutilcli.InitCmd(testMbm) + cmd.SetArgs([]string{"appnode-test"}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -179,8 +179,7 @@ func TestEmptyState(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - cmd = server.ExportCmd(nil, home) - cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd = server.ExportCmd(nil) require.NoError(t, cmd.ExecuteContext(ctx)) outC := make(chan string) @@ -265,7 +264,7 @@ func TestInitConfig(t *testing.T) { ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"testnode"}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -274,7 +273,7 @@ func TestInitConfig(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - cmd = server.ExportCmd(nil, home) + cmd = server.ExportCmd(nil) require.NoError(t, cmd.ExecuteContext(ctx)) outC := make(chan string) @@ -313,7 +312,7 @@ func TestInitWithHeight(t *testing.T) { testInitialHeight := int64(333) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"init-height-test", fmt.Sprintf("--%s=%d", flags.FlagInitHeight, testInitialHeight)}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -345,7 +344,7 @@ func TestInitWithNegativeHeight(t *testing.T) { testInitialHeight := int64(-333) - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"init-height-test", fmt.Sprintf("--%s=%d", flags.FlagInitHeight, testInitialHeight)}) require.NoError(t, cmd.ExecuteContext(ctx)) diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index 7060f6ab243..3d5e37f99db 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/testutil" @@ -25,8 +24,9 @@ func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) erro return err } - cmd := genutilcli.InitCmd(testMbm, home) + cmd := genutilcli.InitCmd(testMbm) serverCtx := server.NewContext(viper.New(), cfg, logger) + serverCtx.Config.SetRoot(home) clientCtx := client.Context{}.WithCodec(cdc).WithHomeDir(home) _, out := testutil.ApplyMockIO(cmd) @@ -36,7 +36,7 @@ func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) erro ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) + cmd.SetArgs([]string{"appnode-test"}) return cmd.ExecuteContext(ctx) }