From e6e1a853de4b90ba01508fdf84718545addc3fcc Mon Sep 17 00:00:00 2001 From: Marko Date: Tue, 28 May 2024 15:07:36 +0200 Subject: [PATCH] refactor(core,server): make commands not rely on server context (#20422) Co-authored-by: Hieu Vu <72878483+hieuvubk@users.noreply.github.com> Co-authored-by: Julien Robert --- CHANGELOG.md | 1 + client/cmd.go | 41 +++++++++++++ client/snapshot/delete.go | 5 +- client/snapshot/dump.go | 5 +- client/snapshot/export.go | 10 ++-- client/snapshot/list.go | 5 +- client/snapshot/load.go | 5 +- client/snapshot/restore.go | 10 ++-- core/context/server_context.go | 6 ++ core/go.mod | 2 +- core/go.sum | 4 +- server/util.go | 8 ++- simapp/simd/cmd/testnet.go | 6 +- simapp/simd/cmd/testnet_test.go | 11 ++-- simapp/test_helpers.go | 7 ++- tests/e2e/genutil/export_test.go | 21 ++++--- testutil/network/interface.go | 8 ++- testutil/network/network.go | 23 +++++--- testutil/network/util.go | 16 +++-- testutil/network/validator.go | 15 +++-- x/genutil/client/cli/collect.go | 4 +- x/genutil/client/cli/export.go | 17 +++--- x/genutil/client/cli/export_test.go | 27 +++++---- x/genutil/client/cli/genaccount.go | 4 +- x/genutil/client/cli/genaccount_test.go | 11 ++-- x/genutil/client/cli/gentx.go | 5 +- x/genutil/client/cli/init.go | 5 +- x/genutil/client/cli/init_test.go | 75 ++++++++++++++++-------- x/genutil/client/cli/validate_genesis.go | 6 +- x/genutil/client/testutil/helpers.go | 34 ++++++++--- x/genutil/collect_test.go | 3 - 31 files changed, 268 insertions(+), 132 deletions(-) create mode 100644 core/context/server_context.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9be19bde7b1a..dcbae6d38f79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,6 +119,7 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### API Breaking Changes +* (server) [#20422](https://github.com/cosmos/cosmos-sdk/pull/20422) Deprecated `ServerContext`. To get `cmtcfg.Config` from cmd, use `client.GetCometConfigFromCmd(cmd)` instead of `server.GetServerContextFromCmd(cmd).Config` * (types)[#20369](https://github.com/cosmos/cosmos-sdk/pull/20369) The signature of `HasAminoCodec` has changed to accept a `core/legacy.Amino` interface instead of `codec.LegacyAmino`. * (x/simulation)[#20056](https://github.com/cosmos/cosmos-sdk/pull/20056) `SimulateFromSeed` now takes an address codec as argument. * (x/crisis) [#20043](https://github.com/cosmos/cosmos-sdk/pull/20043) Changed `NewMsgVerifyInvariant` to accept a string as argument instead of an `AccAddress`. diff --git a/client/cmd.go b/client/cmd.go index 3fc29ad62be7..1ea5d9d6bfc3 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -8,13 +8,17 @@ import ( "slices" "strings" + cmtcfg "github.com/cometbft/cometbft/config" "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" + corectx "cosmossdk.io/core/context" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -373,3 +377,40 @@ func SetCmdClientContext(cmd *cobra.Command, clientCtx Context) error { return nil } + +func GetViperFromCmd(cmd *cobra.Command) *viper.Viper { + value := cmd.Context().Value(corectx.ViperContextKey{}) + v, ok := value.(*viper.Viper) + if !ok { + return viper.New() + } + return v +} + +func GetConfigFromCmd(cmd *cobra.Command) *cmtcfg.Config { + v := cmd.Context().Value(corectx.ViperContextKey{}) + viper, ok := v.(*viper.Viper) + if !ok { + return cmtcfg.DefaultConfig() + } + return GetConfigFromViper(viper) +} + +func GetLoggerFromCmd(cmd *cobra.Command) log.Logger { + v := cmd.Context().Value(corectx.LoggerContextKey{}) + logger, ok := v.(log.Logger) + if !ok { + return log.NewLogger(cmd.OutOrStdout()) + } + return logger +} + +func GetConfigFromViper(v *viper.Viper) *cmtcfg.Config { + conf := cmtcfg.DefaultConfig() + err := v.Unmarshal(conf) + rootDir := v.GetString(flags.FlagHome) + if err != nil { + return cmtcfg.DefaultConfig().SetRoot(rootDir) + } + return conf.SetRoot(rootDir) +} diff --git a/client/snapshot/delete.go b/client/snapshot/delete.go index 3bf322982925..c4314cd96b45 100644 --- a/client/snapshot/delete.go +++ b/client/snapshot/delete.go @@ -5,6 +5,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" ) @@ -14,7 +15,7 @@ func DeleteSnapshotCmd() *cobra.Command { Short: "Delete a local snapshot", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) + viper := client.GetViperFromCmd(cmd) height, err := strconv.ParseUint(args[0], 10, 64) if err != nil { @@ -25,7 +26,7 @@ func DeleteSnapshotCmd() *cobra.Command { return err } - snapshotStore, err := server.GetSnapshotStore(ctx.Viper) + snapshotStore, err := server.GetSnapshotStore(viper) if err != nil { return err } diff --git a/client/snapshot/dump.go b/client/snapshot/dump.go index 098f5ee6b3f5..1b3ac45f00cd 100644 --- a/client/snapshot/dump.go +++ b/client/snapshot/dump.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" ) @@ -21,8 +22,8 @@ func DumpArchiveCmd() *cobra.Command { Short: "Dump the snapshot as portable archive format", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) - snapshotStore, err := server.GetSnapshotStore(ctx.Viper) + viper := client.GetViperFromCmd(cmd) + snapshotStore, err := server.GetSnapshotStore(viper) if err != nil { return err } diff --git a/client/snapshot/export.go b/client/snapshot/export.go index 61f1951bbafe..30f573676d33 100644 --- a/client/snapshot/export.go +++ b/client/snapshot/export.go @@ -5,6 +5,7 @@ import ( "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" ) @@ -16,20 +17,21 @@ func ExportSnapshotCmd[T servertypes.Application](appCreator servertypes.AppCrea Short: "Export app state to snapshot store", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) + cfg := client.GetConfigFromCmd(cmd) + viper := client.GetViperFromCmd(cmd) height, err := cmd.Flags().GetInt64("height") if err != nil { return err } - home := ctx.Config.RootDir - db, err := openDB(home, server.GetAppDBBackend(ctx.Viper)) + home := cfg.RootDir + db, err := openDB(home, server.GetAppDBBackend(viper)) if err != nil { return err } logger := log.NewLogger(cmd.OutOrStdout()) - app := appCreator(logger, db, nil, ctx.Viper) + app := appCreator(logger, db, nil, viper) if height == 0 { height = app.CommitMultiStore().LastCommitID().Version diff --git a/client/snapshot/list.go b/client/snapshot/list.go index 501bfd7c5291..43ff31cfd4ac 100644 --- a/client/snapshot/list.go +++ b/client/snapshot/list.go @@ -5,6 +5,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" ) @@ -13,8 +14,8 @@ var ListSnapshotsCmd = &cobra.Command{ Use: "list", Short: "List local snapshots", RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) - snapshotStore, err := server.GetSnapshotStore(ctx.Viper) + viper := client.GetViperFromCmd(cmd) + snapshotStore, err := server.GetSnapshotStore(viper) if err != nil { return err } diff --git a/client/snapshot/load.go b/client/snapshot/load.go index 0f638b0e6a84..b64f2eac860d 100644 --- a/client/snapshot/load.go +++ b/client/snapshot/load.go @@ -15,6 +15,7 @@ import ( snapshottypes "cosmossdk.io/store/snapshots/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" ) @@ -27,8 +28,8 @@ func LoadArchiveCmd() *cobra.Command { Short: "Load a snapshot archive file (.tar.gz) into snapshot store", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) - snapshotStore, err := server.GetSnapshotStore(ctx.Viper) + viper := client.GetViperFromCmd(cmd) + snapshotStore, err := server.GetSnapshotStore(viper) if err != nil { return err } diff --git a/client/snapshot/restore.go b/client/snapshot/restore.go index c1f5b21f214c..b0f86b9de678 100644 --- a/client/snapshot/restore.go +++ b/client/snapshot/restore.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" ) @@ -21,7 +22,8 @@ func RestoreSnapshotCmd[T servertypes.Application](appCreator servertypes.AppCre Long: "Restore app state from local snapshot", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - ctx := server.GetServerContextFromCmd(cmd) + cfg := client.GetConfigFromCmd(cmd) + viper := client.GetViperFromCmd(cmd) height, err := strconv.ParseUint(args[0], 10, 64) if err != nil { @@ -32,13 +34,13 @@ func RestoreSnapshotCmd[T servertypes.Application](appCreator servertypes.AppCre return err } - home := ctx.Config.RootDir - db, err := openDB(home, server.GetAppDBBackend(ctx.Viper)) + home := cfg.RootDir + db, err := openDB(home, server.GetAppDBBackend(viper)) if err != nil { return err } logger := log.NewLogger(cmd.OutOrStdout()) - app := appCreator(logger, db, nil, ctx.Viper) + app := appCreator(logger, db, nil, viper) sm := app.SnapshotManager() return sm.RestoreLocalSnapshot(height, uint32(format)) diff --git a/core/context/server_context.go b/core/context/server_context.go new file mode 100644 index 000000000000..98c0821550fa --- /dev/null +++ b/core/context/server_context.go @@ -0,0 +1,6 @@ +package context + +type ( + LoggerContextKey struct{} + ViperContextKey struct{} +) diff --git a/core/go.mod b/core/go.mod index c8797113dc8c..4487c6ddb3e2 100644 --- a/core/go.mod +++ b/core/go.mod @@ -10,7 +10,7 @@ require ( ) require ( - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect diff --git a/core/go.sum b/core/go.sum index e509621710ad..fcac9f809801 100644 --- a/core/go.sum +++ b/core/go.sum @@ -1,8 +1,8 @@ github.com/cosmos/gogoproto v1.4.12 h1:vB6Lbe/rtnYGjQuFxkPiPYiCybqFT8QvLipDZP8JpFE= github.com/cosmos/gogoproto v1.4.12/go.mod h1:LnZob1bXRdUoqMMtwYlcR3wjiElmlC+FkjaZRv1/eLY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= diff --git a/server/util.go b/server/util.go index e247a0c9b372..d185c98e389b 100644 --- a/server/util.go +++ b/server/util.go @@ -24,6 +24,7 @@ import ( "github.com/spf13/viper" "golang.org/x/sync/errgroup" + corectx "cosmossdk.io/core/context" corelog "cosmossdk.io/core/log" "cosmossdk.io/log" "cosmossdk.io/store" @@ -46,6 +47,7 @@ import ( const ServerContextKey = sdk.ContextKey("server.context") // Context server context +// Deprecated: Do not use since we use viper to track all config type Context struct { Viper *viper.Viper Config *cmtcfg.Config @@ -224,7 +226,11 @@ func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error { cmdCtx = cmd.Context() } - cmd.SetContext(context.WithValue(cmdCtx, ServerContextKey, serverCtx)) + cmdCtx = context.WithValue(cmdCtx, ServerContextKey, serverCtx) + cmdCtx = context.WithValue(cmdCtx, corectx.ViperContextKey{}, serverCtx.Viper) + cmdCtx = context.WithValue(cmdCtx, corectx.LoggerContextKey{}, serverCtx.Logger) + + cmd.SetContext(cmdCtx) return nil } diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 9ae538f00f36..56fffd41479c 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -140,8 +140,7 @@ Example: return err } - serverCtx := server.GetServerContextFromCmd(cmd) - config := serverCtx.Config + config := client.GetConfigFromCmd(cmd) args := initArgs{} args.outputDir, _ = cmd.Flags().GetString(flagOutputDir) @@ -407,6 +406,9 @@ func initTestnetFiles( return err } + // Update viper root since root dir become rootdir/node/simd + client.GetViperFromCmd(cmd).Set(flags.FlagHome, nodeConfig.RootDir) + cmd.PrintErrf("Successfully initialized %d node directories\n", args.numValidators) return nil } diff --git a/simapp/simd/cmd/testnet_test.go b/simapp/simd/cmd/testnet_test.go index 58e93e130d52..fee803721e52 100644 --- a/simapp/simd/cmd/testnet_test.go +++ b/simapp/simd/cmd/testnet_test.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" + corectx "cosmossdk.io/core/context" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/x/auth" @@ -17,7 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/testutil/configurator" "github.com/cosmos/cosmos-sdk/types/module" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -51,13 +51,15 @@ func Test_TestnetCmd(t *testing.T) { cdcOpts := codectestutil.CodecOptions{} encodingConfig := moduletestutil.MakeTestEncodingConfig(cdcOpts, auth.AppModule{}, staking.AppModule{}) logger := log.NewNopLogger() + viper := viper.New() cfg, err := genutiltest.CreateDefaultCometConfig(home) require.NoError(t, err) err = genutiltest.ExecInitCmd(moduleManager, home, encodingConfig.Codec) require.NoError(t, err) - serverCtx := server.NewContext(viper.New(), cfg, logger) + err = genutiltest.WriteAndTrackCometConfig(viper, home, cfg) + require.NoError(t, err) clientCtx := client.Context{}. WithCodec(encodingConfig.Codec). WithHomeDir(home). @@ -66,14 +68,15 @@ func Test_TestnetCmd(t *testing.T) { WithValidatorAddressCodec(cdcOpts.GetValidatorCodec()) ctx := context.Background() - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) cmd := testnetInitFilesCmd(moduleManager, banktypes.GenesisBalancesIterator{}) cmd.SetArgs([]string{fmt.Sprintf("--%s=test", flags.FlagKeyringBackend), fmt.Sprintf("--output-dir=%s", home)}) err = cmd.ExecuteContext(ctx) require.NoError(t, err) - genFile := cfg.GenesisFile() + genFile := client.GetConfigFromCmd(cmd).GenesisFile() appState, _, err := genutiltypes.GenesisStateFromGenFile(genFile) require.NoError(t, err) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 7bff60d44860..4e8b75339a95 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -20,6 +20,7 @@ import ( minttypes "cosmossdk.io/x/mint/types" bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/server" @@ -228,11 +229,11 @@ func NewTestNetworkFixture() network.TestFixture { appCtr := func(val network.ValidatorI) servertypes.Application { return NewSimApp( - val.GetCtx().Logger, dbm.NewMemDB(), nil, true, - simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir), + val.GetLogger(), dbm.NewMemDB(), nil, true, + simtestutil.NewAppOptionsWithFlagHome(client.GetConfigFromViper(val.GetViper()).RootDir), bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), - bam.SetChainID(val.GetCtx().Viper.GetString(flags.FlagChainID)), + bam.SetChainID(val.GetViper().GetString(flags.FlagChainID)), ) } diff --git a/tests/e2e/genutil/export_test.go b/tests/e2e/genutil/export_test.go index d60c40ff1f74..febda09efcff 100644 --- a/tests/e2e/genutil/export_test.go +++ b/tests/e2e/genutil/export_test.go @@ -14,20 +14,24 @@ import ( "testing" abci "github.com/cometbft/cometbft/abci/types" + cmtcfg "github.com/cometbft/cometbft/config" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" + corectx "cosmossdk.io/core/context" "cosmossdk.io/log" "cosmossdk.io/simapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/x/genutil" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + gentestutil "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -55,8 +59,10 @@ func TestExportCmd_ConsensusParams(t *testing.T) { func TestExportCmd_HomeDir(t *testing.T) { _, ctx, _, cmd := setupApp(t, t.TempDir()) - serverCtxPtr := ctx.Value(server.ServerContextKey) - serverCtxPtr.(*server.Context).Config.SetRoot("foobar") + v := ctx.Value(corectx.ViperContextKey{}) + viper, ok := v.(*viper.Viper) + require.True(t, ok) + viper.Set(flags.FlagHome, "foobar") err := cmd.ExecuteContext(ctx) assert.ErrorContains(t, err, "stat foobar/config/genesis.json: no such file or directory") @@ -168,8 +174,9 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge stateBytes, err := json.MarshalIndent(genesisState, "", " ") assert.NilError(t, err) - serverCtx := server.NewDefaultContext() - serverCtx.Config.RootDir = tempDir + viper := viper.New() + err = gentestutil.WriteAndTrackCometConfig(viper, tempDir, cmtcfg.DefaultConfig()) + assert.NilError(t, err) clientCtx := client.Context{}.WithCodec(app.AppCodec()) appGenesis := genutiltypes.AppGenesis{ @@ -181,7 +188,7 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge } // save genesis file - err = genutil.ExportGenesisFile(&appGenesis, serverCtx.Config.GenesisFile()) + err = genutil.ExportGenesisFile(&appGenesis, client.GetConfigFromViper(viper).GenesisFile()) assert.NilError(t, err) _, err = app.InitChain(&abci.InitChainRequest{ @@ -213,7 +220,7 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) return app, ctx, appGenesis, cmd } diff --git a/testutil/network/interface.go b/testutil/network/interface.go index 5503e1571f5f..37356ea525c8 100644 --- a/testutil/network/interface.go +++ b/testutil/network/interface.go @@ -3,9 +3,12 @@ package network import ( "time" + "github.com/spf13/viper" + + "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/server" srvconfig "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -32,7 +35,8 @@ type NetworkI interface { // ValidatorI expose a validator's context and configuration type ValidatorI interface { - GetCtx() *server.Context + GetViper() *viper.Viper + GetLogger() log.Logger GetAppConfig() *srvconfig.Config GetAddress() sdk.AccAddress GetValAddress() sdk.ValAddress diff --git a/testutil/network/network.go b/testutil/network/network.go index 17c9c19fc38b..3717f7e65b9d 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -17,8 +17,10 @@ import ( "testing" "time" + cmtcfg "github.com/cometbft/cometbft/config" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" + "github.com/spf13/viper" "cosmossdk.io/core/address" "cosmossdk.io/core/legacy" @@ -49,7 +51,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/server" srvconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/testutil" @@ -228,7 +229,7 @@ func DefaultConfigWithAppConfig(appConfig depinject.Config) (Config, error) { if err := depinject.Inject( depinject.Configs( appConfig, - depinject.Supply(val.GetCtx().Logger), + depinject.Supply(val.GetLogger()), ), &appBuilder); err != nil { panic(err) @@ -327,6 +328,7 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { monikers := make([]string, cfg.NumValidators) nodeIDs := make([]string, cfg.NumValidators) valPubKeys := make([]cryptotypes.PubKey, cfg.NumValidators) + cmtConfigs := make([]*cmtcfg.Config, cfg.NumValidators) var ( genAccounts []authtypes.GenesisAccount @@ -345,8 +347,10 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { appCfg.API.Swagger = false appCfg.Telemetry.Enabled = false - ctx := server.NewDefaultContext() - cmtCfg := ctx.Config + viper := viper.New() + // Create default cometbft config for each validator + cmtCfg := client.GetConfigFromViper(viper) + cmtCfg.Consensus.TimeoutCommit = cfg.TimeoutCommit // Only allow the first validator to expose an RPC, API and gRPC @@ -400,8 +404,6 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { logger = log.NewLogger(os.Stdout) // TODO(mr): enable selection of log destination. } - ctx.Logger = logger - nodeDirName := fmt.Sprintf("node%d", i) nodeDir := filepath.Join(network.BaseDir, nodeDirName, "simd") clientDir := filepath.Join(network.BaseDir, nodeDirName, "simcli") @@ -437,6 +439,8 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { cmtCfg.P2P.AddrBookStrict = false cmtCfg.P2P.AllowDuplicateIP = true + cmtConfigs[i] = cmtCfg + var mnemonic string if i < len(cfg.Mnemonics) { mnemonic = cfg.Mnemonics[i] @@ -567,12 +571,13 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { WithNodeURI(cmtCfg.RPC.ListenAddress) // Provide ChainID here since we can't modify it in the Comet config. - ctx.Viper.Set(flags.FlagChainID, cfg.ChainID) + viper.Set(flags.FlagChainID, cfg.ChainID) network.Validators[i] = &Validator{ AppConfig: appCfg, clientCtx: clientCtx, - ctx: ctx, + viper: viper, + logger: logger, dir: filepath.Join(network.BaseDir, nodeDirName), nodeID: nodeID, pubKey: pubKey, @@ -589,7 +594,7 @@ func New(l Logger, baseDir string, cfg Config) (NetworkI, error) { if err != nil { return nil, err } - err = collectGenFiles(cfg, network.Validators, network.BaseDir) + err = collectGenFiles(cfg, network.Validators, cmtConfigs, network.BaseDir) if err != nil { return nil, err } diff --git a/testutil/network/util.go b/testutil/network/util.go index e7746ec44086..a3662bf6ea67 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -21,18 +21,20 @@ import ( authtypes "cosmossdk.io/x/auth/types" banktypes "cosmossdk.io/x/bank/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" servercmtlog "github.com/cosmos/cosmos-sdk/server/log" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) func startInProcess(cfg Config, val *Validator) error { - logger := val.ctx.Logger - cmtCfg := val.ctx.Config + logger := val.GetLogger() + cmtCfg := client.GetConfigFromViper(val.GetViper()) cmtCfg.Instrumentation.Prometheus = false if err := val.AppConfig.ValidateBasic(); err != nil { @@ -133,14 +135,14 @@ func startInProcess(cfg Config, val *Validator) error { return nil } -func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { +func collectGenFiles(cfg Config, vals []*Validator, cmtConfigs []*cmtcfg.Config, outputDir string) error { genTime := cfg.GenesisTime if genTime.IsZero() { genTime = cmttime.Now() } for i := 0; i < cfg.NumValidators; i++ { - cmtCfg := vals[i].ctx.Config + cmtCfg := cmtConfigs[i] nodeDir := filepath.Join(outputDir, vals[i].moniker, "simd") gentxsDir := filepath.Join(outputDir, "gentxs") @@ -167,6 +169,12 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { if err := genutil.ExportGenesisFileWithTime(genFile, cfg.ChainID, nil, appState, genTime); err != nil { return err } + + v := vals[i].GetViper() + err = genutiltest.TrackCometConfig(v, nodeDir) + if err != nil { + return err + } } return nil diff --git a/testutil/network/validator.go b/testutil/network/validator.go index 261ecde385cd..d3ba6b40fad5 100644 --- a/testutil/network/validator.go +++ b/testutil/network/validator.go @@ -6,12 +6,14 @@ import ( "github.com/cometbft/cometbft/node" cmtclient "github.com/cometbft/cometbft/rpc/client" + "github.com/spf13/viper" "golang.org/x/sync/errgroup" "google.golang.org/grpc" + "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" srvconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" @@ -24,7 +26,8 @@ import ( type Validator struct { AppConfig *srvconfig.Config clientCtx client.Context - ctx *server.Context + viper *viper.Viper + logger log.Logger dir string nodeID string pubKey cryptotypes.PubKey @@ -47,8 +50,12 @@ type Validator struct { var _ ValidatorI = &Validator{} -func (v *Validator) GetCtx() *server.Context { - return v.ctx +func (v *Validator) GetViper() *viper.Viper { + return v.viper +} + +func (v *Validator) GetLogger() log.Logger { + return v.logger } func (v *Validator) GetClientCtx() client.Context { diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index 3983a859b18e..3b0354c1073b 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/server" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -22,8 +21,7 @@ func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, validator ty Use: "collect-gentxs", Short: "Collect genesis txs and output a genesis.json file", RunE: func(cmd *cobra.Command, _ []string) error { - serverCtx := server.GetServerContextFromCmd(cmd) - config := serverCtx.Config + config := client.GetConfigFromCmd(cmd) clientCtx := client.GetClientContextFromCmd(cmd) cdc := clientCtx.Codec diff --git a/x/genutil/client/cli/export.go b/x/genutil/client/cli/export.go index b59a17969b13..986b9c1cdb2d 100644 --- a/x/genutil/client/cli/export.go +++ b/x/genutil/client/cli/export.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" @@ -31,13 +32,15 @@ func ExportCmd(appExporter servertypes.AppExporter) *cobra.Command { Short: "Export state to JSON", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - serverCtx := server.GetServerContextFromCmd(cmd) + config := client.GetConfigFromCmd(cmd) + viper := client.GetViperFromCmd(cmd) + logger := client.GetLoggerFromCmd(cmd) - if _, err := os.Stat(serverCtx.Config.GenesisFile()); os.IsNotExist(err) { + if _, err := os.Stat(config.GenesisFile()); os.IsNotExist(err) { return err } - db, err := server.OpenDB(serverCtx.Config.RootDir, server.GetAppDBBackend(serverCtx.Viper)) + db, err := server.OpenDB(config.RootDir, server.GetAppDBBackend(viper)) if err != nil { return err } @@ -51,7 +54,7 @@ func ExportCmd(appExporter servertypes.AppExporter) *cobra.Command { // It is possible that the genesis file is large, // so we don't need to read it all into memory // before we stream it out. - f, err := os.OpenFile(serverCtx.Config.GenesisFile(), os.O_RDONLY, 0) + f, err := os.OpenFile(config.GenesisFile(), os.O_RDONLY, 0) if err != nil { return err } @@ -65,7 +68,7 @@ func ExportCmd(appExporter servertypes.AppExporter) *cobra.Command { } traceWriterFile, _ := cmd.Flags().GetString(flagTraceStore) - traceWriter, cleanup, err := server.SetupTraceWriter(serverCtx.Logger, traceWriterFile) //resleak:notresource + traceWriter, cleanup, err := server.SetupTraceWriter(logger, traceWriterFile) //resleak:notresource if err != nil { return err } @@ -77,12 +80,12 @@ func ExportCmd(appExporter servertypes.AppExporter) *cobra.Command { modulesToExport, _ := cmd.Flags().GetStringSlice(flagModulesToExport) outputDocument, _ := cmd.Flags().GetString(flags.FlagOutputDocument) - exported, err := appExporter(serverCtx.Logger, db, traceWriter, height, forZeroHeight, jailAllowedAddrs, serverCtx.Viper, modulesToExport) + exported, err := appExporter(logger, db, traceWriter, height, forZeroHeight, jailAllowedAddrs, viper, modulesToExport) if err != nil { return fmt.Errorf("error exporting state: %w", err) } - appGenesis, err := genutiltypes.AppGenesisFromFile(serverCtx.Config.GenesisFile()) + appGenesis, err := genutiltypes.AppGenesisFromFile(config.GenesisFile()) if err != nil { return err } diff --git a/x/genutil/client/cli/export_test.go b/x/genutil/client/cli/export_test.go index 8f58fc5e2eef..3c3c870c7fee 100644 --- a/x/genutil/client/cli/export_test.go +++ b/x/genutil/client/cli/export_test.go @@ -11,17 +11,16 @@ import ( "time" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" - cmtcfg "github.com/cometbft/cometbft/config" cmttypes "github.com/cometbft/cometbft/types" dbm "github.com/cosmos/cosmos-db" "github.com/rs/zerolog" "github.com/spf13/viper" "github.com/stretchr/testify/require" + corectx "cosmossdk.io/core/context" "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/testutil/cmdtest" "github.com/cosmos/cosmos-sdk/types/module" @@ -37,8 +36,8 @@ type ExportSystem struct { Ctx context.Context - Sctx *server.Context - Cctx client.Context + Viper *viper.Viper + Logger log.Logger HomeDir string } @@ -65,23 +64,25 @@ func NewExportSystem(t *testing.T, exporter types.AppExporter) *ExportSystem { tw := zerolog.NewTestWriter(t) tw.Frame = 5 // Seems to be the magic number to get source location to match logger calls. - sCtx := server.NewContext( - viper.New(), - cmtcfg.DefaultConfig(), - log.NewCustomLogger(zerolog.New(tw)), - ) - sCtx.Config.SetRoot(homeDir) + viper := viper.New() + logger := log.NewCustomLogger(zerolog.New(tw)) + err := writeAndTrackDefaultConfig(viper, homeDir) + if err != nil { + t.Fatal(err) + } cCtx := (client.Context{}).WithHomeDir(homeDir) - ctx := context.WithValue(context.Background(), server.ServerContextKey, sCtx) + ctx := context.WithValue(context.Background(), corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) + ctx = context.WithValue(ctx, client.ClientContextKey, &cCtx) return &ExportSystem{ sys: sys, Ctx: ctx, - Sctx: sCtx, - Cctx: cCtx, + Viper: viper, + Logger: logger, HomeDir: homeDir, } } diff --git a/x/genutil/client/cli/genaccount.go b/x/genutil/client/cli/genaccount.go index 1cbb42b42379..8debe3f97a6d 100644 --- a/x/genutil/client/cli/genaccount.go +++ b/x/genutil/client/cli/genaccount.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -38,8 +37,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - serverCtx := server.GetServerContextFromCmd(cmd) - config := serverCtx.Config + config := client.GetConfigFromCmd(cmd) var kr keyring.Keyring addr, err := addressCodec.StringToBytes(args[0]) diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index 51cb42a3ac0e..6351a76ea3b2 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" + corectx "cosmossdk.io/core/context" "cosmossdk.io/log" "cosmossdk.io/x/auth" @@ -15,7 +16,6 @@ import ( codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -71,14 +71,14 @@ func TestAddGenesisAccountCmd(t *testing.T) { t.Run(tc.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() appCodec := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}).Codec err = genutiltest.ExecInitCmd(testMbm, home, appCodec) require.NoError(t, err) - serverCtx := server.NewContext(viper.New(), cfg, logger) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) clientCtx := client.Context{}.WithCodec(appCodec).WithHomeDir(home).WithAddressCodec(ac) if tc.withKeyring { @@ -92,7 +92,8 @@ func TestAddGenesisAccountCmd(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.AddGenesisAccountCmd(addresscodec.NewBech32Codec("cosmos")) cmd.SetArgs([]string{ diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 533c1ae0dfde..9c6d0c5034c7 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -55,15 +55,14 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o `, defaultsDesc, version.AppName, ), RunE: func(cmd *cobra.Command, args []string) error { - serverCtx := server.GetServerContextFromCmd(cmd) + config := client.GetConfigFromCmd(cmd) clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } cdc := clientCtx.Codec - config := serverCtx.Config - nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(serverCtx.Config) + nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") } diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 2765eafc9acb..920dfcec260f 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" - "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" @@ -81,9 +80,7 @@ func InitCmd(mm *module.Manager) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - serverCtx := server.GetServerContextFromCmd(cmd) - config := serverCtx.Config - + config := client.GetConfigFromCmd(cmd) chainID, _ := cmd.Flags().GetString(flags.FlagChainID) switch { case chainID != "": diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index a958a47544e9..b57bba44cd50 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -13,6 +13,7 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" + corectx "cosmossdk.io/core/context" "cosmossdk.io/log" "cosmossdk.io/x/staking" @@ -63,10 +64,10 @@ func TestInitCmd(t *testing.T) { t.Run(tt.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() - serverCtx := server.NewContext(viper.New(), cfg, logger) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -76,7 +77,8 @@ func TestInitCmd(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs( @@ -96,10 +98,10 @@ func TestInitCmd(t *testing.T) { func TestInitRecover(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() - serverCtx := server.NewContext(viper.New(), cfg, logger) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -109,9 +111,11 @@ func TestInitRecover(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.InitCmd(testMbm) + cmd.SetContext(ctx) mockIn := testutil.ApplyMockIODiscardOutErr(cmd) cmd.SetArgs([]string{ @@ -127,10 +131,10 @@ func TestInitRecover(t *testing.T) { func TestInitDefaultBondDenom(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() - serverCtx := server.NewContext(viper.New(), cfg, logger) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -140,7 +144,8 @@ func TestInitDefaultBondDenom(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.InitCmd(testMbm) @@ -154,11 +159,10 @@ func TestInitDefaultBondDenom(t *testing.T) { func TestEmptyState(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() - serverCtx := server.NewContext(viper.New(), cfg, logger) - serverCtx.Config.SetRoot(home) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -168,7 +172,8 @@ func TestEmptyState(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"appnode-test"}) @@ -248,10 +253,10 @@ func TestInitNodeValidatorFiles(t *testing.T) { func TestInitConfig(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() - cfg, err := genutiltest.CreateDefaultCometConfig(home) - require.NoError(t, err) + viper := viper.New() - serverCtx := server.NewContext(viper.New(), cfg, logger) + err := writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -262,12 +267,14 @@ func TestInitConfig(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd := genutilcli.InitCmd(testMbm) cmd.SetArgs([]string{"testnode"}) - require.NoError(t, cmd.ExecuteContext(ctx)) + err = cmd.ExecuteContext(ctx) + require.NoError(t, err) old := os.Stdout r, w, _ := os.Pipe() @@ -294,10 +301,12 @@ func TestInitConfig(t *testing.T) { func TestInitWithHeight(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() + viper := viper.New() cfg, err := genutiltest.CreateDefaultCometConfig(home) require.NoError(t, err) - serverCtx := server.NewContext(viper.New(), cfg, logger) + err = writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -308,11 +317,14 @@ func TestInitWithHeight(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) testInitialHeight := int64(333) cmd := genutilcli.InitCmd(testMbm) + + fmt.Println("RootDir", viper.Get(flags.FlagHome)) cmd.SetArgs([]string{"init-height-test", fmt.Sprintf("--%s=%d", flags.FlagInitHeight, testInitialHeight)}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -326,10 +338,12 @@ func TestInitWithHeight(t *testing.T) { func TestInitWithNegativeHeight(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() + viper := viper.New() cfg, err := genutiltest.CreateDefaultCometConfig(home) require.NoError(t, err) - serverCtx := server.NewContext(viper.New(), cfg, logger) + err = writeAndTrackDefaultConfig(viper, home) + require.NoError(t, err) interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. @@ -340,7 +354,8 @@ func TestInitWithNegativeHeight(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) testInitialHeight := int64(-333) @@ -367,3 +382,11 @@ func makeCodec() codec.Codec { interfaceRegistry := types.NewInterfaceRegistry() return codec.NewProtoCodec(interfaceRegistry) } + +func writeAndTrackDefaultConfig(v *viper.Viper, home string) error { + cfg, err := genutiltest.CreateDefaultCometConfig(home) + if err != nil { + return err + } + return genutiltest.WriteAndTrackCometConfig(v, home, cfg) +} diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 232097cda5c0..735fc51ccd89 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -21,12 +21,12 @@ func ValidateGenesisCmd(mm *module.Manager) *cobra.Command { Args: cobra.RangeArgs(0, 1), Short: "Validates the genesis file at the default location or at the location passed as an arg", RunE: func(cmd *cobra.Command, args []string) (err error) { - serverCtx := server.GetServerContextFromCmd(cmd) + cfg := client.GetConfigFromCmd(cmd) // Load default if passed no args, otherwise load passed file var genesis string if len(args) == 0 { - genesis = serverCtx.Config.GenesisFile() + genesis = cfg.GenesisFile() } else { genesis = args[0] } diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index ecfbb3e008b0..54df530e86ce 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -3,15 +3,17 @@ package testutil import ( "context" "fmt" + "path/filepath" cmtcfg "github.com/cometbft/cometbft/config" "github.com/spf13/viper" + corectx "cosmossdk.io/core/context" "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" "github.com/cosmos/cosmos-sdk/types/module" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" @@ -19,14 +21,13 @@ import ( func ExecInitCmd(mm *module.Manager, home string, cdc codec.Codec) error { logger := log.NewNopLogger() - cfg, err := CreateDefaultCometConfig(home) + viper := viper.New() + cmd := genutilcli.InitCmd(mm) + cfg, _ := CreateDefaultCometConfig(home) + err := WriteAndTrackCometConfig(viper, home, cfg) if err != nil { return err } - - cmd := genutilcli.InitCmd(mm) - serverCtx := server.NewContext(viper.New(), cfg, logger) - serverCtx.Config.SetRoot(home) clientCtx := client.Context{}.WithCodec(cdc).WithHomeDir(home) _, out := testutil.ApplyMockIO(cmd) @@ -34,7 +35,8 @@ func ExecInitCmd(mm *module.Manager, home string, cdc codec.Codec) error { ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + ctx = context.WithValue(ctx, corectx.ViperContextKey{}, viper) + ctx = context.WithValue(ctx, corectx.LoggerContextKey{}, logger) cmd.SetArgs([]string{"appnode-test"}) @@ -52,3 +54,21 @@ func CreateDefaultCometConfig(rootDir string) (*cmtcfg.Config, error) { return conf, nil } + +func WriteAndTrackCometConfig(v *viper.Viper, home string, cfg *cmtcfg.Config) error { + cmtcfg.WriteConfigFile(filepath.Join(home, "config", "config.toml"), cfg) + + v.Set(flags.FlagHome, home) + v.SetConfigType("toml") + v.SetConfigName("config") + v.AddConfigPath(filepath.Join(home, "config")) + return v.ReadInConfig() +} + +func TrackCometConfig(v *viper.Viper, home string) error { + v.Set(flags.FlagHome, home) + v.SetConfigType("toml") + v.SetConfigName("config") + v.AddConfigPath(filepath.Join(home, "config")) + return v.ReadInConfig() +} diff --git a/x/genutil/collect_test.go b/x/genutil/collect_test.go index fd8295728ee5..15215076fd4c 100644 --- a/x/genutil/collect_test.go +++ b/x/genutil/collect_test.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" addresscodec "github.com/cosmos/cosmos-sdk/codec/address" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/genutil/types" @@ -54,8 +53,6 @@ func TestCollectTxsHandlesDirectories(t *testing.T) { }) // 2. Ensure that we don't encounter any error traversing the directory. - srvCtx := server.NewDefaultContext() - _ = srvCtx cdc := codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) genesis := &types.AppGenesis{AppState: []byte("{}")} balItr := new(doNothingIterator)