From aecceec83151dbf60af0385be6ffdc1d421f48ed Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Fri, 5 Mar 2021 15:42:50 -0800 Subject: [PATCH 01/14] add client config draft --- client/config/config.go | 234 +++++++++++++++++++++++++++++++++++ client/config/config_test.go | 59 +++++++++ go.mod | 2 +- simapp/simd/cmd/root.go | 7 +- 4 files changed, 299 insertions(+), 3 deletions(-) create mode 100644 client/config/config.go create mode 100644 client/config/config_test.go diff --git a/client/config/config.go b/client/config/config.go new file mode 100644 index 000000000000..3d9594f587ad --- /dev/null +++ b/client/config/config.go @@ -0,0 +1,234 @@ +package config + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "path" + "strconv" + + toml "github.com/pelletier/go-toml" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/client/flags" +) + +const ( + flagGet = "get" +) + +/* + +Plan: + +0. When the user uses the gaiacli config node command to set the node value, + the new value is written successfully to the ~/.gaiacli/config/config.toml + +1.Create $NODE_DIR/config/client.toml to hold all client-side configuration +(e.g. keyring-backend, node, chain-id etc...)+ + + +2. Enable get functionality of client-side configuration + +get examples + +config keyring-backend --get //keyring-backend returns value from config file +config with no args --get //prints default config and exits +config invalidArg --get // returns error unknown conf key +config keyring-backend output --get // returns error too many arguments + +config without arguments // just print config from config file + + +3.Enable set functionality of client side configuration + +config keyring-backend test // sets keyring-backend = test - expected behavior + +config keyring-backend with no arguments // outputs default +config invalidKey invalidValue + + +CLI flags + +do i need to add all flags? from client/flags/flags.go + +"keyring-dir" : "", +"ledger": false, +"height": 0, +"gas-adjustment": flags.DefaultGasAdjustment,//float +"from": "", +"account-number": 0, +"sequence": 0, +"memo": "", +"fees": "", +"gas-prices":"", +"dry-run": false, +"generate-only":false, +"offline": false, +"yes": true, //doublec heck skip-confirmation = true + + + + + + + + +*/ + +var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") + +// is this full client side configuration? +// add height = 0 +var configDefaults = map[string]string{ + + "chain-id": "", + "keyring-backend": "os", + "output": "text", + "node": "tcp://localhost:26657", + "broadcast-mode": "sync", +} + +// ConfigCmd returns a CLI command to interactively create an application CLI +// config file. +func Cmd(defaultCLIHome string) *cobra.Command { + cmd := &cobra.Command{ + Use: "config [value]", + Short: "Create or query an application CLI configuration file", + RunE: runConfigCmd, + Args: cobra.RangeArgs(0, 2), + } + + cmd.Flags().String(flags.FlagHome, defaultCLIHome, + "set client's home directory for configuration") + cmd.Flags().Bool(flagGet, false, + "print configuration value or its default if unset") + return cmd +} + +func runConfigCmd(cmd *cobra.Command, args []string) error { + cfgFile, err := ensureConfFile(viper.GetString(flags.FlagHome)) + if err != nil { + return err + } + + getAction := viper.GetBool(flagGet) + if getAction && len(args) != 1 { + return fmt.Errorf("wrong number of arguments") + } + + // load configuration + tree, err := loadConfigFile(cfgFile) + if err != nil { + return err + } + + // print the default config and exit + if len(args) == 0 { + s, err := tree.ToTomlString() + if err != nil { + return err + } + fmt.Print(s) + return nil + } + + key := args[0] + + // get config value for a given key + if getAction { + switch key { + case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": + fmt.Println(tree.Get(key).(string)) + + default: + // do we need to print out default value here in case key is invalid? + if defaultValue, ok := configDefaults[key]; ok { + fmt.Println(tree.GetDefault(key, defaultValue).(string)) + return nil + } + + return errUnknownConfigKey(key) + } + + return nil + } + + // if we set value in configuration, the number of arguments must be 2 + if len(args) != 2 { + return ErrWrongNumberOfArgs + } + + value := args[1] + + // set config value for a given key + switch key { + case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": + tree.Set(key, value) + + // do we need to check if key matches one of these? + case "trace", "trust-node", "indent": + boolVal, err := strconv.ParseBool(value) + if err != nil { + return err + } + + tree.Set(key, boolVal) + + default: + return errUnknownConfigKey(key) + } + + // save configuration to disk + if err := saveConfigFile(cfgFile, tree); err != nil { + return err + } + + fmt.Fprintf(os.Stderr, "configuration saved to %s\n", cfgFile) + return nil +} + +func ensureConfFile(rootDir string) (string, error) { + cfgPath := path.Join(rootDir, "config") + if err := os.MkdirAll(cfgPath, os.ModePerm); err != nil { // config directory + return "", err + } + + return path.Join(cfgPath, "client.toml"), nil +} + +func loadConfigFile(cfgFile string) (*toml.Tree, error) { + if _, err := os.Stat(cfgFile); os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "%s does not exist\n", cfgFile) + return toml.Load(``) + } + + bz, err := ioutil.ReadFile(cfgFile) + if err != nil { + return nil, err + } + + tree, err := toml.LoadBytes(bz) + if err != nil { + return nil, err + } + + return tree, nil +} + +func saveConfigFile(cfgFile string, tree io.WriterTo) error { + fp, err := os.OpenFile(cfgFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) + if err != nil { + return err + } + defer fp.Close() + + _, err = tree.WriteTo(fp) + return err +} + +func errUnknownConfigKey(key string) error { + return fmt.Errorf("unknown configuration key: %q", key) +} diff --git a/client/config/config_test.go b/client/config/config_test.go new file mode 100644 index 000000000000..983bfbd97b90 --- /dev/null +++ b/client/config/config_test.go @@ -0,0 +1,59 @@ +package config + +import ( + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/client/flags" +) + +// For https://github.com/cosmos/cosmos-sdk/issues/3899 +func Test_runConfigCmdTwiceWithShorterNodeValue(t *testing.T) { + // Prepare environment + t.Parallel() + configHome, cleanup := tmpDir(t) + defer cleanup() + _ = os.RemoveAll(filepath.Join(configHome, "config")) + viper.Set(flags.FlagHome, configHome) + + // Init command config + cmd := Cmd(configHome) + assert.NotNil(t, cmd) + + err := cmd.RunE(cmd, []string{"node", "tcp://localhost:26657"}) + assert.Nil(t, err) + + err = cmd.RunE(cmd, []string{"node", "--get"}) + assert.Nil(t, err) + + err = cmd.RunE(cmd, []string{"node", "tcp://local:26657"}) + assert.Nil(t, err) + + err = cmd.RunE(cmd, []string{"node", "--get"}) + assert.Nil(t, err) + + err = cmd.RunE(cmd, nil) + assert.Nil(t, err) + + err = cmd.RunE(cmd, []string{"invalidKey", "--get"}) + require.Equal(t, err, errUnknownConfigKey("invalidKey")) + + err = cmd.RunE(cmd, []string{"invalidArg1"}) + require.Equal(t, err, ErrWrongNumberOfArgs) + + err = cmd.RunE(cmd, []string{"invalidKey", "invalidValue"}) + require.Equal(t, err, errUnknownConfigKey("invalidKey")) + +} + +func tmpDir(t *testing.T) (string, func()) { + dir, err := ioutil.TempDir("", t.Name()+"_") + require.NoError(t, err) + return dir, func() { _ = os.RemoveAll(dir) } +} diff --git a/go.mod b/go.mod index d409d401313f..2a9836c0581e 100644 --- a/go.mod +++ b/go.mod @@ -30,7 +30,7 @@ require ( github.com/magiconair/properties v1.8.4 github.com/mattn/go-isatty v0.0.12 github.com/otiai10/copy v1.5.0 - github.com/pelletier/go-toml v1.8.1 // indirect + github.com/pelletier/go-toml v1.8.1 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.9.0 github.com/prometheus/common v0.18.0 diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 836036bcf08c..676427248971 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" + clicfg "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" @@ -83,16 +84,18 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { a := appCreator{encodingConfig} server.AddCommands(rootCmd, simapp.DefaultNodeHome, a.newApp, a.appExport, addModuleInitFlags) - // add keybase, auxiliary RPC, query, and tx child commands + // add keybase, auxiliary RPC, query and tx child commands rootCmd.AddCommand( rpc.StatusCommand(), queryCommand(), txCommand(), keys.Commands(simapp.DefaultNodeHome), ) - // add rosetta rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler)) + + // add cli config + rootCmd.AddCommand(clicfg.Cmd(flags.FlagHome)) } func addModuleInitFlags(startCmd *cobra.Command) { From 536ec0d1860378b53dbb3d6a82802327a49cdf75 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Tue, 9 Mar 2021 14:40:49 -0800 Subject: [PATCH 02/14] my current state --- client/config/config.go | 170 +++++++++++++++++++++++++---------- client/config/config_test.go | 2 + client/config/toml.go | 87 ++++++++++++++++++ go.mod | 1 + 4 files changed, 214 insertions(+), 46 deletions(-) create mode 100644 client/config/toml.go diff --git a/client/config/config.go b/client/config/config.go index 3d9594f587ad..cb66efa2bf94 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -3,15 +3,17 @@ package config import ( "fmt" "io" - "io/ioutil" "os" - "path" "strconv" + "errors" + toml "github.com/pelletier/go-toml" "github.com/spf13/cobra" "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/client/flags" ) @@ -50,48 +52,35 @@ config keyring-backend with no arguments // outputs default config invalidKey invalidValue -CLI flags - -do i need to add all flags? from client/flags/flags.go - -"keyring-dir" : "", -"ledger": false, -"height": 0, -"gas-adjustment": flags.DefaultGasAdjustment,//float -"from": "", -"account-number": 0, -"sequence": 0, -"memo": "", -"fees": "", -"gas-prices":"", -"dry-run": false, -"generate-only":false, -"offline": false, -"yes": true, //doublec heck skip-confirmation = true - - - - +*/ +var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") +type ClientConfig struct{ -*/ + ChainID string `mapstructure:"chain-id"` + KeyringBackend string `mapstructure:"keyring-backend"` + Output string `mapstructure:"output"` + Node string `mapstructure:"node"` + BroadcastMode string `mapstructure:"broadcast-mode"` + Trace bool `mapstructure:"trace"` +} -var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") +func DefaultClientConfig() *ClientConfig { + return &ClientConfig{ + ChainID : "", + KeyringBackend :"os", + Output : "text", + Node: "tcp://localhost:26657", + BroadcastMode : "sync", + Trace : false, + } +} -// is this full client side configuration? -// add height = 0 -var configDefaults = map[string]string{ - "chain-id": "", - "keyring-backend": "os", - "output": "text", - "node": "tcp://localhost:26657", - "broadcast-mode": "sync", -} -// ConfigCmd returns a CLI command to interactively create an application CLI +// Cmd returns a CLI command to interactively create an application CLI // config file. func Cmd(defaultCLIHome string) *cobra.Command { cmd := &cobra.Command{ @@ -108,6 +97,98 @@ func Cmd(defaultCLIHome string) *cobra.Command { return cmd } +func runConfigCmd(cmd *cobra.Command, args []string) error { + + + InitConfigTemplate() + + cfgPath, err := ensureConfFile(viper.GetString(flags.FlagHome)) + if err != nil { + return err + } + + getAction := viper.GetBool(flagGet) + if getAction && len(args) != 1 { + return ErrWrongNumberOfArgs + } + + cliConfig, err := getClientConfig(cfgPath) + if err != nil { + return fmt.Errorf("Unable to get client config %v", err) + } + + + switch len(args) { + case 0: + // print all client config fields to sdt out + // TODO implement method to print out all client config fiels + fmt.Println(cliConfig.ChainID) + fmt.Println(cliConfig.KeyringBackend) + fmt.Println(cliConfig.Output) + fmt.Println(cliConfig.Node) + fmt.Println(cliConfig.BroadcastMode) + fmt.Println(cliConfig.Trace) + + case 1: + // it's a get + // TODO implement method for get + key := args[0] + switch key { + case "chain-id": fmt.Println(cliConfig.ChainID) + case "keyring-backend": fmt.Println(cliConfig.KeyringBackend) + case "output": fmt.Println(cliConfig.Output) + case "node": fmt.Println(cliConfig.Node) + case "broadcast-mode": fmt.Println(cliConfig.BroadcastMode) + case "trace": fmt.Println(cliConfig.Trace) + default : + return errUnknownConfigKey(key) + } + + case 2: + // it's set + // TODO impement method for set + // TODO implement setters + key, value := args[0], args[1] + switch key { + case "chain-id": cliConfig.ChainID = value + case "keyring-backend": cliConfig.KeyringBackend = value + case "output": cliConfig.Output = value + case "node": cliConfig.Node = value + case "broadcast-mode": cliConfig.BroadcastMode = value + case "trace": + boolVal, err := strconv.ParseBool(value) + if err != nil { + return err + } + cliConfig.Trace = boolVal + default : + return errUnknownConfigKey(key) + } + + default: + // print error + return errors.New("Unknown configuration error") + } + + + WriteConfigFile() + + + + return nil + + + + + + + + +} + + + +/* func runConfigCmd(cmd *cobra.Command, args []string) error { cfgFile, err := ensureConfFile(viper.GetString(flags.FlagHome)) if err != nil { @@ -143,6 +224,9 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": fmt.Println(tree.Get(key).(string)) + case "trace": + fmt.Println(tree.Get(key).(bool)) + default: // do we need to print out default value here in case key is invalid? if defaultValue, ok := configDefaults[key]; ok { @@ -168,8 +252,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": tree.Set(key, value) - // do we need to check if key matches one of these? - case "trace", "trust-node", "indent": + case "trace": boolVal, err := strconv.ParseBool(value) if err != nil { return err @@ -189,16 +272,10 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { fmt.Fprintf(os.Stderr, "configuration saved to %s\n", cfgFile) return nil } +*/ -func ensureConfFile(rootDir string) (string, error) { - cfgPath := path.Join(rootDir, "config") - if err := os.MkdirAll(cfgPath, os.ModePerm); err != nil { // config directory - return "", err - } - - return path.Join(cfgPath, "client.toml"), nil -} +/* func loadConfigFile(cfgFile string) (*toml.Tree, error) { if _, err := os.Stat(cfgFile); os.IsNotExist(err) { fmt.Fprintf(os.Stderr, "%s does not exist\n", cfgFile) @@ -217,6 +294,7 @@ func loadConfigFile(cfgFile string) (*toml.Tree, error) { return tree, nil } +*/ func saveConfigFile(cfgFile string, tree io.WriterTo) error { fp, err := os.OpenFile(cfgFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) diff --git a/client/config/config_test.go b/client/config/config_test.go index 983bfbd97b90..0e0f64a166fd 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -50,6 +50,8 @@ func Test_runConfigCmdTwiceWithShorterNodeValue(t *testing.T) { err = cmd.RunE(cmd, []string{"invalidKey", "invalidValue"}) require.Equal(t, err, errUnknownConfigKey("invalidKey")) + // TODO add testing of pririty environmental variable, flag and file + } func tmpDir(t *testing.T) (string, func()) { diff --git a/client/config/toml.go b/client/config/toml.go new file mode 100644 index 000000000000..7332a81becac --- /dev/null +++ b/client/config/toml.go @@ -0,0 +1,87 @@ +package config + +import ( + "bytes" + "text/template" + "os" + "path" + + + "github.com/spf13/viper" + tmos "github.com/tendermint/tendermint/libs/os" +) + +const defaultConfigTemplate = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Client Configuration ### +############################################################################### + + +chain-id = "{{ .ClientConfig.ChainID }}" +keyring-backend = "{{ .ClientConfig.KeyringBackend }}" +output = "{{ .ClientConfig.Output }}" +node = "{{ .ClientConfig.Node }}" +broadcast-mode = "{{ .ClientConfig.BroadcastMode }}" +trace = "{{ .ClientConfig.Trace }}" +` + +var configTemplate *template.Template + +func InitConfigTemplate() { + var err error + + tmpl := template.New("clientConfigFileTemplate") + + if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { + panic(err) + } + +} + +// ParseConfig retrieves the default environment configuration for the +// application. +func ParseConfig() *ClientConfig { + conf := DefaultClientConfig() + _ = viper.Unmarshal(conf) + + return conf +} + +// WriteConfigFile renders config using the template and writes it to +// configFilePath. +func WriteConfigFile(configFilePath string, config *ClientConfig) { + var buffer bytes.Buffer + + if err := configTemplate.Execute(&buffer, config); err != nil { + panic(err) + } + + tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) +} + +func ensureConfFile(rootDir string) (string, error) { + cfgPath := path.Join(rootDir, "config") + if err := os.MkdirAll(cfgPath, os.ModePerm); err != nil { // config directory + return "", err + } + + return cfgPath, nil +} + +func getClientConfig(cfgPath string) (*ClientConfig, error) { + viper.AddConfigPath(cfgPath) + viper.SetConfigName("client") + viper.SetConfigType("toml") + if err := viper.ReadInConfig(); err != nil { + return nil, err + } + + conf := new(ClientConfig) + if err := viper.Unmarshal(conf); err != nil { + return nil, err + } + + return conf,nil +} diff --git a/go.mod b/go.mod index 2a9836c0581e..3fc4d5184bf3 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,7 @@ require ( github.com/improbable-eng/grpc-web v0.14.0 github.com/magiconair/properties v1.8.4 github.com/mattn/go-isatty v0.0.12 + github.com/mitchellh/mapstructure v1.3.3 github.com/otiai10/copy v1.5.0 github.com/pelletier/go-toml v1.8.1 github.com/pkg/errors v0.9.1 From 8dbc688b441ac530c9daa4ce44453feb7cba3713 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Tue, 9 Mar 2021 21:11:49 -0800 Subject: [PATCH 03/14] refactored code,feedback required --- client/config/config.go | 292 +++++++++------------------------------- client/config/toml.go | 45 ++++--- server/util.go | 13 ++ simapp/simd/cmd/root.go | 2 +- 4 files changed, 103 insertions(+), 249 deletions(-) diff --git a/client/config/config.go b/client/config/config.go index cb66efa2bf94..39cbac3aa5d5 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -1,85 +1,41 @@ package config import ( + "errors" "fmt" - "io" "os" + "path" "strconv" - "errors" - - toml "github.com/pelletier/go-toml" "github.com/spf13/cobra" "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client/flags" + tmcli "github.com/tendermint/tendermint/libs/cli" ) -const ( - flagGet = "get" -) - -/* - -Plan: - -0. When the user uses the gaiacli config node command to set the node value, - the new value is written successfully to the ~/.gaiacli/config/config.toml - -1.Create $NODE_DIR/config/client.toml to hold all client-side configuration -(e.g. keyring-backend, node, chain-id etc...)+ - - -2. Enable get functionality of client-side configuration - -get examples - -config keyring-backend --get //keyring-backend returns value from config file -config with no args --get //prints default config and exits -config invalidArg --get // returns error unknown conf key -config keyring-backend output --get // returns error too many arguments - -config without arguments // just print config from config file - - -3.Enable set functionality of client side configuration - -config keyring-backend test // sets keyring-backend = test - expected behavior - -config keyring-backend with no arguments // outputs default -config invalidKey invalidValue - - -*/ - var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") - -type ClientConfig struct{ - - ChainID string `mapstructure:"chain-id"` +type ClientConfig struct { + ChainID string `mapstructure:"chain-id"` KeyringBackend string `mapstructure:"keyring-backend"` - Output string `mapstructure:"output"` - Node string `mapstructure:"node"` - BroadcastMode string `mapstructure:"broadcast-mode"` - Trace bool `mapstructure:"trace"` + Output string `mapstructure:"output"` + Node string `mapstructure:"node"` + BroadcastMode string `mapstructure:"broadcast-mode"` + Trace bool `mapstructure:"trace"` } func DefaultClientConfig() *ClientConfig { return &ClientConfig{ - ChainID : "", - KeyringBackend :"os", - Output : "text", - Node: "tcp://localhost:26657", - BroadcastMode : "sync", - Trace : false, + ChainID: "", + KeyringBackend: "os", + Output: "text", + Node: "tcp://localhost:26657", + BroadcastMode: "sync", + Trace: false, } } - - // Cmd returns a CLI command to interactively create an application CLI // config file. func Cmd(defaultCLIHome string) *cobra.Command { @@ -92,220 +48,104 @@ func Cmd(defaultCLIHome string) *cobra.Command { cmd.Flags().String(flags.FlagHome, defaultCLIHome, "set client's home directory for configuration") - cmd.Flags().Bool(flagGet, false, - "print configuration value or its default if unset") + // cmd.Flags().Bool(flagGet, false, + // "print configuration value or its default if unset") return cmd } func runConfigCmd(cmd *cobra.Command, args []string) error { - - InitConfigTemplate() + v := viper.New() - cfgPath, err := ensureConfFile(viper.GetString(flags.FlagHome)) + cfgPath, err := ensureCfgPath(v.GetString(flags.FlagHome)) if err != nil { + fmt.Fprintf(os.Stderr, "Unable to make config path: %v\n", err) return err } - getAction := viper.GetBool(flagGet) - if getAction && len(args) != 1 { - return ErrWrongNumberOfArgs - } - - cliConfig, err := getClientConfig(cfgPath) + cliConfig, err := getClientConfig(cfgPath, v) if err != nil { - return fmt.Errorf("Unable to get client config %v", err) + fmt.Fprintf(os.Stderr, "Unable to get client config: %v\n", err) + return err } - switch len(args) { case 0: // print all client config fields to sdt out - // TODO implement method to print out all client config fiels + // TODO implement method to print out all client config fields fmt.Println(cliConfig.ChainID) fmt.Println(cliConfig.KeyringBackend) fmt.Println(cliConfig.Output) fmt.Println(cliConfig.Node) fmt.Println(cliConfig.BroadcastMode) fmt.Println(cliConfig.Trace) - + case 1: - // it's a get + // it's a get // TODO implement method for get + // should i implement getters here? key := args[0] switch key { - case "chain-id": fmt.Println(cliConfig.ChainID) - case "keyring-backend": fmt.Println(cliConfig.KeyringBackend) - case "output": fmt.Println(cliConfig.Output) - case "node": fmt.Println(cliConfig.Node) - case "broadcast-mode": fmt.Println(cliConfig.BroadcastMode) - case "trace": fmt.Println(cliConfig.Trace) - default : - return errUnknownConfigKey(key) + case flags.FlagChainID: + fmt.Println(cliConfig.ChainID) + case flags.FlagKeyringBackend: + fmt.Println(cliConfig.KeyringBackend) + case tmcli.OutputFlag: + fmt.Println(cliConfig.Output) + case flags.FlagNode: + fmt.Println(cliConfig.Node) + case flags.FlagBroadcastMode: + fmt.Println(cliConfig.BroadcastMode) + case "trace": + fmt.Println(cliConfig.Trace) + default: + err := errUnknownConfigKey(key) + fmt.Fprintf(os.Stderr, "Unable to get the value for the key: %v, error: %v\n", key, err) + return err } case 2: // it's set // TODO impement method for set // TODO implement setters - key, value := args[0], args[1] - switch key { - case "chain-id": cliConfig.ChainID = value - case "keyring-backend": cliConfig.KeyringBackend = value - case "output": cliConfig.Output = value - case "node": cliConfig.Node = value - case "broadcast-mode": cliConfig.BroadcastMode = value - case "trace": - boolVal, err := strconv.ParseBool(value) - if err != nil { - return err - } - cliConfig.Trace = boolVal - default : - return errUnknownConfigKey(key) - } - - default: - // print error - return errors.New("Unknown configuration error") - } - - - WriteConfigFile() - - - - return nil - - - - - - - - -} + key, value := args[0], args[1] - -/* -func runConfigCmd(cmd *cobra.Command, args []string) error { - cfgFile, err := ensureConfFile(viper.GetString(flags.FlagHome)) - if err != nil { - return err - } - - getAction := viper.GetBool(flagGet) - if getAction && len(args) != 1 { - return fmt.Errorf("wrong number of arguments") - } - - // load configuration - tree, err := loadConfigFile(cfgFile) - if err != nil { - return err - } - - // print the default config and exit - if len(args) == 0 { - s, err := tree.ToTomlString() - if err != nil { - return err - } - fmt.Print(s) - return nil - } - - key := args[0] - - // get config value for a given key - if getAction { switch key { - case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": - fmt.Println(tree.Get(key).(string)) - + case flags.FlagChainID: + cliConfig.ChainID = value + case flags.FlagKeyringBackend: + cliConfig.KeyringBackend = value + case tmcli.OutputFlag: + cliConfig.Output = value + case flags.FlagNode: + cliConfig.Node = value + case flags.FlagBroadcastMode: + cliConfig.BroadcastMode = value case "trace": - fmt.Println(tree.Get(key).(bool)) - - default: - // do we need to print out default value here in case key is invalid? - if defaultValue, ok := configDefaults[key]; ok { - fmt.Println(tree.GetDefault(key, defaultValue).(string)) - return nil + boolVal, err := strconv.ParseBool(value) + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to parse value to bool, err: %v\n", err) + return err } - + cliConfig.Trace = boolVal + default: return errUnknownConfigKey(key) } - return nil - } - - // if we set value in configuration, the number of arguments must be 2 - if len(args) != 2 { - return ErrWrongNumberOfArgs - } - - value := args[1] - - // set config value for a given key - switch key { - case "chain-id", "keyring-backend", "output", "node", "broadcast-mode": - tree.Set(key, value) - - case "trace": - boolVal, err := strconv.ParseBool(value) - if err != nil { - return err - } - - tree.Set(key, boolVal) + configTemplate := InitConfigTemplate() + cfgFile := path.Join(cfgPath, "config.toml") + WriteConfigFile(cfgFile, cliConfig, configTemplate) default: - return errUnknownConfigKey(key) - } - - // save configuration to disk - if err := saveConfigFile(cfgFile, tree); err != nil { + // print error + err := errors.New("unable to execute config command") + fmt.Fprintf(os.Stderr, "%v\n", err) return err } - fmt.Fprintf(os.Stderr, "configuration saved to %s\n", cfgFile) return nil } -*/ - - -/* -func loadConfigFile(cfgFile string) (*toml.Tree, error) { - if _, err := os.Stat(cfgFile); os.IsNotExist(err) { - fmt.Fprintf(os.Stderr, "%s does not exist\n", cfgFile) - return toml.Load(``) - } - - bz, err := ioutil.ReadFile(cfgFile) - if err != nil { - return nil, err - } - - tree, err := toml.LoadBytes(bz) - if err != nil { - return nil, err - } - - return tree, nil -} -*/ - -func saveConfigFile(cfgFile string, tree io.WriterTo) error { - fp, err := os.OpenFile(cfgFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) - if err != nil { - return err - } - defer fp.Close() - - _, err = tree.WriteTo(fp) - return err -} func errUnknownConfigKey(key string) error { return fmt.Errorf("unknown configuration key: %q", key) diff --git a/client/config/toml.go b/client/config/toml.go index 7332a81becac..0b2c38494624 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -2,10 +2,9 @@ package config import ( "bytes" - "text/template" "os" "path" - + "text/template" "github.com/spf13/viper" tmos "github.com/tendermint/tendermint/libs/os" @@ -27,41 +26,42 @@ broadcast-mode = "{{ .ClientConfig.BroadcastMode }}" trace = "{{ .ClientConfig.Trace }}" ` -var configTemplate *template.Template - -func InitConfigTemplate() { - var err error - +// InitConfigTemplate initiates config template that will be used in +// WriteConfigFile +func InitConfigTemplate() *template.Template { tmpl := template.New("clientConfigFileTemplate") - - if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { + configTemplate, err := tmpl.Parse(defaultConfigTemplate) + if err != nil { panic(err) } + return configTemplate } // ParseConfig retrieves the default environment configuration for the // application. -func ParseConfig() *ClientConfig { +func ParseConfig(v *viper.Viper) (*ClientConfig, error) { conf := DefaultClientConfig() - _ = viper.Unmarshal(conf) + if err := v.Unmarshal(conf); err != nil { + return nil, err + } - return conf + return conf, nil } // WriteConfigFile renders config using the template and writes it to // configFilePath. -func WriteConfigFile(configFilePath string, config *ClientConfig) { +func WriteConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil { panic(err) } - tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) + tmos.MustWriteFile(cfgFile, buffer.Bytes(), 0644) } -func ensureConfFile(rootDir string) (string, error) { +func ensureCfgPath(rootDir string) (string, error) { cfgPath := path.Join(rootDir, "config") if err := os.MkdirAll(cfgPath, os.ModePerm); err != nil { // config directory return "", err @@ -70,18 +70,19 @@ func ensureConfFile(rootDir string) (string, error) { return cfgPath, nil } -func getClientConfig(cfgPath string) (*ClientConfig, error) { - viper.AddConfigPath(cfgPath) - viper.SetConfigName("client") - viper.SetConfigType("toml") - if err := viper.ReadInConfig(); err != nil { +func getClientConfig(cfgPath string, v *viper.Viper) (*ClientConfig, error) { + v.AddConfigPath(cfgPath) + v.SetConfigName("client") + v.SetConfigType("toml") + v.AutomaticEnv() + if err := v.ReadInConfig(); err != nil { return nil, err } conf := new(ClientConfig) - if err := viper.Unmarshal(conf); err != nil { + if err := v.Unmarshal(conf); err != nil { return nil, err } - return conf,nil + return conf, nil } diff --git a/server/util.go b/server/util.go index 68f1c4828166..86c9f0fd7d75 100644 --- a/server/util.go +++ b/server/util.go @@ -14,6 +14,7 @@ import ( "syscall" "time" + clicfg "github.com/cosmos/cosmos-sdk/client/config" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/spf13/cobra" @@ -242,6 +243,18 @@ func interceptConfigs(rootViper *viper.Viper) (*tmcfg.Config, error) { return nil, fmt.Errorf("failed to merge configuration: %w", err) } + // Adding default ClientConfig and writing it into "client.toml" + cliCfgFilePath := filepath.Join(configPath, "client.toml") + if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { + cliConfig, err := clicfg.ParseConfig(rootViper) + if err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", cliCfgFilePath, err) + } + + configTemplate := clicfg.InitConfigTemplate() + clicfg.WriteConfigFile(cliCfgFilePath, cliConfig, configTemplate) + } + return conf, nil } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 676427248971..0c7f7725bc29 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -94,7 +94,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { // add rosetta rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler)) - // add cli config + // add client config rootCmd.AddCommand(clicfg.Cmd(flags.FlagHome)) } From b7c9376628bfa6737e96513c30dbbcf4fddd5ba0 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 11 Mar 2021 11:39:32 -0800 Subject: [PATCH 04/14] use json to print out all fields of ClientConfig struct --- client/config/config.go | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/client/config/config.go b/client/config/config.go index 39cbac3aa5d5..b4b5665186f1 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -1,6 +1,7 @@ package config import ( + "encoding/json" "errors" "fmt" "os" @@ -17,12 +18,12 @@ import ( var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") type ClientConfig struct { - ChainID string `mapstructure:"chain-id"` - KeyringBackend string `mapstructure:"keyring-backend"` - Output string `mapstructure:"output"` - Node string `mapstructure:"node"` - BroadcastMode string `mapstructure:"broadcast-mode"` - Trace bool `mapstructure:"trace"` + ChainID string `mapstructure:"chain-id" json:"chain-id"` + KeyringBackend string `mapstructure:"keyring-backend" json:"keyring-backend"` + Output string `mapstructure:"output" json:"output"` + Node string `mapstructure:"node" json:"node"` + BroadcastMode string `mapstructure:"broadcast-mode" json:"broadcast-mode"` + Trace bool `mapstructure:"trace" json:"trace"` } func DefaultClientConfig() *ClientConfig { @@ -72,13 +73,8 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { switch len(args) { case 0: // print all client config fields to sdt out - // TODO implement method to print out all client config fields - fmt.Println(cliConfig.ChainID) - fmt.Println(cliConfig.KeyringBackend) - fmt.Println(cliConfig.Output) - fmt.Println(cliConfig.Node) - fmt.Println(cliConfig.BroadcastMode) - fmt.Println(cliConfig.Trace) + s, _ := json.MarshalIndent(cliConfig, "", "\t") + fmt.Print(string(s)) case 1: // it's a get From d0a3197534b66a192cabd26f25e77eaaeb3be558 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 11 Mar 2021 12:14:22 -0800 Subject: [PATCH 05/14] introduce default constant values for ClientConfig --- client/config/config.go | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/client/config/config.go b/client/config/config.go index b4b5665186f1..1bf250dd5de5 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -15,6 +15,16 @@ import ( tmcli "github.com/tendermint/tendermint/libs/cli" ) +// Default constants +const ( + chainID = "" + keyringBackend = "os" + output = "text" + node = "tcp://localhost:26657" + broadcastMode = "sync" + trace = false +) + var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") type ClientConfig struct { @@ -27,14 +37,7 @@ type ClientConfig struct { } func DefaultClientConfig() *ClientConfig { - return &ClientConfig{ - ChainID: "", - KeyringBackend: "os", - Output: "text", - Node: "tcp://localhost:26657", - BroadcastMode: "sync", - Trace: false, - } + return &ClientConfig{chainID, keyringBackend, output, node, broadcastMode, trace} } // Cmd returns a CLI command to interactively create an application CLI From db07ea23fbb6309ede9aba9a01aa50e5a9252961 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 11 Mar 2021 12:28:16 -0800 Subject: [PATCH 06/14] removed panic from WriteConfigFile and InitConfigTemplate --- client/config/config.go | 12 ++++++++++-- client/config/toml.go | 12 +++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/client/config/config.go b/client/config/config.go index 1bf250dd5de5..a4e309bd4bea 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -132,9 +132,17 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { return errUnknownConfigKey(key) } - configTemplate := InitConfigTemplate() + configTemplate, err := InitConfigTemplate() + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to initiate config template, err: %v\n", err) + return err + } + cfgFile := path.Join(cfgPath, "config.toml") - WriteConfigFile(cfgFile, cliConfig, configTemplate) + if err := WriteConfigFile(cfgFile, cliConfig, configTemplate); err != nil { + fmt.Fprintf(os.Stderr, "Unable to write client config to the file, err: %v\n", err) + return err + } default: // print error diff --git a/client/config/toml.go b/client/config/toml.go index 0b2c38494624..592ac32d2fb2 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -28,14 +28,14 @@ trace = "{{ .ClientConfig.Trace }}" // InitConfigTemplate initiates config template that will be used in // WriteConfigFile -func InitConfigTemplate() *template.Template { +func InitConfigTemplate() (*template.Template, error) { tmpl := template.New("clientConfigFileTemplate") configTemplate, err := tmpl.Parse(defaultConfigTemplate) if err != nil { - panic(err) + return nil, err } - return configTemplate + return configTemplate, nil } // ParseConfig retrieves the default environment configuration for the @@ -51,14 +51,16 @@ func ParseConfig(v *viper.Viper) (*ClientConfig, error) { // WriteConfigFile renders config using the template and writes it to // configFilePath. -func WriteConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) { +func WriteConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) error { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil { - panic(err) + return err } tmos.MustWriteFile(cfgFile, buffer.Bytes(), 0644) + return nil + } func ensureCfgPath(rootDir string) (string, error) { From 7a1f9a8f63a9230c516e7da45284ec0087528eca Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 11 Mar 2021 13:05:47 -0800 Subject: [PATCH 07/14] implemented setters for ClientConfig --- client/config/config.go | 48 ++++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/client/config/config.go b/client/config/config.go index a4e309bd4bea..03f5cbb043e8 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -36,6 +36,36 @@ type ClientConfig struct { Trace bool `mapstructure:"trace" json:"trace"` } +// TODO Validate values in setters +func (c *ClientConfig) SetChainID(chainID string) { + c.ChainID = chainID +} + +func (c *ClientConfig) SetKeyringBackend(keyringBackend string) { + c.KeyringBackend = keyringBackend +} + +func (c *ClientConfig) SetOutput(output string) { + c.Output = output +} + +func (c *ClientConfig) SetNode(node string) { + c.Node = node +} + +func (c *ClientConfig) SetBroadcastMode(broadcastMode string) { + c.BroadcastMode = broadcastMode +} + +func (c *ClientConfig) SetTrace(trace string) error { + boolVal, err := strconv.ParseBool(trace) + if err != nil { + return err + } + c.Trace = boolVal + return nil +} + func DefaultClientConfig() *ClientConfig { return &ClientConfig{chainID, keyringBackend, output, node, broadcastMode, trace} } @@ -52,8 +82,6 @@ func Cmd(defaultCLIHome string) *cobra.Command { cmd.Flags().String(flags.FlagHome, defaultCLIHome, "set client's home directory for configuration") - // cmd.Flags().Bool(flagGet, false, - // "print configuration value or its default if unset") return cmd } @@ -105,29 +133,25 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { case 2: // it's set - // TODO impement method for set - // TODO implement setters key, value := args[0], args[1] switch key { case flags.FlagChainID: - cliConfig.ChainID = value + cliConfig.SetChainID(value) case flags.FlagKeyringBackend: - cliConfig.KeyringBackend = value + cliConfig.SetKeyringBackend(value) case tmcli.OutputFlag: - cliConfig.Output = value + cliConfig.SetOutput(value) case flags.FlagNode: - cliConfig.Node = value + cliConfig.SetNode(value) case flags.FlagBroadcastMode: - cliConfig.BroadcastMode = value + cliConfig.SetBroadcastMode(value) case "trace": - boolVal, err := strconv.ParseBool(value) - if err != nil { + if err := cliConfig.SetTrace(value); err != nil { fmt.Fprintf(os.Stderr, "Unable to parse value to bool, err: %v\n", err) return err } - cliConfig.Trace = boolVal default: return errUnknownConfigKey(key) } From 20f5f98aa0392dea17d2a0477721d0d8efe9391c Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Fri, 12 Mar 2021 11:14:41 -0800 Subject: [PATCH 08/14] modified root.go to add clicfg.Cmd to rootCmd and util.go in interceptConfigs --- server/util.go | 20 +++++++++++++------- simapp/simd/cmd/root.go | 3 +-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/server/util.go b/server/util.go index 86c9f0fd7d75..6efc2fc4f0a4 100644 --- a/server/util.go +++ b/server/util.go @@ -245,15 +245,21 @@ func interceptConfigs(rootViper *viper.Viper) (*tmcfg.Config, error) { // Adding default ClientConfig and writing it into "client.toml" cliCfgFilePath := filepath.Join(configPath, "client.toml") - if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { - cliConfig, err := clicfg.ParseConfig(rootViper) - if err != nil { - return nil, fmt.Errorf("failed to parse %s: %w", cliCfgFilePath, err) - } + // if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { + cliConfig, err := clicfg.ParseConfig(rootViper) + if err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", cliCfgFilePath, err) + } + + configTemplate, err := clicfg.InitConfigTemplate() + if err != nil { + return nil, fmt.Errorf("failed to initiate config template %s: %w", cliCfgFilePath, err) + } - configTemplate := clicfg.InitConfigTemplate() - clicfg.WriteConfigFile(cliCfgFilePath, cliConfig, configTemplate) + if err := clicfg.WriteConfigFile(cliCfgFilePath, cliConfig, configTemplate); err != nil { + return nil, fmt.Errorf("failed to write into config file %s: %w", cliCfgFilePath, err) } + // } return conf, nil } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 0c7f7725bc29..57e62ffb52e7 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -79,6 +79,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { tmcli.NewCompletionCmd(rootCmd, true), testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), + clicfg.Cmd(flags.FlagHome), ) a := appCreator{encodingConfig} @@ -94,8 +95,6 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { // add rosetta rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler)) - // add client config - rootCmd.AddCommand(clicfg.Cmd(flags.FlagHome)) } func addModuleInitFlags(startCmd *cobra.Command) { From f4f6dde29effa02eb754c05a8caf05f706bb5296 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Sun, 14 Mar 2021 20:36:36 -0700 Subject: [PATCH 09/14] able to write config to client.toml --- client/config/toml.go | 12 ++++++------ go.mod | 3 +-- server/util.go | 1 + 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/client/config/toml.go b/client/config/toml.go index 592ac32d2fb2..fa8886e2e91b 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -18,12 +18,12 @@ const defaultConfigTemplate = `# This is a TOML config file. ############################################################################### -chain-id = "{{ .ClientConfig.ChainID }}" -keyring-backend = "{{ .ClientConfig.KeyringBackend }}" -output = "{{ .ClientConfig.Output }}" -node = "{{ .ClientConfig.Node }}" -broadcast-mode = "{{ .ClientConfig.BroadcastMode }}" -trace = "{{ .ClientConfig.Trace }}" +chain-id = "{{ .ChainID }}" +keyring-backend = "{{ .KeyringBackend }}" +output = "{{ .Output }}" +node = "{{ .Node }}" +broadcast-mode = "{{ .BroadcastMode }}" +trace = "{{ .Trace }}" ` // InitConfigTemplate initiates config template that will be used in diff --git a/go.mod b/go.mod index 3fc4d5184bf3..d409d401313f 100644 --- a/go.mod +++ b/go.mod @@ -29,9 +29,8 @@ require ( github.com/improbable-eng/grpc-web v0.14.0 github.com/magiconair/properties v1.8.4 github.com/mattn/go-isatty v0.0.12 - github.com/mitchellh/mapstructure v1.3.3 github.com/otiai10/copy v1.5.0 - github.com/pelletier/go-toml v1.8.1 + github.com/pelletier/go-toml v1.8.1 // indirect github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.9.0 github.com/prometheus/common v0.18.0 diff --git a/server/util.go b/server/util.go index 6efc2fc4f0a4..d61bdcd18396 100644 --- a/server/util.go +++ b/server/util.go @@ -243,6 +243,7 @@ func interceptConfigs(rootViper *viper.Viper) (*tmcfg.Config, error) { return nil, fmt.Errorf("failed to merge configuration: %w", err) } + // TODO test It if it works // Adding default ClientConfig and writing it into "client.toml" cliCfgFilePath := filepath.Join(configPath, "client.toml") // if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { From 560a7409d377d9d7a16e65ec53287848b3ae0df2 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Mon, 15 Mar 2021 13:34:35 -0700 Subject: [PATCH 10/14] refactored, config subcommand works --- client/config/config.go | 57 +++--- client/config/toml.go | 19 +- client/context.go | 8 + go.mod | 1 + go.sum | 4 + home/config/app.toml | 189 +++++++++++++++++++ home/config/client.toml | 14 ++ home/config/config.toml | 393 ++++++++++++++++++++++++++++++++++++++++ server/util.go | 6 +- simapp/simd/cmd/root.go | 7 +- 10 files changed, 652 insertions(+), 46 deletions(-) create mode 100644 home/config/app.toml create mode 100644 home/config/client.toml create mode 100644 home/config/config.toml diff --git a/client/config/config.go b/client/config/config.go index 03f5cbb043e8..ea9d898f7c34 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -4,15 +4,15 @@ import ( "encoding/json" "errors" "fmt" - "os" - "path" + "path/filepath" "strconv" "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/flags" tmcli "github.com/tendermint/tendermint/libs/cli" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" ) // Default constants @@ -87,25 +87,24 @@ func Cmd(defaultCLIHome string) *cobra.Command { func runConfigCmd(cmd *cobra.Command, args []string) error { - v := viper.New() + clientCtx := client.GetClientContextFromCmd(cmd) - cfgPath, err := ensureCfgPath(v.GetString(flags.FlagHome)) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to make config path: %v\n", err) - return err + configPath := filepath.Join(clientCtx.HomeDir, "config") + + if err := ensureConfigPath(configPath); err != nil { + return fmt.Errorf("couldn't make config config: %v", err) } - cliConfig, err := getClientConfig(cfgPath, v) + cliConfig, err := getClientConfig(configPath, clientCtx.Viper) if err != nil { - fmt.Fprintf(os.Stderr, "Unable to get client config: %v\n", err) - return err + return fmt.Errorf("couldn't get client config: %v", err) } switch len(args) { case 0: // print all client config fields to sdt out s, _ := json.MarshalIndent(cliConfig, "", "\t") - fmt.Print(string(s)) + cmd.Println(string(s)) case 1: // it's a get @@ -114,21 +113,20 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { key := args[0] switch key { case flags.FlagChainID: - fmt.Println(cliConfig.ChainID) + cmd.Println(cliConfig.ChainID) case flags.FlagKeyringBackend: - fmt.Println(cliConfig.KeyringBackend) + cmd.Println(cliConfig.KeyringBackend) case tmcli.OutputFlag: - fmt.Println(cliConfig.Output) + cmd.Println(cliConfig.Output) case flags.FlagNode: - fmt.Println(cliConfig.Node) + cmd.Println(cliConfig.Node) case flags.FlagBroadcastMode: - fmt.Println(cliConfig.BroadcastMode) + cmd.Println(cliConfig.BroadcastMode) case "trace": - fmt.Println(cliConfig.Trace) + cmd.Println(cliConfig.Trace) default: err := errUnknownConfigKey(key) - fmt.Fprintf(os.Stderr, "Unable to get the value for the key: %v, error: %v\n", key, err) - return err + return fmt.Errorf("couldn't get the value for the key: %v, error: %v\n", key, err) } case 2: @@ -149,8 +147,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { cliConfig.SetBroadcastMode(value) case "trace": if err := cliConfig.SetTrace(value); err != nil { - fmt.Fprintf(os.Stderr, "Unable to parse value to bool, err: %v\n", err) - return err + return fmt.Errorf("couldn't parse bool value: %v", err) } default: return errUnknownConfigKey(key) @@ -158,21 +155,17 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { configTemplate, err := InitConfigTemplate() if err != nil { - fmt.Fprintf(os.Stderr, "Unable to initiate config template, err: %v\n", err) - return err + return fmt.Errorf("could not initiate config template: %v", err) } - cfgFile := path.Join(cfgPath, "config.toml") - if err := WriteConfigFile(cfgFile, cliConfig, configTemplate); err != nil { - fmt.Fprintf(os.Stderr, "Unable to write client config to the file, err: %v\n", err) - return err + cliConfigFile := filepath.Join(configPath, "client.toml") + if err := WriteConfigFile(cliConfigFile, cliConfig, configTemplate); err != nil { + return fmt.Errorf("could not write client config to the file: %v", err) } default: // print error - err := errors.New("unable to execute config command") - fmt.Fprintf(os.Stderr, "%v\n", err) - return err + return errors.New("cound not execute config command") } return nil diff --git a/client/config/toml.go b/client/config/toml.go index fa8886e2e91b..7816655b9e2f 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -3,7 +3,6 @@ package config import ( "bytes" "os" - "path" "text/template" "github.com/spf13/viper" @@ -63,25 +62,25 @@ func WriteConfigFile(cfgFile string, config *ClientConfig, configTemplate *templ } -func ensureCfgPath(rootDir string) (string, error) { - cfgPath := path.Join(rootDir, "config") - if err := os.MkdirAll(cfgPath, os.ModePerm); err != nil { // config directory - return "", err +func ensureConfigPath(configPath string) error { + if err := os.MkdirAll(configPath, os.ModePerm); err != nil { + return err } - return cfgPath, nil + return nil } -func getClientConfig(cfgPath string, v *viper.Viper) (*ClientConfig, error) { - v.AddConfigPath(cfgPath) +func getClientConfig(configPath string, v *viper.Viper) (*ClientConfig, error) { + + v.AddConfigPath(configPath) v.SetConfigName("client") v.SetConfigType("toml") - v.AutomaticEnv() + if err := v.ReadInConfig(); err != nil { return nil, err } - conf := new(ClientConfig) + conf := DefaultClientConfig() if err := v.Unmarshal(conf); err != nil { return nil, err } diff --git a/client/context.go b/client/context.go index f7f555339c2c..dd9cfcc892ab 100644 --- a/client/context.go +++ b/client/context.go @@ -5,6 +5,7 @@ import ( "io" "os" + "github.com/spf13/viper" "gopkg.in/yaml.v2" "github.com/gogo/protobuf/proto" @@ -45,6 +46,7 @@ type Context struct { AccountRetriever AccountRetriever NodeURI string FeeGranter sdk.AccAddress + Viper *viper.Viper // TODO: Deprecated (remove). LegacyAmino *codec.LegacyAmino @@ -213,6 +215,12 @@ func (ctx Context) WithInterfaceRegistry(interfaceRegistry codectypes.InterfaceR return ctx } +// WithViper returns the context with Viper field +func (ctx Context) WithViper() Context { + ctx.Viper = viper.New() + return ctx +} + // PrintString prints the raw string to ctx.Output if it's defined, otherwise to os.Stdout func (ctx Context) PrintString(str string) error { return ctx.PrintBytes([]byte(str)) diff --git a/go.mod b/go.mod index d409d401313f..8803baf48f90 100644 --- a/go.mod +++ b/go.mod @@ -51,6 +51,7 @@ require ( github.com/tendermint/tendermint v0.34.8 github.com/tendermint/tm-db v0.6.4 golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad + golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 // indirect google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f google.golang.org/grpc v1.36.0 google.golang.org/protobuf v1.25.0 diff --git a/go.sum b/go.sum index a2c9cd63ed57..133863758638 100644 --- a/go.sum +++ b/go.sum @@ -763,6 +763,7 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.1.1-0.20191209134235-331c550502dd/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -853,6 +854,8 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e h1:AyodaIpKjppX+cBfTASF2E1US3H2JFBj920Ot3rtDjs= golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -888,6 +891,7 @@ golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a h1:CB3a9Nez8M13wwlr/E2YtwoU+qYHKfC+JrDa45RXXoQ= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/home/config/app.toml b/home/config/app.toml new file mode 100644 index 000000000000..0cffaed95838 --- /dev/null +++ b/home/config/app.toml @@ -0,0 +1,189 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Base Configuration ### +############################################################################### + +# The minimum gas prices a validator is willing to accept for processing a +# transaction. A transaction's fees must meet the minimum of any denomination +# specified in this config (e.g. 0.25token1;0.0001token2). +minimum-gas-prices = "" + +# default: the last 100 states are kept in addition to every 500th state; pruning at 10 block intervals +# nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node) +# everything: all saved states will be deleted, storing only the current state; pruning at 10 block intervals +# custom: allow pruning options to be manually specified through 'pruning-keep-recent', 'pruning-keep-every', and 'pruning-interval' +pruning = "default" + +# These are applied if and only if the pruning strategy is custom. +pruning-keep-recent = "0" +pruning-keep-every = "0" +pruning-interval = "0" + +# HaltHeight contains a non-zero block height at which a node will gracefully +# halt and shutdown that can be used to assist upgrades and testing. +# +# Note: Commitment of state will be attempted on the corresponding block. +halt-height = 0 + +# HaltTime contains a non-zero minimum block time (in Unix seconds) at which +# a node will gracefully halt and shutdown that can be used to assist upgrades +# and testing. +# +# Note: Commitment of state will be attempted on the corresponding block. +halt-time = 0 + +# MinRetainBlocks defines the minimum block height offset from the current +# block being committed, such that all blocks past this offset are pruned +# from Tendermint. It is used as part of the process of determining the +# ResponseCommit.RetainHeight value during ABCI Commit. A value of 0 indicates +# that no blocks should be pruned. +# +# This configuration value is only responsible for pruning Tendermint blocks. +# It has no bearing on application state pruning which is determined by the +# "pruning-*" configurations. +# +# Note: Tendermint block pruning is dependant on this parameter in conunction +# with the unbonding (safety threshold) period, state pruning and state sync +# snapshot parameters to determine the correct minimum value of +# ResponseCommit.RetainHeight. +min-retain-blocks = 0 + +# InterBlockCache enables inter-block caching. +inter-block-cache = true + +# IndexEvents defines the set of events in the form {eventType}.{attributeKey}, +# which informs Tendermint what to index. If empty, all events will be indexed. +# +# Example: +# ["message.sender", "message.recipient"] +index-events = [] + +############################################################################### +### Telemetry Configuration ### +############################################################################### + +[telemetry] + +# Prefixed with keys to separate services. +service-name = "" + +# Enabled enables the application telemetry functionality. When enabled, +# an in-memory sink is also enabled by default. Operators may also enabled +# other sinks such as Prometheus. +enabled = false + +# Enable prefixing gauge values with hostname. +enable-hostname = false + +# Enable adding hostname to labels. +enable-hostname-label = false + +# Enable adding service to labels. +enable-service-label = false + +# PrometheusRetentionTime, when positive, enables a Prometheus metrics sink. +prometheus-retention-time = 0 + +# GlobalLabels defines a global set of name/value label tuples applied to all +# metrics emitted using the wrapper functions defined in telemetry package. +# +# Example: +# [["chain_id", "cosmoshub-1"]] +global-labels = [ +] + +############################################################################### +### API Configuration ### +############################################################################### + +[api] + +# Enable defines if the API server should be enabled. +enable = false + +# Swagger defines if swagger documentation should automatically be registered. +swagger = false + +# Address defines the API server to listen on. +address = "tcp://0.0.0.0:1317" + +# MaxOpenConnections defines the number of maximum open connections. +max-open-connections = 1000 + +# RPCReadTimeout defines the Tendermint RPC read timeout (in seconds). +rpc-read-timeout = 10 + +# RPCWriteTimeout defines the Tendermint RPC write timeout (in seconds). +rpc-write-timeout = 0 + +# RPCMaxBodyBytes defines the Tendermint maximum response body (in bytes). +rpc-max-body-bytes = 1000000 + +# EnableUnsafeCORS defines if CORS should be enabled (unsafe - use it at your own risk). +enabled-unsafe-cors = false + +############################################################################### +### Rosetta Configuration ### +############################################################################### + +[rosetta] + +# Enable defines if the Rosetta API server should be enabled. +enable = false + +# Address defines the Rosetta API server to listen on. +address = ":8080" + +# Network defines the name of the blockchain that will be returned by Rosetta. +blockchain = "app" + +# Network defines the name of the network that will be returned by Rosetta. +network = "network" + +# Retries defines the number of retries when connecting to the node before failing. +retries = 3 + +# Offline defines if Rosetta server should run in offline mode. +offline = false + +############################################################################### +### gRPC Configuration ### +############################################################################### + +[grpc] + +# Enable defines if the gRPC server should be enabled. +enable = true + +# Address defines the gRPC server address to bind to. +address = "0.0.0.0:9090" + +############################################################################### +### gRPC Web Configuration ### +############################################################################### + +[grpc-web] + +# GRPCWebEnable defines if the gRPC-web should be enabled. +# NOTE: gRPC must also be enabled, otherwise, this configuration is a no-op. +enable = true + +# Address defines the gRPC-web server address to bind to. +address = "0.0.0.0:9091" + +############################################################################### +### State Sync Configuration ### +############################################################################### + +# State sync snapshots allow other nodes to rapidly join the network without replaying historical +# blocks, instead downloading and applying a snapshot of the application state at a given height. +[state-sync] + +# snapshot-interval specifies the block interval at which local state sync snapshots are +# taken (0 to disable). Must be a multiple of pruning-keep-every. +snapshot-interval = 0 + +# snapshot-keep-recent specifies the number of recent snapshots to keep and serve (0 to keep all). +snapshot-keep-recent = 2 diff --git a/home/config/client.toml b/home/config/client.toml new file mode 100644 index 000000000000..8720aca96e5d --- /dev/null +++ b/home/config/client.toml @@ -0,0 +1,14 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Client Configuration ### +############################################################################### + + +chain-id = "" +keyring-backend = "os" +output = "text" +node = "tcp://localhost:26657" +broadcast-mode = "sync" +trace = "false" diff --git a/home/config/config.toml b/home/config/config.toml new file mode 100644 index 000000000000..114fd49098b7 --- /dev/null +++ b/home/config/config.toml @@ -0,0 +1,393 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +# NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or +# relative to the home directory (e.g. "data"). The home directory is +# "$HOME/.tendermint" by default, but could be changed via $TMHOME env variable +# or --home cmd flag. + +####################################################################### +### Main Base Config Options ### +####################################################################### + +# TCP or UNIX socket address of the ABCI application, +# or the name of an ABCI application compiled in with the Tendermint binary +proxy_app = "tcp://127.0.0.1:26658" + +# A custom human readable name for this node +moniker = "ai-ThinkPad-T450" + +# If this node is many blocks behind the tip of the chain, FastSync +# allows them to catchup quickly by downloading blocks in parallel +# and verifying their commits +fast_sync = true + +# Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb +# * goleveldb (github.com/syndtr/goleveldb - most popular implementation) +# - pure go +# - stable +# * cleveldb (uses levigo wrapper) +# - fast +# - requires gcc +# - use cleveldb build tag (go build -tags cleveldb) +# * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) +# - EXPERIMENTAL +# - may be faster is some use-cases (random reads - indexer) +# - use boltdb build tag (go build -tags boltdb) +# * rocksdb (uses github.com/tecbot/gorocksdb) +# - EXPERIMENTAL +# - requires gcc +# - use rocksdb build tag (go build -tags rocksdb) +# * badgerdb (uses github.com/dgraph-io/badger) +# - EXPERIMENTAL +# - use badgerdb build tag (go build -tags badgerdb) +db_backend = "goleveldb" + +# Database directory +db_dir = "data" + +# Output level for logging, including package level options +log_level = "info" + +# Output format: 'plain' (colored text) or 'json' +log_format = "plain" + +##### additional base config options ##### + +# Path to the JSON file containing the initial validator set and other meta data +genesis_file = "config/genesis.json" + +# Path to the JSON file containing the private key to use as a validator in the consensus protocol +priv_validator_key_file = "config/priv_validator_key.json" + +# Path to the JSON file containing the last sign state of a validator +priv_validator_state_file = "data/priv_validator_state.json" + +# TCP or UNIX socket address for Tendermint to listen on for +# connections from an external PrivValidator process +priv_validator_laddr = "" + +# Path to the JSON file containing the private key to use for node authentication in the p2p protocol +node_key_file = "config/node_key.json" + +# Mechanism to connect to the ABCI application: socket | grpc +abci = "socket" + +# If true, query the ABCI app on connecting to a new peer +# so the app can decide if we should keep the connection or not +filter_peers = false + + +####################################################################### +### Advanced Configuration Options ### +####################################################################### + +####################################################### +### RPC Server Configuration Options ### +####################################################### +[rpc] + +# TCP or UNIX socket address for the RPC server to listen on +laddr = "tcp://127.0.0.1:26657" + +# A list of origins a cross-domain request can be executed from +# Default value '[]' disables cors support +# Use '["*"]' to allow any origin +cors_allowed_origins = [] + +# A list of methods the client is allowed to use with cross-domain requests +cors_allowed_methods = ["HEAD", "GET", "POST", ] + +# A list of non simple headers the client is allowed to use with cross-domain requests +cors_allowed_headers = ["Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time", ] + +# TCP or UNIX socket address for the gRPC server to listen on +# NOTE: This server only supports /broadcast_tx_commit +grpc_laddr = "" + +# Maximum number of simultaneous connections. +# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +grpc_max_open_connections = 900 + +# Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool +unsafe = false + +# Maximum number of simultaneous connections (including WebSocket). +# Does not include gRPC connections. See grpc_max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +max_open_connections = 900 + +# Maximum number of unique clientIDs that can /subscribe +# If you're using /broadcast_tx_commit, set to the estimated maximum number +# of broadcast_tx_commit calls per block. +max_subscription_clients = 100 + +# Maximum number of unique queries a given client can /subscribe to +# If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to +# the estimated # maximum number of broadcast_tx_commit calls per block. +max_subscriptions_per_client = 5 + +# How long to wait for a tx to be committed during /broadcast_tx_commit. +# WARNING: Using a value larger than 10s will result in increasing the +# global HTTP write timeout, which applies to all connections and endpoints. +# See https://github.com/tendermint/tendermint/issues/3435 +timeout_broadcast_tx_commit = "10s" + +# Maximum size of request body, in bytes +max_body_bytes = 1000000 + +# Maximum size of request header, in bytes +max_header_bytes = 1048576 + +# The path to a file containing certificate that is used to create the HTTPS server. +# Might be either absolute path or path related to Tendermint's config directory. +# If the certificate is signed by a certificate authority, +# the certFile should be the concatenation of the server's certificate, any intermediates, +# and the CA's certificate. +# NOTE: both tls_cert_file and tls_key_file must be present for Tendermint to create HTTPS server. +# Otherwise, HTTP server is run. +tls_cert_file = "" + +# The path to a file containing matching private key that is used to create the HTTPS server. +# Might be either absolute path or path related to Tendermint's config directory. +# NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server. +# Otherwise, HTTP server is run. +tls_key_file = "" + +# pprof listen address (https://golang.org/pkg/net/http/pprof) +pprof_laddr = "localhost:6060" + +####################################################### +### P2P Configuration Options ### +####################################################### +[p2p] + +# Address to listen for incoming connections +laddr = "tcp://0.0.0.0:26656" + +# Address to advertise to peers for them to dial +# If empty, will use the same port as the laddr, +# and will introspect on the listener or use UPnP +# to figure out the address. +external_address = "" + +# Comma separated list of seed nodes to connect to +seeds = "" + +# Comma separated list of nodes to keep persistent connections to +persistent_peers = "" + +# UPNP port forwarding +upnp = false + +# Path to address book +addr_book_file = "config/addrbook.json" + +# Set true for strict address routability rules +# Set false for private or local networks +addr_book_strict = true + +# Maximum number of inbound peers +max_num_inbound_peers = 40 + +# Maximum number of outbound peers to connect to, excluding persistent peers +max_num_outbound_peers = 10 + +# List of node IDs, to which a connection will be (re)established ignoring any existing limits +unconditional_peer_ids = "" + +# Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) +persistent_peers_max_dial_period = "0s" + +# Time to wait before flushing messages out on the connection +flush_throttle_timeout = "100ms" + +# Maximum size of a message packet payload, in bytes +max_packet_msg_payload_size = 1024 + +# Rate at which packets can be sent, in bytes/second +send_rate = 5120000 + +# Rate at which packets can be received, in bytes/second +recv_rate = 5120000 + +# Set true to enable the peer-exchange reactor +pex = true + +# Seed mode, in which node constantly crawls the network and looks for +# peers. If another node asks it for addresses, it responds and disconnects. +# +# Does not work if the peer-exchange reactor is disabled. +seed_mode = false + +# Comma separated list of peer IDs to keep private (will not be gossiped to other peers) +private_peer_ids = "" + +# Toggle to disable guard against peers connecting from the same ip. +allow_duplicate_ip = false + +# Peer connection configuration. +handshake_timeout = "20s" +dial_timeout = "3s" + +####################################################### +### Mempool Configuration Option ### +####################################################### +[mempool] + +recheck = true +broadcast = true +wal_dir = "" + +# Maximum number of transactions in the mempool +size = 5000 + +# Limit the total size of all txs in the mempool. +# This only accounts for raw transactions (e.g. given 1MB transactions and +# max_txs_bytes=5MB, mempool will only accept 5 transactions). +max_txs_bytes = 1073741824 + +# Size of the cache (used to filter transactions we saw earlier) in transactions +cache_size = 10000 + +# Do not remove invalid transactions from the cache (default: false) +# Set to true if it's not possible for any invalid transaction to become valid +# again in the future. +keep-invalid-txs-in-cache = false + +# Maximum size of a single transaction. +# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. +max_tx_bytes = 1048576 + +# Maximum size of a batch of transactions to send to a peer +# Including space needed by encoding (one varint per transaction). +# XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 +max_batch_bytes = 0 + +####################################################### +### State Sync Configuration Options ### +####################################################### +[statesync] +# State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine +# snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in +# the network to take and serve state machine snapshots. State sync is not attempted if the node +# has any local state (LastBlockHeight > 0). The node will have a truncated block history, +# starting from the height of the snapshot. +enable = false + +# RPC servers (comma-separated) for light client verification of the synced state machine and +# retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding +# header hash obtained from a trusted source, and a period during which validators can be trusted. +# +# For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 +# weeks) during which they can be financially punished (slashed) for misbehavior. +rpc_servers = "" +trust_height = 0 +trust_hash = "" +trust_period = "168h0m0s" + +# Time to spend discovering snapshots before initiating a restore. +discovery_time = "15s" + +# Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). +# Will create a new, randomly named directory within, and remove it when done. +temp_dir = "" + +####################################################### +### Fast Sync Configuration Connections ### +####################################################### +[fastsync] + +# Fast Sync version to use: +# 1) "v0" (default) - the legacy fast sync implementation +# 2) "v1" - refactor of v0 version for better testability +# 2) "v2" - complete redesign of v0, optimized for testability & readability +version = "v0" + +####################################################### +### Consensus Configuration Options ### +####################################################### +[consensus] + +wal_file = "data/cs.wal/wal" + +# How long we wait for a proposal block before prevoting nil +timeout_propose = "3s" +# How much timeout_propose increases with each round +timeout_propose_delta = "500ms" +# How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) +timeout_prevote = "1s" +# How much the timeout_prevote increases with each round +timeout_prevote_delta = "500ms" +# How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) +timeout_precommit = "1s" +# How much the timeout_precommit increases with each round +timeout_precommit_delta = "500ms" +# How long we wait after committing a block, before starting on the new +# height (this gives us a chance to receive some more precommits, even +# though we already have +2/3). +timeout_commit = "5s" + +# How many blocks to look back to check existence of the node's consensus votes before joining consensus +# When non-zero, the node will panic upon restart +# if the same consensus key was used to sign {double_sign_check_height} last blocks. +# So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. +double_sign_check_height = 0 + +# Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) +skip_timeout_commit = false + +# EmptyBlocks mode and possible interval between empty blocks +create_empty_blocks = true +create_empty_blocks_interval = "0s" + +# Reactor sleep duration parameters +peer_gossip_sleep_duration = "100ms" +peer_query_maj23_sleep_duration = "2s" + +####################################################### +### Transaction Indexer Configuration Options ### +####################################################### +[tx_index] + +# What indexer to use for transactions +# +# The application will set which txs to index. In some cases a node operator will be able +# to decide which txs to index based on configuration set in the application. +# +# Options: +# 1) "null" +# 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). +# - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. +indexer = "kv" + +####################################################### +### Instrumentation Configuration Options ### +####################################################### +[instrumentation] + +# When true, Prometheus metrics are served under /metrics on +# PrometheusListenAddr. +# Check out the documentation for the list of available metrics. +prometheus = false + +# Address to listen for Prometheus collector(s) connections +prometheus_listen_addr = ":26660" + +# Maximum number of simultaneous connections. +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = 3 + +# Instrumentation namespace +namespace = "tendermint" diff --git a/server/util.go b/server/util.go index d61bdcd18396..b26af4aefa56 100644 --- a/server/util.go +++ b/server/util.go @@ -14,7 +14,6 @@ import ( "syscall" "time" - clicfg "github.com/cosmos/cosmos-sdk/client/config" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/spf13/cobra" @@ -24,6 +23,8 @@ import ( tmlog "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" + clicfg "github.com/cosmos/cosmos-sdk/client/config" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/server/types" @@ -244,9 +245,12 @@ func interceptConfigs(rootViper *viper.Viper) (*tmcfg.Config, error) { } // TODO test It if it works + // Adding default ClientConfig and writing it into "client.toml" cliCfgFilePath := filepath.Join(configPath, "client.toml") // if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { + + // TODO use clientCtx.Viper instead of rootViper cliConfig, err := clicfg.ParseConfig(rootViper) if err != nil { return nil, fmt.Errorf("failed to parse %s: %w", cliCfgFilePath, err) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 57e62ffb52e7..84cf138c2a27 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -47,7 +47,8 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithBroadcastMode(flags.BroadcastBlock). - WithHomeDir(simapp.DefaultNodeHome) + WithHomeDir(simapp.DefaultNodeHome). + WithViper() rootCmd := &cobra.Command{ Use: "simd", @@ -108,7 +109,7 @@ func queryCommand() *cobra.Command { Short: "Querying subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( @@ -131,7 +132,7 @@ func txCommand() *cobra.Command { Short: "Transactions subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( From a807879205ac55cddd6baefb16c6020ae99bc968 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Tue, 16 Mar 2021 10:40:53 -0700 Subject: [PATCH 11/14] UpdateClientContextFromClientConfig --- client/cmd.go | 2 +- client/config/cmd.go | 119 +++++++++++++++++++++++++++++ client/config/config.go | 140 ++++++++--------------------------- client/config/config_test.go | 18 ++--- client/config/toml.go | 18 +---- client/context.go | 7 +- docker-compose.yml | 2 +- server/util.go | 24 +----- simapp/simd/cmd/root.go | 5 +- 9 files changed, 173 insertions(+), 162 deletions(-) create mode 100644 client/config/cmd.go diff --git a/client/cmd.go b/client/cmd.go index 437022695d47..6213b4f59238 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -120,7 +120,7 @@ func ReadPersistentCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Cont keyringBackend, _ := flagSet.GetString(flags.FlagKeyringBackend) if keyringBackend != "" { - kr, err := newKeyringFromFlags(clientCtx, keyringBackend) + kr, err := NewKeyringFromFlags(clientCtx, keyringBackend) if err != nil { return clientCtx, err } diff --git a/client/config/cmd.go b/client/config/cmd.go new file mode 100644 index 000000000000..a6526ff83fd0 --- /dev/null +++ b/client/config/cmd.go @@ -0,0 +1,119 @@ +package config + +import ( + "encoding/json" + "errors" + "fmt" + "path/filepath" + + tmcli "github.com/tendermint/tendermint/libs/cli" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" +) + +// Cmd returns a CLI command to interactively create an application CLI +// config file. +func Cmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "config [value]", + Short: "Create or query an application CLI configuration file", + RunE: runConfigCmd, + Args: cobra.RangeArgs(0, 2), + } + return cmd +} + +func runConfigCmd(cmd *cobra.Command, args []string) error { + + clientCtx := client.GetClientContextFromCmd(cmd) + + configPath := filepath.Join(clientCtx.HomeDir, "config") + + if err := ensureConfigPath(configPath); err != nil { + return fmt.Errorf("couldn't make client config: %v", err) + } + + cliConfig, err := getClientConfig(configPath, clientCtx.Viper) + if err != nil { + return fmt.Errorf("couldn't get client config: %v", err) + } + + switch len(args) { + case 0: + // print all client config fields to sdt out + s, _ := json.MarshalIndent(cliConfig, "", "\t") + cmd.Println(string(s)) + + case 1: + // it's a get + // TODO implement method for get + // should i implement getters here? + key := args[0] + switch key { + case flags.FlagChainID: + cmd.Println(cliConfig.ChainID) + case flags.FlagKeyringBackend: + cmd.Println(cliConfig.KeyringBackend) + case tmcli.OutputFlag: + cmd.Println(cliConfig.Output) + case flags.FlagNode: + cmd.Println(cliConfig.Node) + case flags.FlagBroadcastMode: + cmd.Println(cliConfig.BroadcastMode) + // case "trace": + // cmd.Println(cliConfig.Trace) + default: + err := errUnknownConfigKey(key) + return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) + } + + case 2: + // it's set + + key, value := args[0], args[1] + + switch key { + case flags.FlagChainID: + cliConfig.SetChainID(value) + case flags.FlagKeyringBackend: + cliConfig.SetKeyringBackend(value) + case tmcli.OutputFlag: + cliConfig.SetOutput(value) + case flags.FlagNode: + cliConfig.SetNode(value) + case flags.FlagBroadcastMode: + cliConfig.SetBroadcastMode(value) + /* + case "trace": + if err := cliConfig.SetTrace(value); err != nil { + return fmt.Errorf("couldn't parse bool value: %v", err) + } + */ + default: + return errUnknownConfigKey(key) + } + + configTemplate, err := initConfigTemplate() + if err != nil { + return fmt.Errorf("could not initiate config template: %v", err) + } + + cliConfigFile := filepath.Join(configPath, "client.toml") + if err := writeConfigFile(cliConfigFile, cliConfig, configTemplate); err != nil { + return fmt.Errorf("could not write client config to the file: %v", err) + } + + default: + // print error + return errors.New("cound not execute config command") + } + + return nil +} + +func errUnknownConfigKey(key string) error { + return fmt.Errorf("unknown configuration key: %q", key) +} diff --git a/client/config/config.go b/client/config/config.go index ea9d898f7c34..07de46ac76f7 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -1,18 +1,10 @@ package config import ( - "encoding/json" - "errors" - "fmt" + // "fmt" "path/filepath" - "strconv" - - "github.com/spf13/cobra" - - tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" ) // Default constants @@ -22,10 +14,9 @@ const ( output = "text" node = "tcp://localhost:26657" broadcastMode = "sync" - trace = false -) -var ErrWrongNumberOfArgs = fmt.Errorf("wrong number of arguments") +// trace = false +) type ClientConfig struct { ChainID string `mapstructure:"chain-id" json:"chain-id"` @@ -33,10 +24,13 @@ type ClientConfig struct { Output string `mapstructure:"output" json:"output"` Node string `mapstructure:"node" json:"node"` BroadcastMode string `mapstructure:"broadcast-mode" json:"broadcast-mode"` - Trace bool `mapstructure:"trace" json:"trace"` + // Trace bool `mapstructure:"trace" json:"trace"` +} + +func DefaultClientConfig() *ClientConfig { + return &ClientConfig{chainID, keyringBackend, output, node, broadcastMode} } -// TODO Validate values in setters func (c *ClientConfig) SetChainID(chainID string) { c.ChainID = chainID } @@ -57,6 +51,7 @@ func (c *ClientConfig) SetBroadcastMode(broadcastMode string) { c.BroadcastMode = broadcastMode } +/* func (c *ClientConfig) SetTrace(trace string) error { boolVal, err := strconv.ParseBool(trace) if err != nil { @@ -65,112 +60,37 @@ func (c *ClientConfig) SetTrace(trace string) error { c.Trace = boolVal return nil } +*/ -func DefaultClientConfig() *ClientConfig { - return &ClientConfig{chainID, keyringBackend, output, node, broadcastMode, trace} -} - -// Cmd returns a CLI command to interactively create an application CLI -// config file. -func Cmd(defaultCLIHome string) *cobra.Command { - cmd := &cobra.Command{ - Use: "config [value]", - Short: "Create or query an application CLI configuration file", - RunE: runConfigCmd, - Args: cobra.RangeArgs(0, 2), - } - - cmd.Flags().String(flags.FlagHome, defaultCLIHome, - "set client's home directory for configuration") - return cmd -} - -func runConfigCmd(cmd *cobra.Command, args []string) error { +func UpdateClientContextFromClientConfig(ctx client.Context) client.Context { + configPath := filepath.Join(ctx.HomeDir, "config") - clientCtx := client.GetClientContextFromCmd(cmd) - - configPath := filepath.Join(clientCtx.HomeDir, "config") - - if err := ensureConfigPath(configPath); err != nil { - return fmt.Errorf("couldn't make config config: %v", err) - } - - cliConfig, err := getClientConfig(configPath, clientCtx.Viper) - if err != nil { - return fmt.Errorf("couldn't get client config: %v", err) - } - - switch len(args) { - case 0: - // print all client config fields to sdt out - s, _ := json.MarshalIndent(cliConfig, "", "\t") - cmd.Println(string(s)) - - case 1: - // it's a get - // TODO implement method for get - // should i implement getters here? - key := args[0] - switch key { - case flags.FlagChainID: - cmd.Println(cliConfig.ChainID) - case flags.FlagKeyringBackend: - cmd.Println(cliConfig.KeyringBackend) - case tmcli.OutputFlag: - cmd.Println(cliConfig.Output) - case flags.FlagNode: - cmd.Println(cliConfig.Node) - case flags.FlagBroadcastMode: - cmd.Println(cliConfig.BroadcastMode) - case "trace": - cmd.Println(cliConfig.Trace) - default: - err := errUnknownConfigKey(key) - return fmt.Errorf("couldn't get the value for the key: %v, error: %v\n", key, err) + /* + if err := ensureConfigPath(configPath); err != nil { + return ctx, fmt.Errorf("couldn't make client config: %v", err) } - case 2: - // it's set - - key, value := args[0], args[1] - - switch key { - case flags.FlagChainID: - cliConfig.SetChainID(value) - case flags.FlagKeyringBackend: - cliConfig.SetKeyringBackend(value) - case tmcli.OutputFlag: - cliConfig.SetOutput(value) - case flags.FlagNode: - cliConfig.SetNode(value) - case flags.FlagBroadcastMode: - cliConfig.SetBroadcastMode(value) - case "trace": - if err := cliConfig.SetTrace(value); err != nil { - return fmt.Errorf("couldn't parse bool value: %v", err) - } - default: - return errUnknownConfigKey(key) + cliConfig, err := getClientConfig(configPath, ctx.Viper) + if err != nil { + return ctx, fmt.Errorf("couldn't get client config: %v", err) } - configTemplate, err := InitConfigTemplate() + + keyRing, err := client.NewKeyringFromFlags(ctx, cliConfig.KeyringBackend) if err != nil { - return fmt.Errorf("could not initiate config template: %v", err) + return ctx, fmt.Errorf("couldn't get key ring: %v", err) } + */ - cliConfigFile := filepath.Join(configPath, "client.toml") - if err := WriteConfigFile(cliConfigFile, cliConfig, configTemplate); err != nil { - return fmt.Errorf("could not write client config to the file: %v", err) - } + cliConfig, _ := getClientConfig(configPath, ctx.Viper) - default: - // print error - return errors.New("cound not execute config command") - } + keyRing, _ := client.NewKeyringFromFlags(ctx, cliConfig.KeyringBackend) - return nil -} + ctx = ctx.WithChainID(cliConfig.ChainID). + WithKeyring(keyRing). + WithOutputFormat(cliConfig.Output). + WithNodeURI(cliConfig.Node). + WithBroadcastMode(cliConfig.BroadcastMode) -func errUnknownConfigKey(key string) error { - return fmt.Errorf("unknown configuration key: %q", key) + return ctx } diff --git a/client/config/config_test.go b/client/config/config_test.go index 0e0f64a166fd..8da9dbeefea6 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -1,29 +1,28 @@ package config import ( + "errors" "io/ioutil" "os" "path/filepath" "testing" - "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client/flags" ) +var ErrWrongNumberOfArgs = errors.New("wrong number of arguments") + // For https://github.com/cosmos/cosmos-sdk/issues/3899 func Test_runConfigCmdTwiceWithShorterNodeValue(t *testing.T) { // Prepare environment t.Parallel() - configHome, cleanup := tmpDir(t) + cleanup := tmpDir(t) defer cleanup() - _ = os.RemoveAll(filepath.Join(configHome, "config")) - viper.Set(flags.FlagHome, configHome) + _ = os.RemoveAll(filepath.Join("config")) // Init command config - cmd := Cmd(configHome) + cmd := Cmd() assert.NotNil(t, cmd) err := cmd.RunE(cmd, []string{"node", "tcp://localhost:26657"}) @@ -51,11 +50,12 @@ func Test_runConfigCmdTwiceWithShorterNodeValue(t *testing.T) { require.Equal(t, err, errUnknownConfigKey("invalidKey")) // TODO add testing of pririty environmental variable, flag and file + // for now manual testign is ok } -func tmpDir(t *testing.T) (string, func()) { +func tmpDir(t *testing.T) func() { dir, err := ioutil.TempDir("", t.Name()+"_") require.NoError(t, err) - return dir, func() { _ = os.RemoveAll(dir) } + return func() { _ = os.RemoveAll(dir) } } diff --git a/client/config/toml.go b/client/config/toml.go index 7816655b9e2f..daad2626d7e4 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -22,12 +22,11 @@ keyring-backend = "{{ .KeyringBackend }}" output = "{{ .Output }}" node = "{{ .Node }}" broadcast-mode = "{{ .BroadcastMode }}" -trace = "{{ .Trace }}" ` // InitConfigTemplate initiates config template that will be used in // WriteConfigFile -func InitConfigTemplate() (*template.Template, error) { +func initConfigTemplate() (*template.Template, error) { tmpl := template.New("clientConfigFileTemplate") configTemplate, err := tmpl.Parse(defaultConfigTemplate) if err != nil { @@ -37,20 +36,9 @@ func InitConfigTemplate() (*template.Template, error) { return configTemplate, nil } -// ParseConfig retrieves the default environment configuration for the -// application. -func ParseConfig(v *viper.Viper) (*ClientConfig, error) { - conf := DefaultClientConfig() - if err := v.Unmarshal(conf); err != nil { - return nil, err - } - - return conf, nil -} - -// WriteConfigFile renders config using the template and writes it to +// writeConfigFile renders config using the template and writes it to // configFilePath. -func WriteConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) error { +func writeConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) error { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil { diff --git a/client/context.go b/client/context.go index dd9cfcc892ab..2e3c5a1507fb 100644 --- a/client/context.go +++ b/client/context.go @@ -217,7 +217,10 @@ func (ctx Context) WithInterfaceRegistry(interfaceRegistry codectypes.InterfaceR // WithViper returns the context with Viper field func (ctx Context) WithViper() Context { - ctx.Viper = viper.New() + v := viper.New() + // Automatically overrides config field by env variable if this exists + v.AutomaticEnv() + ctx.Viper = v return ctx } @@ -331,7 +334,7 @@ func GetFromFields(kr keyring.Keyring, from string, genOnly bool) (sdk.AccAddres return info.GetAddress(), info.GetName(), info.GetType(), nil } -func newKeyringFromFlags(ctx Context, backend string) (keyring.Keyring, error) { +func NewKeyringFromFlags(ctx Context, backend string) (keyring.Keyring, error) { if ctx.GenerateOnly { return keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, ctx.KeyringDir, ctx.Input) } diff --git a/docker-compose.yml b/docker-compose.yml index d335b9a06c47..f0c8b9011d6d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: container_name: simdnode0 image: "cosmossdk/simd-env" ports: - - "26656-26657:26656-26657" + - "26600-26601:26656-26657" - "1317:1317" - "9090:9090" environment: diff --git a/server/util.go b/server/util.go index b26af4aefa56..01af6e216987 100644 --- a/server/util.go +++ b/server/util.go @@ -23,7 +23,7 @@ import ( tmlog "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" - clicfg "github.com/cosmos/cosmos-sdk/client/config" + // clicfg "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server/config" @@ -244,28 +244,6 @@ func interceptConfigs(rootViper *viper.Viper) (*tmcfg.Config, error) { return nil, fmt.Errorf("failed to merge configuration: %w", err) } - // TODO test It if it works - - // Adding default ClientConfig and writing it into "client.toml" - cliCfgFilePath := filepath.Join(configPath, "client.toml") - // if _, err := os.Stat(cliCfgFilePath); os.IsNotExist(err) { - - // TODO use clientCtx.Viper instead of rootViper - cliConfig, err := clicfg.ParseConfig(rootViper) - if err != nil { - return nil, fmt.Errorf("failed to parse %s: %w", cliCfgFilePath, err) - } - - configTemplate, err := clicfg.InitConfigTemplate() - if err != nil { - return nil, fmt.Errorf("failed to initiate config template %s: %w", cliCfgFilePath, err) - } - - if err := clicfg.WriteConfigFile(cliCfgFilePath, cliConfig, configTemplate); err != nil { - return nil, fmt.Errorf("failed to write into config file %s: %w", cliCfgFilePath, err) - } - // } - return conf, nil } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 84cf138c2a27..d8398a736012 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -50,10 +50,13 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithHomeDir(simapp.DefaultNodeHome). WithViper() + initClientCtx = clicfg.UpdateClientContextFromClientConfig(initClientCtx) + 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 } @@ -80,7 +83,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { tmcli.NewCompletionCmd(rootCmd, true), testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), - clicfg.Cmd(flags.FlagHome), + clicfg.Cmd(), ) a := appCreator{encodingConfig} From 8125d5e3af51d38c39651a36b7e03329430c2be3 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 18 Mar 2021 14:52:46 -0700 Subject: [PATCH 12/14] ReadFromClientConfig --- client/config/cmd.go | 8 ----- client/config/config.go | 65 +++++++++++++++++++++-------------------- client/config/toml.go | 3 +- simapp/simd/cmd/root.go | 13 ++++++--- 4 files changed, 44 insertions(+), 45 deletions(-) diff --git a/client/config/cmd.go b/client/config/cmd.go index a6526ff83fd0..fb6748a9edc2 100644 --- a/client/config/cmd.go +++ b/client/config/cmd.go @@ -63,8 +63,6 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { cmd.Println(cliConfig.Node) case flags.FlagBroadcastMode: cmd.Println(cliConfig.BroadcastMode) - // case "trace": - // cmd.Println(cliConfig.Trace) default: err := errUnknownConfigKey(key) return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) @@ -86,12 +84,6 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { cliConfig.SetNode(value) case flags.FlagBroadcastMode: cliConfig.SetBroadcastMode(value) - /* - case "trace": - if err := cliConfig.SetTrace(value); err != nil { - return fmt.Errorf("couldn't parse bool value: %v", err) - } - */ default: return errUnknownConfigKey(key) } diff --git a/client/config/config.go b/client/config/config.go index 07de46ac76f7..8ae634c89c95 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -1,7 +1,8 @@ package config import ( - // "fmt" + "fmt" + "os" "path/filepath" "github.com/cosmos/cosmos-sdk/client" @@ -14,8 +15,6 @@ const ( output = "text" node = "tcp://localhost:26657" broadcastMode = "sync" - -// trace = false ) type ClientConfig struct { @@ -24,7 +23,6 @@ type ClientConfig struct { Output string `mapstructure:"output" json:"output"` Node string `mapstructure:"node" json:"node"` BroadcastMode string `mapstructure:"broadcast-mode" json:"broadcast-mode"` - // Trace bool `mapstructure:"trace" json:"trace"` } func DefaultClientConfig() *ClientConfig { @@ -51,46 +49,49 @@ func (c *ClientConfig) SetBroadcastMode(broadcastMode string) { c.BroadcastMode = broadcastMode } -/* -func (c *ClientConfig) SetTrace(trace string) error { - boolVal, err := strconv.ParseBool(trace) - if err != nil { - return err - } - c.Trace = boolVal - return nil -} -*/ - -func UpdateClientContextFromClientConfig(ctx client.Context) client.Context { +// ReadFromClientConfig reads values from client.toml file and updates them in client Context +func ReadFromClientConfig(ctx client.Context) (client.Context, error) { configPath := filepath.Join(ctx.HomeDir, "config") + configFilePath := filepath.Join(configPath, "client.toml") + + conf := DefaultClientConfig() - /* + switch _, err := os.Stat(configFilePath); { + // config file does not exist + case os.IsNotExist(err): + // we create ~/.simapp/config/client.toml with default values + + // create a directority configPath if err := ensureConfigPath(configPath); err != nil { return ctx, fmt.Errorf("couldn't make client config: %v", err) } - cliConfig, err := getClientConfig(configPath, ctx.Viper) + configTemplate, err := initConfigTemplate() if err != nil { - return ctx, fmt.Errorf("couldn't get client config: %v", err) + return ctx, fmt.Errorf("could not initiate config template: %v", err) } - - keyRing, err := client.NewKeyringFromFlags(ctx, cliConfig.KeyringBackend) + if err := writeConfigFile(configFilePath, conf, configTemplate); err != nil { + return ctx, fmt.Errorf("could not write client config to the file: %v", err) + } + // config file exists and we read config values from client.toml file + default: + conf, err = getClientConfig(configPath, ctx.Viper) if err != nil { - return ctx, fmt.Errorf("couldn't get key ring: %v", err) + return ctx, fmt.Errorf("couldn't get client config: %v", err) } - */ - - cliConfig, _ := getClientConfig(configPath, ctx.Viper) + } - keyRing, _ := client.NewKeyringFromFlags(ctx, cliConfig.KeyringBackend) + keyring, err := client.NewKeyringFromFlags(ctx, conf.KeyringBackend) + if err != nil { + return ctx, fmt.Errorf("couldn't get key ring: %v", err) + } - ctx = ctx.WithChainID(cliConfig.ChainID). - WithKeyring(keyRing). - WithOutputFormat(cliConfig.Output). - WithNodeURI(cliConfig.Node). - WithBroadcastMode(cliConfig.BroadcastMode) + ctx = ctx.WithChainID(conf.ChainID). + WithKeyring(keyring). + WithOutputFormat(conf.Output). + WithNodeURI(conf.Node). + WithBroadcastMode(conf.BroadcastMode) - return ctx + return ctx, nil } diff --git a/client/config/toml.go b/client/config/toml.go index daad2626d7e4..7f87c5c54944 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -63,12 +63,13 @@ func getClientConfig(configPath string, v *viper.Viper) (*ClientConfig, error) { v.AddConfigPath(configPath) v.SetConfigName("client") v.SetConfigType("toml") + v.AutomaticEnv() if err := v.ReadInConfig(); err != nil { return nil, err } - conf := DefaultClientConfig() + conf := new(ClientConfig) if err := v.Unmarshal(conf); err != nil { return nil, err } diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index d8398a736012..8b69a137920a 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "fmt" "io" "os" "path/filepath" @@ -14,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" - clicfg "github.com/cosmos/cosmos-sdk/client/config" + config "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" @@ -50,13 +51,17 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithHomeDir(simapp.DefaultNodeHome). WithViper() - initClientCtx = clicfg.UpdateClientContextFromClientConfig(initClientCtx) - rootCmd := &cobra.Command{ Use: "simd", Short: "simulation app", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + initClientCtx, err := config.ReadFromClientConfig(initClientCtx) + if err != nil { + return err + } + fmt.Printf("Node URI is %s", initClientCtx.NodeURI) + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { return err } @@ -83,7 +88,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { tmcli.NewCompletionCmd(rootCmd, true), testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), - clicfg.Cmd(), + config.Cmd(), ) a := appCreator{encodingConfig} From ec04cac972d713ca53dcd6e432d371d3cdb5b6c8 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Thu, 18 Mar 2021 21:30:58 -0700 Subject: [PATCH 13/14] homeflag bug fixed --- client/config/cmd.go | 9 +- client/config/config.go | 1 + client/config/toml.go | 1 - client/context.go | 20 +- docker-compose.yml | 2 +- simapp/simd/cmd/root.go | 4 +- test/config/app.toml | 189 +++++++++++++ test/config/client.toml | 13 + test/config/config.toml | 393 ++++++++++++++++++++++++++++ test/config/genesis.json | 153 +++++++++++ test/config/node_key.json | 1 + test/config/priv_validator_key.json | 11 + test/data/priv_validator_state.json | 5 + 13 files changed, 792 insertions(+), 10 deletions(-) create mode 100644 test/config/app.toml create mode 100644 test/config/client.toml create mode 100644 test/config/config.toml create mode 100644 test/config/genesis.json create mode 100644 test/config/node_key.json create mode 100644 test/config/priv_validator_key.json create mode 100644 test/data/priv_validator_state.json diff --git a/client/config/cmd.go b/client/config/cmd.go index fb6748a9edc2..0d32e5b882b7 100644 --- a/client/config/cmd.go +++ b/client/config/cmd.go @@ -29,12 +29,13 @@ func Cmd() *cobra.Command { func runConfigCmd(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - configPath := filepath.Join(clientCtx.HomeDir, "config") - if err := ensureConfigPath(configPath); err != nil { - return fmt.Errorf("couldn't make client config: %v", err) - } + /* + if err := ensureConfigPath(configPath); err != nil { + return fmt.Errorf("couldn't make client config: %v", err) + } + */ cliConfig, err := getClientConfig(configPath, clientCtx.Viper) if err != nil { diff --git a/client/config/config.go b/client/config/config.go index 8ae634c89c95..9b4ac719dbbd 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -51,6 +51,7 @@ func (c *ClientConfig) SetBroadcastMode(broadcastMode string) { // ReadFromClientConfig reads values from client.toml file and updates them in client Context func ReadFromClientConfig(ctx client.Context) (client.Context, error) { + configPath := filepath.Join(ctx.HomeDir, "config") configFilePath := filepath.Join(configPath, "client.toml") diff --git a/client/config/toml.go b/client/config/toml.go index 7f87c5c54944..e24b471af128 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -63,7 +63,6 @@ func getClientConfig(configPath string, v *viper.Viper) (*ClientConfig, error) { v.AddConfigPath(configPath) v.SetConfigName("client") v.SetConfigType("toml") - v.AutomaticEnv() if err := v.ReadInConfig(); err != nil { return nil, err diff --git a/client/context.go b/client/context.go index 2e3c5a1507fb..c751d0855be9 100644 --- a/client/context.go +++ b/client/context.go @@ -5,6 +5,7 @@ import ( "io" "os" + "github.com/spf13/cobra" "github.com/spf13/viper" "gopkg.in/yaml.v2" @@ -12,6 +13,7 @@ import ( "github.com/pkg/errors" rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -218,12 +220,26 @@ func (ctx Context) WithInterfaceRegistry(interfaceRegistry codectypes.InterfaceR // WithViper returns the context with Viper field func (ctx Context) WithViper() Context { v := viper.New() - // Automatically overrides config field by env variable if this exists - v.AutomaticEnv() ctx.Viper = v return ctx } +// WithHomeFlag checks if home flag is changed. +// If this is a case, we update HomeDir field of Client Context +/* Discovered a bug with Cory +./build/simd init andrei --home ./test +cd test/config there is no client.toml configuration file +*/ + +func (ctx Context) WithHomeFlag(cmd *cobra.Command) Context { + if cmd.Flags().Changed(flags.FlagHome) { + rootDir, _ := cmd.Flags().GetString(flags.FlagHome) + ctx = ctx.WithHomeDir(rootDir) + } + + return ctx +} + // PrintString prints the raw string to ctx.Output if it's defined, otherwise to os.Stdout func (ctx Context) PrintString(str string) error { return ctx.PrintBytes([]byte(str)) diff --git a/docker-compose.yml b/docker-compose.yml index f0c8b9011d6d..d335b9a06c47 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: container_name: simdnode0 image: "cosmossdk/simd-env" ports: - - "26600-26601:26656-26657" + - "26656-26657:26656-26657" - "1317:1317" - "9090:9090" environment: diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 8b69a137920a..cabfc6865095 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -2,7 +2,6 @@ package cmd import ( "errors" - "fmt" "io" "os" "path/filepath" @@ -56,11 +55,12 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { Short: "simulation app", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + initClientCtx = initClientCtx.WithHomeFlag(cmd) + initClientCtx, err := config.ReadFromClientConfig(initClientCtx) if err != nil { return err } - fmt.Printf("Node URI is %s", initClientCtx.NodeURI) if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { return err diff --git a/test/config/app.toml b/test/config/app.toml new file mode 100644 index 000000000000..0cffaed95838 --- /dev/null +++ b/test/config/app.toml @@ -0,0 +1,189 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Base Configuration ### +############################################################################### + +# The minimum gas prices a validator is willing to accept for processing a +# transaction. A transaction's fees must meet the minimum of any denomination +# specified in this config (e.g. 0.25token1;0.0001token2). +minimum-gas-prices = "" + +# default: the last 100 states are kept in addition to every 500th state; pruning at 10 block intervals +# nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node) +# everything: all saved states will be deleted, storing only the current state; pruning at 10 block intervals +# custom: allow pruning options to be manually specified through 'pruning-keep-recent', 'pruning-keep-every', and 'pruning-interval' +pruning = "default" + +# These are applied if and only if the pruning strategy is custom. +pruning-keep-recent = "0" +pruning-keep-every = "0" +pruning-interval = "0" + +# HaltHeight contains a non-zero block height at which a node will gracefully +# halt and shutdown that can be used to assist upgrades and testing. +# +# Note: Commitment of state will be attempted on the corresponding block. +halt-height = 0 + +# HaltTime contains a non-zero minimum block time (in Unix seconds) at which +# a node will gracefully halt and shutdown that can be used to assist upgrades +# and testing. +# +# Note: Commitment of state will be attempted on the corresponding block. +halt-time = 0 + +# MinRetainBlocks defines the minimum block height offset from the current +# block being committed, such that all blocks past this offset are pruned +# from Tendermint. It is used as part of the process of determining the +# ResponseCommit.RetainHeight value during ABCI Commit. A value of 0 indicates +# that no blocks should be pruned. +# +# This configuration value is only responsible for pruning Tendermint blocks. +# It has no bearing on application state pruning which is determined by the +# "pruning-*" configurations. +# +# Note: Tendermint block pruning is dependant on this parameter in conunction +# with the unbonding (safety threshold) period, state pruning and state sync +# snapshot parameters to determine the correct minimum value of +# ResponseCommit.RetainHeight. +min-retain-blocks = 0 + +# InterBlockCache enables inter-block caching. +inter-block-cache = true + +# IndexEvents defines the set of events in the form {eventType}.{attributeKey}, +# which informs Tendermint what to index. If empty, all events will be indexed. +# +# Example: +# ["message.sender", "message.recipient"] +index-events = [] + +############################################################################### +### Telemetry Configuration ### +############################################################################### + +[telemetry] + +# Prefixed with keys to separate services. +service-name = "" + +# Enabled enables the application telemetry functionality. When enabled, +# an in-memory sink is also enabled by default. Operators may also enabled +# other sinks such as Prometheus. +enabled = false + +# Enable prefixing gauge values with hostname. +enable-hostname = false + +# Enable adding hostname to labels. +enable-hostname-label = false + +# Enable adding service to labels. +enable-service-label = false + +# PrometheusRetentionTime, when positive, enables a Prometheus metrics sink. +prometheus-retention-time = 0 + +# GlobalLabels defines a global set of name/value label tuples applied to all +# metrics emitted using the wrapper functions defined in telemetry package. +# +# Example: +# [["chain_id", "cosmoshub-1"]] +global-labels = [ +] + +############################################################################### +### API Configuration ### +############################################################################### + +[api] + +# Enable defines if the API server should be enabled. +enable = false + +# Swagger defines if swagger documentation should automatically be registered. +swagger = false + +# Address defines the API server to listen on. +address = "tcp://0.0.0.0:1317" + +# MaxOpenConnections defines the number of maximum open connections. +max-open-connections = 1000 + +# RPCReadTimeout defines the Tendermint RPC read timeout (in seconds). +rpc-read-timeout = 10 + +# RPCWriteTimeout defines the Tendermint RPC write timeout (in seconds). +rpc-write-timeout = 0 + +# RPCMaxBodyBytes defines the Tendermint maximum response body (in bytes). +rpc-max-body-bytes = 1000000 + +# EnableUnsafeCORS defines if CORS should be enabled (unsafe - use it at your own risk). +enabled-unsafe-cors = false + +############################################################################### +### Rosetta Configuration ### +############################################################################### + +[rosetta] + +# Enable defines if the Rosetta API server should be enabled. +enable = false + +# Address defines the Rosetta API server to listen on. +address = ":8080" + +# Network defines the name of the blockchain that will be returned by Rosetta. +blockchain = "app" + +# Network defines the name of the network that will be returned by Rosetta. +network = "network" + +# Retries defines the number of retries when connecting to the node before failing. +retries = 3 + +# Offline defines if Rosetta server should run in offline mode. +offline = false + +############################################################################### +### gRPC Configuration ### +############################################################################### + +[grpc] + +# Enable defines if the gRPC server should be enabled. +enable = true + +# Address defines the gRPC server address to bind to. +address = "0.0.0.0:9090" + +############################################################################### +### gRPC Web Configuration ### +############################################################################### + +[grpc-web] + +# GRPCWebEnable defines if the gRPC-web should be enabled. +# NOTE: gRPC must also be enabled, otherwise, this configuration is a no-op. +enable = true + +# Address defines the gRPC-web server address to bind to. +address = "0.0.0.0:9091" + +############################################################################### +### State Sync Configuration ### +############################################################################### + +# State sync snapshots allow other nodes to rapidly join the network without replaying historical +# blocks, instead downloading and applying a snapshot of the application state at a given height. +[state-sync] + +# snapshot-interval specifies the block interval at which local state sync snapshots are +# taken (0 to disable). Must be a multiple of pruning-keep-every. +snapshot-interval = 0 + +# snapshot-keep-recent specifies the number of recent snapshots to keep and serve (0 to keep all). +snapshot-keep-recent = 2 diff --git a/test/config/client.toml b/test/config/client.toml new file mode 100644 index 000000000000..849c072cc9b2 --- /dev/null +++ b/test/config/client.toml @@ -0,0 +1,13 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Client Configuration ### +############################################################################### + + +chain-id = "" +keyring-backend = "os" +output = "text" +node = "tcp://localhost:26657" +broadcast-mode = "sync" diff --git a/test/config/config.toml b/test/config/config.toml new file mode 100644 index 000000000000..3ea3e522acf7 --- /dev/null +++ b/test/config/config.toml @@ -0,0 +1,393 @@ +# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +# NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or +# relative to the home directory (e.g. "data"). The home directory is +# "$HOME/.tendermint" by default, but could be changed via $TMHOME env variable +# or --home cmd flag. + +####################################################################### +### Main Base Config Options ### +####################################################################### + +# TCP or UNIX socket address of the ABCI application, +# or the name of an ABCI application compiled in with the Tendermint binary +proxy_app = "tcp://127.0.0.1:26658" + +# A custom human readable name for this node +moniker = "andrei" + +# If this node is many blocks behind the tip of the chain, FastSync +# allows them to catchup quickly by downloading blocks in parallel +# and verifying their commits +fast_sync = true + +# Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb +# * goleveldb (github.com/syndtr/goleveldb - most popular implementation) +# - pure go +# - stable +# * cleveldb (uses levigo wrapper) +# - fast +# - requires gcc +# - use cleveldb build tag (go build -tags cleveldb) +# * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) +# - EXPERIMENTAL +# - may be faster is some use-cases (random reads - indexer) +# - use boltdb build tag (go build -tags boltdb) +# * rocksdb (uses github.com/tecbot/gorocksdb) +# - EXPERIMENTAL +# - requires gcc +# - use rocksdb build tag (go build -tags rocksdb) +# * badgerdb (uses github.com/dgraph-io/badger) +# - EXPERIMENTAL +# - use badgerdb build tag (go build -tags badgerdb) +db_backend = "goleveldb" + +# Database directory +db_dir = "data" + +# Output level for logging, including package level options +log_level = "info" + +# Output format: 'plain' (colored text) or 'json' +log_format = "plain" + +##### additional base config options ##### + +# Path to the JSON file containing the initial validator set and other meta data +genesis_file = "config/genesis.json" + +# Path to the JSON file containing the private key to use as a validator in the consensus protocol +priv_validator_key_file = "config/priv_validator_key.json" + +# Path to the JSON file containing the last sign state of a validator +priv_validator_state_file = "data/priv_validator_state.json" + +# TCP or UNIX socket address for Tendermint to listen on for +# connections from an external PrivValidator process +priv_validator_laddr = "" + +# Path to the JSON file containing the private key to use for node authentication in the p2p protocol +node_key_file = "config/node_key.json" + +# Mechanism to connect to the ABCI application: socket | grpc +abci = "socket" + +# If true, query the ABCI app on connecting to a new peer +# so the app can decide if we should keep the connection or not +filter_peers = false + + +####################################################################### +### Advanced Configuration Options ### +####################################################################### + +####################################################### +### RPC Server Configuration Options ### +####################################################### +[rpc] + +# TCP or UNIX socket address for the RPC server to listen on +laddr = "tcp://127.0.0.1:26657" + +# A list of origins a cross-domain request can be executed from +# Default value '[]' disables cors support +# Use '["*"]' to allow any origin +cors_allowed_origins = [] + +# A list of methods the client is allowed to use with cross-domain requests +cors_allowed_methods = ["HEAD", "GET", "POST", ] + +# A list of non simple headers the client is allowed to use with cross-domain requests +cors_allowed_headers = ["Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time", ] + +# TCP or UNIX socket address for the gRPC server to listen on +# NOTE: This server only supports /broadcast_tx_commit +grpc_laddr = "" + +# Maximum number of simultaneous connections. +# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +grpc_max_open_connections = 900 + +# Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool +unsafe = false + +# Maximum number of simultaneous connections (including WebSocket). +# Does not include gRPC connections. See grpc_max_open_connections +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} +# 1024 - 40 - 10 - 50 = 924 = ~900 +max_open_connections = 900 + +# Maximum number of unique clientIDs that can /subscribe +# If you're using /broadcast_tx_commit, set to the estimated maximum number +# of broadcast_tx_commit calls per block. +max_subscription_clients = 100 + +# Maximum number of unique queries a given client can /subscribe to +# If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to +# the estimated # maximum number of broadcast_tx_commit calls per block. +max_subscriptions_per_client = 5 + +# How long to wait for a tx to be committed during /broadcast_tx_commit. +# WARNING: Using a value larger than 10s will result in increasing the +# global HTTP write timeout, which applies to all connections and endpoints. +# See https://github.com/tendermint/tendermint/issues/3435 +timeout_broadcast_tx_commit = "10s" + +# Maximum size of request body, in bytes +max_body_bytes = 1000000 + +# Maximum size of request header, in bytes +max_header_bytes = 1048576 + +# The path to a file containing certificate that is used to create the HTTPS server. +# Might be either absolute path or path related to Tendermint's config directory. +# If the certificate is signed by a certificate authority, +# the certFile should be the concatenation of the server's certificate, any intermediates, +# and the CA's certificate. +# NOTE: both tls_cert_file and tls_key_file must be present for Tendermint to create HTTPS server. +# Otherwise, HTTP server is run. +tls_cert_file = "" + +# The path to a file containing matching private key that is used to create the HTTPS server. +# Might be either absolute path or path related to Tendermint's config directory. +# NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server. +# Otherwise, HTTP server is run. +tls_key_file = "" + +# pprof listen address (https://golang.org/pkg/net/http/pprof) +pprof_laddr = "localhost:6060" + +####################################################### +### P2P Configuration Options ### +####################################################### +[p2p] + +# Address to listen for incoming connections +laddr = "tcp://0.0.0.0:26656" + +# Address to advertise to peers for them to dial +# If empty, will use the same port as the laddr, +# and will introspect on the listener or use UPnP +# to figure out the address. +external_address = "" + +# Comma separated list of seed nodes to connect to +seeds = "" + +# Comma separated list of nodes to keep persistent connections to +persistent_peers = "" + +# UPNP port forwarding +upnp = false + +# Path to address book +addr_book_file = "config/addrbook.json" + +# Set true for strict address routability rules +# Set false for private or local networks +addr_book_strict = true + +# Maximum number of inbound peers +max_num_inbound_peers = 40 + +# Maximum number of outbound peers to connect to, excluding persistent peers +max_num_outbound_peers = 10 + +# List of node IDs, to which a connection will be (re)established ignoring any existing limits +unconditional_peer_ids = "" + +# Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) +persistent_peers_max_dial_period = "0s" + +# Time to wait before flushing messages out on the connection +flush_throttle_timeout = "100ms" + +# Maximum size of a message packet payload, in bytes +max_packet_msg_payload_size = 1024 + +# Rate at which packets can be sent, in bytes/second +send_rate = 5120000 + +# Rate at which packets can be received, in bytes/second +recv_rate = 5120000 + +# Set true to enable the peer-exchange reactor +pex = true + +# Seed mode, in which node constantly crawls the network and looks for +# peers. If another node asks it for addresses, it responds and disconnects. +# +# Does not work if the peer-exchange reactor is disabled. +seed_mode = false + +# Comma separated list of peer IDs to keep private (will not be gossiped to other peers) +private_peer_ids = "" + +# Toggle to disable guard against peers connecting from the same ip. +allow_duplicate_ip = false + +# Peer connection configuration. +handshake_timeout = "20s" +dial_timeout = "3s" + +####################################################### +### Mempool Configuration Option ### +####################################################### +[mempool] + +recheck = true +broadcast = true +wal_dir = "" + +# Maximum number of transactions in the mempool +size = 5000 + +# Limit the total size of all txs in the mempool. +# This only accounts for raw transactions (e.g. given 1MB transactions and +# max_txs_bytes=5MB, mempool will only accept 5 transactions). +max_txs_bytes = 1073741824 + +# Size of the cache (used to filter transactions we saw earlier) in transactions +cache_size = 10000 + +# Do not remove invalid transactions from the cache (default: false) +# Set to true if it's not possible for any invalid transaction to become valid +# again in the future. +keep-invalid-txs-in-cache = false + +# Maximum size of a single transaction. +# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. +max_tx_bytes = 1048576 + +# Maximum size of a batch of transactions to send to a peer +# Including space needed by encoding (one varint per transaction). +# XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 +max_batch_bytes = 0 + +####################################################### +### State Sync Configuration Options ### +####################################################### +[statesync] +# State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine +# snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in +# the network to take and serve state machine snapshots. State sync is not attempted if the node +# has any local state (LastBlockHeight > 0). The node will have a truncated block history, +# starting from the height of the snapshot. +enable = false + +# RPC servers (comma-separated) for light client verification of the synced state machine and +# retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding +# header hash obtained from a trusted source, and a period during which validators can be trusted. +# +# For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 +# weeks) during which they can be financially punished (slashed) for misbehavior. +rpc_servers = "" +trust_height = 0 +trust_hash = "" +trust_period = "168h0m0s" + +# Time to spend discovering snapshots before initiating a restore. +discovery_time = "15s" + +# Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). +# Will create a new, randomly named directory within, and remove it when done. +temp_dir = "" + +####################################################### +### Fast Sync Configuration Connections ### +####################################################### +[fastsync] + +# Fast Sync version to use: +# 1) "v0" (default) - the legacy fast sync implementation +# 2) "v1" - refactor of v0 version for better testability +# 2) "v2" - complete redesign of v0, optimized for testability & readability +version = "v0" + +####################################################### +### Consensus Configuration Options ### +####################################################### +[consensus] + +wal_file = "data/cs.wal/wal" + +# How long we wait for a proposal block before prevoting nil +timeout_propose = "3s" +# How much timeout_propose increases with each round +timeout_propose_delta = "500ms" +# How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) +timeout_prevote = "1s" +# How much the timeout_prevote increases with each round +timeout_prevote_delta = "500ms" +# How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) +timeout_precommit = "1s" +# How much the timeout_precommit increases with each round +timeout_precommit_delta = "500ms" +# How long we wait after committing a block, before starting on the new +# height (this gives us a chance to receive some more precommits, even +# though we already have +2/3). +timeout_commit = "5s" + +# How many blocks to look back to check existence of the node's consensus votes before joining consensus +# When non-zero, the node will panic upon restart +# if the same consensus key was used to sign {double_sign_check_height} last blocks. +# So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. +double_sign_check_height = 0 + +# Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) +skip_timeout_commit = false + +# EmptyBlocks mode and possible interval between empty blocks +create_empty_blocks = true +create_empty_blocks_interval = "0s" + +# Reactor sleep duration parameters +peer_gossip_sleep_duration = "100ms" +peer_query_maj23_sleep_duration = "2s" + +####################################################### +### Transaction Indexer Configuration Options ### +####################################################### +[tx_index] + +# What indexer to use for transactions +# +# The application will set which txs to index. In some cases a node operator will be able +# to decide which txs to index based on configuration set in the application. +# +# Options: +# 1) "null" +# 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). +# - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. +indexer = "kv" + +####################################################### +### Instrumentation Configuration Options ### +####################################################### +[instrumentation] + +# When true, Prometheus metrics are served under /metrics on +# PrometheusListenAddr. +# Check out the documentation for the list of available metrics. +prometheus = false + +# Address to listen for Prometheus collector(s) connections +prometheus_listen_addr = ":26660" + +# Maximum number of simultaneous connections. +# If you want to accept a larger number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = 3 + +# Instrumentation namespace +namespace = "tendermint" diff --git a/test/config/genesis.json b/test/config/genesis.json new file mode 100644 index 000000000000..c0fc09392881 --- /dev/null +++ b/test/config/genesis.json @@ -0,0 +1,153 @@ +{ + "genesis_time": "2021-03-19T03:56:47.340205466Z", + "chain_id": "test-chain-Q0sJg8", + "initial_height": "1", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "-1", + "time_iota_ms": "1000" + }, + "evidence": { + "max_age_num_blocks": "100000", + "max_age_duration": "172800000000000", + "max_bytes": "1048576" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + }, + "version": {} + }, + "app_hash": "", + "app_state": { + "auth": { + "params": { + "max_memo_characters": "256", + "tx_sig_limit": "7", + "tx_size_cost_per_byte": "10", + "sig_verify_cost_ed25519": "590", + "sig_verify_cost_secp256k1": "1000" + }, + "accounts": [] + }, + "authz": { + "authorization": [] + }, + "bank": { + "params": { + "send_enabled": [], + "default_send_enabled": true + }, + "balances": [], + "supply": [], + "denom_metadata": [] + }, + "capability": { + "index": "1", + "owners": [] + }, + "crisis": { + "constant_fee": { + "denom": "stake", + "amount": "1000" + } + }, + "distribution": { + "params": { + "community_tax": "0.020000000000000000", + "base_proposer_reward": "0.010000000000000000", + "bonus_proposer_reward": "0.040000000000000000", + "withdraw_addr_enabled": true + }, + "fee_pool": { + "community_pool": [] + }, + "delegator_withdraw_infos": [], + "previous_proposer": "", + "outstanding_rewards": [], + "validator_accumulated_commissions": [], + "validator_historical_rewards": [], + "validator_current_rewards": [], + "delegator_starting_infos": [], + "validator_slash_events": [] + }, + "evidence": { + "evidence": [] + }, + "feegrant": { + "fee_allowances": [] + }, + "genutil": { + "gen_txs": [] + }, + "gov": { + "starting_proposal_id": "1", + "deposits": [], + "votes": [], + "proposals": [], + "deposit_params": { + "min_deposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "max_deposit_period": "172800s" + }, + "voting_params": { + "voting_period": "172800s" + }, + "tally_params": { + "quorum": "0.334000000000000000", + "threshold": "0.500000000000000000", + "veto_threshold": "0.334000000000000000" + } + }, + "mint": { + "minter": { + "inflation": "0.130000000000000000", + "annual_provisions": "0.000000000000000000" + }, + "params": { + "mint_denom": "stake", + "inflation_rate_change": "0.130000000000000000", + "inflation_max": "0.200000000000000000", + "inflation_min": "0.070000000000000000", + "goal_bonded": "0.670000000000000000", + "blocks_per_year": "6311520" + } + }, + "params": null, + "slashing": { + "params": { + "signed_blocks_window": "100", + "min_signed_per_window": "0.500000000000000000", + "downtime_jail_duration": "600s", + "slash_fraction_double_sign": "0.050000000000000000", + "slash_fraction_downtime": "0.010000000000000000" + }, + "signing_infos": [], + "missed_blocks": [] + }, + "staking": { + "params": { + "unbonding_time": "1814400s", + "max_validators": 100, + "max_entries": 7, + "historical_entries": 10000, + "bond_denom": "stake" + }, + "last_total_power": "0", + "last_validator_powers": [], + "validators": [], + "delegations": [], + "unbonding_delegations": [], + "redelegations": [], + "exported": false + }, + "upgrade": {}, + "vesting": {} + } +} \ No newline at end of file diff --git a/test/config/node_key.json b/test/config/node_key.json new file mode 100644 index 000000000000..a89b97bae573 --- /dev/null +++ b/test/config/node_key.json @@ -0,0 +1 @@ +{"priv_key":{"type":"tendermint/PrivKeyEd25519","value":"vOcudpnAFVv+QfY7DU8Fn+RpHI0ZX1GeI0Mgbq3m49al289Ccipl54VzybCVlobF40qeR6ckmFtpfVKPRk4qjA=="}} \ No newline at end of file diff --git a/test/config/priv_validator_key.json b/test/config/priv_validator_key.json new file mode 100644 index 000000000000..561c478035d1 --- /dev/null +++ b/test/config/priv_validator_key.json @@ -0,0 +1,11 @@ +{ + "address": "A7F632110F05FCAE6D7D9BD0A94F6ED12A4A91D7", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "iN4mfwi6wRLymvWR+abi1K+BH+5dMdn195I01IygTas=" + }, + "priv_key": { + "type": "tendermint/PrivKeyEd25519", + "value": "biTbdoqY8tswc9BRozkdkSrN2k+I+YZ2gZQ3bjj1IwWI3iZ/CLrBEvKa9ZH5puLUr4Ef7l0x2fX3kjTUjKBNqw==" + } +} \ No newline at end of file diff --git a/test/data/priv_validator_state.json b/test/data/priv_validator_state.json new file mode 100644 index 000000000000..48f3b67e3f85 --- /dev/null +++ b/test/data/priv_validator_state.json @@ -0,0 +1,5 @@ +{ + "height": "0", + "round": 0, + "step": 0 +} \ No newline at end of file From d2250f6660b5fde04c85b87fad3676a382657ee8 Mon Sep 17 00:00:00 2001 From: Andrei Ivasko Date: Mon, 22 Mar 2021 10:57:02 -0700 Subject: [PATCH 14/14] current state --- client/cmd.go | 1 + client/config/cmd.go | 37 +++++++---------- client/config/config.go | 40 +++++++++++-------- client/config/toml.go | 17 ++++++-- client/keys/list.go | 6 +-- codec/unknownproto/unknown_fields_test.go | 8 ++-- cosmovisor/upgrade.go | 2 - cosmovisor/upgrade_test.go | 4 +- .../keys/secp256r1/privkey_internal_test.go | 5 ++- crypto/ledger/ledger_mock.go | 2 - simapp/simd/cmd/cmd_test.go | 4 +- testutil/testdata/tx.go | 3 +- types/address.go | 3 +- types/coin_test.go | 2 +- x/auth/client/cli/query.go | 2 +- x/auth/tx/encode_decode_test.go | 2 +- x/auth/vesting/client/cli/tx.go | 2 +- x/auth/vesting/msg_server.go | 2 - x/authz/client/cli/query.go | 2 +- x/authz/client/cli/tx.go | 2 +- x/bank/client/cli/query.go | 2 +- x/bank/client/cli/tx.go | 2 +- x/bank/keeper/msg_server.go | 2 - x/crisis/client/cli/tx.go | 2 +- x/distribution/client/cli/query.go | 2 +- x/distribution/client/cli/tx.go | 2 +- x/distribution/keeper/msg_server.go | 2 - x/evidence/client/cli/query.go | 2 +- x/evidence/client/cli/tx.go | 2 +- x/feegrant/client/cli/query.go | 2 +- x/feegrant/client/cli/tx.go | 2 +- x/genutil/client/cli/init.go | 1 - x/genutil/utils.go | 1 - x/gov/client/cli/query.go | 2 +- x/gov/client/cli/tx.go | 2 +- x/gov/keeper/msg_server.go | 2 - x/mint/client/cli/query.go | 2 +- x/params/client/cli/query.go | 2 +- x/slashing/client/cli/query.go | 2 +- x/slashing/client/cli/tx.go | 2 +- x/staking/client/cli/query.go | 2 +- x/staking/client/cli/tx.go | 2 +- 42 files changed, 94 insertions(+), 94 deletions(-) diff --git a/client/cmd.go b/client/cmd.go index 6213b4f59238..4a541e11c62f 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -131,6 +131,7 @@ func ReadPersistentCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Cont if clientCtx.Client == nil || flagSet.Changed(flags.FlagNode) { rpcURI, _ := flagSet.GetString(flags.FlagNode) + // lines 135- 141 extract to the function newClientFromNodeFlag if rpcURI != "" { clientCtx = clientCtx.WithNodeURI(rpcURI) diff --git a/client/config/cmd.go b/client/config/cmd.go index 0d32e5b882b7..529fac2696bc 100644 --- a/client/config/cmd.go +++ b/client/config/cmd.go @@ -31,13 +31,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) configPath := filepath.Join(clientCtx.HomeDir, "config") - /* - if err := ensureConfigPath(configPath); err != nil { - return fmt.Errorf("couldn't make client config: %v", err) - } - */ - - cliConfig, err := getClientConfig(configPath, clientCtx.Viper) + conf, err := getClientConfig(configPath, clientCtx.Viper) if err != nil { return fmt.Errorf("couldn't get client config: %v", err) } @@ -45,25 +39,24 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { switch len(args) { case 0: // print all client config fields to sdt out - s, _ := json.MarshalIndent(cliConfig, "", "\t") + s, _ := json.MarshalIndent(conf, "", "\t") cmd.Println(string(s)) case 1: // it's a get - // TODO implement method for get - // should i implement getters here? + key := args[0] switch key { case flags.FlagChainID: - cmd.Println(cliConfig.ChainID) + cmd.Println(conf.ChainID) case flags.FlagKeyringBackend: - cmd.Println(cliConfig.KeyringBackend) + cmd.Println(conf.KeyringBackend) case tmcli.OutputFlag: - cmd.Println(cliConfig.Output) + cmd.Println(conf.Output) case flags.FlagNode: - cmd.Println(cliConfig.Node) + cmd.Println(conf.Node) case flags.FlagBroadcastMode: - cmd.Println(cliConfig.BroadcastMode) + cmd.Println(conf.BroadcastMode) default: err := errUnknownConfigKey(key) return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) @@ -76,15 +69,15 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { switch key { case flags.FlagChainID: - cliConfig.SetChainID(value) + conf.SetChainID(value) case flags.FlagKeyringBackend: - cliConfig.SetKeyringBackend(value) + conf.SetKeyringBackend(value) case tmcli.OutputFlag: - cliConfig.SetOutput(value) + conf.SetOutput(value) case flags.FlagNode: - cliConfig.SetNode(value) + conf.SetNode(value) case flags.FlagBroadcastMode: - cliConfig.SetBroadcastMode(value) + conf.SetBroadcastMode(value) default: return errUnknownConfigKey(key) } @@ -94,8 +87,8 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { return fmt.Errorf("could not initiate config template: %v", err) } - cliConfigFile := filepath.Join(configPath, "client.toml") - if err := writeConfigFile(cliConfigFile, cliConfig, configTemplate); err != nil { + confFile := filepath.Join(configPath, "client.toml") + if err := writeConfigFile(confFile, conf, configTemplate); err != nil { return fmt.Errorf("could not write client config to the file: %v", err) } diff --git a/client/config/config.go b/client/config/config.go index 9b4ac719dbbd..0b94a67cd66a 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -25,6 +25,7 @@ type ClientConfig struct { BroadcastMode string `mapstructure:"broadcast-mode" json:"broadcast-mode"` } +// DefaultClientConfig returns the reference to ClientConfig with default values. func DefaultClientConfig() *ClientConfig { return &ClientConfig{chainID, keyringBackend, output, node, broadcastMode} } @@ -57,12 +58,8 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { conf := DefaultClientConfig() - switch _, err := os.Stat(configFilePath); { - // config file does not exist - case os.IsNotExist(err): - // we create ~/.simapp/config/client.toml with default values - - // create a directority configPath + // if config.toml file does not exist we create it and write default ClientConfig values into it. + if _, err := os.Stat(configFilePath); os.IsNotExist(err) { if err := ensureConfigPath(configPath); err != nil { return ctx, fmt.Errorf("couldn't make client config: %v", err) } @@ -75,23 +72,34 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { if err := writeConfigFile(configFilePath, conf, configTemplate); err != nil { return ctx, fmt.Errorf("could not write client config to the file: %v", err) } - // config file exists and we read config values from client.toml file - default: - conf, err = getClientConfig(configPath, ctx.Viper) - if err != nil { - return ctx, fmt.Errorf("couldn't get client config: %v", err) - } } + conf, err := getClientConfig(configPath, ctx.Viper) + if err != nil { + return ctx, fmt.Errorf("couldn't get client config: %v", err) + } + + ctx = ctx.WithOutputFormat(conf.Output) + + //we need to update KeyringDir field on Client Context first cause it is used in NewKeyringFromFlags + ctx = ctx.WithKeyringDir(ctx.HomeDir) + + ctx = ctx.WithChainID(conf.ChainID) + keyring, err := client.NewKeyringFromFlags(ctx, conf.KeyringBackend) if err != nil { return ctx, fmt.Errorf("couldn't get key ring: %v", err) } - ctx = ctx.WithChainID(conf.ChainID). - WithKeyring(keyring). - WithOutputFormat(conf.Output). - WithNodeURI(conf.Node). + ctx = ctx.WithKeyring(keyring) + + client, err := newClientFromNodeFlag(conf.Node) + if err != nil { + return ctx, fmt.Errorf("couldn't get client from nodeURI: %v", err) + } + + ctx = ctx.WithNodeURI(conf.Node). + WithClient(client). WithBroadcastMode(conf.BroadcastMode) return ctx, nil diff --git a/client/config/toml.go b/client/config/toml.go index e24b471af128..3b8ff5e4ee70 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/viper" tmos "github.com/tendermint/tendermint/libs/os" + rpchttp "github.com/tendermint/tendermint/rpc/client/http" ) const defaultConfigTemplate = `# This is a TOML config file. @@ -24,8 +25,8 @@ node = "{{ .Node }}" broadcast-mode = "{{ .BroadcastMode }}" ` -// InitConfigTemplate initiates config template that will be used in -// WriteConfigFile +// initConfigTemplate initiates config template that will be used in +// writeConfigFile func initConfigTemplate() (*template.Template, error) { tmpl := template.New("clientConfigFileTemplate") configTemplate, err := tmpl.Parse(defaultConfigTemplate) @@ -38,18 +39,19 @@ func initConfigTemplate() (*template.Template, error) { // writeConfigFile renders config using the template and writes it to // configFilePath. -func writeConfigFile(cfgFile string, config *ClientConfig, configTemplate *template.Template) error { +func writeConfigFile(configFilePath string, config *ClientConfig, configTemplate *template.Template) error { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil { return err } - tmos.MustWriteFile(cfgFile, buffer.Bytes(), 0644) + tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) return nil } +// ensureConfigPath creates a directory configPath if it does not exist func ensureConfigPath(configPath string) error { if err := os.MkdirAll(configPath, os.ModePerm); err != nil { return err @@ -58,6 +60,13 @@ func ensureConfigPath(configPath string) error { return nil } +// newClientFromNodeFlag sets up Client implementation that communicates with a Tendermint node over +// JSON RPC and WebSockets +func newClientFromNodeFlag(nodeURI string) (*rpchttp.HTTP, error) { + return rpchttp.New(nodeURI, "/websocket") +} + +// getClientConfig reads values from client.toml file and unmarshalls them into ClientConfig func getClientConfig(configPath string, v *viper.Viper) (*ClientConfig, error) { v.AddConfigPath(configPath) diff --git a/client/keys/list.go b/client/keys/list.go index de7681acc9c0..863ce4cf4d8a 100644 --- a/client/keys/list.go +++ b/client/keys/list.go @@ -2,7 +2,7 @@ package keys import ( "github.com/spf13/cobra" - "github.com/tendermint/tendermint/libs/cli" + //"github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" ) @@ -37,8 +37,8 @@ func runListCmd(cmd *cobra.Command, _ []string) error { cmd.SetOut(cmd.OutOrStdout()) if ok, _ := cmd.Flags().GetBool(flagListNames); !ok { - output, _ := cmd.Flags().GetString(cli.OutputFlag) - printInfos(cmd.OutOrStdout(), infos, output) + + printInfos(cmd.OutOrStdout(), infos, clientCtx.OutputFormat) return nil } diff --git a/codec/unknownproto/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index ad3926cedb55..a610bbe29098 100644 --- a/codec/unknownproto/unknown_fields_test.go +++ b/codec/unknownproto/unknown_fields_test.go @@ -76,7 +76,7 @@ func TestRejectUnknownFieldsRepeated(t *testing.T) { }, }, { - name: "Unknown field in midst of repeated values, allowUnknownNonCriticals set", + name: "Unknown field in midst of repeated values, allowUnknownNonCriticals set", allowUnknownNonCriticals: true, in: &testdata.TestVersion2{ C: []*testdata.TestVersion2{ @@ -178,7 +178,7 @@ func TestRejectUnknownFieldsRepeated(t *testing.T) { hasUnknownNonCriticals: true, }, { - name: "Unknown field in midst of repeated values, non-critical field ignored", + name: "Unknown field in midst of repeated values, non-critical field ignored", allowUnknownNonCriticals: true, in: &testdata.TestVersion3{ C: []*testdata.TestVersion3{ @@ -257,7 +257,7 @@ func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { }, }, { - name: "Field that's in the reserved range, toggle allowUnknownNonCriticals", + name: "Field that's in the reserved range, toggle allowUnknownNonCriticals", allowUnknownNonCriticals: true, in: &testdata.Customer2{ Id: 289, @@ -266,7 +266,7 @@ func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { wantErr: nil, }, { - name: "Unknown fields that are critical, but with allowUnknownNonCriticals set", + name: "Unknown fields that are critical, but with allowUnknownNonCriticals set", allowUnknownNonCriticals: true, in: &testdata.Customer2{ Id: 289, diff --git a/cosmovisor/upgrade.go b/cosmovisor/upgrade.go index 3057597f7df1..28ba108851dd 100644 --- a/cosmovisor/upgrade.go +++ b/cosmovisor/upgrade.go @@ -10,8 +10,6 @@ import ( "path/filepath" "runtime" "strings" - - "github.com/hashicorp/go-getter" ) // DoUpgrade will be called after the log message has been parsed and the process has terminated. diff --git a/cosmovisor/upgrade_test.go b/cosmovisor/upgrade_test.go index 2123df8e4035..0c214d4785b6 100644 --- a/cosmovisor/upgrade_test.go +++ b/cosmovisor/upgrade_test.go @@ -231,8 +231,8 @@ func (s *upgradeTestSuite) TestDownloadBinary() { home := copyTestData(s.T(), "download") cfg := &cosmovisor.Config{ - Home: home, - Name: "autod", + Home: home, + Name: "autod", AllowDownloadBinaries: true, } diff --git a/crypto/keys/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index ae48b47e3d68..ff1f06423d6f 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -5,11 +5,12 @@ import ( "github.com/tendermint/tendermint/crypto" + proto "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - proto "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/suite" ) var _ cryptotypes.PrivKey = &PrivKey{} diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index 4f7feb2c52de..33717b27c1c9 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -11,8 +11,6 @@ import ( secp256k1 "github.com/tendermint/btcd/btcec" "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/go-bip39" - "github.com/cosmos/cosmos-sdk/crypto/hd" csecp256k1 "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/testutil" diff --git a/simapp/simd/cmd/cmd_test.go b/simapp/simd/cmd/cmd_test.go index 1a9183d33e08..601f84e65dac 100644 --- a/simapp/simd/cmd/cmd_test.go +++ b/simapp/simd/cmd/cmd_test.go @@ -15,8 +15,8 @@ import ( func TestInitCmd(t *testing.T) { rootCmd, _ := cmd.NewRootCmd() rootCmd.SetArgs([]string{ - "init", // Test the init cmd - "simapp-test", // Moniker + "init", // Test the init cmd + "simapp-test", // Moniker fmt.Sprintf("--%s=%s", cli.FlagOverwrite, "true"), // Overwrite genesis.json, in case it already exists }) diff --git a/testutil/testdata/tx.go b/testutil/testdata/tx.go index cb7ae9d370e2..4da80c9e4e8f 100644 --- a/testutil/testdata/tx.go +++ b/testutil/testdata/tx.go @@ -3,11 +3,12 @@ package testdata import ( "encoding/json" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" ) // KeyTestPubAddr generates a new secp256k1 keypair. diff --git a/types/address.go b/types/address.go index c6f6404e8775..ec9df8d3f135 100644 --- a/types/address.go +++ b/types/address.go @@ -11,13 +11,14 @@ import ( yaml "gopkg.in/yaml.v2" + "github.com/hashicorp/golang-lru/simplelru" + "github.com/cosmos/cosmos-sdk/codec/legacy" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/internal/conv" "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/types/bech32" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/hashicorp/golang-lru/simplelru" ) const ( diff --git a/types/coin_test.go b/types/coin_test.go index ab69f16a17db..d3108b09308e 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -651,7 +651,7 @@ func (s *coinTestSuite) TestParseCoins() { expected sdk.Coins // if valid is true, make sure this is returned }{ {"", true, nil}, - {"0stake", true, sdk.Coins{}}, // remove zero coins + {"0stake", true, sdk.Coins{}}, // remove zero coins {"0stake,1foo,99bar", true, sdk.Coins{{"bar", sdk.NewInt(99)}, {"foo", one}}}, // remove zero coins {"1foo", true, sdk.Coins{{"foo", one}}}, {"10btc,1atom,20btc", false, nil}, diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 9604959cbdb5..fdf0722ceb0b 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -29,7 +29,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the auth module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( diff --git a/x/auth/tx/encode_decode_test.go b/x/auth/tx/encode_decode_test.go index 55fff38c366f..91a029d45ac8 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -61,7 +61,7 @@ func TestUnknownFields(t *testing.T) { { name: "non-critical fields in TxBody should not error on decode, but should error with amino", body: &testdata.TestUpdatedTxBody{ - Memo: "foo", + Memo: "foo", SomeNewFieldNonCriticalField: "blah", }, authInfo: &testdata.TestUpdatedAuthInfo{}, diff --git a/x/auth/vesting/client/cli/tx.go b/x/auth/vesting/client/cli/tx.go index c6c2ac1432d2..050fbef61f14 100644 --- a/x/auth/vesting/client/cli/tx.go +++ b/x/auth/vesting/client/cli/tx.go @@ -25,7 +25,7 @@ func GetTxCmd() *cobra.Command { Short: "Vesting transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } txCmd.AddCommand( diff --git a/x/auth/vesting/msg_server.go b/x/auth/vesting/msg_server.go index dadd65dbcf1c..e60b631ae2f7 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -5,8 +5,6 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/armon/go-metrics" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/authz/client/cli/query.go b/x/authz/client/cli/query.go index 269a68e099f0..8bfd9f9ceae6 100644 --- a/x/authz/client/cli/query.go +++ b/x/authz/client/cli/query.go @@ -23,7 +23,7 @@ func GetQueryCmd() *cobra.Command { Long: "", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } authorizationQueryCmd.AddCommand( diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 44df6f5e9aa4..7459a17d2fcb 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -39,7 +39,7 @@ func GetTxCmd() *cobra.Command { Long: "Authorize and revoke access to execute transactions on behalf of your address", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } AuthorizationTxCmd.AddCommand( diff --git a/x/bank/client/cli/query.go b/x/bank/client/cli/query.go index a192c8deba1b..9b80d87823df 100644 --- a/x/bank/client/cli/query.go +++ b/x/bank/client/cli/query.go @@ -26,7 +26,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the bank module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index 4a615d5045ca..c94199601db4 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -18,7 +18,7 @@ func NewTxCmd() *cobra.Command { Short: "Bank transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } txCmd.AddCommand(NewSendTxCmd()) diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go index b318db2cc461..a108b2560554 100644 --- a/x/bank/keeper/msg_server.go +++ b/x/bank/keeper/msg_server.go @@ -3,8 +3,6 @@ package keeper import ( "context" - "github.com/armon/go-metrics" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index c1288b95ed27..e8dc6038226a 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -19,7 +19,7 @@ func NewTxCmd() *cobra.Command { Short: "Crisis transactions subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } txCmd.AddCommand(NewMsgVerifyInvariantTxCmd()) diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index aa087f5f8b27..b8784fcad88e 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -21,7 +21,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the distribution module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } distQueryCmd.AddCommand( diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 6237bf92ef5e..1e7479914eee 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -34,7 +34,7 @@ func NewTxCmd() *cobra.Command { Short: "Distribution transactions subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } distTxCmd.AddCommand( diff --git a/x/distribution/keeper/msg_server.go b/x/distribution/keeper/msg_server.go index bff869ee55d7..5bd4c4265778 100644 --- a/x/distribution/keeper/msg_server.go +++ b/x/distribution/keeper/msg_server.go @@ -3,8 +3,6 @@ package keeper import ( "context" - "github.com/armon/go-metrics" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" diff --git a/x/evidence/client/cli/query.go b/x/evidence/client/cli/query.go index 9c987fb15e36..f23f5bcbe08e 100644 --- a/x/evidence/client/cli/query.go +++ b/x/evidence/client/cli/query.go @@ -34,7 +34,7 @@ $ %s query %s --page=2 --limit=50 Args: cobra.MaximumNArgs(1), DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: QueryEvidenceCmd(), + RunE: QueryEvidenceCmd(), } flags.AddQueryFlagsToCmd(cmd) diff --git a/x/evidence/client/cli/tx.go b/x/evidence/client/cli/tx.go index f13e3e8e2f65..c7fcda1ff82c 100644 --- a/x/evidence/client/cli/tx.go +++ b/x/evidence/client/cli/tx.go @@ -18,7 +18,7 @@ func GetTxCmd(childCmds []*cobra.Command) *cobra.Command { Short: "Evidence transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } submitEvidenceCmd := SubmitEvidenceCmd() diff --git a/x/feegrant/client/cli/query.go b/x/feegrant/client/cli/query.go index 5fd10cd1beda..64b621ae9808 100644 --- a/x/feegrant/client/cli/query.go +++ b/x/feegrant/client/cli/query.go @@ -20,7 +20,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the feegrant module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } feegrantQueryCmd.AddCommand( diff --git a/x/feegrant/client/cli/tx.go b/x/feegrant/client/cli/tx.go index 49702e0c7882..f54250a93df8 100644 --- a/x/feegrant/client/cli/tx.go +++ b/x/feegrant/client/cli/tx.go @@ -32,7 +32,7 @@ func GetTxCmd() *cobra.Command { Long: "Grant and revoke fee allowance for a grantee by a granter", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } feegrantTxCmd.AddCommand( diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 074bb7da4e74..dc16e5764c11 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -7,7 +7,6 @@ import ( "os" "path/filepath" - "github.com/cosmos/go-bip39" "github.com/pkg/errors" "github.com/spf13/cobra" cfg "github.com/tendermint/tendermint/config" diff --git a/x/genutil/utils.go b/x/genutil/utils.go index 4c46bdb6f121..6f2693b34598 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -6,7 +6,6 @@ import ( "path/filepath" "time" - "github.com/cosmos/go-bip39" cfg "github.com/tendermint/tendermint/config" tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" tmos "github.com/tendermint/tendermint/libs/os" diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index b382f540e26b..ba8d2b86aa10 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -23,7 +23,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the governance module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } govQueryCmd.AddCommand( diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 8ea8f00238bf..b56265bb667d 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -57,7 +57,7 @@ func NewTxCmd(propCmds []*cobra.Command) *cobra.Command { Short: "Governance transactions subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmdSubmitProp := NewCmdSubmitProposal() diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 86e6e9326704..2f2d17022845 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -5,8 +5,6 @@ import ( "fmt" "strconv" - "github.com/armon/go-metrics" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 792fa8a6798f..abaf6a5cfdc8 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -17,7 +17,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the minting module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } mintingQueryCmd.AddCommand( diff --git a/x/params/client/cli/query.go b/x/params/client/cli/query.go index ce7b45d0602d..2afb3ef5b96e 100644 --- a/x/params/client/cli/query.go +++ b/x/params/client/cli/query.go @@ -16,7 +16,7 @@ func NewQueryCmd() *cobra.Command { Short: "Querying commands for the params module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand(NewQuerySubspaceParamsCmd()) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 6cb2f803d085..9e1e731972e1 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -20,7 +20,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the slashing module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } slashingQueryCmd.AddCommand( diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 67a83e6a6510..db24a7efce2c 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -18,7 +18,7 @@ func NewTxCmd() *cobra.Command { Short: "Slashing transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } slashingTxCmd.AddCommand(NewUnjailTxCmd()) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 7bf3ae41ccbe..bb668eb2ed68 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -21,7 +21,7 @@ func GetQueryCmd() *cobra.Command { Short: "Querying commands for the staking module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } stakingQueryCmd.AddCommand( diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index b7cd500cfae8..92cae2df73b5 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -35,7 +35,7 @@ func NewTxCmd() *cobra.Command { Short: "Staking transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, + RunE: client.ValidateCmd, } stakingTxCmd.AddCommand(