From 4a1fb2776525ee4e5192e389d765fc17724495c9 Mon Sep 17 00:00:00 2001 From: DauTT Date: Sun, 28 Jun 2020 23:40:57 +0200 Subject: [PATCH 01/33] Merge simcli into simd --- Makefile | 1 - go.mod | 1 - simapp/cmd/{simcli/main.go => simd/client.go} | 42 ++----- simapp/cmd/simd/daemon.go | 103 ++++++++++++++++++ simapp/cmd/simd/main.go | 101 ++--------------- 5 files changed, 121 insertions(+), 127 deletions(-) rename simapp/cmd/{simcli/main.go => simd/client.go} (74%) create mode 100644 simapp/cmd/simd/daemon.go diff --git a/Makefile b/Makefile index b52ce1cf4a81..f11a8c76ed4b 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,6 @@ build: go.sum build-sim: go.sum mkdir -p $(BUILDDIR) go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/cmd/simd - go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/cmd/simcli build-sim-linux: go.sum LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-sim diff --git a/go.mod b/go.mod index ee9584a3d148..11e264f4eb9f 100644 --- a/go.mod +++ b/go.mod @@ -39,7 +39,6 @@ require ( github.com/tendermint/iavl v0.14.0-rc1 github.com/tendermint/tendermint v0.33.5 github.com/tendermint/tm-db v0.5.1 - golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e google.golang.org/grpc v1.30.0 gopkg.in/yaml.v2 v2.3.0 ) diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simd/client.go similarity index 74% rename from simapp/cmd/simcli/main.go rename to simapp/cmd/simd/client.go index 1b3eae7194c9..a88e71d7c7c5 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simd/client.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "os" "path" @@ -31,53 +30,28 @@ func init() { authclient.Codec = encodingConfig.Marshaler } -func main() { - // Configure cobra to sort commands - cobra.EnableCommandSorting = false - - // Read in the configuration file for the sdk - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) - config.Seal() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - rootCmd := &cobra.Command{ - Use: "simcli", - Short: "Command line interface for interacting with simd", - } +func addClientCommands(config *sdk.Config, rootClientCmd *cobra.Command) *cobra.Command { // Add --chain-id to persistent flags and mark it required - rootCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") - rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { - return initConfig(rootCmd) + rootClientCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") + rootClientCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { + return initConfig(rootClientCmd) } // Construct Root Command - rootCmd.AddCommand( + rootClientCmd.AddCommand( rpc.StatusCommand(), - client.ConfigCmd(simapp.DefaultCLIHome), + client.ConfigCmd(simapp.DefaultNodeHome), queryCmd(encodingConfig), txCmd(encodingConfig), flags.LineBreak, flags.LineBreak, keys.Commands(), flags.LineBreak, - flags.NewCompletionCmd(rootCmd, true), + flags.NewCompletionCmd(rootClientCmd, true), ) - // Add flags and prefix all env exposed with GA - executor := cli.PrepareMainCmd(rootCmd, "GA", simapp.DefaultCLIHome) - - err := executor.Execute() - if err != nil { - fmt.Printf("Failed executing CLI command: %s, exiting...\n", err) - os.Exit(1) - } + return rootClientCmd } func queryCmd(config simappparams.EncodingConfig) *cobra.Command { diff --git a/simapp/cmd/simd/daemon.go b/simapp/cmd/simd/daemon.go new file mode 100644 index 000000000000..1579f61e9bcc --- /dev/null +++ b/simapp/cmd/simd/daemon.go @@ -0,0 +1,103 @@ +package main + +import ( + "encoding/json" + "io" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tm-db" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +const flagInvCheckPeriod = "inv-check-period" + +var invCheckPeriod uint + +func addDaemonCommands(config *sdk.Config, rootDaemonCmd *cobra.Command) *cobra.Command { + appCodec, cdc := simapp.MakeCodecs() + + ctx := server.NewDefaultContext() + rootDaemonCmd.PersistentPreRunE = server.PersistentPreRunEFn(ctx) + + rootDaemonCmd.AddCommand( + genutilcli.InitCmd(ctx, cdc, simapp.ModuleBasics, simapp.DefaultNodeHome), + genutilcli.CollectGenTxsCmd(ctx, cdc, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), + genutilcli.MigrateGenesisCmd(ctx, cdc), + genutilcli.GenTxCmd( + ctx, cdc, simapp.ModuleBasics, staking.AppModuleBasic{}, + banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome, simapp.DefaultNodeHome, + ), + genutilcli.ValidateGenesisCmd(ctx, cdc, simapp.ModuleBasics), + AddGenesisAccountCmd(ctx, cdc, appCodec, simapp.DefaultNodeHome, simapp.DefaultCLIHome), + flags.NewCompletionCmd(rootDaemonCmd, true), + testnetCmd(ctx, cdc, simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), + debug.Cmd(cdc)) + + server.AddCommands(ctx, cdc, rootDaemonCmd, newApp, exportAppStateAndTMValidators) + + // prepare and add flags + rootDaemonCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, + 0, "Assert registered invariants every N blocks") + + return rootDaemonCmd +} + +func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) server.Application { + var cache sdk.MultiStorePersistentCache + + if viper.GetBool(server.FlagInterBlockCache) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { + skipUpgradeHeights[int64(h)] = true + } + + pruningOpts, err := server.GetPruningOptionsFromFlags() + if err != nil { + panic(err) + } + + // TODO: Make sure custom pruning works. + return simapp.NewSimApp( + logger, db, traceStore, true, skipUpgradeHeights, + viper.GetString(flags.FlagHome), invCheckPeriod, + baseapp.SetPruning(pruningOpts), + baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), + baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), + baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), + baseapp.SetInterBlockCache(cache), + ) +} + +func exportAppStateAndTMValidators( + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, +) (json.RawMessage, []tmtypes.GenesisValidator, *abci.ConsensusParams, error) { + + var simApp *simapp.SimApp + if height != -1 { + simApp = simapp.NewSimApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1)) + err := simApp.LoadHeight(height) + if err != nil { + return nil, nil, nil, err + } + } else { + simApp = simapp.NewSimApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1)) + } + return simApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) +} diff --git a/simapp/cmd/simd/main.go b/simapp/cmd/simd/main.go index 7e999194901b..e8ff0b69aa20 100644 --- a/simapp/cmd/simd/main.go +++ b/simapp/cmd/simd/main.go @@ -1,118 +1,37 @@ package main import ( - "encoding/json" - "io" - "github.com/spf13/cobra" - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking" ) -const flagInvCheckPeriod = "inv-check-period" - -var invCheckPeriod uint - func main() { - appCodec, cdc := simapp.MakeCodecs() + cobra.EnableCommandSorting = false + + // Read in the configuration file for the sdk config := sdk.GetConfig() config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) config.Seal() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "simd", - Short: "Simulation Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), + rootComd := &cobra.Command{ + Use: "simd", + Short: "simulation app binary", } - rootCmd.AddCommand( - genutilcli.InitCmd(ctx, cdc, simapp.ModuleBasics, simapp.DefaultNodeHome), - genutilcli.CollectGenTxsCmd(ctx, cdc, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), - genutilcli.MigrateGenesisCmd(ctx, cdc), - genutilcli.GenTxCmd( - ctx, cdc, simapp.ModuleBasics, staking.AppModuleBasic{}, - banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome, simapp.DefaultCLIHome, - ), - genutilcli.ValidateGenesisCmd(ctx, cdc, simapp.ModuleBasics), - AddGenesisAccountCmd(ctx, cdc, appCodec, simapp.DefaultNodeHome, simapp.DefaultCLIHome), - flags.NewCompletionCmd(rootCmd, true), - testnetCmd(ctx, cdc, simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), - debug.Cmd(cdc)) + // Construct Root Command + rootComd = addClientCommands(config, rootComd) + rootComd = addDaemonCommands(config, rootComd) - server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "GA", simapp.DefaultNodeHome) - rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, - 0, "Assert registered invariants every N blocks") + executor := cli.PrepareMainCmd(rootComd, "GA", simapp.DefaultNodeHome) err := executor.Execute() if err != nil { panic(err) } -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) server.Application { - var cache sdk.MultiStorePersistentCache - - if viper.GetBool(server.FlagInterBlockCache) { - cache = store.NewCommitKVStoreCacheManager() - } - skipUpgradeHeights := make(map[int64]bool) - for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { - skipUpgradeHeights[int64(h)] = true - } - - pruningOpts, err := server.GetPruningOptionsFromFlags() - if err != nil { - panic(err) - } - - // TODO: Make sure custom pruning works. - return simapp.NewSimApp( - logger, db, traceStore, true, skipUpgradeHeights, - viper.GetString(flags.FlagHome), invCheckPeriod, - baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), - baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), - baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), - baseapp.SetInterBlockCache(cache), - ) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, -) (json.RawMessage, []tmtypes.GenesisValidator, *abci.ConsensusParams, error) { - - var simApp *simapp.SimApp - if height != -1 { - simApp = simapp.NewSimApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1)) - err := simApp.LoadHeight(height) - if err != nil { - return nil, nil, nil, err - } - } else { - simApp = simapp.NewSimApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1)) - } - return simApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } From 26aea15eb8f07113a2122f9f33e88f8d020bb1ce Mon Sep 17 00:00:00 2001 From: DauTT Date: Sun, 28 Jun 2020 23:56:09 +0200 Subject: [PATCH 02/33] Get rid of the unused variable config --- simapp/cmd/simd/client.go | 3 +-- simapp/cmd/simd/daemon.go | 2 +- simapp/cmd/simd/main.go | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/simapp/cmd/simd/client.go b/simapp/cmd/simd/client.go index a88e71d7c7c5..0873e1382b2f 100644 --- a/simapp/cmd/simd/client.go +++ b/simapp/cmd/simd/client.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -30,7 +29,7 @@ func init() { authclient.Codec = encodingConfig.Marshaler } -func addClientCommands(config *sdk.Config, rootClientCmd *cobra.Command) *cobra.Command { +func addClientCommands(rootClientCmd *cobra.Command) *cobra.Command { // Add --chain-id to persistent flags and mark it required rootClientCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") diff --git a/simapp/cmd/simd/daemon.go b/simapp/cmd/simd/daemon.go index 1579f61e9bcc..ed66f29604c6 100644 --- a/simapp/cmd/simd/daemon.go +++ b/simapp/cmd/simd/daemon.go @@ -27,7 +27,7 @@ const flagInvCheckPeriod = "inv-check-period" var invCheckPeriod uint -func addDaemonCommands(config *sdk.Config, rootDaemonCmd *cobra.Command) *cobra.Command { +func addDaemonCommands(rootDaemonCmd *cobra.Command) *cobra.Command { appCodec, cdc := simapp.MakeCodecs() ctx := server.NewDefaultContext() diff --git a/simapp/cmd/simd/main.go b/simapp/cmd/simd/main.go index e8ff0b69aa20..1553241ed988 100644 --- a/simapp/cmd/simd/main.go +++ b/simapp/cmd/simd/main.go @@ -25,8 +25,8 @@ func main() { } // Construct Root Command - rootComd = addClientCommands(config, rootComd) - rootComd = addDaemonCommands(config, rootComd) + rootComd = addClientCommands(rootComd) + rootComd = addDaemonCommands(rootComd) executor := cli.PrepareMainCmd(rootComd, "GA", simapp.DefaultNodeHome) err := executor.Execute() From b7fee058e4cfb68dc459ccf43015b4490862ef41 Mon Sep 17 00:00:00 2001 From: DauTT Date: Sun, 28 Jun 2020 23:58:48 +0200 Subject: [PATCH 03/33] Rename SimcliBinary to SimdBinary --- tests/cli/fixtures.go | 2 -- tests/cli/helpers.go | 14 ++++----- x/auth/client/testutil/helpers.go | 14 ++++----- x/bank/client/testutil/helpers.go | 10 +++--- x/distribution/client/testutil/helpers.go | 20 ++++++------ x/gov/client/testutil/helpers.go | 28 ++++++++--------- x/mint/client/testutil/helpers.go | 6 ++-- x/slashing/client/testutil/helpers.go | 4 +-- x/staking/client/testutil/helpers.go | 38 +++++++++++------------ 9 files changed, 67 insertions(+), 69 deletions(-) diff --git a/tests/cli/fixtures.go b/tests/cli/fixtures.go index b5837f5c9ae3..0d2b04938537 100644 --- a/tests/cli/fixtures.go +++ b/tests/cli/fixtures.go @@ -21,7 +21,6 @@ type Fixtures struct { BuildDir string RootDir string SimdBinary string - SimcliBinary string ChainID string RPCAddr string Port string @@ -56,7 +55,6 @@ func NewFixtures(t *testing.T) *Fixtures { BuildDir: buildDir, RootDir: tmpDir, SimdBinary: filepath.Join(buildDir, "simd"), - SimcliBinary: filepath.Join(buildDir, "simcli"), SimdHome: filepath.Join(tmpDir, ".simd"), SimcliHome: filepath.Join(tmpDir, ".simcli"), RPCAddr: servAddr, diff --git a/tests/cli/helpers.go b/tests/cli/helpers.go index 72e665b0b818..b0948a4c9978 100644 --- a/tests/cli/helpers.go +++ b/tests/cli/helpers.go @@ -113,14 +113,14 @@ func (f *Fixtures) ValidateGenesis() { // KeysDelete is simcli keys delete func (f *Fixtures) KeysDelete(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys delete --keyring-backend=test --home=%s %s", f.SimcliBinary, + cmd := fmt.Sprintf("%s keys delete --keyring-backend=test --home=%s %s", f.SimdBinary, f.SimcliHome, name) ExecuteWrite(f.T, AddFlags(cmd, append(append(flags, "-y"), "-f"))) } // KeysAdd is simcli keys add func (f *Fixtures) KeysAdd(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s %s", f.SimcliBinary, + cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s %s", f.SimdBinary, f.SimcliHome, name) ExecuteWriteCheckErr(f.T, AddFlags(cmd, flags)) } @@ -128,20 +128,20 @@ func (f *Fixtures) KeysAdd(name string, flags ...string) { // KeysAddRecover prepares simcli keys add --recover func (f *Fixtures) KeysAddRecover(name, mnemonic string, flags ...string) (exitSuccess bool, stdout, stderr string) { cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s --recover %s", - f.SimcliBinary, f.SimcliHome, name) + f.SimdBinary, f.SimcliHome, name) return ExecuteWriteRetStdStreams(f.T, AddFlags(cmd, flags), mnemonic) } // KeysAddRecoverHDPath prepares simcli keys add --recover --account --index func (f *Fixtures) KeysAddRecoverHDPath(name, mnemonic string, account uint32, index uint32, flags ...string) { cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s --recover %s --account %d"+ - " --index %d", f.SimcliBinary, f.SimcliHome, name, account, index) + " --index %d", f.SimdBinary, f.SimcliHome, name, account, index) ExecuteWriteCheckErr(f.T, AddFlags(cmd, flags), mnemonic) } // KeysShow is simcli keys show func (f *Fixtures) KeysShow(name string, flags ...string) keyring.KeyOutput { - cmd := fmt.Sprintf("%s keys show --keyring-backend=test --home=%s %s", f.SimcliBinary, + cmd := fmt.Sprintf("%s keys show --keyring-backend=test --home=%s %s", f.SimdBinary, f.SimcliHome, name) out, _ := tests.ExecuteT(f.T, AddFlags(cmd, flags), "") var ko keyring.KeyOutput @@ -164,7 +164,7 @@ func (f *Fixtures) KeyAddress(name string) sdk.AccAddress { // QueryTxs is simcli query txs func (f *Fixtures) QueryTxs(page, limit int, events ...string) *sdk.SearchTxsResult { cmd := fmt.Sprintf("%s query txs --page=%d --limit=%d --events='%s' %v", - f.SimcliBinary, page, limit, buildEventsQueryString(events), f.Flags()) + f.SimdBinary, page, limit, buildEventsQueryString(events), f.Flags()) out, _ := tests.ExecuteT(f.T, cmd, "") var result sdk.SearchTxsResult @@ -178,7 +178,7 @@ func (f *Fixtures) QueryTxs(page, limit int, events ...string) *sdk.SearchTxsRes // CLIConfig is simcli config func (f *Fixtures) CLIConfig(key, value string, flags ...string) { - cmd := fmt.Sprintf("%s config --home=%s %s %s", f.SimcliBinary, f.SimcliHome, key, value) + cmd := fmt.Sprintf("%s config --home=%s %s %s", f.SimdBinary, f.SimcliHome, key, value) ExecuteWriteCheckErr(f.T, AddFlags(cmd, flags)) } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 23aa367cf27c..bf460889807b 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -10,26 +10,26 @@ import ( // TxSign is simcli sign func TxSign(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign %v --keyring-backend=test --from=%s %v", f.SimcliBinary, f.Flags(), signer, fileName) + cmd := fmt.Sprintf("%s tx sign %v --keyring-backend=test --from=%s %v", f.SimdBinary, f.Flags(), signer, fileName) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxBroadcast is simcli tx broadcast func TxBroadcast(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx broadcast %v %v", f.SimcliBinary, f.Flags(), fileName) + cmd := fmt.Sprintf("%s tx broadcast %v %v", f.SimdBinary, f.Flags(), fileName) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxEncode is simcli tx encode func TxEncode(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx encode %v %v", f.SimcliBinary, f.Flags(), fileName) + cmd := fmt.Sprintf("%s tx encode %v %v", f.SimdBinary, f.Flags(), fileName) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxValidateSignatures is simcli tx validate-signatures func TxValidateSignatures(f *cli.Fixtures, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx validate-signatures %v --keyring-backend=test %v", f.SimcliBinary, + cmd := fmt.Sprintf("%s tx validate-signatures %v --keyring-backend=test %v", f.SimdBinary, f.Flags(), fileName) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) @@ -39,21 +39,21 @@ func TxValidateSignatures(f *cli.Fixtures, fileName string, flags ...string) (bo func TxMultisign(f *cli.Fixtures, fileName, name string, signaturesFiles []string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx multisign --keyring-backend=test %v %s %s %s", f.SimcliBinary, f.Flags(), + cmd := fmt.Sprintf("%s tx multisign --keyring-backend=test %v %s %s %s", f.SimdBinary, f.Flags(), fileName, name, strings.Join(signaturesFiles, " "), ) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags)) } func TxSignBatch(f *cli.Fixtures, signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign-batch %v --keyring-backend=test --from=%s %v", f.SimcliBinary, f.Flags(), signer, fileName) + cmd := fmt.Sprintf("%s tx sign-batch %v --keyring-backend=test --from=%s %v", f.SimdBinary, f.Flags(), signer, fileName) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxDecode is simcli tx decode func TxDecode(f *cli.Fixtures, encodedTx string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx decode %v %v", f.SimcliBinary, f.Flags(), encodedTx) + cmd := fmt.Sprintf("%s tx decode %v %v", f.SimdBinary, f.Flags(), encodedTx) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } diff --git a/x/bank/client/testutil/helpers.go b/x/bank/client/testutil/helpers.go index 4c2d1eca1475..37c6747d2908 100644 --- a/x/bank/client/testutil/helpers.go +++ b/x/bank/client/testutil/helpers.go @@ -15,14 +15,14 @@ import ( // TxSend is simcli tx send func TxSend(f *cli.Fixtures, from string, to sdk.AccAddress, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx send --keyring-backend=test %s %s %s %v", f.SimcliBinary, from, + cmd := fmt.Sprintf("%s tx send --keyring-backend=test %s %s %s %v", f.SimdBinary, from, to, amount, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // QueryAccount is simcli query account func QueryAccount(f *cli.Fixtures, address sdk.AccAddress, flags ...string) authtypes.BaseAccount { - cmd := fmt.Sprintf("%s query account %s %v", f.SimcliBinary, address, f.Flags()) + cmd := fmt.Sprintf("%s query account %s %v", f.SimdBinary, address, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") @@ -41,7 +41,7 @@ func QueryAccount(f *cli.Fixtures, address sdk.AccAddress, flags ...string) auth // QueryBalances executes the bank query balances command for a given address and // flag set. func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk.Coins { - cmd := fmt.Sprintf("%s query bank balances %s %v", f.SimcliBinary, address, f.Flags()) + cmd := fmt.Sprintf("%s query bank balances %s %v", f.SimdBinary, address, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var balances sdk.Coins @@ -53,7 +53,7 @@ func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk // QueryTotalSupply returns the total supply of coins func QueryTotalSupply(f *cli.Fixtures, flags ...string) (totalSupply sdk.Coins) { - cmd := fmt.Sprintf("%s query bank total %s", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query bank total %s", f.SimdBinary, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) @@ -64,7 +64,7 @@ func QueryTotalSupply(f *cli.Fixtures, flags ...string) (totalSupply sdk.Coins) // QueryTotalSupplyOf returns the total supply of a given coin denom func QueryTotalSupplyOf(f *cli.Fixtures, denom string, flags ...string) sdk.Int { - cmd := fmt.Sprintf("%s query bank total %s %s", f.SimcliBinary, denom, f.Flags()) + cmd := fmt.Sprintf("%s query bank total %s %s", f.SimdBinary, denom, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) diff --git a/x/distribution/client/testutil/helpers.go b/x/distribution/client/testutil/helpers.go index 8670931b418b..7b9d5d0df3ec 100644 --- a/x/distribution/client/testutil/helpers.go +++ b/x/distribution/client/testutil/helpers.go @@ -14,31 +14,31 @@ import ( // TxWithdrawRewards raises a txn to withdraw rewards func TxWithdrawRewards(f *cli.Fixtures, valAddr sdk.ValAddress, from string, flags ...string) bool { - cmd := fmt.Sprintf("%s tx distribution withdraw-rewards %s %v --keyring-backend=test --from=%s", f.SimcliBinary, valAddr, f.Flags(), from) + cmd := fmt.Sprintf("%s tx distribution withdraw-rewards %s %v --keyring-backend=test --from=%s", f.SimdBinary, valAddr, f.Flags(), from) return cli.ExecuteWrite(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxSetWithdrawAddress helps to set the withdraw address for rewards associated with a delegator address func TxSetWithdrawAddress(f *cli.Fixtures, from, withDrawAddr string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx distribution set-withdraw-addr %s --from %s %v --keyring-backend=test", f.SimcliBinary, withDrawAddr, from, f.Flags()) + cmd := fmt.Sprintf("%s tx distribution set-withdraw-addr %s --from %s %v --keyring-backend=test", f.SimdBinary, withDrawAddr, from, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxWithdrawAllRewards raises a txn to withdraw all rewards of a delegator address func TxWithdrawAllRewards(f *cli.Fixtures, from string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx distribution withdraw-all-rewards %v --keyring-backend=test --from=%s", f.SimcliBinary, f.Flags(), from) + cmd := fmt.Sprintf("%s tx distribution withdraw-all-rewards %v --keyring-backend=test --from=%s", f.SimdBinary, f.Flags(), from) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxFundCommunityPool Funds the community pool with the specified amount func TxFundCommunityPool(f *cli.Fixtures, from string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx distribution fund-community-pool %v %v --keyring-backend=test --from=%s", f.SimcliBinary, amount, f.Flags(), from) + cmd := fmt.Sprintf("%s tx distribution fund-community-pool %v %v --keyring-backend=test --from=%s", f.SimdBinary, amount, f.Flags(), from) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // QueryRewards returns the rewards of a delegator func QueryRewards(f *cli.Fixtures, delAddr sdk.AccAddress, flags ...string) types.QueryDelegatorTotalRewardsResponse { - cmd := fmt.Sprintf("%s query distribution rewards %s %s", f.SimcliBinary, delAddr, f.Flags()) + cmd := fmt.Sprintf("%s query distribution rewards %s %s", f.SimdBinary, delAddr, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) @@ -49,7 +49,7 @@ func QueryRewards(f *cli.Fixtures, delAddr sdk.AccAddress, flags ...string) type // QueryValidatorOutstandingRewards distribution outstanding (un-withdrawn) rewards func QueryValidatorOutstandingRewards(f *cli.Fixtures, valAddr string) types.ValidatorOutstandingRewards { - cmd := fmt.Sprintf("%s query distribution validator-outstanding-rewards %s %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query distribution validator-outstanding-rewards %s %v", f.SimdBinary, valAddr, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) @@ -60,7 +60,7 @@ func QueryValidatorOutstandingRewards(f *cli.Fixtures, valAddr string) types.Val // QueryParameters is simcli query distribution parameters func QueryParameters(f *cli.Fixtures, flags ...string) types.Params { - cmd := fmt.Sprintf("%s query distribution params %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query distribution params %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -71,7 +71,7 @@ func QueryParameters(f *cli.Fixtures, flags ...string) types.Params { // QueryCommission returns validator commission rewards from delegators to that validator. func QueryCommission(f *cli.Fixtures, valAddr string, flags ...string) types.ValidatorAccumulatedCommission { - cmd := fmt.Sprintf("%s query distribution commission %s %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query distribution commission %s %v", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -82,7 +82,7 @@ func QueryCommission(f *cli.Fixtures, valAddr string, flags ...string) types.Val // QuerySlashes returns all slashes of a validator for a given block range. func QuerySlashes(f *cli.Fixtures, valAddr string, flags ...string) []types.ValidatorSlashEvent { - cmd := fmt.Sprintf("%s query distribution slashes %s 0 5 %v ", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query distribution slashes %s 0 5 %v ", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -93,7 +93,7 @@ func QuerySlashes(f *cli.Fixtures, valAddr string, flags ...string) []types.Vali // QueryCommunityPool returns the amount of coins in the community pool func QueryCommunityPool(f *cli.Fixtures, flags ...string) sdk.DecCoins { - cmd := fmt.Sprintf("%s query distribution community-pool %v ", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query distribution community-pool %v ", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) diff --git a/x/gov/client/testutil/helpers.go b/x/gov/client/testutil/helpers.go index 1f2abb8e6a5c..c39486389382 100644 --- a/x/gov/client/testutil/helpers.go +++ b/x/gov/client/testutil/helpers.go @@ -18,7 +18,7 @@ import ( // QueryGovParamDeposit is simcli query gov param deposit func QueryGovParamDeposit(f *cli.Fixtures) types.DepositParams { - cmd := fmt.Sprintf("%s query gov param deposit %s", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query gov param deposit %s", f.SimdBinary, f.Flags()) out, _ := tests.ExecuteT(f.T, cmd, "") var depositParam types.DepositParams @@ -29,7 +29,7 @@ func QueryGovParamDeposit(f *cli.Fixtures) types.DepositParams { // QueryGovParamVoting is simcli query gov param voting func QueryGovParamVoting(f *cli.Fixtures) types.VotingParams { - cmd := fmt.Sprintf("%s query gov param voting %s", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query gov param voting %s", f.SimdBinary, f.Flags()) out, _ := tests.ExecuteT(f.T, cmd, "") var votingParam types.VotingParams @@ -40,7 +40,7 @@ func QueryGovParamVoting(f *cli.Fixtures) types.VotingParams { // QueryGovParamTallying is simcli query gov param tallying func QueryGovParamTallying(f *cli.Fixtures) types.TallyParams { - cmd := fmt.Sprintf("%s query gov param tallying %s", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query gov param tallying %s", f.SimdBinary, f.Flags()) out, _ := tests.ExecuteT(f.T, cmd, "") var tallyingParam types.TallyParams @@ -51,7 +51,7 @@ func QueryGovParamTallying(f *cli.Fixtures) types.TallyParams { // QueryGovProposal is simcli query gov proposal func QueryGovProposal(f *cli.Fixtures, proposalID int, flags ...string) types.Proposal { - cmd := fmt.Sprintf("%s query gov proposal %d %v", f.SimcliBinary, proposalID, f.Flags()) + cmd := fmt.Sprintf("%s query gov proposal %d %v", f.SimdBinary, proposalID, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var proposal types.Proposal @@ -62,7 +62,7 @@ func QueryGovProposal(f *cli.Fixtures, proposalID int, flags ...string) types.Pr // QueryGovProposals is simcli query gov proposals func QueryGovProposals(f *cli.Fixtures, flags ...string) types.Proposals { - cmd := fmt.Sprintf("%s query gov proposals %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query gov proposals %v", f.SimdBinary, f.Flags()) stdout, stderr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") if strings.Contains(stderr, "no matching proposals found") { return types.Proposals{} @@ -77,7 +77,7 @@ func QueryGovProposals(f *cli.Fixtures, flags ...string) types.Proposals { // QueryGovVote is simcli query gov vote func QueryGovVote(f *cli.Fixtures, proposalID int, voter sdk.AccAddress, flags ...string) types.Vote { - cmd := fmt.Sprintf("%s query gov vote %d %s %v", f.SimcliBinary, proposalID, voter, f.Flags()) + cmd := fmt.Sprintf("%s query gov vote %d %s %v", f.SimdBinary, proposalID, voter, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var vote types.Vote @@ -88,7 +88,7 @@ func QueryGovVote(f *cli.Fixtures, proposalID int, voter sdk.AccAddress, flags . // QueryGovVotes is simcli query gov votes func QueryGovVotes(f *cli.Fixtures, proposalID int, flags ...string) []types.Vote { - cmd := fmt.Sprintf("%s query gov votes %d %v", f.SimcliBinary, proposalID, f.Flags()) + cmd := fmt.Sprintf("%s query gov votes %d %v", f.SimdBinary, proposalID, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var votes []types.Vote @@ -99,7 +99,7 @@ func QueryGovVotes(f *cli.Fixtures, proposalID int, flags ...string) []types.Vot // QueryGovDeposit is simcli query gov deposit func QueryGovDeposit(f *cli.Fixtures, proposalID int, depositor sdk.AccAddress, flags ...string) types.Deposit { - cmd := fmt.Sprintf("%s query gov deposit %d %s %v", f.SimcliBinary, proposalID, depositor, f.Flags()) + cmd := fmt.Sprintf("%s query gov deposit %d %s %v", f.SimdBinary, proposalID, depositor, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var deposit types.Deposit @@ -110,7 +110,7 @@ func QueryGovDeposit(f *cli.Fixtures, proposalID int, depositor sdk.AccAddress, // QueryGovDeposits is simcli query gov deposits func QueryGovDeposits(f *cli.Fixtures, propsalID int, flags ...string) []types.Deposit { - cmd := fmt.Sprintf("%s query gov deposits %d %v", f.SimcliBinary, propsalID, f.Flags()) + cmd := fmt.Sprintf("%s query gov deposits %d %v", f.SimdBinary, propsalID, f.Flags()) out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var deposits []types.Deposit @@ -125,7 +125,7 @@ func QueryGovDeposits(f *cli.Fixtures, propsalID int, flags ...string) []types.D // TxGovSubmitProposal is simcli tx gov submit-proposal func TxGovSubmitProposal(f *cli.Fixtures, from, typ, title, description string, deposit sdk.Coin, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx gov submit-proposal %v --keyring-backend=test --from=%s --type=%s", - f.SimcliBinary, f.Flags(), from, typ) + f.SimdBinary, f.Flags(), from, typ) cmd += fmt.Sprintf(" --title=%s --description=%s --deposit=%s", title, description, deposit) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } @@ -133,14 +133,14 @@ func TxGovSubmitProposal(f *cli.Fixtures, from, typ, title, description string, // TxGovDeposit is simcli tx gov deposit func TxGovDeposit(f *cli.Fixtures, proposalID int, from string, amount sdk.Coin, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx gov deposit %d %s --keyring-backend=test --from=%s %v", - f.SimcliBinary, proposalID, amount, from, f.Flags()) + f.SimdBinary, proposalID, amount, from, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxGovVote is simcli tx gov vote func TxGovVote(f *cli.Fixtures, proposalID int, option types.VoteOption, from string, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx gov vote %d %s --keyring-backend=test --from=%s %v", - f.SimcliBinary, proposalID, option, from, f.Flags()) + f.SimdBinary, proposalID, option, from, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } @@ -152,7 +152,7 @@ func TxGovSubmitParamChangeProposal(f *cli.Fixtures, cmd := fmt.Sprintf( "%s tx gov submit-proposal param-change %s --keyring-backend=test --from=%s %v", - f.SimcliBinary, proposalPath, from, f.Flags(), + f.SimdBinary, proposalPath, from, f.Flags(), ) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) @@ -166,7 +166,7 @@ func TxGovSubmitCommunityPoolSpendProposal(f *cli.Fixtures, cmd := fmt.Sprintf( "%s tx gov submit-proposal community-pool-spend %s --keyring-backend=test --from=%s %v", - f.SimcliBinary, proposalPath, from, f.Flags(), + f.SimdBinary, proposalPath, from, f.Flags(), ) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) diff --git a/x/mint/client/testutil/helpers.go b/x/mint/client/testutil/helpers.go index 2a8f6ac9796e..1d59ff6b925e 100644 --- a/x/mint/client/testutil/helpers.go +++ b/x/mint/client/testutil/helpers.go @@ -13,7 +13,7 @@ import ( // QueryMintingParams returns the current minting parameters func QueryMintingParams(f *cli.Fixtures, flags ...string) types.Params { - cmd := fmt.Sprintf("%s query mint params %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query mint params %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -24,7 +24,7 @@ func QueryMintingParams(f *cli.Fixtures, flags ...string) types.Params { // QueryInflation returns the current minting inflation value func QueryInflation(f *cli.Fixtures, flags ...string) sdk.Dec { - cmd := fmt.Sprintf("%s query mint inflation %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query mint inflation %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -35,7 +35,7 @@ func QueryInflation(f *cli.Fixtures, flags ...string) sdk.Dec { // QueryAnnualProvisions returns the current minting annual provisions value func QueryAnnualProvisions(f *cli.Fixtures, flags ...string) sdk.Dec { - cmd := fmt.Sprintf("%s query mint annual-provisions %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query mint annual-provisions %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) diff --git a/x/slashing/client/testutil/helpers.go b/x/slashing/client/testutil/helpers.go index ca58ad5110f5..b28f66f478e1 100644 --- a/x/slashing/client/testutil/helpers.go +++ b/x/slashing/client/testutil/helpers.go @@ -12,7 +12,7 @@ import ( // QuerySigningInfo returns the signing info for a validator func QuerySigningInfo(f *cli.Fixtures, val string) types.ValidatorSigningInfo { - cmd := fmt.Sprintf("%s query slashing signing-info %s %s", f.SimcliBinary, val, f.Flags()) + cmd := fmt.Sprintf("%s query slashing signing-info %s %s", f.SimdBinary, val, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) @@ -24,7 +24,7 @@ func QuerySigningInfo(f *cli.Fixtures, val string) types.ValidatorSigningInfo { // QuerySlashingParams returns query slashing params func QuerySlashingParams(f *cli.Fixtures) types.Params { - cmd := fmt.Sprintf("%s query slashing params %s", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query slashing params %s", f.SimdBinary, f.Flags()) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) diff --git a/x/staking/client/testutil/helpers.go b/x/staking/client/testutil/helpers.go index ace7c49bb948..7e10b4fda717 100644 --- a/x/staking/client/testutil/helpers.go +++ b/x/staking/client/testutil/helpers.go @@ -15,7 +15,7 @@ import ( // TxStakingCreateValidator is simcli tx staking create-validator func TxStakingCreateValidator(f *cli.Fixtures, from, consPubKey string, amount sdk.Coin, flags ...string) (bool, string, string) { cmd := fmt.Sprintf("%s tx staking create-validator %v --keyring-backend=test --from=%s"+ - " --pubkey=%s", f.SimcliBinary, f.Flags(), from, consPubKey) + " --pubkey=%s", f.SimdBinary, f.Flags(), from, consPubKey) cmd += fmt.Sprintf(" --amount=%v --moniker=%v --commission-rate=%v", amount, from, "0.05") cmd += fmt.Sprintf(" --commission-max-rate=%v --commission-max-change-rate=%v", "0.20", "0.10") cmd += fmt.Sprintf(" --min-self-delegation=%v", "1") @@ -25,7 +25,7 @@ func TxStakingCreateValidator(f *cli.Fixtures, from, consPubKey string, amount s // TxStakingEditValidator is simcli tx staking update validator info func TxStakingEditValidator(f *cli.Fixtures, from, moniker, website, identity, details string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx staking edit-validator %v --keyring-backend=test --from=%s", f.SimcliBinary, f.Flags(), from) + cmd := fmt.Sprintf("%s tx staking edit-validator %v --keyring-backend=test --from=%s", f.SimdBinary, f.Flags(), from) cmd += fmt.Sprintf(" --moniker=%v --website=%s", moniker, website) cmd += fmt.Sprintf(" --identity=%s --details=%s", identity, details) @@ -35,25 +35,25 @@ func TxStakingEditValidator(f *cli.Fixtures, from, moniker, website, identity, d // TxStakingUnbond is simcli tx staking unbond func TxStakingUnbond(f *cli.Fixtures, from, shares string, validator sdk.ValAddress, flags ...string) bool { cmd := fmt.Sprintf("%s tx staking unbond --keyring-backend=test %s %v --from=%s %v", - f.SimcliBinary, validator, shares, from, f.Flags()) + f.SimdBinary, validator, shares, from, f.Flags()) return cli.ExecuteWrite(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxStakingDelegate is simcli tx staking delegate func TxStakingDelegate(f *cli.Fixtures, from, valOperAddr string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx staking delegate %s %v --keyring-backend=test --from=%s %v", f.SimcliBinary, valOperAddr, amount, from, f.Flags()) + cmd := fmt.Sprintf("%s tx staking delegate %s %v --keyring-backend=test --from=%s %v", f.SimdBinary, valOperAddr, amount, from, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // TxStakingRedelegate is simcli tx staking redelegate func TxStakingRedelegate(f *cli.Fixtures, from, srcVal, dstVal string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx staking redelegate %s %s %v --keyring-backend=test --from=%s %v", f.SimcliBinary, srcVal, dstVal, amount, from, f.Flags()) + cmd := fmt.Sprintf("%s tx staking redelegate %s %s %v --keyring-backend=test --from=%s %v", f.SimdBinary, srcVal, dstVal, amount, from, f.Flags()) return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass) } // QueryStakingValidator is simcli query staking validator func QueryStakingValidator(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) staking.Validator { - cmd := fmt.Sprintf("%s query staking validator %s %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking validator %s %v", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -65,7 +65,7 @@ func QueryStakingValidator(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...str // QueryStakingValidators is simcli query staking validators func QueryStakingValidators(f *cli.Fixtures, flags ...string) []staking.Validator { - cmd := fmt.Sprintf("%s query staking validators %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query staking validators %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -77,7 +77,7 @@ func QueryStakingValidators(f *cli.Fixtures, flags ...string) []staking.Validato // QueryStakingUnbondingDelegationsFrom is simcli query staking unbonding-delegations-from func QueryStakingUnbondingDelegationsFrom(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) []staking.UnbondingDelegation { - cmd := fmt.Sprintf("%s query staking unbonding-delegations-from %s %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking unbonding-delegations-from %s %v", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -89,7 +89,7 @@ func QueryStakingUnbondingDelegationsFrom(f *cli.Fixtures, valAddr sdk.ValAddres // QueryStakingDelegationsTo is simcli query staking delegations-to func QueryStakingDelegationsTo(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) []staking.Delegation { - cmd := fmt.Sprintf("%s query staking delegations-to %s %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking delegations-to %s %v", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -101,7 +101,7 @@ func QueryStakingDelegationsTo(f *cli.Fixtures, valAddr sdk.ValAddress, flags .. // QueryStakingPool is simcli query staking pool func QueryStakingPool(f *cli.Fixtures, flags ...string) staking.Pool { - cmd := fmt.Sprintf("%s query staking pool %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query staking pool %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -113,7 +113,7 @@ func QueryStakingPool(f *cli.Fixtures, flags ...string) staking.Pool { // QueryStakingParameters is simcli query staking parameters func QueryStakingParameters(f *cli.Fixtures, flags ...string) staking.Params { - cmd := fmt.Sprintf("%s query staking params %v", f.SimcliBinary, f.Flags()) + cmd := fmt.Sprintf("%s query staking params %v", f.SimdBinary, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -125,7 +125,7 @@ func QueryStakingParameters(f *cli.Fixtures, flags ...string) staking.Params { // QueryStakingDelegation is simcli query staking delegation func QueryStakingDelegation(f *cli.Fixtures, from string, valAddr sdk.ValAddress, flags ...string) staking.Delegation { - cmd := fmt.Sprintf("%s query staking delegation %s %s %v", f.SimcliBinary, from, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking delegation %s %s %v", f.SimdBinary, from, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -137,7 +137,7 @@ func QueryStakingDelegation(f *cli.Fixtures, from string, valAddr sdk.ValAddress // QueryStakingDelegations is simcli query staking delegations func QueryStakingDelegations(f *cli.Fixtures, from string, flags ...string) []staking.Delegation { - cmd := fmt.Sprintf("%s query staking delegations %s %v", f.SimcliBinary, from, f.Flags()) + cmd := fmt.Sprintf("%s query staking delegations %s %v", f.SimdBinary, from, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -149,7 +149,7 @@ func QueryStakingDelegations(f *cli.Fixtures, from string, flags ...string) []st // QueryStakingRedelegation is simcli query staking redelegation func QueryStakingRedelegation(f *cli.Fixtures, delAdrr, srcVal, dstVal string, flags ...string) []staking.RedelegationResponse { - cmd := fmt.Sprintf("%s query staking redelegation %v %v %v %v", f.SimcliBinary, delAdrr, srcVal, dstVal, f.Flags()) + cmd := fmt.Sprintf("%s query staking redelegation %v %v %v %v", f.SimdBinary, delAdrr, srcVal, dstVal, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -161,7 +161,7 @@ func QueryStakingRedelegation(f *cli.Fixtures, delAdrr, srcVal, dstVal string, f // QueryStakingRedelegations is simcli query staking redelegation func QueryStakingRedelegations(f *cli.Fixtures, delAdrr string, flags ...string) []staking.RedelegationResponse { - cmd := fmt.Sprintf("%s query staking redelegations %v %v", f.SimcliBinary, delAdrr, f.Flags()) + cmd := fmt.Sprintf("%s query staking redelegations %v %v", f.SimdBinary, delAdrr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -173,7 +173,7 @@ func QueryStakingRedelegations(f *cli.Fixtures, delAdrr string, flags ...string) // QueryStakingRedelegationsFrom is simcli query staking redelegations-from func QueryStakingRedelegationsFrom(f *cli.Fixtures, valAddr string, flags ...string) []staking.RedelegationResponse { - cmd := fmt.Sprintf("%s query staking redelegations-from %v %v", f.SimcliBinary, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking redelegations-from %v %v", f.SimdBinary, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -185,7 +185,7 @@ func QueryStakingRedelegationsFrom(f *cli.Fixtures, valAddr string, flags ...str // QueryStakingUnbondingDelegation is simcli query staking unbonding-delegation func QueryStakingUnbondingDelegation(f *cli.Fixtures, delAdrr, valAddr string, flags ...string) staking.UnbondingDelegation { - cmd := fmt.Sprintf("%s query staking unbonding-delegation %v %v %v", f.SimcliBinary, delAdrr, valAddr, f.Flags()) + cmd := fmt.Sprintf("%s query staking unbonding-delegation %v %v %v", f.SimdBinary, delAdrr, valAddr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -197,7 +197,7 @@ func QueryStakingUnbondingDelegation(f *cli.Fixtures, delAdrr, valAddr string, f // QueryStakingUnbondingDelegations is simcli query staking unbonding-delegations func QueryStakingUnbondingDelegations(f *cli.Fixtures, delAdrr string, flags ...string) []staking.UnbondingDelegation { - cmd := fmt.Sprintf("%s query staking unbonding-delegations %v %v", f.SimcliBinary, delAdrr, f.Flags()) + cmd := fmt.Sprintf("%s query staking unbonding-delegations %v %v", f.SimdBinary, delAdrr, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) @@ -209,7 +209,7 @@ func QueryStakingUnbondingDelegations(f *cli.Fixtures, delAdrr string, flags ... // QueryStakingHistoricalInfo is simcli query staking historical-info func QueryStakingHistoricalInfo(f *cli.Fixtures, height uint, flags ...string) staking.HistoricalInfo { - cmd := fmt.Sprintf("%s query staking historical-info %d %v", f.SimcliBinary, height, f.Flags()) + cmd := fmt.Sprintf("%s query staking historical-info %d %v", f.SimdBinary, height, f.Flags()) out, errStr := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") require.Empty(f.T, errStr) From 84ef4c6f04f521eb52897810fa66a5585a29bb25 Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 00:46:37 +0200 Subject: [PATCH 04/33] Resolve flag -o shorthand ambiguity. (It is used both to indicate and ) --- tests/cli/helpers.go | 2 +- x/genutil/client/cli/init.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cli/helpers.go b/tests/cli/helpers.go index b0948a4c9978..db5ffbcf9b40 100644 --- a/tests/cli/helpers.go +++ b/tests/cli/helpers.go @@ -51,7 +51,7 @@ func (f *Fixtures) UnsafeResetAll(flags ...string) { // SDInit is simd init // NOTE: SDInit sets the ChainID for the Fixtures instance func (f *Fixtures) SDInit(moniker string, flags ...string) { - cmd := fmt.Sprintf("%s init -o --home=%s %s", f.SimdBinary, f.SimdHome, moniker) + cmd := fmt.Sprintf("%s init --overwrite --home=%s %s", f.SimdBinary, f.SimdHome, moniker) _, stderr := tests.ExecuteT(f.T, AddFlags(cmd, flags), clientkeys.DefaultKeyPass) var chainID string diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 6797405ba98c..86ac84b952b0 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -117,7 +117,7 @@ func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManag } cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") - cmd.Flags().BoolP(flagOverwrite, "o", false, "overwrite the genesis.json file") + cmd.Flags().Bool(flagOverwrite, false, "overwrite the genesis.json file") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") return cmd From 103e884dc91b3e9fafc27fe3ea8076d5977a73b8 Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 01:05:04 +0200 Subject: [PATCH 05/33] Resolve flags conflict with genTx cmd in x/genutil/client/cli/gentx.go --- x/staking/client/cli/tx.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 324230c02d16..13fba3ea9356 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -79,8 +79,12 @@ func NewCreateValidatorCmd(clientCtx client.Context) *cobra.Command { cmd.Flags().String(FlagNodeID, "", "The node's ID") _ = cmd.MarkFlagRequired(flags.FlagFrom) - _ = cmd.MarkFlagRequired(FlagAmount) - _ = cmd.MarkFlagRequired(FlagPubKey) + + // TODO: Investigate why the the following two required flag, "FlagAmount" and "FlagPubKey", are force to the genTx cmd in x/genutil/client/cli/gentx.go. + // To resolved the conflict with genTx, we will temporarily comment the following two line of code: + + // _ = cmd.MarkFlagRequired(FlagAmount) + // _ = cmd.MarkFlagRequired(FlagPubKey) _ = cmd.MarkFlagRequired(FlagMoniker) return cmd From fd964da70d28338735b0e7dd2545a74ee7c2e27c Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 21:58:11 +0200 Subject: [PATCH 06/33] Move ./simapp/cmd/simd to ./cmd/simd --- Makefile | 2 +- {simapp/cmd => cmd}/simd/client.go | 0 {simapp/cmd => cmd}/simd/daemon.go | 0 {simapp/cmd => cmd}/simd/genaccounts.go | 0 {simapp/cmd => cmd}/simd/main.go | 0 {simapp/cmd => cmd}/simd/testnet.go | 0 6 files changed, 1 insertion(+), 1 deletion(-) rename {simapp/cmd => cmd}/simd/client.go (100%) rename {simapp/cmd => cmd}/simd/daemon.go (100%) rename {simapp/cmd => cmd}/simd/genaccounts.go (100%) rename {simapp/cmd => cmd}/simd/main.go (100%) rename {simapp/cmd => cmd}/simd/testnet.go (100%) diff --git a/Makefile b/Makefile index f11a8c76ed4b..3e10c3fef9c3 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ build: go.sum build-sim: go.sum mkdir -p $(BUILDDIR) - go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/cmd/simd + go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./cmd/simd build-sim-linux: go.sum LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-sim diff --git a/simapp/cmd/simd/client.go b/cmd/simd/client.go similarity index 100% rename from simapp/cmd/simd/client.go rename to cmd/simd/client.go diff --git a/simapp/cmd/simd/daemon.go b/cmd/simd/daemon.go similarity index 100% rename from simapp/cmd/simd/daemon.go rename to cmd/simd/daemon.go diff --git a/simapp/cmd/simd/genaccounts.go b/cmd/simd/genaccounts.go similarity index 100% rename from simapp/cmd/simd/genaccounts.go rename to cmd/simd/genaccounts.go diff --git a/simapp/cmd/simd/main.go b/cmd/simd/main.go similarity index 100% rename from simapp/cmd/simd/main.go rename to cmd/simd/main.go diff --git a/simapp/cmd/simd/testnet.go b/cmd/simd/testnet.go similarity index 100% rename from simapp/cmd/simd/testnet.go rename to cmd/simd/testnet.go From 01da4cf7d0a3a7c90640b05a98c24102d9b0a2fb Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 22:10:20 +0200 Subject: [PATCH 07/33] Sort available commands --- cmd/simd/client.go | 5 ----- cmd/simd/main.go | 4 ++-- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/cmd/simd/client.go b/cmd/simd/client.go index 0873e1382b2f..51b8e7c37d4b 100644 --- a/cmd/simd/client.go +++ b/cmd/simd/client.go @@ -43,10 +43,7 @@ func addClientCommands(rootClientCmd *cobra.Command) *cobra.Command { client.ConfigCmd(simapp.DefaultNodeHome), queryCmd(encodingConfig), txCmd(encodingConfig), - flags.LineBreak, - flags.LineBreak, keys.Commands(), - flags.LineBreak, flags.NewCompletionCmd(rootClientCmd, true), ) @@ -67,12 +64,10 @@ func queryCmd(config simappparams.EncodingConfig) *cobra.Command { queryCmd.AddCommand( authcmd.GetAccountCmd(cdc), - flags.LineBreak, rpc.ValidatorCommand(cdc), rpc.BlockCommand(), authcmd.QueryTxsByEventsCmd(cdc), authcmd.QueryTxCmd(cdc), - flags.LineBreak, ) // add modules' query commands diff --git a/cmd/simd/main.go b/cmd/simd/main.go index 1553241ed988..0fa878fec863 100644 --- a/cmd/simd/main.go +++ b/cmd/simd/main.go @@ -10,7 +10,7 @@ import ( func main() { - cobra.EnableCommandSorting = false + cobra.EnableCommandSorting = true // Read in the configuration file for the sdk config := sdk.GetConfig() @@ -21,7 +21,7 @@ func main() { rootComd := &cobra.Command{ Use: "simd", - Short: "simulation app binary", + Short: "simulation app", } // Construct Root Command From 7a84bcb392cdab2f48072947ecbd405c8c9dc88b Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 22:18:14 +0200 Subject: [PATCH 08/33] Simplify code --- cmd/simd/client.go | 4 +--- cmd/simd/daemon.go | 3 +-- cmd/simd/main.go | 4 ++-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/cmd/simd/client.go b/cmd/simd/client.go index 51b8e7c37d4b..8b0442a7e82d 100644 --- a/cmd/simd/client.go +++ b/cmd/simd/client.go @@ -29,7 +29,7 @@ func init() { authclient.Codec = encodingConfig.Marshaler } -func addClientCommands(rootClientCmd *cobra.Command) *cobra.Command { +func addClientCommands(rootClientCmd *cobra.Command) { // Add --chain-id to persistent flags and mark it required rootClientCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") @@ -46,8 +46,6 @@ func addClientCommands(rootClientCmd *cobra.Command) *cobra.Command { keys.Commands(), flags.NewCompletionCmd(rootClientCmd, true), ) - - return rootClientCmd } func queryCmd(config simappparams.EncodingConfig) *cobra.Command { diff --git a/cmd/simd/daemon.go b/cmd/simd/daemon.go index ed66f29604c6..d63f6eaaf86b 100644 --- a/cmd/simd/daemon.go +++ b/cmd/simd/daemon.go @@ -27,7 +27,7 @@ const flagInvCheckPeriod = "inv-check-period" var invCheckPeriod uint -func addDaemonCommands(rootDaemonCmd *cobra.Command) *cobra.Command { +func addDaemonCommands(rootDaemonCmd *cobra.Command) { appCodec, cdc := simapp.MakeCodecs() ctx := server.NewDefaultContext() @@ -53,7 +53,6 @@ func addDaemonCommands(rootDaemonCmd *cobra.Command) *cobra.Command { rootDaemonCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, 0, "Assert registered invariants every N blocks") - return rootDaemonCmd } func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) server.Application { diff --git a/cmd/simd/main.go b/cmd/simd/main.go index 0fa878fec863..f40b82d0d6b0 100644 --- a/cmd/simd/main.go +++ b/cmd/simd/main.go @@ -25,8 +25,8 @@ func main() { } // Construct Root Command - rootComd = addClientCommands(rootComd) - rootComd = addDaemonCommands(rootComd) + addClientCommands(rootComd) + addDaemonCommands(rootComd) executor := cli.PrepareMainCmd(rootComd, "GA", simapp.DefaultNodeHome) err := executor.Execute() From 4bc67f4bcdb38c784edde3452129ee438f99aed3 Mon Sep 17 00:00:00 2001 From: DauTT Date: Mon, 29 Jun 2020 22:27:54 +0200 Subject: [PATCH 09/33] Uncomment line. Issue got reolved automatically. :) --- x/staking/client/cli/tx.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 13fba3ea9356..324230c02d16 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -79,12 +79,8 @@ func NewCreateValidatorCmd(clientCtx client.Context) *cobra.Command { cmd.Flags().String(FlagNodeID, "", "The node's ID") _ = cmd.MarkFlagRequired(flags.FlagFrom) - - // TODO: Investigate why the the following two required flag, "FlagAmount" and "FlagPubKey", are force to the genTx cmd in x/genutil/client/cli/gentx.go. - // To resolved the conflict with genTx, we will temporarily comment the following two line of code: - - // _ = cmd.MarkFlagRequired(FlagAmount) - // _ = cmd.MarkFlagRequired(FlagPubKey) + _ = cmd.MarkFlagRequired(FlagAmount) + _ = cmd.MarkFlagRequired(FlagPubKey) _ = cmd.MarkFlagRequired(FlagMoniker) return cmd From 24fc533ac7341e7e774e33827698105aca3c5286 Mon Sep 17 00:00:00 2001 From: DauTT Date: Tue, 30 Jun 2020 21:48:27 +0200 Subject: [PATCH 10/33] Adjust version module to use only one binary and refactor accordingly --- client/debug/main.go | 6 ++--- version/version.go | 34 +++++++++++-------------- version/version_test.go | 13 +++++----- x/auth/client/cli/query.go | 2 +- x/auth/client/cli/tx_multisign.go | 2 +- x/bank/client/cli/query.go | 2 +- x/distribution/client/cli/query.go | 10 ++++---- x/distribution/client/cli/tx.go | 10 ++++---- x/evidence/client/cli/query.go | 2 +- x/genutil/client/cli/migrate.go | 2 +- x/gov/client/cli/query.go | 20 +++++++-------- x/gov/client/cli/tx.go | 6 ++--- x/ibc-transfer/client/cli/query.go | 4 +-- x/ibc-transfer/client/cli/tx.go | 2 +- x/ibc/02-client/client/cli/query.go | 12 ++++----- x/ibc/03-connection/client/cli/query.go | 16 ++++++------ x/ibc/03-connection/client/cli/tx.go | 8 +++--- x/ibc/04-channel/client/cli/query.go | 4 +-- x/ibc/07-tendermint/client/cli/tx.go | 6 ++--- x/ibc/09-localhost/client/cli/tx.go | 2 +- x/params/client/cli/tx.go | 2 +- x/staking/client/cli/query.go | 28 ++++++++++---------- x/staking/client/cli/tx.go | 6 ++--- 23 files changed, 97 insertions(+), 102 deletions(-) diff --git a/client/debug/main.go b/client/debug/main.go index 5264983caf75..54b4c2f0907a 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -77,7 +77,7 @@ func PubkeyCmd(cdc *codec.Codec) *cobra.Command { Example: $ %s debug pubkey TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz $ %s debug pubkey cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg - `, version.ClientName, version.ClientName), + `, version.AppName, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { pk, err := getPubKeyFromString(args[0]) @@ -127,7 +127,7 @@ func AddrCmd() *cobra.Command { Example: $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg - `, version.ClientName), + `, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -171,7 +171,7 @@ func RawBytesCmd() *cobra.Command { Example: $ %s debug raw-bytes [72 101 108 108 111 44 32 112 108 97 121 103 114 111 117 110 100] - `, version.ClientName), + `, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { stringBytes := args[0] diff --git a/version/version.go b/version/version.go index 9429a9c1f9f1..ef8146f2d209 100644 --- a/version/version.go +++ b/version/version.go @@ -11,7 +11,7 @@ // // go build -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ // -X github.com/cosmos/cosmos-sdk/version.ServerName=gaiad \ -// -X github.com/cosmos/cosmos-sdk/version.ClientName=gaiacli \ +// -X github.com/cosmos/cosmos-sdk/version.AppName=gaiacli \ // -X github.com/cosmos/cosmos-sdk/version.Version=1.0 \ // -X github.com/cosmos/cosmos-sdk/version.Commit=f0f7b7dab7e36c20b757cebce0e8f4fc5b95de60 \ // -X "github.com/cosmos/cosmos-sdk/version.BuildTags=linux darwin amd64" @@ -25,10 +25,8 @@ import ( var ( // application's name Name = "" - // server binary name - ServerName = "" - // client binary name - ClientName = "" + // application binary name + AppName = "" // application's version string Version = "" // commit @@ -39,24 +37,22 @@ var ( // Info defines the application version information. type Info struct { - Name string `json:"name" yaml:"name"` - ServerName string `json:"server_name" yaml:"server_name"` - ClientName string `json:"client_name" yaml:"client_name"` - Version string `json:"version" yaml:"version"` - GitCommit string `json:"commit" yaml:"commit"` - BuildTags string `json:"build_tags" yaml:"build_tags"` - GoVersion string `json:"go" yaml:"go"` + Name string `json:"name" yaml:"name"` + AppName string `json:"server_name" yaml:"server_name"` + Version string `json:"version" yaml:"version"` + GitCommit string `json:"commit" yaml:"commit"` + BuildTags string `json:"build_tags" yaml:"build_tags"` + GoVersion string `json:"go" yaml:"go"` } func NewInfo() Info { return Info{ - Name: Name, - ServerName: ServerName, - ClientName: ClientName, - Version: Version, - GitCommit: Commit, - BuildTags: BuildTags, - GoVersion: fmt.Sprintf("go version %s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH), + Name: Name, + AppName: AppName, + Version: Version, + GitCommit: Commit, + BuildTags: BuildTags, + GoVersion: fmt.Sprintf("go version %s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH), } } diff --git a/version/version_test.go b/version/version_test.go index 25616b5f3b9a..7fad6572ae75 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -25,13 +25,12 @@ build tags: func TestInfo_String(t *testing.T) { info := Info{ - Name: "testapp", - ServerName: "testappd", - ClientName: "testappcli", - Version: "1.0.0", - GitCommit: "1b78457135a4104bc3af97f20654d49e2ea87454", - BuildTags: "netgo,ledger", - GoVersion: "go version go1.14 linux/amd64", + Name: "testapp", + AppName: "testappd", + Version: "1.0.0", + GitCommit: "1b78457135a4104bc3af97f20654d49e2ea87454", + BuildTags: "netgo,ledger", + GoVersion: "go version go1.14 linux/amd64", } want := `testapp: 1.0.0 git commit: 1b78457135a4104bc3af97f20654d49e2ea87454 diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 581a00cfe2ce..d1b324e5a3a4 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -115,7 +115,7 @@ documents its respective events under 'xx_events.md'. Example: $ %s query txs --%s 'message.sender=cosmos1...&message.action=withdraw_delegator_reward' --page 1 --limit 30 -`, eventFormat, version.ClientName, flagEvents), +`, eventFormat, version.AppName, flagEvents), ), RunE: func(cmd *cobra.Command, args []string) error { eventsStr := strings.Trim(viper.GetString(flagEvents), "'") diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index dd707f4468d4..50a6f36d7a84 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -42,7 +42,7 @@ The --offline flag makes sure that the client will not reach out to an external Thus account number or sequence number lookups will not be performed and it is recommended to set such parameters manually. `, - version.ClientName, + version.AppName, ), ), RunE: makeMultiSignCmd(clientCtx), diff --git a/x/bank/client/cli/query.go b/x/bank/client/cli/query.go index a310c76112ef..72c9251ce6dc 100644 --- a/x/bank/client/cli/query.go +++ b/x/bank/client/cli/query.go @@ -90,7 +90,7 @@ $ %s query %s total To query for the total supply of a specific coin denomination use: $ %s query %s total stake `, - version.ClientName, types.ModuleName, version.ClientName, types.ModuleName, + version.AppName, types.ModuleName, version.AppName, types.ModuleName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 105928c61c4f..5a9af1f5c23c 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -76,7 +76,7 @@ for a validator and all their delegations. Example: $ %s query distribution validator-outstanding-rewards cosmosvaloper1lwjmdnks33xwnmfayc64ycprww49n33mtm92ne `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -123,7 +123,7 @@ func GetCmdQueryValidatorCommission(queryRoute string, cdc *codec.Codec) *cobra. Example: $ %s query distribution commission cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -158,7 +158,7 @@ func GetCmdQueryValidatorSlashes(queryRoute string, cdc *codec.Codec) *cobra.Com Example: $ %s query distribution slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 100 `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -212,7 +212,7 @@ Example: $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -273,7 +273,7 @@ func GetCmdQueryCommunityPool(queryRoute string, cdc *codec.Codec) *cobra.Comman Example: $ %s query distribution community-pool `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index eba522998db0..d82192a346d5 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -91,7 +91,7 @@ Example: $ %s tx distribution withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey $ %s tx distribution withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --commission `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -132,7 +132,7 @@ func NewWithdrawAllRewardsCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx distribution withdraw-all-rewards --from mykey `, - version.ClientName, + version.AppName, ), ), Args: cobra.NoArgs, @@ -171,7 +171,7 @@ func NewSetWithdrawAddrCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx distribution set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from mykey `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -206,7 +206,7 @@ func NewFundCommunityPoolCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx distribution fund-community-pool 100uatom --from mykey `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -253,7 +253,7 @@ Where proposal.json contains: "deposit": "1000stake" } `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/evidence/client/cli/query.go b/x/evidence/client/cli/query.go index b3218b96b552..ccd1db5bb09d 100644 --- a/x/evidence/client/cli/query.go +++ b/x/evidence/client/cli/query.go @@ -29,7 +29,7 @@ Example: $ %s query %s DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660 $ %s query %s --page=2 --limit=50 `, - version.ClientName, types.ModuleName, version.ClientName, types.ModuleName, + version.AppName, types.ModuleName, version.AppName, types.ModuleName, ), ), Args: cobra.MaximumNArgs(1), diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index 8514ad021f8b..8e0b97991ea3 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -63,7 +63,7 @@ func MigrateGenesisCmd(_ *server.Context, cdc *codec.Codec) *cobra.Command { Example: $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2019-04-22T17:00:00Z -`, version.ServerName), +`, version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { var err error diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index fd52c0b140b1..91b4c859e198 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -56,7 +56,7 @@ proposal-id by running "%s query gov proposals". Example: $ %s query gov proposal 1 `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -95,7 +95,7 @@ $ %s query gov proposals --voter cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) $ %s query gov proposals --page=2 --limit=100 `, - version.ClientName, version.ClientName, version.ClientName, version.ClientName, + version.AppName, version.AppName, version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -183,7 +183,7 @@ func GetCmdQueryVote(queryRoute string, cdc *codec.Codec) *cobra.Command { Example: $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -253,7 +253,7 @@ Example: $ %[1]s query gov votes 1 $ %[1]s query gov votes 1 --page=2 --limit=100 `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -317,7 +317,7 @@ func GetCmdQueryDeposit(queryRoute string, cdc *codec.Codec) *cobra.Command { Example: $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -380,7 +380,7 @@ You can find the proposal-id by running "%s query gov proposals". Example: $ %s query gov deposits 1 `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -438,7 +438,7 @@ the proposal-id by running "%s query gov proposals". Example: $ %s query gov tally 1 `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -487,7 +487,7 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { Example: $ %s query gov params `, - version.ClientName, + version.AppName, ), ), Args: cobra.NoArgs, @@ -532,7 +532,7 @@ $ %s query gov param voting $ %s query gov param tallying $ %s query gov param deposit `, - version.ClientName, version.ClientName, version.ClientName, + version.AppName, version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -578,7 +578,7 @@ func GetCmdQueryProposer(queryRoute string, cdc *codec.Codec) *cobra.Command { Example: $ %s query gov proposer 1 `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 83ab6eecfe1f..07dc958c0cfb 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -101,7 +101,7 @@ Which is equivalent to: $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome proposal" --type="Text" --deposit="10test" --from mykey `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -154,7 +154,7 @@ find the proposal-id by running "%s query gov proposals". Example: $ %s tx gov deposit 1 10stake --from mykey `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -200,7 +200,7 @@ find the proposal-id by running "%s query gov proposals". Example: $ %s tx gov vote 1 yes --from mykey `, - version.ClientName, version.ClientName, + version.AppName, version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/ibc-transfer/client/cli/query.go b/x/ibc-transfer/client/cli/query.go index a562f3425bf8..03d0804cfda7 100644 --- a/x/ibc-transfer/client/cli/query.go +++ b/x/ibc-transfer/client/cli/query.go @@ -23,9 +23,9 @@ func GetCmdQueryNextSequence(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc-transfer next-recv [port-id] [channel-id] - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc-transfer next-recv [port-id] [channel-id]", version.ClientName), + Example: fmt.Sprintf("%s query ibc-transfer next-recv [port-id] [channel-id]", version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() diff --git a/x/ibc-transfer/client/cli/tx.go b/x/ibc-transfer/client/cli/tx.go index b2e04a2fbc68..054504f77e45 100644 --- a/x/ibc-transfer/client/cli/tx.go +++ b/x/ibc-transfer/client/cli/tx.go @@ -23,7 +23,7 @@ func NewTransferTxCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "transfer [src-port] [src-channel] [receiver] [amount]", Short: "Transfer a fungible token through IBC", - Example: fmt.Sprintf("%s tx ibc-transfer transfer [src-port] [src-channel] [receiver] [amount]", version.ClientName), + Example: fmt.Sprintf("%s tx ibc-transfer transfer [src-port] [src-channel] [receiver] [amount]", version.AppName), Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.InitWithInput(cmd.InOrStdin()) diff --git a/x/ibc/02-client/client/cli/query.go b/x/ibc/02-client/client/cli/query.go index ee15b2bf74fb..c069616d760a 100644 --- a/x/ibc/02-client/client/cli/query.go +++ b/x/ibc/02-client/client/cli/query.go @@ -27,9 +27,9 @@ func GetCmdQueryClientStates(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc client states - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc client states", version.ClientName), + Example: fmt.Sprintf("%s query ibc client states", version.AppName), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() @@ -61,7 +61,7 @@ func GetCmdQueryClientState(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc client state [client-id] - `, version.ClientName), + `, version.AppName), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -94,7 +94,7 @@ func GetCmdQueryConsensusState(clientCtx client.Context) *cobra.Command { Use: "consensus-state [client-id] [height]", Short: "Query the consensus state of a client at a given height", Long: "Query the consensus state for a particular light client at a given height", - Example: fmt.Sprintf("%s query ibc client consensus-state [client-id] [height]", version.ClientName), + Example: fmt.Sprintf("%s query ibc client consensus-state [client-id] [height]", version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() @@ -130,7 +130,7 @@ func GetCmdQueryHeader(clientCtx client.Context) *cobra.Command { Use: "header", Short: "Query the latest header of the running chain", Long: "Query the latest Tendermint header of the running chain", - Example: fmt.Sprintf("%s query ibc client header", version.ClientName), + Example: fmt.Sprintf("%s query ibc client header", version.AppName), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() @@ -156,7 +156,7 @@ func GetCmdNodeConsensusState(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc client node-state - `, version.ClientName), + `, version.AppName), ), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/ibc/03-connection/client/cli/query.go b/x/ibc/03-connection/client/cli/query.go index 76c172e8a798..0cdddb0559ae 100644 --- a/x/ibc/03-connection/client/cli/query.go +++ b/x/ibc/03-connection/client/cli/query.go @@ -24,9 +24,9 @@ func GetCmdQueryConnections(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc connection connections - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc connection connections", version.ClientName), + Example: fmt.Sprintf("%s query ibc connection connections", version.AppName), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { clientCtx = clientCtx.Init() @@ -58,9 +58,9 @@ func GetCmdQueryConnection(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc connection end [connection-id] - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc connection end [connection-id]", version.ClientName), + Example: fmt.Sprintf("%s query ibc connection end [connection-id]", version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() @@ -91,9 +91,9 @@ func GetCmdQueryAllClientConnections(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc connection paths - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc connection paths", version.ClientName), + Example: fmt.Sprintf("%s query ibc connection paths", version.AppName), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { clientCtx = clientCtx.Init() @@ -125,9 +125,9 @@ func GetCmdQueryClientConnections(clientCtx client.Context) *cobra.Command { Example: $ %s query ibc connection path [client-id] - `, version.ClientName), + `, version.AppName), ), - Example: fmt.Sprintf("%s query ibc connection path [client-id]", version.ClientName), + Example: fmt.Sprintf("%s query ibc connection path [client-id]", version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() diff --git a/x/ibc/03-connection/client/cli/tx.go b/x/ibc/03-connection/client/cli/tx.go index e5225bf3f402..30d09966e248 100644 --- a/x/ibc/03-connection/client/cli/tx.go +++ b/x/ibc/03-connection/client/cli/tx.go @@ -23,7 +23,7 @@ func NewConnectionOpenInitCmd(clientCtx client.Context) *cobra.Command { Long: "Initialize a connection on chain A with a given counterparty chain B", Example: fmt.Sprintf( "%s tx %s %s open-init [connection-id] [client-id] [counterparty-connection-id] [counterparty-client-id] [path/to/counterparty_prefix.json]", - version.ClientName, host.ModuleName, types.SubModuleName, + version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.ExactArgs(5), RunE: func(cmd *cobra.Command, args []string) error { @@ -68,7 +68,7 @@ func NewConnectionOpenTryCmd(clientCtx client.Context) *cobra.Command { `%s tx %s %s open-try connection-id] [client-id] \ [counterparty-connection-id] [counterparty-client-id] [path/to/counterparty_prefix.json] \ [counterparty-versions] [path/to/proof_init.json] [path/tp/proof_consensus.json]`, - version.ClientName, host.ModuleName, types.SubModuleName, + version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.ExactArgs(8), RunE: func(cmd *cobra.Command, args []string) error { @@ -129,7 +129,7 @@ func NewConnectionOpenAckCmd(clientCtx client.Context) *cobra.Command { Long: "Relay the acceptance of a connection open attempt from chain B to chain A", Example: fmt.Sprintf( "%s tx %s %s open-ack [connection-id] [path/to/proof_try.json] [path/to/proof_consensus.json] [version]", - version.ClientName, host.ModuleName, types.SubModuleName, + version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) error { @@ -180,7 +180,7 @@ func NewConnectionOpenConfirmCmd(clientCtx client.Context) *cobra.Command { Long: "Confirm to chain B that connection is open on chain A", Example: fmt.Sprintf( "%s tx %s %s open-confirm [connection-id] [path/to/proof_ack.json]", - version.ClientName, host.ModuleName, types.SubModuleName, + version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/ibc/04-channel/client/cli/query.go b/x/ibc/04-channel/client/cli/query.go index 4e1a78fb96bb..6ec3396e09e1 100644 --- a/x/ibc/04-channel/client/cli/query.go +++ b/x/ibc/04-channel/client/cli/query.go @@ -21,7 +21,7 @@ func GetCmdQueryChannel(clientCtx client.Context) *cobra.Command { Short: "Query a channel end", Long: "Query an IBC channel end from a port and channel identifiers", Example: fmt.Sprintf( - "%s query %s %s end [port-id] [channel-id]", version.ClientName, host.ModuleName, types.SubModuleName, + "%s query %s %s end [port-id] [channel-id]", version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -51,7 +51,7 @@ func GetCmdQueryChannelClientState(clientCtx client.Context) *cobra.Command { Use: "client-state [port-id] [channel-id]", Short: "Query the client state associated with a channel", Long: "Query the client state associated with a channel, by providing its port and channel identifiers.", - Example: fmt.Sprintf("%s query ibc channel client-state [port-id] [channel-id]", version.ClientName), + Example: fmt.Sprintf("%s query ibc channel client-state [port-id] [channel-id]", version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx = clientCtx.Init() diff --git a/x/ibc/07-tendermint/client/cli/tx.go b/x/ibc/07-tendermint/client/cli/tx.go index e9cc6a1d101d..1759bb56a66d 100644 --- a/x/ibc/07-tendermint/client/cli/tx.go +++ b/x/ibc/07-tendermint/client/cli/tx.go @@ -43,7 +43,7 @@ func GetCmdCreateClient(cdc *codec.Codec) *cobra.Command { Long: `Create a new tendermint IBC client. - 'trust-level' flag can be a fraction (eg: '1/3') or 'default' - 'proof-specs' flag can be JSON input, a path to a .json file or 'default'`, - Example: fmt.Sprintf("%s tx ibc %s create [client-id] [path/to/consensus_state.json] [trusting_period] [unbonding_period] [max_clock_drift] --trust-level default --proof-specs [path/to/proof-specs.json] --from node0 --home ../node0/cli --chain-id $CID", version.ClientName, ibctmtypes.SubModuleName), + Example: fmt.Sprintf("%s tx ibc %s create [client-id] [path/to/consensus_state.json] [trusting_period] [unbonding_period] [max_clock_drift] --trust-level default --proof-specs [path/to/proof-specs.json] --from node0 --home ../node0/cli --chain-id $CID", version.AppName, ibctmtypes.SubModuleName), Args: cobra.ExactArgs(5), RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) @@ -135,7 +135,7 @@ func GetCmdUpdateClient(cdc *codec.Codec) *cobra.Command { Long: "update existing tendermint client with a tendermint header", Example: fmt.Sprintf( "$ %s tx ibc %s update [client-id] [path/to/header.json] --from node0 --home ../node0/cli --chain-id $CID", - version.ClientName, ibctmtypes.SubModuleName, + version.AppName, ibctmtypes.SubModuleName, ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -177,7 +177,7 @@ func GetCmdSubmitMisbehaviour(cdc *codec.Codec) *cobra.Command { Long: "submit a client misbehaviour to invalidate to invalidate previous state roots and prevent future updates", Example: fmt.Sprintf( "$ %s tx ibc %s misbehaviour [path/to/evidence.json] --from node0 --home ../node0/cli --chain-id $CID", - version.ClientName, ibctmtypes.SubModuleName, + version.AppName, ibctmtypes.SubModuleName, ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/ibc/09-localhost/client/cli/tx.go b/x/ibc/09-localhost/client/cli/tx.go index 31c65784628c..901826db90ca 100644 --- a/x/ibc/09-localhost/client/cli/tx.go +++ b/x/ibc/09-localhost/client/cli/tx.go @@ -26,7 +26,7 @@ func GetCmdCreateClient(cdc *codec.Codec) *cobra.Command { Long: strings.TrimSpace(fmt.Sprintf(`create new localhost (loopback) client: Example: $ %s tx ibc client localhost create --from node0 --home ../node0/cli --chain-id $CID -`, version.ClientName), +`, version.AppName), ), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 7a8cc8c29487..3b16ab11819f 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -53,7 +53,7 @@ Where proposal.json contains: "deposit": "1000stake" } `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 4d2fa8fea5d6..29af3439166f 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -55,7 +55,7 @@ func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { Example: $ %s query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -98,7 +98,7 @@ func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { Example: $ %s query staking validators `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -135,7 +135,7 @@ func GetCmdQueryValidatorUnbondingDelegations(queryRoute string, cdc *codec.Code Example: $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -182,7 +182,7 @@ func GetCmdQueryValidatorRedelegations(queryRoute string, cdc *codec.Codec) *cob Example: $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -226,7 +226,7 @@ func GetCmdQueryDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { Example: $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(2), @@ -276,7 +276,7 @@ func GetCmdQueryDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command Example: $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -321,7 +321,7 @@ func GetCmdQueryValidatorDelegations(queryRoute string, cdc *codec.Codec) *cobra Example: $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -371,7 +371,7 @@ func GetCmdQueryUnbondingDelegation(queryRoute string, cdc *codec.Codec) *cobra. Example: $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(2), @@ -421,7 +421,7 @@ func GetCmdQueryUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra Example: $ %s query staking unbonding-delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(1), @@ -466,7 +466,7 @@ func GetCmdQueryRedelegation(queryRoute string, cdc *codec.Codec) *cobra.Command Example: $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, - version.ClientName, + version.AppName, ), ), Args: cobra.ExactArgs(3), @@ -522,7 +522,7 @@ func GetCmdQueryRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Comman Example: $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -566,7 +566,7 @@ func GetCmdQueryHistoricalInfo(queryRoute string, cdc *codec.Codec) *cobra.Comma Example: $ %s query staking historical-info 5 `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -610,7 +610,7 @@ func GetCmdQueryPool(storeName string, cdc *codec.Codec) *cobra.Command { Example: $ %s query staking pool `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -643,7 +643,7 @@ func GetCmdQueryParams(storeName string, cdc *codec.Codec) *cobra.Command { Example: $ %s query staking params `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 324230c02d16..08e5633addd1 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -154,7 +154,7 @@ func NewDelegateCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -194,7 +194,7 @@ func NewRedelegateCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 100stake --from mykey `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { @@ -239,7 +239,7 @@ func NewUnbondCmd(clientCtx client.Context) *cobra.Command { Example: $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from mykey `, - version.ClientName, + version.AppName, ), ), RunE: func(cmd *cobra.Command, args []string) error { From 3b346aeecc91f5701454c2699ee61877c34b1630 Mon Sep 17 00:00:00 2001 From: DauTT Date: Tue, 30 Jun 2020 22:08:33 +0200 Subject: [PATCH 11/33] 1) Remove global variables 2) Fix integration test issue related to the gentx command which was not working properly due to using gloabal variables --- x/staking/client/cli/flags.go | 107 ++++++++++++++++++++++------------ x/staking/client/cli/tx.go | 24 ++++---- 2 files changed, 83 insertions(+), 48 deletions(-) diff --git a/x/staking/client/cli/flags.go b/x/staking/client/cli/flags.go index 3312e2fc2238..e84be5785afb 100644 --- a/x/staking/client/cli/flags.go +++ b/x/staking/client/cli/flags.go @@ -32,41 +32,76 @@ const ( FlagIP = "ip" ) -// common flagsets to add to various functions -var ( - FsPk = flag.NewFlagSet("", flag.ContinueOnError) - FsAmount = flag.NewFlagSet("", flag.ContinueOnError) - fsShares = flag.NewFlagSet("", flag.ContinueOnError) - fsDescriptionCreate = flag.NewFlagSet("", flag.ContinueOnError) - FsCommissionCreate = flag.NewFlagSet("", flag.ContinueOnError) - fsCommissionUpdate = flag.NewFlagSet("", flag.ContinueOnError) - FsMinSelfDelegation = flag.NewFlagSet("", flag.ContinueOnError) - fsDescriptionEdit = flag.NewFlagSet("", flag.ContinueOnError) - fsValidator = flag.NewFlagSet("", flag.ContinueOnError) - fsRedelegation = flag.NewFlagSet("", flag.ContinueOnError) -) +// Define common flagsets to add to various functions + +func FsPk() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagPubKey, "", "The Bech32 encoded PubKey of the validator") + return f +} + +func FsAmount() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagAmount, "", "Amount of coins to bond") + return f +} + +func fsShares() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagSharesAmount, "", "Amount of source-shares to either unbond or redelegate as a positive integer or decimal") + f.String(FlagSharesFraction, "", "Fraction of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1") + return f +} + +func fsDescriptionCreate() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagMoniker, "", "The validator's name") + f.String(FlagIdentity, "", "The optional identity signature (ex. UPort or Keybase)") + f.String(FlagWebsite, "", "The validator's (optional) website") + f.String(FlagSecurityContact, "", "The validator's (optional) security contact email") + f.String(FlagDetails, "", "The validator's (optional) details") + return f +} + +func fsCommissionUpdate() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagCommissionRate, "", "The new commission rate percentage") + return f +} + +func FsCommissionCreate() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagCommissionRate, "", "The initial commission rate percentage") + f.String(FlagCommissionMaxRate, "", "The maximum commission rate percentage") + f.String(FlagCommissionMaxChangeRate, "", "The maximum commission change rate percentage (per day)") + return f +} + +func FsMinSelfDelegation() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagMinSelfDelegation, "", "The minimum self delegation required on the validator") + return f +} + +func fsDescriptionEdit() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagMoniker, types.DoNotModifyDesc, "The validator's name") + f.String(FlagIdentity, types.DoNotModifyDesc, "The (optional) identity signature (ex. UPort or Keybase)") + f.String(FlagWebsite, types.DoNotModifyDesc, "The validator's (optional) website") + f.String(FlagSecurityContact, types.DoNotModifyDesc, "The validator's (optional) security contact email") + f.String(FlagDetails, types.DoNotModifyDesc, "The validator's (optional) details") + return f +} + +func fsValidator() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagAddressValidator, "", "The Bech32 address of the validator") + return f +} -func init() { - FsPk.String(FlagPubKey, "", "The Bech32 encoded PubKey of the validator") - FsAmount.String(FlagAmount, "", "Amount of coins to bond") - fsShares.String(FlagSharesAmount, "", "Amount of source-shares to either unbond or redelegate as a positive integer or decimal") - fsShares.String(FlagSharesFraction, "", "Fraction of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1") - fsDescriptionCreate.String(FlagMoniker, "", "The validator's name") - fsDescriptionCreate.String(FlagIdentity, "", "The optional identity signature (ex. UPort or Keybase)") - fsDescriptionCreate.String(FlagWebsite, "", "The validator's (optional) website") - fsDescriptionCreate.String(FlagSecurityContact, "", "The validator's (optional) security contact email") - fsDescriptionCreate.String(FlagDetails, "", "The validator's (optional) details") - fsCommissionUpdate.String(FlagCommissionRate, "", "The new commission rate percentage") - FsCommissionCreate.String(FlagCommissionRate, "", "The initial commission rate percentage") - FsCommissionCreate.String(FlagCommissionMaxRate, "", "The maximum commission rate percentage") - FsCommissionCreate.String(FlagCommissionMaxChangeRate, "", "The maximum commission change rate percentage (per day)") - FsMinSelfDelegation.String(FlagMinSelfDelegation, "", "The minimum self delegation required on the validator") - fsDescriptionEdit.String(FlagMoniker, types.DoNotModifyDesc, "The validator's name") - fsDescriptionEdit.String(FlagIdentity, types.DoNotModifyDesc, "The (optional) identity signature (ex. UPort or Keybase)") - fsDescriptionEdit.String(FlagWebsite, types.DoNotModifyDesc, "The validator's (optional) website") - fsDescriptionEdit.String(FlagSecurityContact, types.DoNotModifyDesc, "The validator's (optional) security contact email") - fsDescriptionEdit.String(FlagDetails, types.DoNotModifyDesc, "The validator's (optional) details") - fsValidator.String(FlagAddressValidator, "", "The Bech32 address of the validator") - fsRedelegation.String(FlagAddressValidatorSrc, "", "The Bech32 address of the source validator") - fsRedelegation.String(FlagAddressValidatorDst, "", "The Bech32 address of the destination validator") +func fsRedelegation() *flag.FlagSet { + f := flag.NewFlagSet("", flag.ContinueOnError) + f.String(FlagAddressValidatorSrc, "", "The Bech32 address of the source validator") + f.String(FlagAddressValidatorDst, "", "The Bech32 address of the destination validator") + return f } diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 08e5633addd1..c53ed15b11d1 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -69,11 +69,11 @@ func NewCreateValidatorCmd(clientCtx client.Context) *cobra.Command { return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) }, } - cmd.Flags().AddFlagSet(FsPk) - cmd.Flags().AddFlagSet(FsAmount) - cmd.Flags().AddFlagSet(fsDescriptionCreate) - cmd.Flags().AddFlagSet(FsCommissionCreate) - cmd.Flags().AddFlagSet(FsMinSelfDelegation) + cmd.Flags().AddFlagSet(FsPk()) + cmd.Flags().AddFlagSet(FsAmount()) + cmd.Flags().AddFlagSet(fsDescriptionCreate()) + cmd.Flags().AddFlagSet(FsCommissionCreate()) + cmd.Flags().AddFlagSet(FsMinSelfDelegation()) cmd.Flags().String(FlagIP, "", fmt.Sprintf("The node's public IP. It takes effect only when used in combination with --%s", flags.FlagGenerateOnly)) cmd.Flags().String(FlagNodeID, "", "The node's ID") @@ -136,9 +136,9 @@ func NewEditValidatorCmd(clientCtx client.Context) *cobra.Command { }, } - cmd.Flags().AddFlagSet(fsDescriptionEdit) - cmd.Flags().AddFlagSet(fsCommissionUpdate) - cmd.Flags().AddFlagSet(FsMinSelfDelegation) + cmd.Flags().AddFlagSet(fsDescriptionEdit()) + cmd.Flags().AddFlagSet(fsCommissionUpdate()) + cmd.Flags().AddFlagSet(FsMinSelfDelegation()) return cmd } @@ -337,10 +337,10 @@ func CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, fsCreateValidator.String(FlagSecurityContact, "", "The validator's (optional) security contact email") fsCreateValidator.String(FlagDetails, "", "The validator's (optional) details") fsCreateValidator.String(FlagIdentity, "", "The (optional) identity signature (ex. UPort or Keybase)") - fsCreateValidator.AddFlagSet(FsCommissionCreate) - fsCreateValidator.AddFlagSet(FsMinSelfDelegation) - fsCreateValidator.AddFlagSet(FsAmount) - fsCreateValidator.AddFlagSet(FsPk) + fsCreateValidator.AddFlagSet(FsCommissionCreate()) + fsCreateValidator.AddFlagSet(FsMinSelfDelegation()) + fsCreateValidator.AddFlagSet(FsAmount()) + fsCreateValidator.AddFlagSet(FsPk()) defaultsDesc = fmt.Sprintf(` delegation amount: %s From e80e1b331276fb912621c2558a8177d24c95f590 Mon Sep 17 00:00:00 2001 From: DauTT Date: Tue, 30 Jun 2020 23:08:32 +0200 Subject: [PATCH 12/33] Fix lint error message (Remove unused flags: fsShares, fsValidator, fsRedelegation) Update Dockerfile --- Dockerfile | 5 ++--- x/staking/client/cli/flags.go | 20 -------------------- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/Dockerfile b/Dockerfile index 34ae16ec2513..b6a305ad4bb2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,8 +7,8 @@ # > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simapp:/root/.simapp simapp simd start # # Client: (Note the simapp binary always looks at ~/.simapp we can bind to different local storage) -# > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simcli keys add foo -# > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simcli keys list +# > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simd keys add foo +# > docker run -it -p 26657:26657 -p 26656:26656 -v ~/.simappcli:/root/.simapp simapp simd keys list # TODO: demo connecting rest-server (or is this in server now?) FROM golang:alpine AS build-env @@ -38,7 +38,6 @@ WORKDIR /root # Copy over binaries from the build-env COPY --from=build-env /go/bin/simd /usr/bin/simd -COPY --from=build-env /go/bin/simcli /usr/bin/simcli EXPOSE 26656 26657 1317 diff --git a/x/staking/client/cli/flags.go b/x/staking/client/cli/flags.go index e84be5785afb..35fd622f0958 100644 --- a/x/staking/client/cli/flags.go +++ b/x/staking/client/cli/flags.go @@ -46,13 +46,6 @@ func FsAmount() *flag.FlagSet { return f } -func fsShares() *flag.FlagSet { - f := flag.NewFlagSet("", flag.ContinueOnError) - f.String(FlagSharesAmount, "", "Amount of source-shares to either unbond or redelegate as a positive integer or decimal") - f.String(FlagSharesFraction, "", "Fraction of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1") - return f -} - func fsDescriptionCreate() *flag.FlagSet { f := flag.NewFlagSet("", flag.ContinueOnError) f.String(FlagMoniker, "", "The validator's name") @@ -92,16 +85,3 @@ func fsDescriptionEdit() *flag.FlagSet { f.String(FlagDetails, types.DoNotModifyDesc, "The validator's (optional) details") return f } - -func fsValidator() *flag.FlagSet { - f := flag.NewFlagSet("", flag.ContinueOnError) - f.String(FlagAddressValidator, "", "The Bech32 address of the validator") - return f -} - -func fsRedelegation() *flag.FlagSet { - f := flag.NewFlagSet("", flag.ContinueOnError) - f.String(FlagAddressValidatorSrc, "", "The Bech32 address of the source validator") - f.String(FlagAddressValidatorDst, "", "The Bech32 address of the destination validator") - return f -} From 2b58e8df70f215fe163e27d174224413bff5641f Mon Sep 17 00:00:00 2001 From: DauTT Date: Thu, 2 Jul 2020 00:20:36 +0200 Subject: [PATCH 13/33] Delete TODO during the merge. Added it back --- cmd/simd/client.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cmd/simd/client.go b/cmd/simd/client.go index 3427323f8901..0c5022b932e9 100644 --- a/cmd/simd/client.go +++ b/cmd/simd/client.go @@ -32,6 +32,10 @@ func init() { func addClientCommands(rootClientCmd *cobra.Command) { + // TODO: setup keybase, viper object, etc. to be passed into + // the below functions and eliminate global vars, like we do + // with the cdc + // Add --chain-id to persistent flags and mark it required rootClientCmd.PersistentFlags().String(flags.FlagChainID, "", "network chain ID") From 052db8c72974e3f049ce5baa29f280f2a0fe435a Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Thu, 2 Jul 2020 09:03:46 -0400 Subject: [PATCH 14/33] Apply suggestions from code review Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- version/version.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/version/version.go b/version/version.go index ef8146f2d209..1e40d483db0b 100644 --- a/version/version.go +++ b/version/version.go @@ -10,8 +10,7 @@ // can be passed as build flags as shown in the following example: // // go build -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ -// -X github.com/cosmos/cosmos-sdk/version.ServerName=gaiad \ -// -X github.com/cosmos/cosmos-sdk/version.AppName=gaiacli \ +// -X github.com/cosmos/cosmos-sdk/version.AppName=gaiad \ // -X github.com/cosmos/cosmos-sdk/version.Version=1.0 \ // -X github.com/cosmos/cosmos-sdk/version.Commit=f0f7b7dab7e36c20b757cebce0e8f4fc5b95de60 \ // -X "github.com/cosmos/cosmos-sdk/version.BuildTags=linux darwin amd64" From bc30fd2d086f25b289114b3f8145058b5a69e765 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 3 Jul 2020 10:00:00 -0400 Subject: [PATCH 15/33] Init commit --- Makefile | 14 ++++---- simapp/simd/cmd/root.go | 34 +++++++++++++++++++ {cmd/simd => simapp/simd/cmd_old}/client.go | 0 {cmd/simd => simapp/simd/cmd_old}/daemon.go | 0 .../simd/cmd_old}/genaccounts.go | 0 {cmd/simd => simapp/simd/cmd_old}/main.go | 0 {cmd/simd => simapp/simd/cmd_old}/testnet.go | 0 simapp/simd/main.go | 13 +++++++ 8 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 simapp/simd/cmd/root.go rename {cmd/simd => simapp/simd/cmd_old}/client.go (100%) rename {cmd/simd => simapp/simd/cmd_old}/daemon.go (100%) rename {cmd/simd => simapp/simd/cmd_old}/genaccounts.go (100%) rename {cmd/simd => simapp/simd/cmd_old}/main.go (100%) rename {cmd/simd => simapp/simd/cmd_old}/testnet.go (100%) create mode 100644 simapp/simd/main.go diff --git a/Makefile b/Makefile index 3e10c3fef9c3..f8e5bbc33e0c 100644 --- a/Makefile +++ b/Makefile @@ -26,14 +26,14 @@ all: tools build lint test build: go.sum @go build -mod=readonly ./... -build-sim: go.sum +build-simapp: go.sum mkdir -p $(BUILDDIR) - go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./cmd/simd + go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/simd -build-sim-linux: go.sum - LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-sim +build-simapp-linux: go.sum + LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-simapp -.PHONY: build build-sim build-sim-linux +.PHONY: build build-simapp build-simapp-linux mocks: $(MOCKS_DIR) mockgen -source=client/account_retriever.go -package mocks -destination tests/mocks/account_retriever.go @@ -128,7 +128,7 @@ test-unit: test-race: @VERSION=$(VERSION) go test -mod=readonly -race $(PACKAGES_NOSIMULATION) -test-integration: build-sim +test-integration: build-simapp BUILDDIR=$(BUILDDIR) go test -mod=readonly -p 4 -tags='ledger test_ledger_mock cli_test' -run ^TestCLI `go list ./.../cli/...` .PHONY: test test-all test-ledger-mock test-ledger test-unit test-race @@ -320,7 +320,7 @@ build-docker-local-simapp: @$(MAKE) -C networks/local # Run a 4-node testnet locally -localnet-start: build-sim-linux localnet-stop +localnet-start: build-simapp-linux localnet-stop @if ! [ -f build/node0/simd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/simd:Z cosmos-sdk/simappnode testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi docker-compose up -d diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go new file mode 100644 index 000000000000..7e282eccc84c --- /dev/null +++ b/simapp/simd/cmd/root.go @@ -0,0 +1,34 @@ +package cmd + +import ( + "context" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" +) + +var ( + rootCmd = &cobra.Command{ + Use: "simd", + Short: "simulation app", + } +) + +// Execute executes the root command. +func Execute() error { + // Create and set a client.Context on the command's Context. During the pre-run + // of the root command, a default initialized client.Context is provided to + // seed child command execution with values such as AccountRetriver, Keyring, + // and a Tendermint RPC. This requires the use of a pointer reference when + // getting and setting the client.Context. Ideally, we utilize + // https://github.com/spf13/cobra/pull/1118. + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{}) + + return rootCmd.ExecuteContext(ctx) +} + +func init() { + +} diff --git a/cmd/simd/client.go b/simapp/simd/cmd_old/client.go similarity index 100% rename from cmd/simd/client.go rename to simapp/simd/cmd_old/client.go diff --git a/cmd/simd/daemon.go b/simapp/simd/cmd_old/daemon.go similarity index 100% rename from cmd/simd/daemon.go rename to simapp/simd/cmd_old/daemon.go diff --git a/cmd/simd/genaccounts.go b/simapp/simd/cmd_old/genaccounts.go similarity index 100% rename from cmd/simd/genaccounts.go rename to simapp/simd/cmd_old/genaccounts.go diff --git a/cmd/simd/main.go b/simapp/simd/cmd_old/main.go similarity index 100% rename from cmd/simd/main.go rename to simapp/simd/cmd_old/main.go diff --git a/cmd/simd/testnet.go b/simapp/simd/cmd_old/testnet.go similarity index 100% rename from cmd/simd/testnet.go rename to simapp/simd/cmd_old/testnet.go diff --git a/simapp/simd/main.go b/simapp/simd/main.go new file mode 100644 index 000000000000..3cc818a49f5c --- /dev/null +++ b/simapp/simd/main.go @@ -0,0 +1,13 @@ +package main + +import ( + "os" + + "github.com/cosmos/cosmos-sdk/simapp/simd/cmd" +) + +func main() { + if err := cmd.Execute(); err != nil { + os.Exit(1) + } +} From 73f22f54210f83419127ce81f5d12d21524740c9 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 3 Jul 2020 12:12:24 -0400 Subject: [PATCH 16/33] remove viper start --- client/keys/add.go | 88 ++++++---- client/keys/root.go | 6 +- server/start.go | 3 + server/util.go | 10 +- simapp/simd/{cmd_old => cmd}/genaccounts.go | 6 +- simapp/simd/cmd/root.go | 172 ++++++++++++++++++++ simapp/simd/{cmd_old => cmd}/testnet.go | 23 +-- simapp/simd/cmd_old/client.go | 110 ------------- simapp/simd/cmd_old/daemon.go | 102 ------------ simapp/simd/cmd_old/main.go | 36 ---- x/genutil/client/cli/init.go | 2 +- 11 files changed, 247 insertions(+), 311 deletions(-) rename simapp/simd/{cmd_old => cmd}/genaccounts.go (99%) rename simapp/simd/{cmd_old => cmd}/testnet.go (92%) delete mode 100644 simapp/simd/cmd_old/client.go delete mode 100644 simapp/simd/cmd_old/daemon.go delete mode 100644 simapp/simd/cmd_old/main.go diff --git a/client/keys/add.go b/client/keys/add.go index 90946ab98ade..acc4154c23ce 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -5,10 +5,13 @@ import ( "bytes" "errors" "fmt" - "io" "sort" bip39 "github.com/cosmos/go-bip39" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" @@ -16,14 +19,10 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/libs/cli" ) +var v = viper.New() + const ( flagInteractive = "interactive" flagRecover = "recover" @@ -80,26 +79,43 @@ the flag --nosort is set. cmd.Flags().Uint32(flagIndex, 0, "Address index number for HD derivation") cmd.Flags().String(flagKeyAlgo, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") - return cmd -} + v.BindPFlag(flagMultisig, cmd.Flags().Lookup(flagMultisig)) + v.BindPFlag(flagMultiSigThreshold, cmd.Flags().Lookup(flagMultiSigThreshold)) + v.BindPFlag(flagNoSort, cmd.Flags().Lookup(flagNoSort)) + v.BindPFlag(FlagPublicKey, cmd.Flags().Lookup(FlagPublicKey)) + v.BindPFlag(flagInteractive, cmd.Flags().Lookup(flagInteractive)) + v.BindPFlag(flags.FlagUseLedger, cmd.Flags().Lookup(flags.FlagUseLedger)) + v.BindPFlag(flagRecover, cmd.Flags().Lookup(flagRecover)) + v.BindPFlag(flagNoBackup, cmd.Flags().Lookup(flagNoBackup)) + v.BindPFlag(flags.FlagDryRun, cmd.Flags().Lookup(flags.FlagDryRun)) + v.BindPFlag(flagHDPath, cmd.Flags().Lookup(flagHDPath)) + v.BindPFlag(flagCoinType, cmd.Flags().Lookup(flagCoinType)) + v.BindPFlag(flagAccount, cmd.Flags().Lookup(flagAccount)) + v.BindPFlag(flagIndex, cmd.Flags().Lookup(flagIndex)) + v.BindPFlag(flagKeyAlgo, cmd.Flags().Lookup(flagKeyAlgo)) -func getKeybase(transient bool, buf io.Reader) (keyring.Keyring, error) { - if transient { - return keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, viper.GetString(flags.FlagHome), buf) - } - - return keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), buf) + return cmd } func runAddCmd(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) - kb, err := getKeybase(viper.GetBool(flags.FlagDryRun), inBuf) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + var ( + kr keyring.Keyring + err error + ) + + if v.GetBool(flags.FlagDryRun) { + kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, homeDir, inBuf) + } else { + kr, err = keyring.New(sdk.KeyringServiceName(), rootViper.GetString(flags.FlagKeyringBackend), homeDir, inBuf) + } if err != nil { return err } - return RunAddCmd(cmd, args, kb, inBuf) + return RunAddCmd(cmd, args, kr, inBuf) } /* @@ -116,16 +132,16 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf name := args[0] - interactive := viper.GetBool(flagInteractive) - showMnemonic := !viper.GetBool(flagNoBackup) + interactive := v.GetBool(flagInteractive) + showMnemonic := !v.GetBool(flagNoBackup) keyringAlgos, _ := kb.SupportedAlgorithms() - algo, err := keyring.NewSigningAlgoFromString(viper.GetString(flagKeyAlgo), keyringAlgos) + algo, err := keyring.NewSigningAlgoFromString(v.GetString(flagKeyAlgo), keyringAlgos) if err != nil { return err } - if !viper.GetBool(flags.FlagDryRun) { + if !v.GetBool(flags.FlagDryRun) { _, err = kb.Key(name) if err == nil { // account exists, ask for user confirmation @@ -144,11 +160,11 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } } - multisigKeys := viper.GetStringSlice(flagMultisig) + multisigKeys := v.GetStringSlice(flagMultisig) if len(multisigKeys) != 0 { var pks []crypto.PubKey - multisigThreshold := viper.GetInt(flagMultiSigThreshold) + multisigThreshold := v.GetInt(flagMultiSigThreshold) if err := validateMultisigThreshold(multisigThreshold, len(multisigKeys)); err != nil { return err } @@ -163,7 +179,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } // Handle --nosort - if !viper.GetBool(flagNoSort) { + if !v.GetBool(flagNoSort) { sort.Slice(pks, func(i, j int) bool { return bytes.Compare(pks[i].Address(), pks[j].Address()) < 0 }) @@ -180,8 +196,8 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } } - if viper.GetString(FlagPublicKey) != "" { - pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, viper.GetString(FlagPublicKey)) + if v.GetString(FlagPublicKey) != "" { + pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, v.GetString(FlagPublicKey)) if err != nil { return err } @@ -193,19 +209,19 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf return nil } - coinType := uint32(viper.GetInt(flagCoinType)) - account := uint32(viper.GetInt(flagAccount)) - index := uint32(viper.GetInt(flagIndex)) - hdPath := viper.GetString(flagHDPath) + coinType := uint32(v.GetInt(flagCoinType)) + account := uint32(v.GetInt(flagAccount)) + index := uint32(v.GetInt(flagIndex)) + hdPath := v.GetString(flagHDPath) if len(hdPath) == 0 { hdPath = hd.CreateHDPath(coinType, account, index).String() - } else if viper.GetBool(flags.FlagUseLedger) { + } else if v.GetBool(flags.FlagUseLedger) { return errors.New("cannot set custom bip32 path with ledger") } // If we're using ledger, only thing we need is the path and the bech32 prefix. - if viper.GetBool(flags.FlagUseLedger) { + if v.GetBool(flags.FlagUseLedger) { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() info, err := kb.SaveLedgerKey(name, hd.Secp256k1, bech32PrefixAccAddr, coinType, account, index) @@ -219,9 +235,9 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf // Get bip39 mnemonic var mnemonic, bip39Passphrase string - if interactive || viper.GetBool(flagRecover) { + if interactive || v.GetBool(flagRecover) { bip39Message := "Enter your bip39 mnemonic" - if !viper.GetBool(flagRecover) { + if !v.GetBool(flagRecover) { bip39Message = "Enter your bip39 mnemonic, or hit enter to generate one." } @@ -276,7 +292,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } // Recover key from seed passphrase - if viper.GetBool(flagRecover) { + if v.GetBool(flagRecover) { // Hide mnemonic from output showMnemonic = false mnemonic = "" @@ -286,7 +302,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic string) error { - output := viper.Get(cli.OutputFlag) + output := v.Get(cli.OutputFlag) switch output { case OutputFormatText: diff --git a/client/keys/root.go b/client/keys/root.go index 801cc065aedd..c432b23bc3e1 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -7,6 +7,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" ) +var rootViper = viper.New() + // Commands registers a sub-tree of commands to interact with // local private key storage. func Commands() *cobra.Command { @@ -48,7 +50,9 @@ The pass backend requires GnuPG: https://gnupg.org/ ParseKeyStringCommand(), MigrateCommand(), ) + cmd.PersistentFlags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") - viper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend)) + rootViper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend)) + return cmd } diff --git a/server/start.go b/server/start.go index a0f6d263abdd..6ed2f8a210e6 100644 --- a/server/start.go +++ b/server/start.go @@ -37,6 +37,7 @@ const ( FlagHaltTime = "halt-time" FlagInterBlockCache = "inter-block-cache" FlagUnsafeSkipUpgrades = "unsafe-skip-upgrades" + FlagInvCheckPeriod = "inv-check-period" FlagPruning = "pruning" FlagPruningKeepRecent = "pruning-keep-recent" @@ -102,11 +103,13 @@ which accepts a path for the resulting pprof file. 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") cmd.Flags().String(flagCPUProfile, "", "Enable CPU profiling and write to the provided file") + cmd.PersistentFlags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") cmd.Flags().String(FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") cmd.Flags().Uint64(FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") cmd.Flags().Uint64(FlagPruningKeepEvery, 0, "Offset heights to keep on disk after 'keep-every' (ignored if pruning is not 'custom')") cmd.Flags().Uint64(FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')") + viper.BindPFlag(FlagPruning, cmd.Flags().Lookup(FlagPruning)) viper.BindPFlag(FlagPruningKeepRecent, cmd.Flags().Lookup(FlagPruningKeepRecent)) viper.BindPFlag(FlagPruningKeepEvery, cmd.Flags().Lookup(FlagPruningKeepEvery)) diff --git a/server/util.go b/server/util.go index 69c8f1f4159e..984bf2938458 100644 --- a/server/util.go +++ b/server/util.go @@ -16,7 +16,6 @@ import ( tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/libs/cli" tmflags "github.com/tendermint/tendermint/libs/cli/flags" "github.com/tendermint/tendermint/libs/log" @@ -43,8 +42,6 @@ func NewContext(config *cfg.Config, logger log.Logger) *Context { return &Context{config, logger} } -//___________________________________________________________________________________ - // PersistentPreRunEFn returns a PersistentPreRunE function for cobra // that initailizes the passed in context with a properly configured // logger and config object. @@ -65,9 +62,10 @@ func PersistentPreRunEFn(context *Context) func(*cobra.Command, []string) error return err } - if viper.GetBool(cli.TraceFlag) { - logger = log.NewTracingLogger(logger) - } + // TODO: Merge master to get trace flag. + // if viper.GetBool(cli.TraceFlag) { + // logger = log.NewTracingLogger(logger) + // } logger = logger.With("module", "main") context.Config = config diff --git a/simapp/simd/cmd_old/genaccounts.go b/simapp/simd/cmd/genaccounts.go similarity index 99% rename from simapp/simd/cmd_old/genaccounts.go rename to simapp/simd/cmd/genaccounts.go index be51bfdb34ac..78a7666d3e74 100644 --- a/simapp/simd/cmd_old/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -1,18 +1,16 @@ -package main +package cmd import ( "bufio" "errors" "fmt" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 7e282eccc84c..213a1578e55c 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -2,17 +2,54 @@ package cmd import ( "context" + "encoding/json" + "io" + "os" "github.com/spf13/cobra" + "github.com/spf13/viper" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking" ) +// TODO: Go through all functions and methods called here and ensure global Viper +// usage is removed. +// +// REF: https://github.com/cosmos/cosmos-sdk/issues/6571 + var ( rootCmd = &cobra.Command{ Use: "simd", Short: "simulation app", } + + encodingConfig = simapp.MakeEncodingConfig() + initClientCtx = client.Context{}. + WithJSONMarshaler(encodingConfig.Marshaler). + WithTxGenerator(encodingConfig.TxGenerator). + WithCodec(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)). + WithBroadcastMode(flags.BroadcastBlock) ) // Execute executes the root command. @@ -30,5 +67,140 @@ func Execute() error { } func init() { + authclient.Codec = encodingConfig.Marshaler + + // add application daemon commands + cdc := encodingConfig.Amino + ctx := server.NewDefaultContext() + // rootCmd.PersistentPreRunE = server.PersistentPreRunEFn(ctx) + rootCmd.PersistentFlags().String(flags.FlagHome, simapp.DefaultNodeHome, "The application's root directory") + + rootCmd.AddCommand( + genutilcli.InitCmd(ctx, cdc, simapp.ModuleBasics, simapp.DefaultNodeHome), + genutilcli.CollectGenTxsCmd(ctx, cdc, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), + genutilcli.MigrateGenesisCmd(ctx, cdc), + genutilcli.GenTxCmd( + ctx, cdc, simapp.ModuleBasics, staking.AppModuleBasic{}, + banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome, simapp.DefaultNodeHome, + ), + genutilcli.ValidateGenesisCmd(ctx, cdc, simapp.ModuleBasics), + AddGenesisAccountCmd(ctx, cdc, encodingConfig.Marshaler, simapp.DefaultNodeHome, simapp.DefaultCLIHome), + flags.NewCompletionCmd(rootCmd, true), + testnetCmd(ctx, cdc, simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), + debug.Cmd(cdc), + ) + + server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) + + // add keybase, auxiliary RPC, query, and tx child commands + rootCmd.AddCommand( + rpc.StatusCommand(), + queryCommand(), + txCommand(), + keys.Commands(), + ) +} + +func queryCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + return client.SetCmdClientContextHandler(initClientCtx, cmd) + }, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetAccountCmd(encodingConfig.Amino), + rpc.ValidatorCommand(encodingConfig.Amino), + rpc.BlockCommand(), + authcmd.QueryTxsByEventsCmd(encodingConfig.Amino), + authcmd.QueryTxCmd(encodingConfig.Amino), + ) + + simapp.ModuleBasics.AddQueryCommands(cmd, initClientCtx) + cmd.PersistentFlags().String(flags.FlagChainID, "", "network chain ID") + + return cmd +} + +func txCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + return client.SetCmdClientContextHandler(initClientCtx, cmd) + }, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetSignCommand(initClientCtx), + authcmd.GetSignBatchCommand(encodingConfig.Amino), + authcmd.GetMultiSignCommand(initClientCtx), + authcmd.GetValidateSignaturesCommand(initClientCtx), + flags.LineBreak, + authcmd.GetBroadcastCommand(initClientCtx), + authcmd.GetEncodeCommand(initClientCtx), + authcmd.GetDecodeCommand(initClientCtx), + flags.LineBreak, + ) + + simapp.ModuleBasics.AddTxCommands(cmd, initClientCtx) + cmd.PersistentFlags().String(flags.FlagChainID, "", "network chain ID") + + return cmd +} + +func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) server.Application { + var cache sdk.MultiStorePersistentCache + + if viper.GetBool(server.FlagInterBlockCache) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { + skipUpgradeHeights[int64(h)] = true + } + + pruningOpts, err := server.GetPruningOptionsFromFlags() + if err != nil { + panic(err) + } + + return simapp.NewSimApp( + logger, db, traceStore, true, skipUpgradeHeights, + viper.GetString(flags.FlagHome), viper.GetUint(server.FlagInvCheckPeriod), + baseapp.SetPruning(pruningOpts), + baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), + baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), + baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), + baseapp.SetInterBlockCache(cache), + ) +} + +func exportAppStateAndTMValidators( + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, +) (json.RawMessage, []tmtypes.GenesisValidator, *abci.ConsensusParams, error) { + + var simApp *simapp.SimApp + if height != -1 { + simApp = simapp.NewSimApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1)) + + err := simApp.LoadHeight(height) + if err != nil { + return nil, nil, nil, err + } + } else { + simApp = simapp.NewSimApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1)) + } + return simApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } diff --git a/simapp/simd/cmd_old/testnet.go b/simapp/simd/cmd/testnet.go similarity index 92% rename from simapp/simd/cmd_old/testnet.go rename to simapp/simd/cmd/testnet.go index 09b1feca29a5..0e1a3ba55832 100644 --- a/simapp/simd/cmd_old/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -1,4 +1,4 @@ -package main +package cmd // DONTCOVER @@ -78,20 +78,13 @@ Example: }, } - cmd.Flags().Int(flagNumValidators, 4, - "Number of validators to initialize the testnet with") - cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", - "Directory to store initialization data for the testnet") - cmd.Flags().String(flagNodeDirPrefix, "node", - "Prefix the directory name for each node with (node results in node0, node1, ...)") - cmd.Flags().String(flagNodeDaemonHome, "simd", - "Home directory of the node's daemon configuration") - cmd.Flags().String(flagNodeCLIHome, "simcli", - "Home directory of the node's cli configuration") - cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", - "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") - cmd.Flags().String( - flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") + cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with") + cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", "Directory to store initialization data for the testnet") + cmd.Flags().String(flagNodeDirPrefix, "node", "Prefix the directory name for each node with (node results in node0, node1, ...)") + cmd.Flags().String(flagNodeDaemonHome, "simd", "Home directory of the node's daemon configuration") + cmd.Flags().String(flagNodeCLIHome, "simcli", "Home directory of the node's cli configuration") + cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") + cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") cmd.Flags().String( server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") diff --git a/simapp/simd/cmd_old/client.go b/simapp/simd/cmd_old/client.go deleted file mode 100644 index b7f08fb9addd..000000000000 --- a/simapp/simd/cmd_old/client.go +++ /dev/null @@ -1,110 +0,0 @@ -package main - -import ( - "context" - "os" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/simapp" - authclient "github.com/cosmos/cosmos-sdk/x/auth/client" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/auth/types" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" -) - -var ( - encodingConfig = simapp.MakeEncodingConfig() - initClientCtx = client.Context{}. - WithJSONMarshaler(encodingConfig.Marshaler). - WithTxGenerator(encodingConfig.TxGenerator). - WithCodec(encodingConfig.Amino). - WithInput(os.Stdin). - WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)). - WithBroadcastMode(flags.BroadcastBlock) -) - -func init() { - authclient.Codec = encodingConfig.Marshaler -} - -// TODO: setup keybase, viper object, etc. to be passed into -// the below functions and eliminate global vars, like we do -// with the cdc -func addClientCommands(rootClientCmd *cobra.Command) context.Context { - // Add --chain-id to persistent flags and mark it required - rootClientCmd.PersistentFlags().String(flags.FlagChainID, "", "network chain ID") - - rootClientCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { - return client.SetCmdClientContextHandler(initClientCtx, cmd) - } - - // Construct Root Command - rootClientCmd.AddCommand( - rpc.StatusCommand(), - queryCmd(), - txCmd(), - keys.Commands(), - flags.NewCompletionCmd(rootClientCmd, true), - ) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{}) - - return ctx -} - -func queryCmd() *cobra.Command { - queryCmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - queryCmd.AddCommand( - authcmd.GetAccountCmd(encodingConfig.Amino), - rpc.ValidatorCommand(encodingConfig.Amino), - rpc.BlockCommand(), - authcmd.QueryTxsByEventsCmd(encodingConfig.Amino), - authcmd.QueryTxCmd(encodingConfig.Amino), - ) - - simapp.ModuleBasics.AddQueryCommands(queryCmd, initClientCtx) - - return queryCmd -} - -func txCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - txCmd.AddCommand( - bankcmd.NewSendTxCmd(), - flags.LineBreak, - authcmd.GetSignCommand(initClientCtx), - authcmd.GetSignBatchCommand(encodingConfig.Amino), - authcmd.GetMultiSignCommand(initClientCtx), - authcmd.GetValidateSignaturesCommand(initClientCtx), - flags.LineBreak, - authcmd.GetBroadcastCommand(initClientCtx), - authcmd.GetEncodeCommand(initClientCtx), - authcmd.GetDecodeCommand(initClientCtx), - flags.LineBreak, - ) - - simapp.ModuleBasics.AddTxCommands(txCmd, initClientCtx) - - return txCmd -} diff --git a/simapp/simd/cmd_old/daemon.go b/simapp/simd/cmd_old/daemon.go deleted file mode 100644 index d63f6eaaf86b..000000000000 --- a/simapp/simd/cmd_old/daemon.go +++ /dev/null @@ -1,102 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -const flagInvCheckPeriod = "inv-check-period" - -var invCheckPeriod uint - -func addDaemonCommands(rootDaemonCmd *cobra.Command) { - appCodec, cdc := simapp.MakeCodecs() - - ctx := server.NewDefaultContext() - rootDaemonCmd.PersistentPreRunE = server.PersistentPreRunEFn(ctx) - - rootDaemonCmd.AddCommand( - genutilcli.InitCmd(ctx, cdc, simapp.ModuleBasics, simapp.DefaultNodeHome), - genutilcli.CollectGenTxsCmd(ctx, cdc, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), - genutilcli.MigrateGenesisCmd(ctx, cdc), - genutilcli.GenTxCmd( - ctx, cdc, simapp.ModuleBasics, staking.AppModuleBasic{}, - banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome, simapp.DefaultNodeHome, - ), - genutilcli.ValidateGenesisCmd(ctx, cdc, simapp.ModuleBasics), - AddGenesisAccountCmd(ctx, cdc, appCodec, simapp.DefaultNodeHome, simapp.DefaultCLIHome), - flags.NewCompletionCmd(rootDaemonCmd, true), - testnetCmd(ctx, cdc, simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), - debug.Cmd(cdc)) - - server.AddCommands(ctx, cdc, rootDaemonCmd, newApp, exportAppStateAndTMValidators) - - // prepare and add flags - rootDaemonCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, - 0, "Assert registered invariants every N blocks") - -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) server.Application { - var cache sdk.MultiStorePersistentCache - - if viper.GetBool(server.FlagInterBlockCache) { - cache = store.NewCommitKVStoreCacheManager() - } - - skipUpgradeHeights := make(map[int64]bool) - for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { - skipUpgradeHeights[int64(h)] = true - } - - pruningOpts, err := server.GetPruningOptionsFromFlags() - if err != nil { - panic(err) - } - - // TODO: Make sure custom pruning works. - return simapp.NewSimApp( - logger, db, traceStore, true, skipUpgradeHeights, - viper.GetString(flags.FlagHome), invCheckPeriod, - baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), - baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), - baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), - baseapp.SetInterBlockCache(cache), - ) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, -) (json.RawMessage, []tmtypes.GenesisValidator, *abci.ConsensusParams, error) { - - var simApp *simapp.SimApp - if height != -1 { - simApp = simapp.NewSimApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1)) - err := simApp.LoadHeight(height) - if err != nil { - return nil, nil, nil, err - } - } else { - simApp = simapp.NewSimApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1)) - } - return simApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) -} diff --git a/simapp/simd/cmd_old/main.go b/simapp/simd/cmd_old/main.go deleted file mode 100644 index 6522e2157181..000000000000 --- a/simapp/simd/cmd_old/main.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func main() { - - cobra.EnableCommandSorting = true - - // Read in the configuration file for the sdk - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) - config.Seal() - - rootComd := &cobra.Command{ - Use: "simd", - Short: "simulation app", - } - - // Construct Root Command - ctx := addClientCommands(rootComd) - addDaemonCommands(rootComd) - - executor := cli.PrepareMainCmd(rootComd, "GA", simapp.DefaultNodeHome) - if err := executor.ExecuteContext(ctx); err != nil { - panic(err) - } - -} diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 86ac84b952b0..6797405ba98c 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -117,7 +117,7 @@ func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManag } cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") - cmd.Flags().Bool(flagOverwrite, false, "overwrite the genesis.json file") + cmd.Flags().BoolP(flagOverwrite, "o", false, "overwrite the genesis.json file") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") return cmd From f77e8316e46d817dd247046e4f426435de38eae7 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 3 Jul 2020 12:18:37 -0400 Subject: [PATCH 17/33] Makefile updates --- Makefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index f8e5bbc33e0c..409fd31fcf0a 100644 --- a/Makefile +++ b/Makefile @@ -26,14 +26,14 @@ all: tools build lint test build: go.sum @go build -mod=readonly ./... -build-simapp: go.sum +build-simd: go.sum mkdir -p $(BUILDDIR) go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/simd -build-simapp-linux: go.sum - LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-simapp +build-simd-linux: go.sum + LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build-simd -.PHONY: build build-simapp build-simapp-linux +.PHONY: build build-simd build-simd-linux mocks: $(MOCKS_DIR) mockgen -source=client/account_retriever.go -package mocks -destination tests/mocks/account_retriever.go @@ -128,7 +128,7 @@ test-unit: test-race: @VERSION=$(VERSION) go test -mod=readonly -race $(PACKAGES_NOSIMULATION) -test-integration: build-simapp +test-integration: build-simd BUILDDIR=$(BUILDDIR) go test -mod=readonly -p 4 -tags='ledger test_ledger_mock cli_test' -run ^TestCLI `go list ./.../cli/...` .PHONY: test test-all test-ledger-mock test-ledger test-unit test-race From f5bc1f07d4351083ff0ba73feb1eb520bafc3375 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 3 Jul 2020 12:20:16 -0400 Subject: [PATCH 18/33] Updates --- client/keys/root.go | 2 +- server/start.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/client/keys/root.go b/client/keys/root.go index c432b23bc3e1..9890e7d7e145 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -52,7 +52,7 @@ The pass backend requires GnuPG: https://gnupg.org/ ) cmd.PersistentFlags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") - rootViper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend)) + rootViper.BindPFlag(flags.FlagKeyringBackend, cmd.PersistentFlags().Lookup(flags.FlagKeyringBackend)) return cmd } diff --git a/server/start.go b/server/start.go index 6ed2f8a210e6..2a8254a89a22 100644 --- a/server/start.go +++ b/server/start.go @@ -103,7 +103,7 @@ which accepts a path for the resulting pprof file. 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") cmd.Flags().String(flagCPUProfile, "", "Enable CPU profiling and write to the provided file") - cmd.PersistentFlags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") + cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") cmd.Flags().String(FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") cmd.Flags().Uint64(FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") From fdf61426d5785f107f10e4d44fd248baa71338a2 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 3 Jul 2020 12:21:19 -0400 Subject: [PATCH 19/33] Updates --- client/keys/add.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/client/keys/add.go b/client/keys/add.go index acc4154c23ce..f4620fc50fd9 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -99,7 +99,6 @@ the flag --nosort is set. func runAddCmd(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) - homeDir, _ := cmd.Flags().GetString(flags.FlagHome) var ( kr keyring.Keyring @@ -107,9 +106,9 @@ func runAddCmd(cmd *cobra.Command, args []string) error { ) if v.GetBool(flags.FlagDryRun) { - kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, homeDir, inBuf) + kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, rootViper.GetString(flags.FlagHome), inBuf) } else { - kr, err = keyring.New(sdk.KeyringServiceName(), rootViper.GetString(flags.FlagKeyringBackend), homeDir, inBuf) + kr, err = keyring.New(sdk.KeyringServiceName(), rootViper.GetString(flags.FlagKeyringBackend), rootViper.GetString(flags.FlagHome), inBuf) } if err != nil { return err From 2fcf3a0ce69d39b9431371b01c50a6d2fa2dd1cc Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Mon, 6 Jul 2020 21:29:39 -0400 Subject: [PATCH 20/33] update keys pkg --- client/keys/add.go | 96 +++++++++++++-------------- client/keys/add_ledger_test.go | 59 +++++++++-------- client/keys/add_test.go | 65 +++++++++++++------ client/keys/delete.go | 72 ++++++++++----------- client/keys/delete_test.go | 53 +++++++++------ client/keys/export.go | 46 ++++++------- client/keys/export_test.go | 18 ++++-- client/keys/import.go | 44 ++++++------- client/keys/import_test.go | 18 ++++-- client/keys/list.go | 12 ++-- client/keys/list_test.go | 51 ++++++++------- client/keys/migrate.go | 17 +++-- client/keys/migrate_test.go | 36 +++++++---- client/keys/mnemonic.go | 83 ++++++++++++------------ client/keys/mnemonic_test.go | 33 ++++++---- client/keys/parse.go | 22 +++---- client/keys/root.go | 8 +-- client/keys/root_test.go | 12 ---- client/keys/show.go | 27 ++++---- client/keys/show_test.go | 115 +++++++++++++++++++++++---------- client/keys/utils.go | 10 ++- 21 files changed, 504 insertions(+), 393 deletions(-) diff --git a/client/keys/add.go b/client/keys/add.go index f4620fc50fd9..d7f3dded67e8 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -9,7 +9,6 @@ import ( bip39 "github.com/cosmos/go-bip39" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" @@ -21,8 +20,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var v = viper.New() - const ( flagInteractive = "interactive" flagRecover = "recover" @@ -64,8 +61,9 @@ the flag --nosort is set. Args: cobra.ExactArgs(1), RunE: runAddCmd, } + cmd.Flags().StringSlice(flagMultisig, nil, "Construct and store a multisig public key (implies --pubkey)") - cmd.Flags().Uint(flagMultiSigThreshold, 1, "K out of N required signatures. For use in conjunction with --multisig") + cmd.Flags().Int(flagMultiSigThreshold, 1, "K out of N required signatures. For use in conjunction with --multisig") cmd.Flags().Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied") cmd.Flags().String(FlagPublicKey, "", "Parse a public key in bech32 format and save it to disk") cmd.Flags().BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic") @@ -79,42 +77,35 @@ the flag --nosort is set. cmd.Flags().Uint32(flagIndex, 0, "Address index number for HD derivation") cmd.Flags().String(flagKeyAlgo, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") - v.BindPFlag(flagMultisig, cmd.Flags().Lookup(flagMultisig)) - v.BindPFlag(flagMultiSigThreshold, cmd.Flags().Lookup(flagMultiSigThreshold)) - v.BindPFlag(flagNoSort, cmd.Flags().Lookup(flagNoSort)) - v.BindPFlag(FlagPublicKey, cmd.Flags().Lookup(FlagPublicKey)) - v.BindPFlag(flagInteractive, cmd.Flags().Lookup(flagInteractive)) - v.BindPFlag(flags.FlagUseLedger, cmd.Flags().Lookup(flags.FlagUseLedger)) - v.BindPFlag(flagRecover, cmd.Flags().Lookup(flagRecover)) - v.BindPFlag(flagNoBackup, cmd.Flags().Lookup(flagNoBackup)) - v.BindPFlag(flags.FlagDryRun, cmd.Flags().Lookup(flags.FlagDryRun)) - v.BindPFlag(flagHDPath, cmd.Flags().Lookup(flagHDPath)) - v.BindPFlag(flagCoinType, cmd.Flags().Lookup(flagCoinType)) - v.BindPFlag(flagAccount, cmd.Flags().Lookup(flagAccount)) - v.BindPFlag(flagIndex, cmd.Flags().Lookup(flagIndex)) - v.BindPFlag(flagKeyAlgo, cmd.Flags().Lookup(flagKeyAlgo)) + cmd.SetOut(cmd.OutOrStdout()) + cmd.SetErr(cmd.ErrOrStderr()) return cmd } func runAddCmd(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) + buf := bufio.NewReader(cmd.InOrStdin()) + + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + dryRun, _ := cmd.Flags().GetBool(flags.FlagHome) var ( kr keyring.Keyring err error ) - if v.GetBool(flags.FlagDryRun) { - kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, rootViper.GetString(flags.FlagHome), inBuf) + if dryRun { + kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, homeDir, buf) } else { - kr, err = keyring.New(sdk.KeyringServiceName(), rootViper.GetString(flags.FlagKeyringBackend), rootViper.GetString(flags.FlagHome), inBuf) + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + kr, err = keyring.New(sdk.KeyringServiceName(), backend, homeDir, buf) } + if err != nil { return err } - return RunAddCmd(cmd, args, kr, inBuf) + return RunAddCmd(cmd, args, kr, buf) } /* @@ -130,17 +121,18 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf var err error name := args[0] - - interactive := v.GetBool(flagInteractive) - showMnemonic := !v.GetBool(flagNoBackup) + interactive, _ := cmd.Flags().GetBool(flagInteractive) + noBackup, _ := cmd.Flags().GetBool(flagNoBackup) + showMnemonic := !noBackup keyringAlgos, _ := kb.SupportedAlgorithms() - algo, err := keyring.NewSigningAlgoFromString(v.GetString(flagKeyAlgo), keyringAlgos) + algoStr, _ := cmd.Flags().GetString(flagKeyAlgo) + algo, err := keyring.NewSigningAlgoFromString(algoStr, keyringAlgos) if err != nil { return err } - if !v.GetBool(flags.FlagDryRun) { + if dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun); !dryRun { _, err = kb.Key(name) if err == nil { // account exists, ask for user confirmation @@ -159,11 +151,11 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } } - multisigKeys := v.GetStringSlice(flagMultisig) + multisigKeys, _ := cmd.Flags().GetStringSlice(flagMultisig) if len(multisigKeys) != 0 { var pks []crypto.PubKey - multisigThreshold := v.GetInt(flagMultiSigThreshold) + multisigThreshold, _ := cmd.Flags().GetInt(flagMultiSigThreshold) if err := validateMultisigThreshold(multisigThreshold, len(multisigKeys)); err != nil { return err } @@ -177,8 +169,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf pks = append(pks, k.GetPubKey()) } - // Handle --nosort - if !v.GetBool(flagNoSort) { + if noSort, _ := cmd.Flags().GetBool(flagNoSort); !noSort { sort.Slice(pks, func(i, j int) bool { return bytes.Compare(pks[i].Address(), pks[j].Address()) < 0 }) @@ -190,13 +181,13 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } cmd.PrintErrf("Key %q saved to disk.\n", name) - return nil } } - if v.GetString(FlagPublicKey) != "" { - pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, v.GetString(FlagPublicKey)) + pubKey, _ := cmd.Flags().GetString(FlagPublicKey) + if pubKey != "" { + pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, pubKey) if err != nil { return err } @@ -208,19 +199,20 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf return nil } - coinType := uint32(v.GetInt(flagCoinType)) - account := uint32(v.GetInt(flagAccount)) - index := uint32(v.GetInt(flagIndex)) - hdPath := v.GetString(flagHDPath) + coinType, _ := cmd.Flags().GetUint32(flagCoinType) + account, _ := cmd.Flags().GetUint32(flagAccount) + index, _ := cmd.Flags().GetUint32(flagIndex) + hdPath, _ := cmd.Flags().GetString(flagHDPath) + useLedger, _ := cmd.Flags().GetBool(flags.FlagUseLedger) if len(hdPath) == 0 { hdPath = hd.CreateHDPath(coinType, account, index).String() - } else if v.GetBool(flags.FlagUseLedger) { + } else if useLedger { return errors.New("cannot set custom bip32 path with ledger") } // If we're using ledger, only thing we need is the path and the bech32 prefix. - if v.GetBool(flags.FlagUseLedger) { + if useLedger { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() info, err := kb.SaveLedgerKey(name, hd.Secp256k1, bech32PrefixAccAddr, coinType, account, index) @@ -234,9 +226,10 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf // Get bip39 mnemonic var mnemonic, bip39Passphrase string - if interactive || v.GetBool(flagRecover) { + recover, _ := cmd.Flags().GetBool(flagRecover) + if interactive || recover { bip39Message := "Enter your bip39 mnemonic" - if !v.GetBool(flagRecover) { + if !recover { bip39Message = "Enter your bip39 mnemonic, or hit enter to generate one." } @@ -291,7 +284,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } // Recover key from seed passphrase - if v.GetBool(flagRecover) { + if recover { // Hide mnemonic from output showMnemonic = false mnemonic = "" @@ -301,19 +294,20 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic string) error { - output := v.Get(cli.OutputFlag) + output, _ := cmd.Flags().GetString(cli.OutputFlag) switch output { case OutputFormatText: cmd.PrintErrln() - printKeyInfo(cmd.OutOrStdout(), info, keyring.Bech32KeyOutput) + printKeyInfo(cmd.OutOrStdout(), info, keyring.Bech32KeyOutput, output) // print mnemonic unless requested not to. if showMnemonic { - cmd.PrintErrln("\n**Important** write this mnemonic phrase in a safe place.") - cmd.PrintErrln("It is the only way to recover your account if you ever forget your password.") - cmd.PrintErrln("") - cmd.PrintErrln(mnemonic) + fmt.Fprintln(cmd.ErrOrStderr(), "\n**Important** write this mnemonic phrase in a safe place.") + fmt.Fprintln(cmd.ErrOrStderr(), "\n**Important** write this mnemonic phrase in a safe place.") + fmt.Fprintln(cmd.ErrOrStderr(), "It is the only way to recover your account if you ever forget your password.") + fmt.Fprintln(cmd.ErrOrStderr(), "") + fmt.Fprintln(cmd.ErrOrStderr(), mnemonic) } case OutputFormatJSON: out, err := keyring.Bech32KeyOutput(info) @@ -330,7 +324,7 @@ func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemo return err } - cmd.PrintErrln(string(jsonString)) + cmd.Println(string(jsonString)) default: return fmt.Errorf("invalid output format %s", output) diff --git a/client/keys/add_ledger_test.go b/client/keys/add_ledger_test.go index e19db3dd9a79..3820e418d71f 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -3,9 +3,9 @@ package keys import ( + "fmt" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/cli" @@ -34,29 +34,31 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { config.SetBech32PrefixForConsensusNode(bech32PrefixConsAddr, bech32PrefixConsPub) cmd := AddKeyCommand() - require.NotNil(t, cmd) + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) // Prepare a keybase kbHome, kbCleanUp := tests.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) - viper.Set(flags.FlagHome, kbHome) - viper.Set(flags.FlagUseLedger, true) - viper.Set(flagAccount, "0") - viper.Set(flagIndex, "0") - viper.Set(flagCoinType, "330") - - // Test Text - viper.Set(cli.OutputFlag, OutputFormatText) - // set algo flag value to the default - viper.Set(flagKeyAlgo, string(hd.Secp256k1Type)) - // Now enter password + + cmd.SetArgs([]string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flags.FlagUseLedger), + fmt.Sprintf("--%s=0", flagAccount), + fmt.Sprintf("--%s=0", flagIndex), + fmt.Sprintf("--%s=330", flagCoinType), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + mockIn, _, _ := tests.ApplyMockIO(cmd) mockIn.Reset("test1234\ntest1234\n") - require.NoError(t, runAddCmd(cmd, []string{"keyname1"})) + require.NoError(t, cmd.Execute()) // Now check that it has been stored properly - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), kbHome, mockIn) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) require.NotNil(t, kb) t.Cleanup(func() { @@ -82,32 +84,35 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { func Test_runAddCmdLedger(t *testing.T) { cmd := AddKeyCommand() - require.NotNil(t, cmd) + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) mockIn, _, _ := tests.ApplyMockIO(cmd) // Prepare a keybase kbHome, kbCleanUp := tests.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) - viper.Set(flags.FlagHome, kbHome) - viper.Set(flags.FlagUseLedger, true) - - // Test Text - viper.Set(cli.OutputFlag, OutputFormatText) - // set algo flag value to the default - viper.Set(flagKeyAlgo, string(hd.Secp256k1Type)) - // Now enter password + + cmd.SetArgs([]string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flags.FlagUseLedger), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%d", flagCoinType, sdk.CoinType), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) mockIn.Reset("test1234\ntest1234\n") - viper.Set(flagCoinType, sdk.CoinType) - require.NoError(t, runAddCmd(cmd, []string{"keyname1"})) + + require.NoError(t, cmd.Execute()) // Now check that it has been stored properly - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), kbHome, mockIn) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) require.NotNil(t, kb) t.Cleanup(func() { _ = kb.Delete("keyname1") }) + mockIn.Reset("test1234\n") key1, err := kb.Key("keyname1") require.NoError(t, err) diff --git a/client/keys/add_test.go b/client/keys/add_test.go index d5532ef3db99..0b6af85b1d5c 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -1,9 +1,9 @@ package keys import ( + "fmt" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/cli" @@ -17,41 +17,66 @@ import ( func Test_runAddCmdBasic(t *testing.T) { cmd := AddKeyCommand() - require.NotNil(t, cmd) + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) mockIn, _, _ := tests.ApplyMockIO(cmd) kbHome, kbCleanUp := tests.NewTestCaseDir(t) require.NotNil(t, kbHome) t.Cleanup(kbCleanUp) - viper.Set(flags.FlagHome, kbHome) - viper.Set(cli.OutputFlag, OutputFormatText) - viper.Set(flags.FlagUseLedger, false) - mockIn.Reset("y\n") - // set algo flag value to the default - viper.Set(flagKeyAlgo, string(hd.Secp256k1Type)) - - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), kbHome, mockIn) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { _ = kb.Delete("keyname1") _ = kb.Delete("keyname2") }) - require.NoError(t, runAddCmd(cmd, []string{"keyname1"})) + + cmd.SetArgs([]string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + mockIn.Reset("y\n") + require.NoError(t, cmd.Execute()) mockIn.Reset("N\n") - require.Error(t, runAddCmd(cmd, []string{"keyname1"})) + require.Error(t, cmd.Execute()) + + cmd.SetArgs([]string{ + "keyname2", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + + require.NoError(t, cmd.Execute()) + require.Error(t, cmd.Execute()) - require.NoError(t, runAddCmd(cmd, []string{"keyname2"})) - require.Error(t, runAddCmd(cmd, []string{"keyname2"})) mockIn.Reset("y\n") - require.NoError(t, runAddCmd(cmd, []string{"keyname2"})) + require.NoError(t, cmd.Execute()) + + cmd.SetArgs([]string{ + "keyname4", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + + require.NoError(t, cmd.Execute()) + require.Error(t, cmd.Execute()) - // test --dry-run - require.NoError(t, runAddCmd(cmd, []string{"keyname4"})) - require.Error(t, runAddCmd(cmd, []string{"keyname4"})) + cmd.SetArgs([]string{ + "keyname5", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flags.FlagDryRun), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flagKeyAlgo, string(hd.Secp256k1Type)), + }) - viper.Set(flags.FlagDryRun, true) - require.NoError(t, runAddCmd(cmd, []string{"keyname4"})) + require.NoError(t, cmd.Execute()) } diff --git a/client/keys/delete.go b/client/keys/delete.go index e05019699988..644598109b48 100644 --- a/client/keys/delete.go +++ b/client/keys/delete.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/cobra" - "github.com/spf13/viper" ) const ( @@ -28,50 +27,49 @@ Note that removing offline or ledger keys will remove only the public key references stored locally, i.e. private keys stored in a ledger device cannot be deleted with the CLI. `, - RunE: runDeleteCmd, Args: cobra.MinimumNArgs(1), - } + RunE: func(cmd *cobra.Command, args []string) error { + buf := bufio.NewReader(cmd.InOrStdin()) - cmd.Flags().BoolP(flagYes, "y", false, - "Skip confirmation prompt when deleting offline or ledger key references") - cmd.Flags().BoolP(flagForce, "f", false, - "Remove the key unconditionally without asking for the passphrase. Deprecated.") - return cmd -} + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, buf) + if err != nil { + return err + } -func runDeleteCmd(cmd *cobra.Command, args []string) error { - buf := bufio.NewReader(cmd.InOrStdin()) + for _, name := range args { + info, err := kb.Key(name) + if err != nil { + return err + } - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), buf) - if err != nil { - return err - } + // confirm deletion, unless -y is passed + if skip, _ := cmd.Flags().GetBool(flagYes); !skip { + if yes, err := input.GetConfirmation("Key reference will be deleted. Continue?", buf, cmd.ErrOrStderr()); err != nil { + return err + } else if !yes { + continue + } + } - for _, name := range args { - info, err := kb.Key(name) - if err != nil { - return err - } + if err := kb.Delete(name); err != nil { + return err + } - // confirm deletion, unless -y is passed - if !viper.GetBool(flagYes) { - if yes, err := input.GetConfirmation("Key reference will be deleted. Continue?", buf, cmd.ErrOrStderr()); err != nil { - return err - } else if !yes { - continue + if info.GetType() == keyring.TypeLedger || info.GetType() == keyring.TypeOffline { + cmd.PrintErrln("Public key reference deleted") + continue + } + cmd.PrintErrln("Key deleted forever (uh oh!)") } - } - - if err := kb.Delete(name); err != nil { - return err - } - if info.GetType() == keyring.TypeLedger || info.GetType() == keyring.TypeOffline { - cmd.PrintErrln("Public key reference deleted") - continue - } - cmd.PrintErrln("Key deleted forever (uh oh!)") + return nil + }, } - return nil + cmd.Flags().BoolP(flagYes, "y", false, "Skip confirmation prompt when deleting offline or ledger key references") + cmd.Flags().BoolP(flagForce, "f", false, "Remove the key unconditionally without asking for the passphrase. Deprecated.") + + return cmd } diff --git a/client/keys/delete_test.go b/client/keys/delete_test.go index 3d2136a7252a..ede5e72db274 100644 --- a/client/keys/delete_test.go +++ b/client/keys/delete_test.go @@ -1,25 +1,25 @@ package keys import ( + "fmt" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runDeleteCmd(t *testing.T) { - deleteKeyCommand := DeleteKeyCommand() - mockIn, _, _ := tests.ApplyMockIO(deleteKeyCommand) + cmd := DeleteKeyCommand() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) + mockIn, _, _ := tests.ApplyMockIO(cmd) - yesF, _ := deleteKeyCommand.Flags().GetBool(flagYes) - forceF, _ := deleteKeyCommand.Flags().GetBool(flagForce) + yesF, _ := cmd.Flags().GetBool(flagYes) + forceF, _ := cmd.Flags().GetBool(flagForce) require.False(t, yesF) require.False(t, forceF) @@ -29,24 +29,30 @@ func Test_runDeleteCmd(t *testing.T) { // Now add a temporary keybase kbHome, cleanUp := tests.NewTestCaseDir(t) t.Cleanup(cleanUp) - viper.Set(flags.FlagHome, kbHome) - // Now path := sdk.GetConfig().GetFullFundraiserPath() - backend := viper.GetString(flags.FlagKeyringBackend) - kb, err := keyring.New(sdk.KeyringServiceName(), backend, kbHome, mockIn) + + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) + _, err = kb.NewAccount(fakeKeyName1, tests.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) + _, _, err = kb.NewMnemonic(fakeKeyName2, keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) require.NoError(t, err) - err = runDeleteCmd(deleteKeyCommand, []string{"blah"}) + cmd.SetArgs([]string{"blah", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome)}) + err = cmd.Execute() require.Error(t, err) require.Equal(t, "The specified item could not be found in the keyring", err.Error()) // User confirmation missing - err = runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1}) + cmd.SetArgs([]string{ + fakeKeyName1, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + err = cmd.Execute() require.Error(t, err) require.Equal(t, "EOF", err.Error()) @@ -54,17 +60,28 @@ func Test_runDeleteCmd(t *testing.T) { require.NoError(t, err) // Now there is a confirmation - viper.Set(flagYes, true) - require.NoError(t, runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1})) + cmd.SetArgs([]string{ + fakeKeyName1, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flagYes), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + require.NoError(t, cmd.Execute()) _, err = kb.Key(fakeKeyName1) require.Error(t, err) // Key1 is gone - viper.Set(flagYes, true) _, err = kb.Key(fakeKeyName2) require.NoError(t, err) - err = runDeleteCmd(deleteKeyCommand, []string{fakeKeyName2}) - require.NoError(t, err) + + cmd.SetArgs([]string{ + fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flagYes), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + require.NoError(t, cmd.Execute()) + _, err = kb.Key(fakeKeyName2) require.Error(t, err) // Key2 is gone } diff --git a/client/keys/export.go b/client/keys/export.go index 2c17bfe84f76..e2248a2f18f6 100644 --- a/client/keys/export.go +++ b/client/keys/export.go @@ -4,7 +4,6 @@ import ( "bufio" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" @@ -19,27 +18,28 @@ func ExportKeyCommand() *cobra.Command { Short: "Export private keys", Long: `Export a private key from the local keybase in ASCII-armored encrypted format.`, Args: cobra.ExactArgs(1), - RunE: runExportCmd, + RunE: func(cmd *cobra.Command, args []string) error { + buf := bufio.NewReader(cmd.InOrStdin()) + + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, buf) + if err != nil { + return err + } + + encryptPassword, err := input.GetPassword("Enter passphrase to encrypt the exported key:", buf) + if err != nil { + return err + } + + armored, err := kb.ExportPrivKeyArmor(args[0], encryptPassword) + if err != nil { + return err + } + + cmd.Println(armored) + return nil + }, } } - -func runExportCmd(cmd *cobra.Command, args []string) error { - buf := bufio.NewReader(cmd.InOrStdin()) - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), buf) - if err != nil { - return err - } - - encryptPassword, err := input.GetPassword("Enter passphrase to encrypt the exported key:", buf) - if err != nil { - return err - } - - armored, err := kb.ExportPrivKeyArmor(args[0], encryptPassword) - if err != nil { - return err - } - - cmd.Println(armored) - return nil -} diff --git a/client/keys/export_test.go b/client/keys/export_test.go index 99262ceaa94b..937582435997 100644 --- a/client/keys/export_test.go +++ b/client/keys/export_test.go @@ -1,9 +1,9 @@ package keys import ( + "fmt" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -15,16 +15,16 @@ import ( ) func Test_runExportCmd(t *testing.T) { - exportKeyCommand := ExportKeyCommand() - mockIn, _, _ := tests.ApplyMockIO(exportKeyCommand) + cmd := ExportKeyCommand() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) + mockIn, _, _ := tests.ApplyMockIO(cmd) // Now add a temporary keybase kbHome, cleanUp := tests.NewTestCaseDir(t) t.Cleanup(cleanUp) - viper.Set(flags.FlagHome, kbHome) // create a key - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), kbHome, mockIn) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { kb.Delete("keyname1") // nolint:errcheck @@ -36,5 +36,11 @@ func Test_runExportCmd(t *testing.T) { // Now enter password mockIn.Reset("123456789\n123456789\n") - require.NoError(t, runExportCmd(exportKeyCommand, []string{"keyname1"})) + cmd.SetArgs([]string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + + require.NoError(t, cmd.Execute()) } diff --git a/client/keys/import.go b/client/keys/import.go index cbba4598dcb2..641ac6ef623e 100644 --- a/client/keys/import.go +++ b/client/keys/import.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" @@ -20,26 +19,27 @@ func ImportKeyCommand() *cobra.Command { Short: "Import private keys into the local keybase", Long: "Import a ASCII armored private key into the local keybase.", Args: cobra.ExactArgs(2), - RunE: runImportCmd, + RunE: func(cmd *cobra.Command, args []string) error { + buf := bufio.NewReader(cmd.InOrStdin()) + + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, buf) + if err != nil { + return err + } + + bz, err := ioutil.ReadFile(args[1]) + if err != nil { + return err + } + + passphrase, err := input.GetPassword("Enter passphrase to decrypt your key:", buf) + if err != nil { + return err + } + + return kb.ImportPrivKey(args[0], string(bz), passphrase) + }, } } - -func runImportCmd(cmd *cobra.Command, args []string) error { - buf := bufio.NewReader(cmd.InOrStdin()) - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), buf) - if err != nil { - return err - } - - bz, err := ioutil.ReadFile(args[1]) - if err != nil { - return err - } - - passphrase, err := input.GetPassword("Enter passphrase to decrypt your key:", buf) - if err != nil { - return err - } - - return kb.ImportPrivKey(args[0], string(bz), passphrase) -} diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 6451277d3e7f..88de08be6bfb 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -1,11 +1,11 @@ package keys import ( + "fmt" "io/ioutil" "path/filepath" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client/flags" @@ -15,15 +15,15 @@ import ( ) func Test_runImportCmd(t *testing.T) { - importKeyCommand := ImportKeyCommand() - mockIn, _, _ := tests.ApplyMockIO(importKeyCommand) + cmd := ImportKeyCommand() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) + mockIn, _, _ := tests.ApplyMockIO(cmd) // Now add a temporary keybase kbHome, cleanUp := tests.NewTestCaseDir(t) t.Cleanup(cleanUp) - viper.Set(flags.FlagHome, kbHome) - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), kbHome, mockIn) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { kb.Delete("keyname1") // nolint:errcheck @@ -41,7 +41,11 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO ` require.NoError(t, ioutil.WriteFile(keyfile, []byte(armoredKey), 0644)) - // Now enter password mockIn.Reset("123456789\n") - require.NoError(t, runImportCmd(importKeyCommand, []string{"keyname1", keyfile})) + cmd.SetArgs([]string{ + "keyname1", keyfile, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + require.NoError(t, cmd.Execute()) } diff --git a/client/keys/list.go b/client/keys/list.go index 4862fccf87fb..0c6eedab26bf 100644 --- a/client/keys/list.go +++ b/client/keys/list.go @@ -2,7 +2,7 @@ package keys import ( "github.com/spf13/cobra" - "github.com/spf13/viper" + "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -26,7 +26,9 @@ along with their associated name and address.`, } func runListCmd(cmd *cobra.Command, _ []string) error { - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), cmd.InOrStdin()) + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, cmd.InOrStdin()) if err != nil { return err } @@ -37,8 +39,10 @@ func runListCmd(cmd *cobra.Command, _ []string) error { } cmd.SetOut(cmd.OutOrStdout()) - if !viper.GetBool(flagListNames) { - printInfos(cmd.OutOrStdout(), infos) + + if ok, _ := cmd.Flags().GetBool(flagListNames); !ok { + output, _ := cmd.Flags().GetString(cli.OutputFlag) + printInfos(cmd.OutOrStdout(), infos, output) return nil } diff --git a/client/keys/list_test.go b/client/keys/list_test.go index 849ac9b8d8df..ad0bcafa9888 100644 --- a/client/keys/list_test.go +++ b/client/keys/list_test.go @@ -1,39 +1,31 @@ package keys import ( + "fmt" "testing" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runListCmd(t *testing.T) { - type args struct { - cmd *cobra.Command - args []string - } + cmd := ListKeysCmd() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - cmdBasic := ListKeysCmd() - - // Prepare some keybases kbHome1, cleanUp1 := tests.NewTestCaseDir(t) t.Cleanup(cleanUp1) - // Do nothing, leave home1 empty kbHome2, cleanUp2 := tests.NewTestCaseDir(t) t.Cleanup(cleanUp2) - viper.Set(flags.FlagHome, kbHome2) - mockIn, _, _ := tests.ApplyMockIO(cmdBasic) - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), mockIn) + mockIn, _, _ := tests.ApplyMockIO(cmd) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome2, mockIn) require.NoError(t, err) path := "" //sdk.GetConfig().GetFullFundraiserPath() @@ -42,28 +34,41 @@ func Test_runListCmd(t *testing.T) { t.Cleanup(func() { kb.Delete("something") // nolint:errcheck - }) + + type args struct { + cmd *cobra.Command + args []string + } + testData := []struct { name string kbDir string - args args wantErr bool }{ - {"keybase: empty", kbHome1, args{cmdBasic, []string{}}, false}, - {"keybase: w/key", kbHome2, args{cmdBasic, []string{}}, false}, + {"keybase: empty", kbHome1, false}, + {"keybase: w/key", kbHome2, false}, } for _, tt := range testData { tt := tt t.Run(tt.name, func(t *testing.T) { - viper.Set(flagListNames, false) - viper.Set(flags.FlagHome, tt.kbDir) - if err := runListCmd(tt.args.cmd, tt.args.args); (err != nil) != tt.wantErr { + cmd.SetArgs([]string{ + fmt.Sprintf("--%s=%s", flags.FlagHome, tt.kbDir), + fmt.Sprintf("--%s=false", flagListNames), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + + if err := cmd.Execute(); (err != nil) != tt.wantErr { t.Errorf("runListCmd() error = %v, wantErr %v", err, tt.wantErr) } - viper.Set(flagListNames, true) - if err := runListCmd(tt.args.cmd, tt.args.args); (err != nil) != tt.wantErr { + cmd.SetArgs([]string{ + fmt.Sprintf("--%s=%s", flags.FlagHome, tt.kbDir), + fmt.Sprintf("--%s=true", flagListNames), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + + if err := cmd.Execute(); (err != nil) != tt.wantErr { t.Errorf("runListCmd() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/client/keys/migrate.go b/client/keys/migrate.go index 8d52bd83faf8..d80bbe163097 100644 --- a/client/keys/migrate.go +++ b/client/keys/migrate.go @@ -6,14 +6,13 @@ import ( "io/ioutil" "os" + "github.com/pkg/errors" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" ) // migratePassphrase is used as a no-op migration key passphrase as a passphrase @@ -41,13 +40,15 @@ It is recommended to run in 'dry-run' mode first to verify all key migration mat } func runMigrateCmd(cmd *cobra.Command, args []string) error { + rootDir, _ := cmd.Flags().GetString(flags.FlagHome) + // instantiate legacy keybase - rootDir := viper.GetString(flags.FlagHome) var legacyKb keyring.LegacyKeybase legacyKb, err := NewLegacyKeyBaseFromDir(rootDir) if err != nil { return err } + defer legacyKb.Close() // fetch list of keys from legacy keybase @@ -64,7 +65,7 @@ func runMigrateCmd(cmd *cobra.Command, args []string) error { migrator keyring.InfoImporter ) - if viper.GetBool(flags.FlagDryRun) { + if dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun); dryRun { tmpDir, err = ioutil.TempDir("", "migrator-migrate-dryrun") if err != nil { return errors.Wrap(err, "failed to create temporary directory for dryrun migration") @@ -74,8 +75,10 @@ func runMigrateCmd(cmd *cobra.Command, args []string) error { migrator, err = keyring.NewInfoImporter(keyringServiceName, "test", tmpDir, buf) } else { - migrator, err = keyring.NewInfoImporter(keyringServiceName, viper.GetString(flags.FlagKeyringBackend), rootDir, buf) + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + migrator, err = keyring.NewInfoImporter(keyringServiceName, backend, rootDir, buf) } + if err != nil { return errors.Wrap(err, fmt.Sprintf( "failed to initialize keybase for service %s at directory %s", diff --git a/client/keys/migrate_test.go b/client/keys/migrate_test.go index 6f24a6387db4..6f36bfc9f490 100644 --- a/client/keys/migrate_test.go +++ b/client/keys/migrate_test.go @@ -1,36 +1,48 @@ package keys import ( + "fmt" + "io/ioutil" "testing" "github.com/otiai10/copy" + "github.com/stretchr/testify/assert" + "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests" - - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - - "github.com/tendermint/tendermint/libs/cli" ) func Test_runMigrateCmd(t *testing.T) { cmd := AddKeyCommand() - assert.NotNil(t, cmd) + cmd.SetErr(ioutil.Discard) + cmd.SetOut(ioutil.Discard) + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) kbHome, kbCleanUp := tests.NewTestCaseDir(t) copy.Copy("testdata", kbHome) assert.NotNil(t, kbHome) t.Cleanup(kbCleanUp) - viper.Set(flags.FlagHome, kbHome) - - viper.Set(cli.OutputFlag, OutputFormatText) - assert.NoError(t, runAddCmd(cmd, []string{"keyname1"})) + cmd.SetArgs([]string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + assert.NoError(t, cmd.Execute()) - viper.Set(flags.FlagDryRun, true) cmd = MigrateCommand() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) mockIn, _, _ := tests.ApplyMockIO(cmd) + + cmd.SetArgs([]string{ + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=true", flags.FlagDryRun), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + }) + mockIn.Reset("test1234\ntest1234\n") - assert.NoError(t, runMigrateCmd(cmd, []string{})) + assert.NoError(t, cmd.Execute()) } diff --git a/client/keys/mnemonic.go b/client/keys/mnemonic.go index 66b3b17d027a..c411612782e6 100644 --- a/client/keys/mnemonic.go +++ b/client/keys/mnemonic.go @@ -23,54 +23,53 @@ func MnemonicKeyCommand() *cobra.Command { Use: "mnemonic", Short: "Compute the bip39 mnemonic for some input entropy", Long: "Create a bip39 mnemonic, sometimes called a seed phrase, by reading from the system entropy. To pass your own entropy, use --unsafe-entropy", - RunE: runMnemonicCmd, - } - cmd.Flags().Bool(flagUserEntropy, false, "Prompt the user to supply their own entropy, instead of relying on the system") - return cmd -} + RunE: func(cmd *cobra.Command, args []string) error { + var entropySeed []byte -func runMnemonicCmd(cmd *cobra.Command, args []string) error { - flags := cmd.Flags() + if userEntropy, _ := cmd.Flags().GetBool(flagUserEntropy); userEntropy { + // prompt the user to enter some entropy + buf := bufio.NewReader(cmd.InOrStdin()) - userEntropy, _ := flags.GetBool(flagUserEntropy) + inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf) + if err != nil { + return err + } - var entropySeed []byte + if len(inputEntropy) < 43 { + return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy)) + } - if userEntropy { - // prompt the user to enter some entropy - buf := bufio.NewReader(cmd.InOrStdin()) - inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf) - if err != nil { - return err - } - if len(inputEntropy) < 43 { - return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy)) - } - conf, err := input.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf, cmd.ErrOrStderr()) - if err != nil { - return err - } - if !conf { - return nil - } + conf, err := input.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf, cmd.ErrOrStderr()) + if err != nil { + return err + } - // hash input entropy to get entropy seed - hashedEntropy := sha256.Sum256([]byte(inputEntropy)) - entropySeed = hashedEntropy[:] - } else { - // read entropy seed straight from crypto.Rand - var err error - entropySeed, err = bip39.NewEntropy(mnemonicEntropySize) - if err != nil { - return err - } - } + if !conf { + return nil + } - mnemonic, err := bip39.NewMnemonic(entropySeed) - if err != nil { - return err + // hash input entropy to get entropy seed + hashedEntropy := sha256.Sum256([]byte(inputEntropy)) + entropySeed = hashedEntropy[:] + } else { + // read entropy seed straight from crypto.Rand + var err error + entropySeed, err = bip39.NewEntropy(mnemonicEntropySize) + if err != nil { + return err + } + } + + mnemonic, err := bip39.NewMnemonic(entropySeed) + if err != nil { + return err + } + + cmd.Println(mnemonic) + return nil + }, } - cmd.Println(mnemonic) - return nil + cmd.Flags().Bool(flagUserEntropy, false, "Prompt the user to supply their own entropy, instead of relying on the system") + return cmd } diff --git a/client/keys/mnemonic_test.go b/client/keys/mnemonic_test.go index a3e84e7182d6..c333657f96eb 100644 --- a/client/keys/mnemonic_test.go +++ b/client/keys/mnemonic_test.go @@ -1,33 +1,38 @@ package keys import ( + "fmt" + "io/ioutil" "strings" "testing" - "github.com/cosmos/cosmos-sdk/tests" - - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/tests" ) func Test_RunMnemonicCmdNormal(t *testing.T) { - cmdBasic := MnemonicKeyCommand() - require.NoError(t, runMnemonicCmd(cmdBasic, []string{})) + cmd := MnemonicKeyCommand() + cmd.SetErr(ioutil.Discard) + cmd.SetOut(ioutil.Discard) + cmd.SetArgs([]string{}) + require.NoError(t, cmd.Execute()) } func Test_RunMnemonicCmdUser(t *testing.T) { - cmdUser := MnemonicKeyCommand() - err := cmdUser.Flags().Set(flagUserEntropy, "1") - assert.NoError(t, err) + cmd := MnemonicKeyCommand() + cmd.SetErr(ioutil.Discard) + cmd.SetOut(ioutil.Discard) - err = runMnemonicCmd(cmdUser, []string{}) + cmd.SetArgs([]string{fmt.Sprintf("--%s=1", flagUserEntropy)}) + err := cmd.Execute() require.Error(t, err) require.Equal(t, "EOF", err.Error()) // Try again - mockIn, _, _ := tests.ApplyMockIO(cmdUser) + mockIn, _, _ := tests.ApplyMockIO(cmd) mockIn.Reset("Hi!\n") - err = runMnemonicCmd(cmdUser, []string{}) + err = cmd.Execute() require.Error(t, err) require.Equal(t, "256-bits is 43 characters in Base-64, and 100 in Base-6. You entered 3, and probably want more", @@ -36,15 +41,15 @@ func Test_RunMnemonicCmdUser(t *testing.T) { // Now provide "good" entropy :) fakeEntropy := strings.Repeat(":)", 40) + "\ny\n" // entropy + accept count mockIn.Reset(fakeEntropy) - require.NoError(t, runMnemonicCmd(cmdUser, []string{})) + require.NoError(t, cmd.Execute()) // Now provide "good" entropy but no answer fakeEntropy = strings.Repeat(":)", 40) + "\n" // entropy + accept count mockIn.Reset(fakeEntropy) - require.Error(t, runMnemonicCmd(cmdUser, []string{})) + require.Error(t, cmd.Execute()) // Now provide "good" entropy but say no fakeEntropy = strings.Repeat(":)", 40) + "\nn\n" // entropy + accept count mockIn.Reset(fakeEntropy) - require.NoError(t, runMnemonicCmd(cmdUser, []string{})) + require.NoError(t, cmd.Execute()) } diff --git a/client/keys/parse.go b/client/keys/parse.go index 47424e58e51a..2af792c03c8e 100644 --- a/client/keys/parse.go +++ b/client/keys/parse.go @@ -9,14 +9,11 @@ import ( "strings" "github.com/spf13/cobra" - "github.com/spf13/viper" - yaml "gopkg.in/yaml.v2" - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/types/bech32" + yaml "gopkg.in/yaml.v2" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" ) func bech32Prefixes(config *sdk.Config) []string { @@ -101,7 +98,8 @@ func doParseKey(cmd *cobra.Command, config *sdk.Config, args []string) error { return errors.New("couldn't parse empty input") } - if !(runFromBech32(outstream, addr) || runFromHex(config, outstream, addr)) { + output, _ := cmd.Flags().GetString(cli.OutputFlag) + if !(runFromBech32(outstream, addr, output) || runFromHex(config, outstream, addr, output)) { return errors.New("couldn't find valid bech32 nor hex data") } @@ -109,36 +107,36 @@ func doParseKey(cmd *cobra.Command, config *sdk.Config, args []string) error { } // print info from bech32 -func runFromBech32(w io.Writer, bech32str string) bool { +func runFromBech32(w io.Writer, bech32str, output string) bool { hrp, bz, err := bech32.DecodeAndConvert(bech32str) if err != nil { return false } - displayParseKeyInfo(w, newHexOutput(hrp, bz)) + displayParseKeyInfo(w, newHexOutput(hrp, bz), output) return true } // print info from hex -func runFromHex(config *sdk.Config, w io.Writer, hexstr string) bool { +func runFromHex(config *sdk.Config, w io.Writer, hexstr, output string) bool { bz, err := hex.DecodeString(hexstr) if err != nil { return false } - displayParseKeyInfo(w, newBech32Output(config, bz)) + displayParseKeyInfo(w, newBech32Output(config, bz), output) return true } -func displayParseKeyInfo(w io.Writer, stringer fmt.Stringer) { +func displayParseKeyInfo(w io.Writer, stringer fmt.Stringer, output string) { var ( err error out []byte ) - switch viper.Get(cli.OutputFlag) { + switch output { case OutputFormatText: out, err = yaml.Marshal(&stringer) diff --git a/client/keys/root.go b/client/keys/root.go index 9890e7d7e145..98bb616867e2 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -2,13 +2,11 @@ package keys import ( "github.com/spf13/cobra" - "github.com/spf13/viper" + "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" ) -var rootViper = viper.New() - // Commands registers a sub-tree of commands to interact with // local private key storage. func Commands() *cobra.Command { @@ -38,6 +36,7 @@ information: The pass backend requires GnuPG: https://gnupg.org/ `, } + cmd.AddCommand( MnemonicKeyCommand(), AddKeyCommand(), @@ -51,8 +50,9 @@ The pass backend requires GnuPG: https://gnupg.org/ MigrateCommand(), ) + cmd.PersistentFlags().String(flags.FlagHome, "", "The application home directory") cmd.PersistentFlags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") - rootViper.BindPFlag(flags.FlagKeyringBackend, cmd.PersistentFlags().Lookup(flags.FlagKeyringBackend)) + cmd.PersistentFlags().String(cli.OutputFlag, "text", "Output format (text|json)") return cmd } diff --git a/client/keys/root_test.go b/client/keys/root_test.go index e995da9796d2..6a81d0c12aaf 100644 --- a/client/keys/root_test.go +++ b/client/keys/root_test.go @@ -1,15 +1,9 @@ package keys import ( - "os" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/assert" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" ) func TestCommands(t *testing.T) { @@ -19,9 +13,3 @@ func TestCommands(t *testing.T) { // Commands are registered assert.Equal(t, 10, len(rootCommands.Commands())) } - -func TestMain(m *testing.M) { - viper.Set(flags.FlagKeyringBackend, keyring.BackendTest) - viper.Set(flagCoinType, sdk.CoinType) - os.Exit(m.Run()) -} diff --git a/client/keys/show.go b/client/keys/show.go index 1d38fe4232ed..10559f407f69 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -5,8 +5,6 @@ import ( "fmt" "github.com/spf13/cobra" - "github.com/spf13/viper" - tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" @@ -48,7 +46,7 @@ consisting of all the keys provided by name and multisig threshold.`, cmd.Flags().BoolP(FlagAddress, "a", false, "Output the address only (overrides --output)") cmd.Flags().BoolP(FlagPublicKey, "p", false, "Output the public key only (overrides --output)") cmd.Flags().BoolP(FlagDevice, "d", false, "Output the address in a ledger device") - cmd.Flags().Uint(flagMultiSigThreshold, 1, "K out of N required signatures") + cmd.Flags().Int(flagMultiSigThreshold, 1, "K out of N required signatures") return cmd } @@ -56,10 +54,13 @@ consisting of all the keys provided by name and multisig threshold.`, func runShowCmd(cmd *cobra.Command, args []string) (err error) { var info keyring.Info - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), cmd.InOrStdin()) + backend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + homeDir, _ := cmd.Flags().GetString(flags.FlagHome) + kb, err := keyring.New(sdk.KeyringServiceName(), backend, homeDir, cmd.InOrStdin()) if err != nil { return err } + if len(args) == 1 { info, err = fetchKey(kb, args[0]) if err != nil { @@ -76,7 +77,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { pks[i] = info.GetPubKey() } - multisigThreshold := viper.GetInt(flagMultiSigThreshold) + multisigThreshold, _ := cmd.Flags().GetInt(flagMultiSigThreshold) err = validateMultisigThreshold(multisigThreshold, len(args)) if err != nil { return err @@ -86,9 +87,9 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { info = keyring.NewMultiInfo(defaultMultiSigKeyName, multikey) } - isShowAddr := viper.GetBool(FlagAddress) - isShowPubKey := viper.GetBool(FlagPublicKey) - isShowDevice := viper.GetBool(FlagDevice) + isShowAddr, _ := cmd.Flags().GetBool(FlagAddress) + isShowPubKey, _ := cmd.Flags().GetBool(FlagPublicKey) + isShowDevice, _ := cmd.Flags().GetBool(FlagDevice) isOutputSet := false tmp := cmd.Flag(cli.OutputFlag) @@ -104,27 +105,31 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { return errors.New("cannot use --output with --address or --pubkey") } - bechKeyOut, err := getBechKeyOut(viper.GetString(FlagBechPrefix)) + bechPrefix, _ := cmd.Flags().GetString(FlagBechPrefix) + bechKeyOut, err := getBechKeyOut(bechPrefix) if err != nil { return err } + output, _ := cmd.Flags().GetString(cli.OutputFlag) + switch { case isShowAddr: printKeyAddress(cmd.OutOrStdout(), info, bechKeyOut) case isShowPubKey: printPubKey(cmd.OutOrStdout(), info, bechKeyOut) default: - printKeyInfo(cmd.OutOrStdout(), info, bechKeyOut) + printKeyInfo(cmd.OutOrStdout(), info, bechKeyOut, output) } if isShowDevice { if isShowPubKey { return fmt.Errorf("the device flag (-d) can only be used for addresses not pubkeys") } - if viper.GetString(FlagBechPrefix) != "acc" { + if bechPrefix != "acc" { return fmt.Errorf("the device flag (-d) can only be used for accounts") } + // Override and show in the device if info.GetType() != keyring.TypeLedger { return fmt.Errorf("the device flag (-d) can only be used for accounts stored in devices") diff --git a/client/keys/show_test.go b/client/keys/show_test.go index 079e56b4a7c5..abc6d1de5b8e 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -1,9 +1,9 @@ package keys import ( + "fmt" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -37,19 +37,22 @@ func Test_showKeysCmd(t *testing.T) { func Test_runShowCmd(t *testing.T) { cmd := ShowKeysCmd() + cmd.Flags().AddFlagSet(Commands().PersistentFlags()) mockIn, _, _ := tests.ApplyMockIO(cmd) - require.EqualError(t, runShowCmd(cmd, []string{"invalid"}), "invalid is not a valid name or address: decoding bech32 failed: invalid bech32 string length 7") - require.EqualError(t, runShowCmd(cmd, []string{"invalid1", "invalid2"}), "invalid1 is not a valid name or address: decoding bech32 failed: invalid index of 1") - // Prepare a key base - // Now add a temporary keybase + cmd.SetArgs([]string{"invalid"}) + require.EqualError(t, cmd.Execute(), "invalid is not a valid name or address: decoding bech32 failed: invalid bech32 string length 7") + + cmd.SetArgs([]string{"invalid1", "invalid2"}) + require.EqualError(t, cmd.Execute(), "invalid1 is not a valid name or address: decoding bech32 failed: invalid index of 1") + kbHome, cleanUp := tests.NewTestCaseDir(t) t.Cleanup(cleanUp) - viper.Set(flags.FlagHome, kbHome) fakeKeyName1 := "runShowCmd_Key1" fakeKeyName2 := "runShowCmd_Key2" - kb, err := keyring.New(sdk.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), mockIn) + + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { kb.Delete("runShowCmd_Key1") @@ -65,44 +68,86 @@ func Test_runShowCmd(t *testing.T) { require.NoError(t, err) // Now try single key - require.EqualError(t, runShowCmd(cmd, []string{fakeKeyName1}), "invalid Bech32 prefix encoding provided: ") + cmd.SetArgs([]string{ + fakeKeyName1, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=", FlagBechPrefix), + }) + require.EqualError(t, cmd.Execute(), "invalid Bech32 prefix encoding provided: ") - // Now try single key - set bech to acc - viper.Set(FlagBechPrefix, sdk.PrefixAccount) + cmd.SetArgs([]string{ + fakeKeyName1, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount), + }) // try fetch by name - require.NoError(t, runShowCmd(cmd, []string{fakeKeyName1})) + require.NoError(t, cmd.Execute()) + // try fetch by addr info, err := kb.Key(fakeKeyName1) + cmd.SetArgs([]string{ + info.GetAddress().String(), + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount), + }) + require.NoError(t, err) - require.NoError(t, runShowCmd(cmd, []string{info.GetAddress().String()})) + require.NoError(t, cmd.Execute()) // Now try multisig key - set bech to acc - viper.Set(FlagBechPrefix, sdk.PrefixAccount) - require.EqualError(t, runShowCmd(cmd, []string{fakeKeyName1, fakeKeyName2}), "threshold must be a positive integer") - - // Now try multisig key - set bech to acc + threshold=2 - viper.Set(FlagBechPrefix, sdk.PrefixAccount) - viper.Set(flagMultiSigThreshold, 2) - err = runShowCmd(cmd, []string{fakeKeyName1, fakeKeyName2}) - require.NoError(t, err) + cmd.SetArgs([]string{ + fakeKeyName1, fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount), + fmt.Sprintf("--%s=0", flagMultiSigThreshold), + }) + require.EqualError(t, cmd.Execute(), "threshold must be a positive integer") + + cmd.SetArgs([]string{ + fakeKeyName1, fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount), + fmt.Sprintf("--%s=2", flagMultiSigThreshold), + }) + require.NoError(t, cmd.Execute()) // Now try multisig key - set bech to acc + threshold=2 - viper.Set(FlagBechPrefix, "acc") - viper.Set(FlagDevice, true) - viper.Set(flagMultiSigThreshold, 2) - err = runShowCmd(cmd, []string{fakeKeyName1, fakeKeyName2}) - require.EqualError(t, err, "the device flag (-d) can only be used for accounts stored in devices") - - viper.Set(FlagBechPrefix, "val") - err = runShowCmd(cmd, []string{fakeKeyName1, fakeKeyName2}) - require.EqualError(t, err, "the device flag (-d) can only be used for accounts") - - viper.Set(FlagPublicKey, true) - err = runShowCmd(cmd, []string{fakeKeyName1, fakeKeyName2}) - require.EqualError(t, err, "the device flag (-d) can only be used for addresses not pubkeys") - - // TODO: Capture stdout and compare + cmd.SetArgs([]string{ + fakeKeyName1, fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=acc", FlagBechPrefix), + fmt.Sprintf("--%s=true", FlagDevice), + fmt.Sprintf("--%s=2", flagMultiSigThreshold), + }) + require.EqualError(t, cmd.Execute(), "the device flag (-d) can only be used for accounts stored in devices") + + cmd.SetArgs([]string{ + fakeKeyName1, fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=val", FlagBechPrefix), + fmt.Sprintf("--%s=true", FlagDevice), + fmt.Sprintf("--%s=2", flagMultiSigThreshold), + }) + require.EqualError(t, cmd.Execute(), "the device flag (-d) can only be used for accounts") + + cmd.SetArgs([]string{ + fakeKeyName1, fakeKeyName2, + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=val", FlagBechPrefix), + fmt.Sprintf("--%s=true", FlagDevice), + fmt.Sprintf("--%s=2", flagMultiSigThreshold), + fmt.Sprintf("--%s=true", FlagPublicKey), + }) + require.EqualError(t, cmd.Execute(), "the device flag (-d) can only be used for addresses not pubkeys") } func Test_validateMultisigThreshold(t *testing.T) { diff --git a/client/keys/utils.go b/client/keys/utils.go index 69f3de80dd6b..891ddeaeb9a9 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -5,8 +5,6 @@ import ( "io" "path/filepath" - "github.com/spf13/viper" - "github.com/tendermint/tendermint/libs/cli" "gopkg.in/yaml.v2" cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -33,13 +31,13 @@ func getLegacyKeyBaseFromDir(rootDir string, opts ...cryptokeyring.KeybaseOption return cryptokeyring.NewLegacy(defaultKeyDBName, filepath.Join(rootDir, "keys"), opts...) } -func printKeyInfo(w io.Writer, keyInfo cryptokeyring.Info, bechKeyOut bechKeyOutFn) { +func printKeyInfo(w io.Writer, keyInfo cryptokeyring.Info, bechKeyOut bechKeyOutFn, output string) { ko, err := bechKeyOut(keyInfo) if err != nil { panic(err) } - switch viper.Get(cli.OutputFlag) { + switch output { case OutputFormatText: printTextInfos(w, []cryptokeyring.KeyOutput{ko}) @@ -53,13 +51,13 @@ func printKeyInfo(w io.Writer, keyInfo cryptokeyring.Info, bechKeyOut bechKeyOut } } -func printInfos(w io.Writer, infos []cryptokeyring.Info) { +func printInfos(w io.Writer, infos []cryptokeyring.Info, output string) { kos, err := cryptokeyring.Bech32KeysOutput(infos) if err != nil { panic(err) } - switch viper.Get(cli.OutputFlag) { + switch output { case OutputFormatText: printTextInfos(w, kos) From 546aadbdc7f11f306568ad7909c3cda6d0c2bfcc Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 09:20:51 -0400 Subject: [PATCH 21/33] server: add missing flag --- server/start.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/start.go b/server/start.go index a6725a13ab17..974ec4425a42 100644 --- a/server/start.go +++ b/server/start.go @@ -103,7 +103,7 @@ which accepts a path for the resulting pprof file. cmd.Flags().Bool(FlagInterBlockCache, true, "Enable inter-block caching") cmd.Flags().String(flagCPUProfile, "", "Enable CPU profiling and write to the provided file") cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") - + cmd.Flags().Bool(FlagTrace, false, "Provide full stack traces for errors in ABCI Log") cmd.Flags().String(FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") cmd.Flags().Uint64(FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") cmd.Flags().Uint64(FlagPruningKeepEvery, 0, "Offset heights to keep on disk after 'keep-every' (ignored if pruning is not 'custom')") From 055f59831287e2cc102a3f4487fdaa992f373197 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:23:30 -0400 Subject: [PATCH 22/33] refactor --- Makefile | 2 +- client/cmd.go | 5 +- client/debug/main.go | 12 +- client/flags/flags.go | 1 - server/export.go | 13 +- server/export_test.go | 2 - server/start.go | 38 +++-- server/tm_cmds.go | 37 +++-- server/util.go | 74 ++++++++-- simapp/simd/cmd/genaccounts.go | 11 +- simapp/simd/cmd/root.go | 48 +++--- simapp/simd/cmd/testnet.go | 12 +- types/context.go | 5 +- x/genutil/client/cli/collect.go | 18 ++- x/genutil/client/cli/gentx.go | 33 ++--- x/genutil/client/cli/init.go | 12 +- x/genutil/client/cli/init_test.go | 180 +++++++++++------------ x/genutil/client/cli/migrate.go | 9 +- x/genutil/client/cli/migrate_test.go | 60 ++++---- x/genutil/client/cli/validate_genesis.go | 12 +- 20 files changed, 327 insertions(+), 257 deletions(-) diff --git a/Makefile b/Makefile index b1387eaab64e..2ca39cdb4da5 100644 --- a/Makefile +++ b/Makefile @@ -320,7 +320,7 @@ build-docker-local-simapp: @$(MAKE) -C networks/local # Run a 4-node testnet locally -localnet-start: build-simapp-linux localnet-stop +localnet-start: build-simd-linux localnet-stop @if ! [ -f build/node0/simd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/simd:Z cosmos-sdk/simappnode testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi docker-compose up -d diff --git a/client/cmd.go b/client/cmd.go index bc5ab303f4bd..5d1af5fe0f68 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -9,13 +9,12 @@ import ( "github.com/spf13/pflag" "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" ) -type contextKey string - // ClientContextKey defines the context key used to retrieve a client.Context from // a command's Context. -const ClientContextKey = contextKey("client.context") +const ClientContextKey = sdk.ContextKey("client.context") // SetCmdClientContextHandler is to be used in a command pre-hook execution to // read flags that populate a Context and sets that to the command's Context. diff --git a/client/debug/main.go b/client/debug/main.go index 54b4c2f0907a..eb2a3ecb2f5f 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -8,24 +8,22 @@ import ( "strings" "github.com/spf13/cobra" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" ) -func Cmd(cdc *codec.Codec) *cobra.Command { +func Cmd() *cobra.Command { cmd := &cobra.Command{ Use: "debug", Short: "Tool for helping with debugging your application", RunE: client.ValidateCmd, } - cmd.AddCommand(PubkeyCmd(cdc)) + cmd.AddCommand(PubkeyCmd()) cmd.AddCommand(AddrCmd()) cmd.AddCommand(RawBytesCmd()) @@ -68,7 +66,7 @@ func getPubKeyFromString(pkstr string) (crypto.PubKey, error) { return nil, fmt.Errorf("pubkey '%s' invalid; expected hex, base64, or bech32", pubKey) } -func PubkeyCmd(cdc *codec.Codec) *cobra.Command { +func PubkeyCmd() *cobra.Command { return &cobra.Command{ Use: "pubkey [pubkey]", Short: "Decode a ED25519 pubkey from hex, base64, or bech32", @@ -80,6 +78,8 @@ $ %s debug pubkey cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg `, version.AppName, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + pk, err := getPubKeyFromString(args[0]) if err != nil { return err @@ -90,7 +90,7 @@ $ %s debug pubkey cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg return fmt.Errorf("invalid pubkey type; expected ED25519") } - pubKeyJSONBytes, err := cdc.MarshalJSON(edPK) + pubKeyJSONBytes, err := clientCtx.JSONMarshaler.MarshalJSON(edPK) if err != nil { return err } diff --git a/client/flags/flags.go b/client/flags/flags.go index 33644850bd7a..960b80012524 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/crypto/keyring" diff --git a/server/export.go b/server/export.go index 91843e18194d..97a6a1bb036c 100644 --- a/server/export.go +++ b/server/export.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,12 +23,16 @@ const ( ) // ExportCmd dumps app state to JSON. -func ExportCmd(ctx *Context, cdc codec.JSONMarshaler, appExporter AppExporter) *cobra.Command { +func ExportCmd(appExporter AppExporter) *cobra.Command { cmd := &cobra.Command{ Use: "export", Short: "Export state to JSON", RunE: func(cmd *cobra.Command, args []string) error { - config := ctx.Config + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + + serverCtx := GetServerContextFromCmd(cmd) + config := serverCtx.Config homeDir, _ := cmd.Flags().GetString(flags.FlagHome) config.SetRoot(homeDir) @@ -61,12 +66,12 @@ func ExportCmd(ctx *Context, cdc codec.JSONMarshaler, appExporter AppExporter) * forZeroHeight, _ := cmd.Flags().GetBool(flagForZeroHeight) jailWhiteList, _ := cmd.Flags().GetStringSlice(flagJailWhitelist) - appState, validators, cp, err := appExporter(ctx.Logger, db, traceWriter, height, forZeroHeight, jailWhiteList) + appState, validators, cp, err := appExporter(serverCtx.Logger, db, traceWriter, height, forZeroHeight, jailWhiteList) if err != nil { return fmt.Errorf("error exporting state: %v", err) } - doc, err := tmtypes.GenesisDocFromFile(ctx.Config.GenesisFile()) + doc, err := tmtypes.GenesisDocFromFile(serverCtx.Config.GenesisFile()) if err != nil { return err } diff --git a/server/export_test.go b/server/export_test.go index 98a5904b07eb..5435f66332e0 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -53,8 +53,6 @@ func TestExportCmd_ConsensusParams(t *testing.T) { app.Commit() cmd := ExportCmd( - ctx, - app.Codec(), func(logger log.Logger, db dbm.DB, writer io.Writer, i int64, b bool, strings []string) (json.RawMessage, []tmtypes.GenesisValidator, *abci.ConsensusParams, error) { return app.ExportAppStateAndValidators(true, []string{}) }) diff --git a/server/start.go b/server/start.go index 974ec4425a42..c024d9faf85c 100644 --- a/server/start.go +++ b/server/start.go @@ -48,7 +48,7 @@ const ( // StartCmd runs the service passed in, either stand-alone or in-process with // Tendermint. -func StartCmd(ctx *Context, cdc codec.JSONMarshaler, appCreator AppCreator) *cobra.Command { +func StartCmd(appCreator AppCreator) *cobra.Command { cmd := &cobra.Command{ Use: "start", Short: "Run the full node", @@ -74,20 +74,29 @@ will not be able to commit subsequent blocks. For profiling and benchmarking purposes, CPU profiling can be enabled via the '--cpu-profile' flag which accepts a path for the resulting pprof file. `, - PreRunE: func(cmd *cobra.Command, args []string) error { - _, err := GetPruningOptionsFromFlags(ctx.Viper) + PreRunE: func(cmd *cobra.Command, _ []string) error { + serverCtx := GetServerContextFromCmd(cmd) + + // Bind flags to the Context's Viper so the app construction can set options + // accordingly. + serverCtx.Viper.BindPFlags(cmd.Flags()) + + _, err := GetPruningOptionsFromFlags(serverCtx.Viper) return err }, - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { + serverCtx := GetServerContextFromCmd(cmd) + clientCtx := client.GetClientContextFromCmd(cmd) + withTM, _ := cmd.Flags().GetBool(flagWithTendermint) if !withTM { - ctx.Logger.Info("starting ABCI without Tendermint") - return startStandAlone(ctx, appCreator) + serverCtx.Logger.Info("starting ABCI without Tendermint") + return startStandAlone(serverCtx, appCreator) } - ctx.Logger.Info("starting ABCI with Tendermint") + serverCtx.Logger.Info("starting ABCI with Tendermint") - err := startInProcess(ctx, cdc, appCreator) + err := startInProcess(serverCtx, clientCtx.JSONMarshaler, appCreator) return err }, } @@ -102,7 +111,6 @@ which accepts a path for the resulting pprof file. 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") cmd.Flags().String(flagCPUProfile, "", "Enable CPU profiling and write to the provided file") - cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") cmd.Flags().Bool(FlagTrace, false, "Provide full stack traces for errors in ABCI Log") cmd.Flags().String(FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") cmd.Flags().Uint64(FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") @@ -110,9 +118,9 @@ which accepts a path for the resulting pprof file. cmd.Flags().Uint64(FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')") cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") - // Bind flags to the Context's Viper so the app construction can set options - // accordingly. - ctx.Viper.BindPFlags(cmd.Flags()) + // // Bind flags to the Context's Viper so the app construction can set options + // // accordingly. + // ctx.Viper.BindPFlags(cmd.Flags()) // add support for all Tendermint-specific command line options tcmd.AddNodeFlags(cmd) @@ -148,9 +156,8 @@ func startStandAlone(ctx *Context, appCreator AppCreator) error { tmos.Exit(err.Error()) } - tmos.TrapSignal(ctx.Logger, func() { - err = svr.Stop() - if err != nil { + TrapSignal(func() { + if err = svr.Stop(); err != nil { tmos.Exit(err.Error()) } }) @@ -163,6 +170,7 @@ func startInProcess(ctx *Context, cdc codec.JSONMarshaler, appCreator AppCreator cfg := ctx.Config home := cfg.RootDir + fmt.Println("HOME:", home) traceWriterFile := ctx.Viper.GetString(flagTraceStore) db, err := openDB(home) if err != nil { diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 47db2f3256f1..7a906380084c 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -7,13 +7,12 @@ import ( "strings" "github.com/spf13/cobra" - yaml "gopkg.in/yaml.v2" - tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/p2p" pvm "github.com/tendermint/tendermint/privval" tversion "github.com/tendermint/tendermint/version" + yaml "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/codec" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -21,16 +20,19 @@ import ( ) // ShowNodeIDCmd - ported from Tendermint, dump node ID to stdout -func ShowNodeIDCmd(ctx *Context) *cobra.Command { +func ShowNodeIDCmd() *cobra.Command { return &cobra.Command{ Use: "show-node-id", Short: "Show this node's ID", RunE: func(cmd *cobra.Command, args []string) error { - cfg := ctx.Config + serverCtx := GetServerContextFromCmd(cmd) + cfg := serverCtx.Config + nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile()) if err != nil { return err } + fmt.Println(nodeKey.ID()) return nil }, @@ -38,12 +40,13 @@ func ShowNodeIDCmd(ctx *Context) *cobra.Command { } // ShowValidator - ported from Tendermint, show this node's validator info -func ShowValidatorCmd(ctx *Context) *cobra.Command { +func ShowValidatorCmd() *cobra.Command { cmd := cobra.Command{ Use: "show-validator", Short: "Show this node's tendermint validator info", RunE: func(cmd *cobra.Command, args []string) error { - cfg := ctx.Config + serverCtx := GetServerContextFromCmd(cmd) + cfg := serverCtx.Config privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) valPubKey, err := privValidator.GetPubKey() @@ -71,12 +74,14 @@ func ShowValidatorCmd(ctx *Context) *cobra.Command { } // ShowAddressCmd - show this node's validator address -func ShowAddressCmd(ctx *Context) *cobra.Command { +func ShowAddressCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show-address", Short: "Shows this node's tendermint validator consensus address", RunE: func(cmd *cobra.Command, args []string) error { - cfg := ctx.Config + serverCtx := GetServerContextFromCmd(cmd) + cfg := serverCtx.Config + privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) valConsAddr := (sdk.ConsAddress)(privValidator.GetAddress()) @@ -95,15 +100,14 @@ func ShowAddressCmd(ctx *Context) *cobra.Command { } // VersionCmd prints tendermint and ABCI version numbers. -func VersionCmd(ctx *Context) *cobra.Command { - cmd := &cobra.Command{ +func VersionCmd() *cobra.Command { + return &cobra.Command{ Use: "version", Short: "Print tendermint libraries' version", Long: `Print protocols' and libraries' version numbers against which this app has been compiled. `, RunE: func(cmd *cobra.Command, args []string) error { - bs, err := yaml.Marshal(&struct { Tendermint string ABCI string @@ -123,28 +127,31 @@ against which this app has been compiled. return nil }, } - return cmd } func printlnJSON(v interface{}) error { cdc := codec.New() cryptocodec.RegisterCrypto(cdc) + marshalled, err := cdc.MarshalJSON(v) if err != nil { return err } + fmt.Println(string(marshalled)) return nil } // UnsafeResetAllCmd - extension of the tendermint command, resets initialization -func UnsafeResetAllCmd(ctx *Context) *cobra.Command { +func UnsafeResetAllCmd() *cobra.Command { return &cobra.Command{ Use: "unsafe-reset-all", Short: "Resets the blockchain database, removes address book files, and resets priv_validator.json to the genesis state", RunE: func(cmd *cobra.Command, args []string) error { - cfg := ctx.Config - tcmd.ResetAll(cfg.DBDir(), cfg.P2P.AddrBookFile(), cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile(), ctx.Logger) + serverCtx := GetServerContextFromCmd(cmd) + cfg := serverCtx.Config + + tcmd.ResetAll(cfg.DBDir(), cfg.P2P.AddrBookFile(), cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile(), serverCtx.Logger) return nil }, } diff --git a/server/util.go b/server/util.go index a31eab0d3112..be11bc6b982f 100644 --- a/server/util.go +++ b/server/util.go @@ -21,11 +21,16 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/config" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" ) // DONTCOVER +// ServerContextKey defines the context key used to retrieve a server.Context from +// a command's Context. +const ServerContextKey = sdk.ContextKey("server.context") + // server context type Context struct { Viper *viper.Viper @@ -41,6 +46,57 @@ func NewContext(v *viper.Viper, config *tmcfg.Config, logger log.Logger) *Contex return &Context{v, config, logger} } +func InterceptConfigsPreRunHandler(cmd *cobra.Command) error { + rootViper := viper.New() + rootViper.BindPFlags(cmd.Flags()) + rootViper.BindPFlags(cmd.PersistentFlags()) + + serverCtx := NewDefaultContext() + config, err := interceptConfigs(serverCtx, rootViper) + if err != nil { + return err + } + + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, tmcfg.DefaultLogLevel()) + if err != nil { + return err + } + + if rootViper.GetBool(tmcli.TraceFlag) { + logger = log.NewTracingLogger(logger) + } + + serverCtx.Config = config + serverCtx.Logger = logger.With("module", "main") + + return SetCmdServerContext(cmd, serverCtx) +} + +// GetServerContextFromCmd returns a Context from a command or an empty Context +// if it has not been set. +func GetServerContextFromCmd(cmd *cobra.Command) *Context { + if v := cmd.Context().Value(ServerContextKey); v != nil { + serverCtxPtr := v.(*Context) + return serverCtxPtr + } + + return NewDefaultContext() +} + +// SetCmdServerContext sets a command's Context value to the provided argument. +func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error { + v := cmd.Context().Value(ServerContextKey) + if v == nil { + return errors.New("server context not set") + } + + serverCtxPtr := v.(*Context) + *serverCtxPtr = *serverCtx + + return nil +} + // PersistentPreRunEFn returns a PersistentPreRunE function for the root daemon // application command. The provided context is typically the default context, // where the logger and config are set based on the execution of parsing or @@ -139,8 +195,8 @@ func interceptConfigs(ctx *Context, rootViper *viper.Viper) (*tmcfg.Config, erro } // add server commands -func AddCommands(ctx *Context, cdc codec.JSONMarshaler, rootCmd *cobra.Command, appCreator AppCreator, appExport AppExporter) { - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") +func AddCommands(rootCmd *cobra.Command, appCreator AppCreator, appExport AppExporter) { + // rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") tendermintCmd := &cobra.Command{ Use: "tendermint", @@ -148,18 +204,18 @@ func AddCommands(ctx *Context, cdc codec.JSONMarshaler, rootCmd *cobra.Command, } tendermintCmd.AddCommand( - ShowNodeIDCmd(ctx), - ShowValidatorCmd(ctx), - ShowAddressCmd(ctx), - VersionCmd(ctx), + ShowNodeIDCmd(), + ShowValidatorCmd(), + ShowAddressCmd(), + VersionCmd(), ) rootCmd.AddCommand( - StartCmd(ctx, cdc, appCreator), - UnsafeResetAllCmd(ctx), + StartCmd(appCreator), + UnsafeResetAllCmd(), flags.LineBreak, tendermintCmd, - ExportCmd(ctx, cdc, appExport), + ExportCmd(appExport), flags.LineBreak, version.Cmd, ) diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 42578db4e859..09591610ce85 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/cli" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -28,7 +29,7 @@ const ( ) // AddGenesisAccountCmd returns add-genesis-account cobra Command. -func AddGenesisAccountCmd(ctx *server.Context, depCdc codec.JSONMarshaler, cdc codec.Marshaler, defaultClientHome string) *cobra.Command { +func AddGenesisAccountCmd(defaultClientHome string) *cobra.Command { cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -39,7 +40,13 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa `, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - config := ctx.Config + clientCtx := client.GetClientContextFromCmd(cmd) + depCdc := clientCtx.Codec + cdc := clientCtx.JSONMarshaler.(codec.Marshaler) + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + homeDir, _ := cmd.Flags().GetString(cli.HomeFlag) config.SetRoot(homeDir) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 331e5acd9f26..d6aea53d03e8 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -35,6 +35,16 @@ var ( rootCmd = &cobra.Command{ Use: "simd", Short: "simulation app", + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { + return err + } + if err := server.InterceptConfigsPreRunHandler(cmd); err != nil { + return err + } + + return nil + }, } encodingConfig = simapp.MakeEncodingConfig() @@ -57,6 +67,7 @@ func Execute() error { // https://github.com/spf13/cobra/pull/1118. ctx := context.Background() ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{}) + ctx = context.WithValue(ctx, server.ServerContextKey, server.NewDefaultContext()) executor := cli.PrepareBaseCmd(rootCmd, "", simapp.DefaultNodeHome) return executor.ExecuteContext(ctx) @@ -65,28 +76,19 @@ func Execute() error { func init() { authclient.Codec = encodingConfig.Marshaler - // add application daemon commands - cdc := encodingConfig.Amino - ctx := server.NewDefaultContext() - rootCmd.PersistentPreRunE = server.PersistentPreRunEFn(ctx) - rootCmd.PersistentFlags().String(flags.FlagHome, simapp.DefaultNodeHome, "The application home directory") - rootCmd.AddCommand( - genutilcli.InitCmd(ctx, cdc, simapp.ModuleBasics, simapp.DefaultNodeHome), - genutilcli.CollectGenTxsCmd(ctx, cdc, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), - genutilcli.MigrateGenesisCmd(ctx, cdc), - genutilcli.GenTxCmd( - ctx, cdc, simapp.ModuleBasics, - banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome, simapp.DefaultNodeHome, - ), - genutilcli.ValidateGenesisCmd(ctx, cdc, simapp.ModuleBasics), - AddGenesisAccountCmd(ctx, cdc, encodingConfig.Marshaler, simapp.DefaultNodeHome), + genutilcli.InitCmd(simapp.ModuleBasics, simapp.DefaultNodeHome), + genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), + genutilcli.MigrateGenesisCmd(), + genutilcli.GenTxCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), + genutilcli.ValidateGenesisCmd(simapp.ModuleBasics), + AddGenesisAccountCmd(simapp.DefaultNodeHome), flags.NewCompletionCmd(rootCmd, true), - testnetCmd(ctx, cdc, simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), - debug.Cmd(cdc), + testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), + debug.Cmd(), ) - server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) + server.AddCommands(rootCmd, newApp, exportAppStateAndTMValidators) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( @@ -104,10 +106,7 @@ func queryCommand() *cobra.Command { Short: "Querying subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - return client.SetCmdClientContextHandler(initClientCtx, cmd) - }, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( @@ -130,10 +129,7 @@ func txCommand() *cobra.Command { Short: "Transactions subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - return client.SetCmdClientContextHandler(initClientCtx, cmd) - }, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 2ef7427426a9..a5bce72881f1 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -18,6 +18,7 @@ import ( "github.com/tendermint/tendermint/types" tmtime "github.com/tendermint/tendermint/types/time" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" clientkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" @@ -43,10 +44,7 @@ var ( ) // get cmd to initialize all files for tendermint testnet and application -func testnetCmd(ctx *server.Context, cdc codec.JSONMarshaler, - mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator, -) *cobra.Command { - +func testnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { cmd := &cobra.Command{ Use: "testnet", Short: "Initialize files for a simapp testnet", @@ -59,7 +57,11 @@ Example: simd testnet --v 4 --output-dir ./output --starting-ip-address 192.168.10.2 `, RunE: func(cmd *cobra.Command, _ []string) error { - config := ctx.Config + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config outputDir, _ := cmd.Flags().GetString(flagOutputDir) keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) diff --git a/types/context.go b/types/context.go index 71783023c46f..ff559d43cde3 100644 --- a/types/context.go +++ b/types/context.go @@ -226,9 +226,10 @@ func (c Context) CacheContext() (cc Context, writeCache func()) { return cc, cms.Write } -type sdkContextKeyType string +// ContextKey defines a type alias for a stdlib Context key. +type ContextKey string -const sdkContextKey sdkContextKeyType = "sdk-context" +const sdkContextKey ContextKey = "sdk-context" // WrapSDKContext returns a stdlib context.Context with the provided sdk.Context's internal // context as a value. It is useful for passing an sdk.Context through methods that take a diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index c857d1203eea..601303eb121e 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/libs/cli" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" + "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" @@ -18,14 +18,20 @@ import ( const flagGenTxDir = "gentx-dir" // CollectGenTxsCmd - return the cobra command to collect genesis transactions -func CollectGenTxsCmd(ctx *server.Context, cdc codec.JSONMarshaler, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command { +func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: "collect-gentxs", Short: "Collect genesis txs and output a genesis.json file", RunE: func(cmd *cobra.Command, _ []string) error { - config := ctx.Config + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + home, _ := cmd.Flags().GetString(cli.HomeFlag) config.SetRoot(home) + nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") @@ -58,11 +64,7 @@ func CollectGenTxsCmd(ctx *server.Context, cdc codec.JSONMarshaler, genBalIterat } cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") - cmd.Flags().String(flagGenTxDir, "", - "override default \"gentx\" directory from which collect and execute "+ - "genesis transactions; default [--home]/config/gentx/") + cmd.Flags().String(flagGenTxDir, "", "override default \"gentx\" directory from which collect and execute genesis transactions; default [--home]/config/gentx/") return cmd } - -// DONTCOVER diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 8c187fcb4253..053ad1c98a28 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -31,8 +31,7 @@ import ( // GenTxCmd builds the application's gentx command. // nolint: errcheck -func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, - genBalIterator types.GenesisBalancesIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { +func GenTxCmd(mbm module.BasicManager, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -47,11 +46,16 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, %s`, defaultsDesc), RunE: func(cmd *cobra.Command, args []string) error { + serverCtx := server.GetServerContextFromCmd(cmd) + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + home, _ := cmd.Flags().GetString(flags.FlagHome) - config := ctx.Config + config := serverCtx.Config config.SetRoot(home) - nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config) + + nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(serverCtx.Config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") } @@ -126,7 +130,8 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, if err != nil { return errors.Wrap(err, "error creating tx builder") } - txBldr = txBldr.WithTxEncoder(authclient.GetTxEncoder(cdc)) + + txBldr = txBldr.WithTxEncoder(authclient.GetTxEncoder(clientCtx.Codec)) from, _ := cmd.Flags().GetString(flags.FlagFrom) fromAddress, _, err := client.GetFromFields(txBldr.Keybase(), from, false) @@ -134,9 +139,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, return errors.Wrap(err, "error getting from address") } - clientCtx := client.Context{}. - WithInput(inBuf).WithCodec(cdc).WithJSONMarshaler(cdc). - WithFromAddress(fromAddress) + clientCtx = clientCtx.WithInput(inBuf).WithFromAddress(fromAddress) // create a 'create-validator' message txBldr, msg, err := cli.BuildCreateValidatorMsg(clientCtx, createValCfg, txBldr, true) @@ -189,18 +192,15 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, }, } - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") - cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory") + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") cmd.Flags().String(flags.FlagName, "", "name of private key with which to sign the gentx") - cmd.Flags().String(flags.FlagOutputDocument, "", - "write the genesis transaction JSON document to the given file instead of the default location") + cmd.Flags().String(flags.FlagOutputDocument, "", "write the genesis transaction JSON document to the given file instead of the default location") cmd.Flags().AddFlagSet(fsCreateValidator) cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") + cmd.MarkFlagRequired(flags.FlagName) flags.PostCommands(cmd) - cmd.MarkFlagRequired(flags.FlagName) - return cmd } @@ -213,7 +213,7 @@ func makeOutputFilepath(rootDir, nodeID string) (string, error) { return filepath.Join(writePath, fmt.Sprintf("gentx-%v.json", nodeID)), nil } -func readUnsignedGenTxFile(cdc *codec.Codec, r io.Reader) (authtypes.StdTx, error) { +func readUnsignedGenTxFile(cdc codec.JSONMarshaler, r io.Reader) (authtypes.StdTx, error) { var stdTx authtypes.StdTx bytes, err := ioutil.ReadAll(r) @@ -222,11 +222,10 @@ func readUnsignedGenTxFile(cdc *codec.Codec, r io.Reader) (authtypes.StdTx, erro } err = cdc.UnmarshalJSON(bytes, &stdTx) - return stdTx, err } -func writeSignedGenTx(cdc *codec.Codec, outputDocument string, tx authtypes.StdTx) error { +func writeSignedGenTx(cdc codec.JSONMarshaler, outputDocument string, tx authtypes.StdTx) error { outputFile, err := os.OpenFile(outputDocument, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) if err != nil { return err diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 2452faaebbd7..a0b7249eab33 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -14,6 +14,7 @@ import ( tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/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" @@ -58,20 +59,23 @@ func displayInfo(cdc codec.JSONMarshaler, info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManager, defaultNodeHome string) *cobra.Command { +func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: "init [moniker]", Short: "Initialize private validator, p2p, genesis, and application configuration files", Long: `Initialize validators's and node's configuration files.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - config := ctx.Config - home, _ := cmd.Flags().GetString(cli.HomeFlag) + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + home, _ := cmd.Flags().GetString(cli.HomeFlag) config.SetRoot(home) chainID, _ := cmd.Flags().GetString(flags.FlagChainID) - if chainID == "" { chainID = fmt.Sprintf("test-chain-%v", tmrand.Str(6)) } diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 2570e56d3a3f..dd53a6ea1a83 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -1,24 +1,16 @@ package cli import ( - "bytes" - "io" - "os" "testing" - "time" "github.com/spf13/viper" "github.com/stretchr/testify/require" - abciServer "github.com/tendermint/tendermint/abci/server" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/mock" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -27,21 +19,21 @@ import ( var testMbm = module.NewBasicManager(genutil.AppModuleBasic{}) -func TestInitCmd(t *testing.T) { - t.SkipNow() - home, cleanup := tests.NewTestCaseDir(t) - t.Cleanup(cleanup) +// func TestInitCmd(t *testing.T) { +// t.SkipNow() +// home, cleanup := tests.NewTestCaseDir(t) +// t.Cleanup(cleanup) - logger := log.NewNopLogger() - cfg, err := tcmd.ParseConfig() - require.Nil(t, err) +// logger := log.NewNopLogger() +// cfg, err := tcmd.ParseConfig() +// require.Nil(t, err) - ctx := server.NewContext(viper.New(), cfg, logger) - cdc := makeCodec() - cmd := InitCmd(ctx, cdc, testMbm, home) +// ctx := server.NewContext(viper.New(), cfg, logger) +// cdc := makeCodec() +// cmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) -} +// require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) +// } func setupClientHome(t *testing.T) func() { clientDir, cleanup := tests.NewTestCaseDir(t) @@ -49,80 +41,80 @@ func setupClientHome(t *testing.T) func() { return cleanup } -func TestEmptyState(t *testing.T) { - t.SkipNow() - t.Cleanup(setupClientHome(t)) - - home, cleanup := tests.NewTestCaseDir(t) - t.Cleanup(cleanup) - - logger := log.NewNopLogger() - cfg, err := tcmd.ParseConfig() - require.Nil(t, err) - - ctx := server.NewContext(viper.New(), cfg, logger) - cdc := makeCodec() - - cmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) - - old := os.Stdout - r, w, _ := os.Pipe() - os.Stdout = w - cmd = server.ExportCmd(ctx, cdc, nil) - - err = cmd.RunE(nil, nil) - require.NoError(t, err) - - outC := make(chan string) - go func() { - var buf bytes.Buffer - io.Copy(&buf, r) - outC <- buf.String() - }() - - w.Close() - os.Stdout = old - out := <-outC - - require.Contains(t, out, "genesis_time") - require.Contains(t, out, "chain_id") - require.Contains(t, out, "consensus_params") - require.Contains(t, out, "app_hash") - require.Contains(t, out, "app_state") -} - -func TestStartStandAlone(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) - t.Cleanup(cleanup) - viper.Set(cli.HomeFlag, home) - t.Cleanup(setupClientHome(t)) - - logger := log.NewNopLogger() - cfg, err := tcmd.ParseConfig() - require.Nil(t, err) - ctx := server.NewContext(viper.New(), cfg, logger) - cdc := makeCodec() - initCmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, initCmd.RunE(initCmd, []string{"appnode-test"})) - - app, err := mock.NewApp(home, logger) - require.Nil(t, err) - svrAddr, _, err := server.FreeTCPAddr() - require.Nil(t, err) - svr, err := abciServer.NewServer(svrAddr, "socket", app) - require.Nil(t, err, "error creating listener") - svr.SetLogger(logger.With("module", "abci-server")) - err = svr.Start() - require.NoError(t, err) - - timer := time.NewTimer(time.Duration(2) * time.Second) - for range timer.C { - err = svr.Stop() - require.NoError(t, err) - break - } -} +// func TestEmptyState(t *testing.T) { +// t.SkipNow() +// t.Cleanup(setupClientHome(t)) + +// home, cleanup := tests.NewTestCaseDir(t) +// t.Cleanup(cleanup) + +// logger := log.NewNopLogger() +// cfg, err := tcmd.ParseConfig() +// require.Nil(t, err) + +// ctx := server.NewContext(viper.New(), cfg, logger) +// cdc := makeCodec() + +// cmd := InitCmd(testMbm, home) +// require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) + +// old := os.Stdout +// r, w, _ := os.Pipe() +// os.Stdout = w +// cmd = server.ExportCmd(nil) + +// err = cmd.RunE(nil, nil) +// require.NoError(t, err) + +// outC := make(chan string) +// go func() { +// var buf bytes.Buffer +// io.Copy(&buf, r) +// outC <- buf.String() +// }() + +// w.Close() +// os.Stdout = old +// out := <-outC + +// require.Contains(t, out, "genesis_time") +// require.Contains(t, out, "chain_id") +// require.Contains(t, out, "consensus_params") +// require.Contains(t, out, "app_hash") +// require.Contains(t, out, "app_state") +// } + +// func TestStartStandAlone(t *testing.T) { +// home, cleanup := tests.NewTestCaseDir(t) +// t.Cleanup(cleanup) +// viper.Set(cli.HomeFlag, home) +// t.Cleanup(setupClientHome(t)) + +// logger := log.NewNopLogger() +// cfg, err := tcmd.ParseConfig() +// require.Nil(t, err) +// ctx := server.NewContext(viper.New(), cfg, logger) +// cdc := makeCodec() +// initCmd := InitCmd(ctx, cdc, testMbm, home) +// require.NoError(t, initCmd.RunE(initCmd, []string{"appnode-test"})) + +// app, err := mock.NewApp(home, logger) +// require.Nil(t, err) +// svrAddr, _, err := server.FreeTCPAddr() +// require.Nil(t, err) +// svr, err := abciServer.NewServer(svrAddr, "socket", app) +// require.Nil(t, err, "error creating listener") +// svr.SetLogger(logger.With("module", "abci-server")) +// err = svr.Start() +// require.NoError(t, err) + +// timer := time.NewTimer(time.Duration(2) * time.Second) +// for range timer.C { +// err = svr.Stop() +// require.NoError(t, err) +// break +// } +// } func TestInitNodeValidatorFiles(t *testing.T) { home, cleanup := tests.NewTestCaseDir(t) diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index d612cfe619c7..2ac83338394f 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -9,8 +9,8 @@ import ( "github.com/spf13/cobra" tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" v036 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_36" @@ -55,7 +55,7 @@ func GetMigrationVersions() []string { } // MigrateGenesisCmd returns a command to execute genesis state migration. -func MigrateGenesisCmd(_ *server.Context, cdc *codec.Codec) *cobra.Command { +func MigrateGenesisCmd() *cobra.Command { cmd := &cobra.Command{ Use: "migrate [target-version] [genesis-file]", Short: "Migrate genesis to a specified target version", @@ -66,6 +66,9 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 `, version.AppName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.JSONMarshaler + var err error target := args[0] @@ -111,7 +114,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 genDoc.ChainID = chainID } - bz, err := cdc.MarshalJSONIndent(genDoc, "", " ") + bz, err := codec.MarshalJSONIndent(cdc, genDoc) if err != nil { return errors.Wrap(err, "failed to marshal genesis doc") } diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index a974a69f9ad8..df6b70356800 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -1,20 +1,10 @@ package cli import ( - "io/ioutil" - "path" "testing" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/stretchr/testify/require" - tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" - "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" ) func setupCmd(genesisTime string, chainID string) *cobra.Command { @@ -36,28 +26,28 @@ func TestGetMigrationCallback(t *testing.T) { } } -func TestMigrateGenesis(t *testing.T) { - home, cleanup := tests.NewTestCaseDir(t) - t.Cleanup(cleanup) - viper.Set(cli.HomeFlag, home) - viper.Set(flags.FlagName, "moniker") - logger := log.NewNopLogger() - cfg, err := tcmd.ParseConfig() - require.Nil(t, err) - ctx := server.NewContext(viper.New(), cfg, logger) - cdc := makeCodec() - - genesisPath := path.Join(home, "genesis.json") - target := "v0.36" - - // Reject if we dont' have the right parameters or genesis does not exists - require.Error(t, MigrateGenesisCmd(ctx, cdc).RunE(nil, []string{target, genesisPath})) - - // Noop migration with minimal genesis - emptyGenesis := []byte(`{"chain_id":"test","app_state":{}}`) - err = ioutil.WriteFile(genesisPath, emptyGenesis, 0644) - require.Nil(t, err) - cmd := setupCmd("", "test2") - require.NoError(t, MigrateGenesisCmd(ctx, cdc).RunE(cmd, []string{target, genesisPath})) - // Every migration function shuold tests its own module separately -} +// func TestMigrateGenesis(t *testing.T) { +// home, cleanup := tests.NewTestCaseDir(t) +// t.Cleanup(cleanup) +// viper.Set(cli.HomeFlag, home) +// viper.Set(flags.FlagName, "moniker") +// logger := log.NewNopLogger() +// cfg, err := tcmd.ParseConfig() +// require.Nil(t, err) +// ctx := server.NewContext(viper.New(), cfg, logger) +// cdc := makeCodec() + +// genesisPath := path.Join(home, "genesis.json") +// target := "v0.36" + +// // Reject if we dont' have the right parameters or genesis does not exists +// require.Error(t, MigrateGenesisCmd().RunE(nil, []string{target, genesisPath})) + +// // Noop migration with minimal genesis +// emptyGenesis := []byte(`{"chain_id":"test","app_state":{}}`) +// err = ioutil.WriteFile(genesisPath, emptyGenesis, 0644) +// require.Nil(t, err) +// cmd := setupCmd("", "test2") +// require.NoError(t, MigrateGenesisCmd().RunE(cmd, []string{target, genesisPath})) +// // Every migration function shuold tests its own module separately +// } diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 1e9ffb74896d..8d4dce3a2793 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -8,23 +8,27 @@ import ( "github.com/spf13/cobra" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/types/module" ) // Validate genesis command takes -func ValidateGenesisCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManager) *cobra.Command { +func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { return &cobra.Command{ Use: "validate-genesis [file]", 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) + clientCtx := client.GetClientContextFromCmd(cmd) + + cdc := clientCtx.JSONMarshaler // Load default if passed no args, otherwise load passed file var genesis string if len(args) == 0 { - genesis = ctx.Config.GenesisFile() + genesis = serverCtx.Config.GenesisFile() } else { genesis = args[0] } @@ -45,8 +49,6 @@ func ValidateGenesisCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module return fmt.Errorf("error validating genesis file %s: %s", genesis, err.Error()) } - // TODO test to make sure initchain doesn't panic - fmt.Printf("File at %s is a valid genesis file\n", genesis) return nil }, From 16442d93f106bb8415859cfa75a04d0dad3bab01 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:25:13 -0400 Subject: [PATCH 23/33] fix start cmd --- server/start.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/server/start.go b/server/start.go index c024d9faf85c..d6adc9e5c960 100644 --- a/server/start.go +++ b/server/start.go @@ -77,8 +77,8 @@ which accepts a path for the resulting pprof file. PreRunE: func(cmd *cobra.Command, _ []string) error { serverCtx := GetServerContextFromCmd(cmd) - // Bind flags to the Context's Viper so the app construction can set options - // accordingly. + // Bind flags to the Context's Viper so the app construction can set + // options accordingly. serverCtx.Viper.BindPFlags(cmd.Flags()) _, err := GetPruningOptionsFromFlags(serverCtx.Viper) @@ -118,10 +118,6 @@ which accepts a path for the resulting pprof file. cmd.Flags().Uint64(FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')") cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") - // // Bind flags to the Context's Viper so the app construction can set options - // // accordingly. - // ctx.Viper.BindPFlags(cmd.Flags()) - // add support for all Tendermint-specific command line options tcmd.AddNodeFlags(cmd) return cmd From ebbde6473451afdea37f1c4674a821ad24195972 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:25:37 -0400 Subject: [PATCH 24/33] fix start cmd --- server/start.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/start.go b/server/start.go index d6adc9e5c960..9dd1418a04e3 100644 --- a/server/start.go +++ b/server/start.go @@ -166,7 +166,6 @@ func startInProcess(ctx *Context, cdc codec.JSONMarshaler, appCreator AppCreator cfg := ctx.Config home := cfg.RootDir - fmt.Println("HOME:", home) traceWriterFile := ctx.Viper.GetString(flagTraceStore) db, err := openDB(home) if err != nil { From 2857d74ece8ae950cc04c17226cc40426263de85 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:28:40 -0400 Subject: [PATCH 25/33] Update godoc --- server/util.go | 46 +++++++--------------------------------------- 1 file changed, 7 insertions(+), 39 deletions(-) diff --git a/server/util.go b/server/util.go index be11bc6b982f..ae2203aba573 100644 --- a/server/util.go +++ b/server/util.go @@ -46,6 +46,13 @@ func NewContext(v *viper.Viper, config *tmcfg.Config, logger log.Logger) *Contex return &Context{v, config, logger} } +// InterceptConfigsPreRunHandler performs a pre-run function for the root daemon +// application command. It will create a Viper literal and a default server +// Context. The server Tendermint configuration will either be read and parsed +// or created and saved to disk, where the server Context is updated to reflect +// the Tendermint configuration. The Viper literal is used to read and parse +// the application configuration. Command handlers can fetch the server Context +// to get the Tendermint configuration or to get access to Viper. func InterceptConfigsPreRunHandler(cmd *cobra.Command) error { rootViper := viper.New() rootViper.BindPFlags(cmd.Flags()) @@ -97,45 +104,6 @@ func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error { return nil } -// PersistentPreRunEFn returns a PersistentPreRunE function for the root daemon -// application command. The provided context is typically the default context, -// where the logger and config are set based on the execution of parsing or -// creating a new Tendermint configuration file (config.toml). The provided -// viper object must be created at the root level and have all necessary flags, -// defined by Tendermint, bound to it. -func PersistentPreRunEFn(ctx *Context) func(*cobra.Command, []string) error { - return func(cmd *cobra.Command, args []string) error { - rootViper := viper.New() - rootViper.BindPFlags(cmd.Flags()) - rootViper.BindPFlags(cmd.PersistentFlags()) - - if cmd.Name() == version.Cmd.Name() { - return nil - } - - config, err := interceptConfigs(ctx, rootViper) - if err != nil { - return err - } - - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, tmcfg.DefaultLogLevel()) - if err != nil { - return err - } - - if rootViper.GetBool(tmcli.TraceFlag) { - logger = log.NewTracingLogger(logger) - } - - logger = logger.With("module", "main") - ctx.Config = config - ctx.Logger = logger - - return nil - } -} - // interceptConfigs parses and updates a Tendermint configuration file or // creates a new one and saves it. It also parses and saves the application // configuration file. The Tendermint configuration file is parsed given a root From 6208fce640db9929702988bf925b80f508ff7a63 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:35:18 -0400 Subject: [PATCH 26/33] remove comment --- server/util.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/server/util.go b/server/util.go index ae2203aba573..862c93345619 100644 --- a/server/util.go +++ b/server/util.go @@ -164,8 +164,6 @@ func interceptConfigs(ctx *Context, rootViper *viper.Viper) (*tmcfg.Config, erro // add server commands func AddCommands(rootCmd *cobra.Command, appCreator AppCreator, appExport AppExporter) { - // rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - tendermintCmd := &cobra.Command{ Use: "tendermint", Short: "Tendermint subcommands", From 9e48e3f7b7933b5456f9afebba3cfe7311e827ce Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:43:04 -0400 Subject: [PATCH 27/33] Fix TestExportCmd_ConsensusParams --- server/export_test.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/server/export_test.go b/server/export_test.go index 5435f66332e0..96f14b139a7a 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -2,6 +2,7 @@ package server import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -16,6 +17,7 @@ import ( tmtypes "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" @@ -36,11 +38,13 @@ func TestExportCmd_ConsensusParams(t *testing.T) { db := dbm.NewMemDB() app := simapp.NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, tempDir, 0) - ctx := NewDefaultContext() - ctx.Config.RootDir = tempDir + serverCtx := NewDefaultContext() + serverCtx.Config.RootDir = tempDir + + clientCtx := client.Context{}.WithJSONMarshaler(app.Codec()) genDoc := newDefaultGenesisDoc(app.Codec()) - err = saveGenesisFile(genDoc, ctx.Config.GenesisFile()) + err = saveGenesisFile(genDoc, serverCtx.Config.GenesisFile()) app.InitChain( abci.RequestInitChain{ @@ -57,10 +61,14 @@ func TestExportCmd_ConsensusParams(t *testing.T) { return app.ExportAppStateAndValidators(true, []string{}) }) + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + ctx = context.WithValue(ctx, ServerContextKey, serverCtx) + output := &bytes.Buffer{} cmd.SetOut(output) cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, tempDir)}) - require.NoError(t, cmd.Execute()) + require.NoError(t, cmd.ExecuteContext(ctx)) var exportedGenDoc tmtypes.GenesisDoc err = app.Codec().UnmarshalJSON(output.Bytes(), &exportedGenDoc) From 5dc8c516aabbdbb32db9812d296de48d27f31da0 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 10:49:36 -0400 Subject: [PATCH 28/33] genutil: Fix TestMigrateGenesis --- x/genutil/client/cli/migrate_test.go | 73 +++++++++++++--------------- 1 file changed, 34 insertions(+), 39 deletions(-) diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index df6b70356800..5602ddc88e9a 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -1,24 +1,16 @@ package cli import ( + "context" + "io/ioutil" + "path" "testing" - "github.com/spf13/cobra" "github.com/stretchr/testify/require" -) - -func setupCmd(genesisTime string, chainID string) *cobra.Command { - c := &cobra.Command{ - Use: "c", - Args: cobra.ArbitraryArgs, - Run: func(_ *cobra.Command, args []string) {}, - } - - c.Flags().String(flagGenesisTime, genesisTime, "") - c.Flags().String(flagChainID, chainID, "") - return c -} + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/tests" +) func TestGetMigrationCallback(t *testing.T) { for _, version := range GetMigrationVersions() { @@ -26,28 +18,31 @@ func TestGetMigrationCallback(t *testing.T) { } } -// func TestMigrateGenesis(t *testing.T) { -// home, cleanup := tests.NewTestCaseDir(t) -// t.Cleanup(cleanup) -// viper.Set(cli.HomeFlag, home) -// viper.Set(flags.FlagName, "moniker") -// logger := log.NewNopLogger() -// cfg, err := tcmd.ParseConfig() -// require.Nil(t, err) -// ctx := server.NewContext(viper.New(), cfg, logger) -// cdc := makeCodec() - -// genesisPath := path.Join(home, "genesis.json") -// target := "v0.36" - -// // Reject if we dont' have the right parameters or genesis does not exists -// require.Error(t, MigrateGenesisCmd().RunE(nil, []string{target, genesisPath})) - -// // Noop migration with minimal genesis -// emptyGenesis := []byte(`{"chain_id":"test","app_state":{}}`) -// err = ioutil.WriteFile(genesisPath, emptyGenesis, 0644) -// require.Nil(t, err) -// cmd := setupCmd("", "test2") -// require.NoError(t, MigrateGenesisCmd().RunE(cmd, []string{target, genesisPath})) -// // Every migration function shuold tests its own module separately -// } +func TestMigrateGenesis(t *testing.T) { + home, cleanup := tests.NewTestCaseDir(t) + t.Cleanup(cleanup) + + cdc := makeCodec() + + genesisPath := path.Join(home, "genesis.json") + target := "v0.36" + + cmd := MigrateGenesisCmd() + cmd.SetErr(ioutil.Discard) + cmd.SetOut(ioutil.Discard) + + clientCtx := client.Context{}.WithJSONMarshaler(cdc) + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + + // Reject if we dont' have the right parameters or genesis does not exists + cmd.SetArgs([]string{target, genesisPath}) + require.Error(t, cmd.ExecuteContext(ctx)) + + // Noop migration with minimal genesis + emptyGenesis := []byte(`{"chain_id":"test","app_state":{}}`) + require.NoError(t, ioutil.WriteFile(genesisPath, emptyGenesis, 0644)) + + cmd.SetArgs([]string{target, genesisPath}) + require.NoError(t, cmd.ExecuteContext(ctx)) +} From 7c08736b7712afeaf28b258e9b5c2e75e1d37b54 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 11:02:30 -0400 Subject: [PATCH 29/33] genutil: fix tests --- x/genutil/client/cli/init_test.go | 216 ++++++++++++++++++------------ 1 file changed, 130 insertions(+), 86 deletions(-) diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index dd53a6ea1a83..400030453f92 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -1,16 +1,28 @@ package cli import ( + "bytes" + "context" + "fmt" + "io" + "os" "testing" + "time" "github.com/spf13/viper" "github.com/stretchr/testify/require" + abci_server "github.com/tendermint/tendermint/abci/server" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + tmcfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/mock" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -19,21 +31,38 @@ import ( var testMbm = module.NewBasicManager(genutil.AppModuleBasic{}) -// func TestInitCmd(t *testing.T) { -// t.SkipNow() -// home, cleanup := tests.NewTestCaseDir(t) -// t.Cleanup(cleanup) +func createDefaultTendermintConfig(rootDir string) (*tmcfg.Config, error) { + conf := tmcfg.DefaultConfig() + conf.SetRoot(rootDir) + tmcfg.EnsureRoot(rootDir) -// logger := log.NewNopLogger() -// cfg, err := tcmd.ParseConfig() -// require.Nil(t, err) + if err := conf.ValidateBasic(); err != nil { + return nil, fmt.Errorf("error in config file: %v", err) + } -// ctx := server.NewContext(viper.New(), cfg, logger) -// cdc := makeCodec() -// cmd := InitCmd(ctx, cdc, testMbm, home) + return conf, nil +} + +func TestInitCmd(t *testing.T) { + home, cleanup := tests.NewTestCaseDir(t) + t.Cleanup(cleanup) + + logger := log.NewNopLogger() + cfg, err := createDefaultTendermintConfig(home) + require.NoError(t, err) -// require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) -// } + serverCtx := server.NewContext(viper.New(), cfg, logger) + clientCtx := client.Context{}.WithJSONMarshaler(makeCodec()) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + + cmd := InitCmd(testMbm, home) + cmd.SetArgs([]string{"appnode-test"}) + + require.NoError(t, cmd.ExecuteContext(ctx)) +} func setupClientHome(t *testing.T) func() { clientDir, cleanup := tests.NewTestCaseDir(t) @@ -41,80 +70,95 @@ func setupClientHome(t *testing.T) func() { return cleanup } -// func TestEmptyState(t *testing.T) { -// t.SkipNow() -// t.Cleanup(setupClientHome(t)) - -// home, cleanup := tests.NewTestCaseDir(t) -// t.Cleanup(cleanup) - -// logger := log.NewNopLogger() -// cfg, err := tcmd.ParseConfig() -// require.Nil(t, err) - -// ctx := server.NewContext(viper.New(), cfg, logger) -// cdc := makeCodec() - -// cmd := InitCmd(testMbm, home) -// require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) - -// old := os.Stdout -// r, w, _ := os.Pipe() -// os.Stdout = w -// cmd = server.ExportCmd(nil) - -// err = cmd.RunE(nil, nil) -// require.NoError(t, err) - -// outC := make(chan string) -// go func() { -// var buf bytes.Buffer -// io.Copy(&buf, r) -// outC <- buf.String() -// }() - -// w.Close() -// os.Stdout = old -// out := <-outC - -// require.Contains(t, out, "genesis_time") -// require.Contains(t, out, "chain_id") -// require.Contains(t, out, "consensus_params") -// require.Contains(t, out, "app_hash") -// require.Contains(t, out, "app_state") -// } - -// func TestStartStandAlone(t *testing.T) { -// home, cleanup := tests.NewTestCaseDir(t) -// t.Cleanup(cleanup) -// viper.Set(cli.HomeFlag, home) -// t.Cleanup(setupClientHome(t)) - -// logger := log.NewNopLogger() -// cfg, err := tcmd.ParseConfig() -// require.Nil(t, err) -// ctx := server.NewContext(viper.New(), cfg, logger) -// cdc := makeCodec() -// initCmd := InitCmd(ctx, cdc, testMbm, home) -// require.NoError(t, initCmd.RunE(initCmd, []string{"appnode-test"})) - -// app, err := mock.NewApp(home, logger) -// require.Nil(t, err) -// svrAddr, _, err := server.FreeTCPAddr() -// require.Nil(t, err) -// svr, err := abciServer.NewServer(svrAddr, "socket", app) -// require.Nil(t, err, "error creating listener") -// svr.SetLogger(logger.With("module", "abci-server")) -// err = svr.Start() -// require.NoError(t, err) - -// timer := time.NewTimer(time.Duration(2) * time.Second) -// for range timer.C { -// err = svr.Stop() -// require.NoError(t, err) -// break -// } -// } +func TestEmptyState(t *testing.T) { + t.Cleanup(setupClientHome(t)) + + home, cleanup := tests.NewTestCaseDir(t) + t.Cleanup(cleanup) + + logger := log.NewNopLogger() + cfg, err := createDefaultTendermintConfig(home) + require.NoError(t, err) + + serverCtx := server.NewContext(viper.New(), cfg, logger) + clientCtx := client.Context{}.WithJSONMarshaler(makeCodec()) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + + cmd := InitCmd(testMbm, home) + cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + + require.NoError(t, cmd.ExecuteContext(ctx)) + + old := os.Stdout + r, w, _ := os.Pipe() + os.Stdout = w + + cmd = server.ExportCmd(nil) + cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + require.NoError(t, cmd.ExecuteContext(ctx)) + + outC := make(chan string) + go func() { + var buf bytes.Buffer + io.Copy(&buf, r) + outC <- buf.String() + }() + + w.Close() + os.Stdout = old + out := <-outC + + require.Contains(t, out, "genesis_time") + require.Contains(t, out, "chain_id") + require.Contains(t, out, "consensus_params") + require.Contains(t, out, "app_hash") + require.Contains(t, out, "app_state") +} + +func TestStartStandAlone(t *testing.T) { + home, cleanup := tests.NewTestCaseDir(t) + t.Cleanup(cleanup) + t.Cleanup(setupClientHome(t)) + + logger := log.NewNopLogger() + cfg, err := createDefaultTendermintConfig(home) + require.NoError(t, err) + + serverCtx := server.NewContext(viper.New(), cfg, logger) + clientCtx := client.Context{}.WithJSONMarshaler(makeCodec()) + + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) + ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) + + cmd := InitCmd(testMbm, home) + cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + + require.NoError(t, cmd.ExecuteContext(ctx)) + + app, err := mock.NewApp(home, logger) + require.NoError(t, err) + + svrAddr, _, err := server.FreeTCPAddr() + require.NoError(t, err) + + svr, err := abci_server.NewServer(svrAddr, "socket", app) + require.NoError(t, err, "error creating listener") + + svr.SetLogger(logger.With("module", "abci-server")) + err = svr.Start() + require.NoError(t, err) + + timer := time.NewTimer(time.Duration(2) * time.Second) + for range timer.C { + err = svr.Stop() + require.NoError(t, err) + break + } +} func TestInitNodeValidatorFiles(t *testing.T) { home, cleanup := tests.NewTestCaseDir(t) From e4f283a77d5ed7f42cecf8ae593a9699bf35149d Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 11:04:19 -0400 Subject: [PATCH 30/33] build: update make targets --- .github/workflows/test.yml | 4 ++-- Dockerfile | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f8cb95c69195..1ad32b856d56 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -205,9 +205,9 @@ jobs: .go .mod .sum - - name: build-sim + - name: build-simd run: | - make build-sim + make build-simd if: "env.GIT_DIFF != ''" - name: cli-test run: | diff --git a/Dockerfile b/Dockerfile index b6a305ad4bb2..4f836543f5d9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -24,7 +24,7 @@ COPY . . # build Cosmos SDK, remove packages RUN make tools && \ - make build-sim && \ + make build-simd && \ cp ./build/sim* /go/bin # make build-sim-linux ?? From c7593da38a178e0207b1c9be5bc3f5c1f47779e7 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 11:16:30 -0400 Subject: [PATCH 31/33] revert client/flags/flags.go --- client/flags/flags.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/client/flags/flags.go b/client/flags/flags.go index 960b80012524..ad2562bff89a 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -81,6 +82,12 @@ func GetCommands(cmds ...*cobra.Command) []*cobra.Command { c.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)") c.Flags().String(FlagKeyringBackend, DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + // TODO: REMOVE VIPER CALLS! + viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode)) + viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger)) + viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode)) + viper.BindPFlag(FlagKeyringBackend, c.Flags().Lookup(FlagKeyringBackend)) + c.MarkFlagRequired(FlagChainID) c.SetErr(c.ErrOrStderr()) @@ -119,6 +126,12 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command { GasFlagAuto, DefaultGasLimit, )) + // TODO: REMOVE VIPER CALLS! + viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode)) + viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger)) + viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode)) + viper.BindPFlag(FlagKeyringBackend, c.Flags().Lookup(FlagKeyringBackend)) + c.MarkFlagRequired(FlagChainID) c.SetErr(c.ErrOrStderr()) From 277e19238ff0ea5fa97b4e634dc3e7da8207c6d9 Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Tue, 7 Jul 2020 11:22:51 -0400 Subject: [PATCH 32/33] Update simapp/simd/cmd/root.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- simapp/simd/cmd/root.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index d6aea53d03e8..7244f445a3d1 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -39,11 +39,7 @@ var ( if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { return err } - if err := server.InterceptConfigsPreRunHandler(cmd); err != nil { - return err - } - - return nil + return server.InterceptConfigsPreRunHandler(cmd) }, } From 15e367312a12c5d71ccdee8484c16951f28489b6 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 7 Jul 2020 11:25:02 -0400 Subject: [PATCH 33/33] genutil: add get commands --- simapp/simd/cmd/genaccounts.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 09591610ce85..26802fbbd7ef 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -167,5 +167,5 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") - return cmd + return flags.GetCommands(cmd)[0] }