diff --git a/cmd/appstate.go b/cmd/appstate.go index 11861e954..4e0e057e8 100644 --- a/cmd/appstate.go +++ b/cmd/appstate.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/relayer/v2/relayer" "github.com/gofrs/flock" - "github.com/spf13/cobra" "github.com/spf13/viper" "go.uber.org/zap" "gopkg.in/yaml.v3" @@ -22,18 +21,61 @@ type appState struct { // Log is the root logger of the application. // Consumers are expected to store and use local copies of the logger // after modifying with the .With method. - Log *zap.Logger + log *zap.Logger - Viper *viper.Viper + viper *viper.Viper - HomePath string - Debug bool - Config *Config + homePath string + debug bool + config *Config } -// AddPathFromFile modifies a.config.Paths to include the content stored in the given file. +func (a *appState) configPath() string { + return path.Join(a.homePath, "config", "config.yaml") +} + +// loadConfigFile reads config file into a.Config if file is present. +func (a *appState) loadConfigFile(ctx context.Context) error { + cfgPath := a.configPath() + + if _, err := os.Stat(cfgPath); err != nil { + // don't return error if file doesn't exist + return nil + } + + // read the config file bytes + file, err := os.ReadFile(cfgPath) + if err != nil { + return fmt.Errorf("error reading file: %w", err) + } + + // unmarshall them into the wrapper struct + cfgWrapper := &ConfigInputWrapper{} + err = yaml.Unmarshal(file, cfgWrapper) + if err != nil { + return fmt.Errorf("error unmarshalling config: %w", err) + } + + // retrieve the runtime configuration from the disk configuration. + newCfg, err := cfgWrapper.RuntimeConfig(ctx, a) + if err != nil { + return err + } + + // validate runtime configuration + if err := newCfg.validateConfig(); err != nil { + return fmt.Errorf("error parsing chain config: %w", err) + } + + // save runtime configuration in app state + a.config = newCfg + + return nil +} + +// addPathFromFile modifies a.config.Paths to include the content stored in the given file. // If a non-nil error is returned, a.config.Paths is not modified. -func (a *appState) AddPathFromFile(ctx context.Context, stderr io.Writer, file, name string) error { +func (a *appState) addPathFromFile(ctx context.Context, stderr io.Writer, file, name string) error { if _, err := os.Stat(file); err != nil { return err } @@ -48,17 +90,22 @@ func (a *appState) AddPathFromFile(ctx context.Context, stderr io.Writer, file, return err } - if err = a.Config.ValidatePath(ctx, stderr, p); err != nil { + if err = a.config.ValidatePath(ctx, stderr, p); err != nil { return err } - return a.Config.Paths.Add(name, p) + return a.config.Paths.Add(name, p) } -// AddPathFromUserInput manually prompts the user to specify all the path details. +// addPathFromUserInput manually prompts the user to specify all the path details. // It returns any input or validation errors. // If the path was successfully added, it returns nil. -func (a *appState) AddPathFromUserInput(ctx context.Context, stdin io.Reader, stderr io.Writer, src, dst, name string) error { +func (a *appState) addPathFromUserInput( + ctx context.Context, + stdin io.Reader, + stderr io.Writer, + src, dst, name string, +) error { // TODO: confirm name is available before going through input. var ( @@ -118,65 +165,15 @@ func (a *appState) AddPathFromUserInput(ctx context.Context, stdin io.Reader, st return err } - if err := a.Config.ValidatePath(ctx, stderr, path); err != nil { - return err - } - - return a.Config.Paths.Add(name, path) -} - -// OverwriteConfig overwrites the config files on disk with the serialization of cfg, -// and it replaces a.Config with cfg. -// -// It is possible to use a brand new Config argument, -// but typically the argument is a.Config. -func (a *appState) OverwriteConfig(cfg *Config) error { - cfgPath := path.Join(a.HomePath, "config", "config.yaml") - if _, err := os.Stat(cfgPath); err != nil { - return fmt.Errorf("failed to check existence of config file at %s: %w", cfgPath, err) - } - - a.Viper.SetConfigFile(cfgPath) - if err := a.Viper.ReadInConfig(); err != nil { - // TODO: if we failed to read in the new config, should we restore the old config? - return fmt.Errorf("failed to read config file at %s: %w", cfgPath, err) - } - - // ensure validateConfig runs properly - if err := validateConfig(cfg); err != nil { - return fmt.Errorf("failed to validate config at %s: %w", cfgPath, err) - } - - // marshal the new config - out, err := yaml.Marshal(cfg.Wrapped()) - if err != nil { + if err := a.config.ValidatePath(ctx, stderr, path); err != nil { return err } - // Overwrite the config file. - if err := os.WriteFile(a.Viper.ConfigFileUsed(), out, 0600); err != nil { - return fmt.Errorf("failed to write config file at %s: %w", cfgPath, err) - } - - // Write the config back into the app state. - a.Config = cfg - return nil + return a.config.Paths.Add(name, path) } -// OverwriteConfigOnTheFly overwrites the config file concurrently, -// locking to read, modify, then write the config. -func (a *appState) OverwriteConfigOnTheFly( - cmd *cobra.Command, - pathName string, - clientSrc, clientDst string, - connectionSrc, connectionDst string, -) error { - if pathName == "" { - return errors.New("empty path name not allowed") - } - - // use lock file to guard concurrent access to config.yaml - lockFilePath := path.Join(a.HomePath, "config", "config.lock") +func (a *appState) performConfigLockingOperation(ctx context.Context, operation func() error) error { + lockFilePath := path.Join(a.homePath, "config", "config.lock") fileLock := flock.New(lockFilePath) _, err := fileLock.TryLock() if err != nil { @@ -184,7 +181,7 @@ func (a *appState) OverwriteConfigOnTheFly( } defer func() { if err := fileLock.Unlock(); err != nil { - a.Log.Error("error unlocking config file lock, please manually delete", + a.log.Error("error unlocking config file lock, please manually delete", zap.String("filepath", lockFilePath), ) } @@ -192,34 +189,27 @@ func (a *appState) OverwriteConfigOnTheFly( // load config from file and validate it. don't want to miss // any changes that may have been made while unlocked. - if err := initConfig(cmd, a); err != nil { + if err := a.loadConfigFile(ctx); err != nil { return fmt.Errorf("failed to initialize config from file: %w", err) } - path, ok := a.Config.Paths[pathName] - if !ok { - return fmt.Errorf("config does not exist for that path: %s", pathName) - } - if clientSrc != "" { - path.Src.ClientID = clientSrc - } - if clientDst != "" { - path.Dst.ClientID = clientDst - } - if connectionSrc != "" { - path.Src.ConnectionID = connectionSrc + // perform the operation that requires config flock. + if err := operation(); err != nil { + return err } - if connectionDst != "" { - path.Dst.ConnectionID = connectionDst + + // validate config after changes have been made. + if err := a.config.validateConfig(); err != nil { + return fmt.Errorf("error parsing chain config: %w", err) } // marshal the new config - out, err := yaml.Marshal(a.Config.Wrapped()) + out, err := yaml.Marshal(a.config.Wrapped()) if err != nil { return err } - cfgPath := a.Viper.ConfigFileUsed() + cfgPath := a.configPath() // Overwrite the config file. if err := os.WriteFile(cfgPath, out, 0600); err != nil { @@ -228,3 +218,36 @@ func (a *appState) OverwriteConfigOnTheFly( return nil } + +// updatePathConfig overwrites the config file concurrently, +// locking to read, modify, then write the config. +func (a *appState) updatePathConfig( + ctx context.Context, + pathName string, + clientSrc, clientDst string, + connectionSrc, connectionDst string, +) error { + if pathName == "" { + return errors.New("empty path name not allowed") + } + + return a.performConfigLockingOperation(ctx, func() error { + path, ok := a.config.Paths[pathName] + if !ok { + return fmt.Errorf("config does not exist for that path: %s", pathName) + } + if clientSrc != "" { + path.Src.ClientID = clientSrc + } + if clientDst != "" { + path.Dst.ClientID = clientDst + } + if connectionSrc != "" { + path.Src.ConnectionID = connectionSrc + } + if connectionDst != "" { + path.Dst.ConnectionID = connectionDst + } + return nil + }) +} diff --git a/cmd/chains.go b/cmd/chains.go index 6cf3117e9..53404cabe 100644 --- a/cmd/chains.go +++ b/cmd/chains.go @@ -54,7 +54,7 @@ func chainsAddrCmd(a *appState) *cobra.Command { $ %s chains address ibc-0 $ %s ch addr ibc-0`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -83,7 +83,7 @@ $ %s chains show ibc-0 --yaml $ %s ch s ibc-0 --json $ %s ch s ibc-0 --yaml`, appName, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - c, ok := a.Config.Chains[args[0]] + c, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -117,7 +117,7 @@ $ %s ch s ibc-0 --yaml`, appName, appName, appName, appName)), } }, } - return jsonFlag(a.Viper, cmd) + return jsonFlag(a.viper, cmd) } func chainsDeleteCmd(a *appState) *cobra.Command { @@ -130,12 +130,15 @@ func chainsDeleteCmd(a *appState) *cobra.Command { $ %s chains delete ibc-0 $ %s ch d ibc-0`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - _, ok := a.Config.Chains[args[0]] - if !ok { - return errChainNotFound(args[0]) - } - a.Config.DeleteChain(args[0]) - return a.OverwriteConfig(a.Config) + chain := args[0] + return a.performConfigLockingOperation(cmd.Context(), func() error { + _, ok := a.config.Chains[chain] + if !ok { + return errChainNotFound(chain) + } + a.config.DeleteChain(chain) + return nil + }) }, } return cmd @@ -158,7 +161,7 @@ func chainsRegistryList(a *appState) *cobra.Command { return err } - chains, err := cregistry.DefaultChainRegistry(a.Log).ListChains(cmd.Context()) + chains, err := cregistry.DefaultChainRegistry(a.log).ListChains(cmd.Context()) if err != nil { return err } @@ -188,7 +191,7 @@ func chainsRegistryList(a *appState) *cobra.Command { return nil }, } - return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd)) + return yamlFlag(a.viper, jsonFlag(a.viper, cmd)) } func chainsListCmd(a *appState) *cobra.Command { @@ -211,7 +214,7 @@ $ %s ch l`, appName, appName)), return err } - configs := a.Config.Wrapped().ProviderConfigs + configs := a.config.Wrapped().ProviderConfigs if len(configs) == 0 { fmt.Fprintln(cmd.ErrOrStderr(), "warning: no chains found (do you need to run 'rly chains add'?)") } @@ -235,7 +238,7 @@ $ %s ch l`, appName, appName)), return nil default: i := 0 - for _, c := range a.Config.Chains { + for _, c := range a.config.Chains { var ( key = xIcon p = xIcon @@ -251,7 +254,7 @@ $ %s ch l`, appName, appName)), bal = check } - for _, pth := range a.Config.Paths { + for _, pth := range a.config.Paths { if pth.Src.ChainID == c.ChainProvider.ChainId() || pth.Dst.ChainID == c.ChainID() { p = check } @@ -263,7 +266,7 @@ $ %s ch l`, appName, appName)), } }, } - return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd)) + return yamlFlag(a.viper, jsonFlag(a.viper, cmd)) } func chainsAddCmd(a *appState) *cobra.Command { @@ -283,48 +286,45 @@ func chainsAddCmd(a *appState) *cobra.Command { return err } - if ok := a.Config; ok == nil { + if ok := a.config; ok == nil { return fmt.Errorf("config not initialized, consider running `rly config init`") } - // default behavior fetch from chain registry - // still allow for adding config from url or file - switch { - case file != "": - var chainName string - switch len(args) { - case 0: - chainName = strings.Split(filepath.Base(file), ".")[0] - case 1: - chainName = args[0] + return a.performConfigLockingOperation(cmd.Context(), func() error { + // default behavior fetch from chain registry + // still allow for adding config from url or file + switch { + case file != "": + var chainName string + switch len(args) { + case 0: + chainName = strings.Split(filepath.Base(file), ".")[0] + case 1: + chainName = args[0] + default: + return errors.New("one chain name is required") + } + if err := addChainFromFile(a, chainName, file); err != nil { + return err + } + case url != "": + if len(args) != 1 { + return errors.New("one chain name is required") + } + if err := addChainFromURL(a, args[0], url); err != nil { + return err + } default: - return errors.New("one chain name is required") - } - if err := addChainFromFile(a, chainName, file); err != nil { - return err - } - case url != "": - if len(args) != 1 { - return errors.New("one chain name is required") - } - if err := addChainFromURL(a, args[0], url); err != nil { - return err - } - default: - if err := addChainsFromRegistry(cmd.Context(), a, args); err != nil { - return err + if err := addChainsFromRegistry(cmd.Context(), a, args); err != nil { + return err + } } - } - - if err := validateConfig(a.Config); err != nil { - return err - } - - return a.OverwriteConfig(a.Config) + return nil + }) }, } - return chainsAddFlags(a.Viper, cmd) + return chainsAddFlags(a.viper, cmd) } func chainsAddDirCmd(a *appState) *cobra.Command { @@ -340,10 +340,7 @@ func chainsAddDirCmd(a *appState) *cobra.Command { $ %s chains add-dir configs/demo/chains $ %s ch ad testnet/chains/`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) (err error) { - if err := addChainsFromDirectory(cmd.ErrOrStderr(), a, args[0]); err != nil { - return err - } - return a.OverwriteConfig(a.Config) + return addChainsFromDirectory(cmd.Context(), cmd.ErrOrStderr(), a, args[0]) }, } @@ -369,15 +366,15 @@ func addChainFromFile(a *appState, chainName string, file string) error { } prov, err := pcw.Value.NewProvider( - a.Log.With(zap.String("provider_type", pcw.Type)), - a.HomePath, a.Debug, chainName, + a.log.With(zap.String("provider_type", pcw.Type)), + a.homePath, a.debug, chainName, ) if err != nil { return fmt.Errorf("failed to build ChainProvider for %s: %w", file, err) } - c := relayer.NewChain(a.Log, prov, a.Debug) - if err = a.Config.AddChain(c); err != nil { + c := relayer.NewChain(a.log, prov, a.debug) + if err = a.config.AddChain(c); err != nil { return err } @@ -409,28 +406,28 @@ func addChainFromURL(a *appState, chainName string, rawurl string) error { // build the ChainProvider before initializing the chain prov, err := pcw.Value.NewProvider( - a.Log.With(zap.String("provider_type", pcw.Type)), - a.HomePath, a.Debug, chainName, + a.log.With(zap.String("provider_type", pcw.Type)), + a.homePath, a.debug, chainName, ) if err != nil { return fmt.Errorf("failed to build ChainProvider for %s: %w", rawurl, err) } - c := relayer.NewChain(a.Log, prov, a.Debug) - if err := a.Config.AddChain(c); err != nil { + c := relayer.NewChain(a.log, prov, a.debug) + if err := a.config.AddChain(c); err != nil { return err } return nil } func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) error { - chainRegistry := cregistry.DefaultChainRegistry(a.Log) + chainRegistry := cregistry.DefaultChainRegistry(a.log) var existed, failed, added []string for _, chain := range chains { - if _, ok := a.Config.Chains[chain]; ok { - a.Log.Warn( + if _, ok := a.config.Chains[chain]; ok { + a.log.Warn( "Chain already exists", zap.String("chain", chain), zap.String("source_link", chainRegistry.SourceLink()), @@ -441,7 +438,7 @@ func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) er chainInfo, err := chainRegistry.GetChain(ctx, chain) if err != nil { - a.Log.Warn( + a.log.Warn( "Error retrieving chain", zap.String("chain", chain), zap.Error(err), @@ -452,7 +449,7 @@ func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) er chainConfig, err := chainInfo.GetChainConfig(ctx) if err != nil { - a.Log.Warn( + a.log.Warn( "Error generating chain config", zap.String("chain", chain), zap.Error(err), @@ -465,11 +462,11 @@ func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) er // build the ChainProvider prov, err := chainConfig.NewProvider( - a.Log.With(zap.String("provider_type", "cosmos")), - a.HomePath, a.Debug, chainInfo.ChainName, + a.log.With(zap.String("provider_type", "cosmos")), + a.homePath, a.debug, chainInfo.ChainName, ) if err != nil { - a.Log.Warn( + a.log.Warn( "Failed to build ChainProvider", zap.String("chain_id", chainConfig.ChainID), zap.Error(err), @@ -479,9 +476,9 @@ func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) er } // add to config - c := relayer.NewChain(a.Log, prov, a.Debug) - if err = a.Config.AddChain(c); err != nil { - a.Log.Warn( + c := relayer.NewChain(a.log, prov, a.debug) + if err = a.config.AddChain(c); err != nil { + a.log.Warn( "Failed to add chain to config", zap.String("chain", chain), zap.Error(err), @@ -494,7 +491,7 @@ func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) er // found the correct chain so move on to next chain in chains } - a.Log.Info("Config update status", + a.log.Info("Config update status", zap.Any("added", added), zap.Any("failed", failed), zap.Any("already existed", existed), diff --git a/cmd/config.go b/cmd/config.go index 1faf6b1bb..510944c76 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -87,14 +87,14 @@ $ %s cfg list`, appName, defaultHome, appName)), case yml && jsn: return fmt.Errorf("can't pass both --json and --yaml, must pick one") case jsn: - out, err := json.Marshal(a.Config.Wrapped()) + out, err := json.Marshal(a.config.Wrapped()) if err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), string(out)) return nil default: - out, err := yaml.Marshal(a.Config.Wrapped()) + out, err := yaml.Marshal(a.config.Wrapped()) if err != nil { return err } @@ -104,7 +104,7 @@ $ %s cfg list`, appName, defaultHome, appName)), }, } - return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd)) + return yamlFlag(a.viper, jsonFlag(a.viper, cmd)) } // Command for initializing an empty config at the --home location @@ -165,7 +165,7 @@ $ %s cfg i`, appName, defaultHome, appName)), return fmt.Errorf("config already exists: %s", cfgPath) }, } - cmd = memoFlag(a.Viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -175,48 +175,51 @@ $ %s cfg i`, appName, defaultHome, appName)), // If any files fail to parse or otherwise are not able to be added to a's chains, // the error is logged. // An error is only returned if the directory cannot be read at all. -func addChainsFromDirectory(stderr io.Writer, a *appState, dir string) error { +func addChainsFromDirectory(ctx context.Context, stderr io.Writer, a *appState, dir string) error { dir = path.Clean(dir) files, err := ioutil.ReadDir(dir) if err != nil { return err } - for _, f := range files { - pth := filepath.Join(dir, f.Name()) - if f.IsDir() { - fmt.Fprintf(stderr, "directory at %s, skipping...\n", pth) - continue - } - byt, err := os.ReadFile(pth) - if err != nil { - fmt.Fprintf(stderr, "failed to read file %s. Err: %v skipping...\n", pth, err) - continue - } + return a.performConfigLockingOperation(ctx, func() error { + for _, f := range files { + pth := filepath.Join(dir, f.Name()) + if f.IsDir() { + fmt.Fprintf(stderr, "directory at %s, skipping...\n", pth) + continue + } - var pcw ProviderConfigWrapper - if err = json.Unmarshal(byt, &pcw); err != nil { - fmt.Fprintf(stderr, "failed to unmarshal file %s. Err: %v skipping...\n", pth, err) - continue - } - chainName := strings.Split(f.Name(), ".")[0] - prov, err := pcw.Value.NewProvider( - a.Log.With(zap.String("provider_type", pcw.Type)), - a.HomePath, a.Debug, chainName, - ) - if err != nil { - fmt.Fprintf(stderr, "failed to build ChainProvider for %s. Err: %v \n", pth, err) - continue - } + byt, err := os.ReadFile(pth) + if err != nil { + fmt.Fprintf(stderr, "failed to read file %s. Err: %v skipping...\n", pth, err) + continue + } + + var pcw ProviderConfigWrapper + if err = json.Unmarshal(byt, &pcw); err != nil { + fmt.Fprintf(stderr, "failed to unmarshal file %s. Err: %v skipping...\n", pth, err) + continue + } + chainName := strings.Split(f.Name(), ".")[0] + prov, err := pcw.Value.NewProvider( + a.log.With(zap.String("provider_type", pcw.Type)), + a.homePath, a.debug, chainName, + ) + if err != nil { + fmt.Fprintf(stderr, "failed to build ChainProvider for %s. Err: %v \n", pth, err) + continue + } - c := relayer.NewChain(a.Log, prov, a.Debug) - if err = a.Config.AddChain(c); err != nil { - fmt.Fprintf(stderr, "failed to add chain %s: %v \n", pth, err) - continue + c := relayer.NewChain(a.log, prov, a.debug) + if err = a.config.AddChain(c); err != nil { + fmt.Fprintf(stderr, "failed to add chain %s: %v \n", pth, err) + continue + } + fmt.Fprintf(stderr, "added chain %s...\n", c.ChainProvider.ChainId()) } - fmt.Fprintf(stderr, "added chain %s...\n", c.ChainProvider.ChainId()) - } - return nil + return nil + }) } // addPathsFromDirectory parses all the files containing JSON-encoded paths in dir, @@ -230,36 +233,38 @@ func addPathsFromDirectory(ctx context.Context, stderr io.Writer, a *appState, d if err != nil { return err } - for _, f := range files { - pth := filepath.Join(dir, f.Name()) - if f.IsDir() { - fmt.Fprintf(stderr, "directory at %s, skipping...\n", pth) - continue - } + return a.performConfigLockingOperation(ctx, func() error { + for _, f := range files { + pth := filepath.Join(dir, f.Name()) + if f.IsDir() { + fmt.Fprintf(stderr, "directory at %s, skipping...\n", pth) + continue + } - byt, err := os.ReadFile(pth) - if err != nil { - return fmt.Errorf("failed to read file %s: %w", pth, err) - } + byt, err := os.ReadFile(pth) + if err != nil { + return fmt.Errorf("failed to read file %s: %w", pth, err) + } - p := &relayer.Path{} - if err = json.Unmarshal(byt, p); err != nil { - return fmt.Errorf("failed to unmarshal file %s: %w", pth, err) - } + p := &relayer.Path{} + if err = json.Unmarshal(byt, p); err != nil { + return fmt.Errorf("failed to unmarshal file %s: %w", pth, err) + } - pthName := strings.Split(f.Name(), ".")[0] - if err := a.Config.ValidatePath(ctx, stderr, p); err != nil { - return fmt.Errorf("failed to validate path %s: %w", pth, err) - } + pthName := strings.Split(f.Name(), ".")[0] + if err := a.config.ValidatePath(ctx, stderr, p); err != nil { + return fmt.Errorf("failed to validate path %s: %w", pth, err) + } - if err := a.Config.AddPath(pthName, p); err != nil { - return fmt.Errorf("failed to add path %s: %w", pth, err) - } + if err := a.config.AddPath(pthName, p); err != nil { + return fmt.Errorf("failed to add path %s: %w", pth, err) + } - fmt.Fprintf(stderr, "added path %s...\n\n", pthName) - } + fmt.Fprintf(stderr, "added path %s...\n\n", pthName) + } - return nil + return nil + }) } // Wrapped converts the Config struct into a ConfigOutputWrapper struct @@ -322,6 +327,34 @@ type ConfigInputWrapper struct { Paths relayer.Paths `yaml:"paths"` } +// RuntimeConfig converts the input disk config into the relayer runtime config. +func (c *ConfigInputWrapper) RuntimeConfig(ctx context.Context, a *appState) (*Config, error) { + // build providers for each chain + chains := make(relayer.Chains) + for chainName, pcfg := range c.ProviderConfigs { + prov, err := pcfg.Value.(provider.ProviderConfig).NewProvider( + a.log.With(zap.String("provider_type", pcfg.Type)), + a.homePath, a.debug, chainName, + ) + if err != nil { + return nil, fmt.Errorf("failed to build ChainProviders: %w", err) + } + + if err := prov.Init(ctx); err != nil { + return nil, fmt.Errorf("failed to initialize provider: %w", err) + } + + chain := relayer.NewChain(a.log, prov, a.debug) + chains[chainName] = chain + } + + return &Config{ + Global: c.Global, + Chains: chains, + Paths: c.Paths, + }, nil +} + type ProviderConfigs map[string]*ProviderConfigWrapper // ProviderConfigWrapper is an intermediary type for parsing arbitrary ProviderConfigs from json files and writing to json/yaml files @@ -531,87 +564,19 @@ func (c *Config) DeleteChain(chain string) { } // validateConfig is used to validate the GlobalConfig values -func validateConfig(c *Config) error { +func (c *Config) validateConfig() error { _, err := time.ParseDuration(c.Global.Timeout) if err != nil { return fmt.Errorf("did you remember to run 'rly config init' error:%w", err) } - return nil -} - -// initConfig reads config file into a.Config if file is present. -func initConfig(cmd *cobra.Command, a *appState) error { - if a.HomePath == "" { - var err error - a.HomePath, err = cmd.PersistentFlags().GetString(flagHome) - if err != nil { - return err - } - } - - cfgPath := path.Join(a.HomePath, "config", "config.yaml") - if _, err := os.Stat(cfgPath); err != nil { - // don't return error if file doesn't exist - return nil - } - a.Viper.SetConfigFile(cfgPath) - if err := a.Viper.ReadInConfig(); err != nil { - return err - } - // read the config file bytes - file, err := os.ReadFile(a.Viper.ConfigFileUsed()) - if err != nil { - fmt.Fprintln(cmd.ErrOrStderr(), "Error reading file:", err) - return err - } - - // unmarshall them into the wrapper struct - cfgWrapper := &ConfigInputWrapper{} - err = yaml.Unmarshal(file, cfgWrapper) - if err != nil { - fmt.Fprintln(cmd.ErrOrStderr(), "Error unmarshalling config:", err) - return err - } - // verify that the channel filter rule is valid for every path in the config - for _, p := range cfgWrapper.Paths { + for _, p := range c.Paths { if err := p.ValidateChannelFilterRule(); err != nil { return fmt.Errorf("error initializing the relayer config for path %s: %w", p.String(), err) } } - // build the config struct - chains := make(relayer.Chains) - for chainName, pcfg := range cfgWrapper.ProviderConfigs { - prov, err := pcfg.Value.(provider.ProviderConfig).NewProvider( - a.Log.With(zap.String("provider_type", pcfg.Type)), - a.HomePath, a.Debug, chainName, - ) - if err != nil { - return fmt.Errorf("failed to build ChainProviders: %w", err) - } - - if err := prov.Init(cmd.Context()); err != nil { - return fmt.Errorf("failed to initialize provider: %w", err) - } - - chain := relayer.NewChain(a.Log, prov, a.Debug) - chains[chainName] = chain - } - - a.Config = &Config{ - Global: cfgWrapper.Global, - Chains: chains, - Paths: cfgWrapper.Paths, - } - - // ensure config has []*relayer.Chain used for all chain operations - if err := validateConfig(a.Config); err != nil { - fmt.Fprintln(cmd.ErrOrStderr(), "Error parsing chain config:", err) - return err - } - return nil } diff --git a/cmd/keys.go b/cmd/keys.go index bcf1c5647..9148946b5 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -65,7 +65,7 @@ $ %s keys add ibc-0 $ %s keys add ibc-1 key2 $ %s k a cosmoshub testkey`, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -120,7 +120,7 @@ $ %s k r cosmoshub faucet-key "[mnemonic-words]"`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { keyName := args[1] - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -168,7 +168,7 @@ $ %s keys delete ibc-0 -y $ %s keys delete ibc-1 key2 -y $ %s k d cosmoshub default`, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -195,7 +195,7 @@ $ %s k d cosmoshub default`, appName, appName, appName)), }, } - return skipConfirm(a.Viper, cmd) + return skipConfirm(a.viper, cmd) } func askForConfirmation(a *appState, stdin io.Reader, stderr io.Writer) bool { @@ -203,7 +203,7 @@ func askForConfirmation(a *appState, stdin io.Reader, stderr io.Writer) bool { _, err := fmt.Fscanln(stdin, &response) if err != nil { - a.Log.Fatal("Failed to read input", zap.Error(err)) + a.log.Fatal("Failed to read input", zap.Error(err)) } switch strings.ToLower(response) { @@ -230,7 +230,7 @@ $ %s k l ibc-1`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { chainName := args[0] - chain, ok := a.Config.Chains[chainName] + chain, ok := a.config.Chains[chainName] if !ok { return errChainNotFound(chainName) } @@ -267,7 +267,7 @@ $ %s keys show ibc-0 $ %s keys show ibc-1 key2 $ %s k s ibc-2 testkey`, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -308,7 +308,7 @@ $ %s keys export ibc-0 testkey $ %s k e cosmoshub testkey`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { keyName := args[1] - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } diff --git a/cmd/paths.go b/cmd/paths.go index 46fc5aec8..0c99c8233 100644 --- a/cmd/paths.go +++ b/cmd/paths.go @@ -49,11 +49,13 @@ func pathsDeleteCmd(a *appState) *cobra.Command { $ %s paths delete demo-path $ %s pth d path-name`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - if _, err := a.Config.Paths.Get(args[0]); err != nil { - return err - } - delete(a.Config.Paths, args[0]) - return a.OverwriteConfig(a.Config) + return a.performConfigLockingOperation(cmd.Context(), func() error { + if _, err := a.config.Paths.Get(args[0]); err != nil { + return err + } + delete(a.config.Paths, args[0]) + return nil + }) }, } return cmd @@ -76,14 +78,14 @@ $ %s pth l`, appName, appName, appName)), case yml && jsn: return fmt.Errorf("can't pass both --json and --yaml, must pick one") case yml: - out, err := yaml.Marshal(a.Config.Paths) + out, err := yaml.Marshal(a.config.Paths) if err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), string(out)) return nil case jsn: - out, err := json.Marshal(a.Config.Paths) + out, err := json.Marshal(a.config.Paths) if err != nil { return err } @@ -91,8 +93,8 @@ $ %s pth l`, appName, appName, appName)), return nil default: i := 0 - for k, pth := range a.Config.Paths { - chains, err := a.Config.Chains.Gets(pth.Src.ChainID, pth.Dst.ChainID) + for k, pth := range a.config.Paths { + chains, err := a.config.Chains.Gets(pth.Src.ChainID, pth.Dst.ChainID) if err != nil { return err } @@ -107,7 +109,7 @@ $ %s pth l`, appName, appName, appName)), } }, } - return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd)) + return yamlFlag(a.viper, jsonFlag(a.viper, cmd)) } func printPath(stdout io.Writer, i int, k string, pth *relayer.Path, chains, clients, connection string) { @@ -133,11 +135,11 @@ $ %s paths show demo-path --yaml $ %s paths show demo-path --json $ %s pth s path-name`, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - p, err := a.Config.Paths.Get(args[0]) + p, err := a.config.Paths.Get(args[0]) if err != nil { return err } - chains, err := a.Config.Chains.Gets(p.Src.ChainID, p.Dst.ChainID) + chains, err := a.config.Chains.Gets(p.Src.ChainID, p.Dst.ChainID) if err != nil { return err } @@ -168,7 +170,7 @@ $ %s pth s path-name`, appName, appName, appName)), return nil }, } - return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd)) + return yamlFlag(a.viper, jsonFlag(a.viper, cmd)) } func pathsAddCmd(a *appState) *cobra.Command { @@ -183,30 +185,32 @@ $ %s paths add ibc-0 ibc-1 demo-path --file paths/demo.json $ %s pth a ibc-0 ibc-1 demo-path`, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { src, dst := args[0], args[1] - _, err := a.Config.Chains.Gets(src, dst) - if err != nil { - return fmt.Errorf("chains need to be configured before paths to them can be added: %w", err) - } - - file, err := cmd.Flags().GetString(flagFile) - if err != nil { - return err - } - if file != "" { - if err := a.AddPathFromFile(cmd.Context(), cmd.ErrOrStderr(), file, args[2]); err != nil { - return err + return a.performConfigLockingOperation(cmd.Context(), func() error { + _, err := a.config.Chains.Gets(src, dst) + if err != nil { + return fmt.Errorf("chains need to be configured before paths to them can be added: %w", err) } - } else { - if err := a.AddPathFromUserInput(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), src, dst, args[2]); err != nil { + + file, err := cmd.Flags().GetString(flagFile) + if err != nil { return err } - } - return a.OverwriteConfig(a.Config) + if file != "" { + if err := a.addPathFromFile(cmd.Context(), cmd.ErrOrStderr(), file, args[2]); err != nil { + return err + } + } else { + if err := a.addPathFromUserInput(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), src, dst, args[2]); err != nil { + return err + } + } + return nil + }) }, } - return fileFlag(a.Viper, cmd) + return fileFlag(a.viper, cmd) } func pathsAddDirCmd(a *appState) *cobra.Command { @@ -220,10 +224,7 @@ func pathsAddDirCmd(a *appState) *cobra.Command { Example: strings.TrimSpace(fmt.Sprintf(` $ %s config add-paths examples/demo/configs/paths`, appName)), RunE: func(cmd *cobra.Command, args []string) (err error) { - if err := addPathsFromDirectory(cmd.Context(), cmd.ErrOrStderr(), a, args[0]); err != nil { - return err - } - return a.OverwriteConfig(a.Config) + return addPathsFromDirectory(cmd.Context(), cmd.ErrOrStderr(), a, args[0]) }, } @@ -241,25 +242,27 @@ $ %s paths new ibc-0 ibc-1 demo-path $ %s pth n ibc-0 ibc-1 demo-path`, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { src, dst := args[0], args[1] - _, err := a.Config.Chains.Gets(src, dst) - if err != nil { - return fmt.Errorf("chains need to be configured before paths to them can be added: %w", err) - } - p := &relayer.Path{ - Src: &relayer.PathEnd{ChainID: src}, - Dst: &relayer.PathEnd{ChainID: dst}, - } + return a.performConfigLockingOperation(cmd.Context(), func() error { + _, err := a.config.Chains.Gets(src, dst) + if err != nil { + return fmt.Errorf("chains need to be configured before paths to them can be added: %w", err) + } - name := args[2] - if err = a.Config.Paths.Add(name, p); err != nil { - return err - } + p := &relayer.Path{ + Src: &relayer.PathEnd{ChainID: src}, + Dst: &relayer.PathEnd{ChainID: dst}, + } - return a.OverwriteConfig(a.Config) + name := args[2] + if err = a.config.Paths.Add(name, p); err != nil { + return err + } + return nil + }) }, } - return channelParameterFlags(a.Viper, cmd) + return channelParameterFlags(a.viper, cmd) } func pathsUpdateCmd(a *appState) *cobra.Command { @@ -280,77 +283,79 @@ $ %s paths update demo-path --src-connection-id connection-02 --dst-connection-i flags := cmd.Flags() - p := a.Config.Paths.MustGet(name) + return a.performConfigLockingOperation(cmd.Context(), func() error { + p := a.config.Paths.MustGet(name) - actionTaken := false + actionTaken := false - filterRule, _ := flags.GetString(flagFilterRule) - if filterRule != blankValue { - if filterRule != "" && filterRule != processor.RuleAllowList && filterRule != processor.RuleDenyList { - return fmt.Errorf( - `invalid filter rule : "%s". valid rules: ("", "%s", "%s")`, - filterRule, processor.RuleAllowList, processor.RuleDenyList) + filterRule, _ := flags.GetString(flagFilterRule) + if filterRule != blankValue { + if filterRule != "" && filterRule != processor.RuleAllowList && filterRule != processor.RuleDenyList { + return fmt.Errorf( + `invalid filter rule : "%s". valid rules: ("", "%s", "%s")`, + filterRule, processor.RuleAllowList, processor.RuleDenyList) + } + p.Filter.Rule = filterRule + actionTaken = true } - p.Filter.Rule = filterRule - actionTaken = true - } - filterChannels, _ := flags.GetString(flagFilterChannels) - if filterChannels != blankValue { - var channelList []string + filterChannels, _ := flags.GetString(flagFilterChannels) + if filterChannels != blankValue { + var channelList []string - if filterChannels != "" { - channelList = strings.Split(filterChannels, ",") - } + if filterChannels != "" { + channelList = strings.Split(filterChannels, ",") + } - p.Filter.ChannelList = channelList - actionTaken = true - } + p.Filter.ChannelList = channelList + actionTaken = true + } - srcChainID, _ := flags.GetString(flagSrcChainID) - if srcChainID != "" { - p.Src.ChainID = srcChainID - actionTaken = true - } + srcChainID, _ := flags.GetString(flagSrcChainID) + if srcChainID != "" { + p.Src.ChainID = srcChainID + actionTaken = true + } - dstChainID, _ := flags.GetString(flagDstChainID) - if dstChainID != "" { - p.Dst.ChainID = dstChainID - actionTaken = true - } + dstChainID, _ := flags.GetString(flagDstChainID) + if dstChainID != "" { + p.Dst.ChainID = dstChainID + actionTaken = true + } - srcClientID, _ := flags.GetString(flagSrcClientID) - if srcClientID != "" { - p.Src.ClientID = srcClientID - actionTaken = true - } + srcClientID, _ := flags.GetString(flagSrcClientID) + if srcClientID != "" { + p.Src.ClientID = srcClientID + actionTaken = true + } - dstClientID, _ := flags.GetString(flagDstClientID) - if dstClientID != "" { - p.Dst.ClientID = dstClientID - actionTaken = true - } + dstClientID, _ := flags.GetString(flagDstClientID) + if dstClientID != "" { + p.Dst.ClientID = dstClientID + actionTaken = true + } - srcConnID, _ := flags.GetString(flagSrcConnID) - if srcConnID != "" { - p.Src.ConnectionID = srcConnID - actionTaken = true - } + srcConnID, _ := flags.GetString(flagSrcConnID) + if srcConnID != "" { + p.Src.ConnectionID = srcConnID + actionTaken = true + } - dstConnID, _ := flags.GetString(flagDstConnID) - if dstConnID != "" { - p.Dst.ConnectionID = dstConnID - actionTaken = true - } + dstConnID, _ := flags.GetString(flagDstConnID) + if dstConnID != "" { + p.Dst.ConnectionID = dstConnID + actionTaken = true + } - if !actionTaken { - return fmt.Errorf("at least one flag must be provided") - } + if !actionTaken { + return fmt.Errorf("at least one flag must be provided") + } - return a.OverwriteConfig(a.Config) + return nil + }) }, } - cmd = pathFilterFlags(a.Viper, cmd) + cmd = pathFilterFlags(a.viper, cmd) return cmd } @@ -367,91 +372,88 @@ $ %s pth fch`, appName, defaultHome, appName)), RunE: func(cmd *cobra.Command, args []string) error { overwrite, _ := cmd.Flags().GetBool(flagOverwriteConfig) - chains := []string{} - for chainName := range a.Config.Chains { - chains = append(chains, chainName) - } + return a.performConfigLockingOperation(cmd.Context(), func() error { + chains := []string{} + for chainName := range a.config.Chains { + chains = append(chains, chainName) + } - // find all combinations of paths for configured chains - chainCombinations := make(map[string]bool) - for _, chainA := range chains { - for _, chainB := range chains { - if chainA == chainB { - continue + // find all combinations of paths for configured chains + chainCombinations := make(map[string]bool) + for _, chainA := range chains { + for _, chainB := range chains { + if chainA == chainB { + continue + } + + pair := chainA + "-" + chainB + if chainB < chainA { + pair = chainB + "-" + chainA + } + chainCombinations[pair] = true } + } - pair := chainA + "-" + chainB - if chainB < chainA { - pair = chainB + "-" + chainA + client := github.NewClient(nil) + for pthName := range chainCombinations { + _, exist := a.config.Paths[pthName] + if exist && !overwrite { + fmt.Fprintf(cmd.ErrOrStderr(), "skipping: %s already exists in config, use -o to overwrite (clears filters)\n", pthName) + continue } - chainCombinations[pair] = true - } - } - client := github.NewClient(nil) - for pthName := range chainCombinations { - _, exist := a.Config.Paths[pthName] - if exist && !overwrite { - fmt.Fprintf(cmd.ErrOrStderr(), "skipping: %s already exists in config, use -o to overwrite (clears filters)\n", pthName) - continue - } + // TODO: Don't use github api. Potentially use: https://github.com/eco-stake/cosmos-directory once they integrate IBC data into restAPI. This will avoid rate limits. + fileName := pthName + ".json" + regPath := path.Join("_IBC", fileName) + client, _, err := client.Repositories.DownloadContents(cmd.Context(), "cosmos", "chain-registry", regPath, nil) + if err != nil { + if errors.As(err, new(*github.RateLimitError)) { + fmt.Println("some paths failed: ", err) + break + } + fmt.Fprintf(cmd.ErrOrStderr(), "failure retrieving: %s: consider adding to cosmos/chain-registry: ERR: %v\n", pthName, err) + continue + } + defer client.Close() - // TODO: Don't use github api. Potentially use: https://github.com/eco-stake/cosmos-directory once they integrate IBC data into restAPI. This will avoid rate limits. - fileName := pthName + ".json" - regPath := path.Join("_IBC", fileName) - client, _, err := client.Repositories.DownloadContents(cmd.Context(), "cosmos", "chain-registry", regPath, nil) - if err != nil { - if errors.As(err, new(*github.RateLimitError)) { - fmt.Println("some paths failed: ", err) - break + b, err := io.ReadAll(client) + if err != nil { + return fmt.Errorf("error reading response body: %w", err) } - fmt.Fprintf(cmd.ErrOrStderr(), "failure retrieving: %s: consider adding to cosmos/chain-registry: ERR: %v\n", pthName, err) - continue - } - defer client.Close() - b, err := io.ReadAll(client) - if err != nil { - return fmt.Errorf("error reading response body: %w", err) - } + ibc := &relayer.IBCdata{} + if err = json.Unmarshal(b, &ibc); err != nil { + return fmt.Errorf("failed to unmarshal: %w ", err) + } - ibc := &relayer.IBCdata{} - if err = json.Unmarshal(b, &ibc); err != nil { - return fmt.Errorf("failed to unmarshal: %w ", err) - } + srcChainName := ibc.Chain1.ChainName + dstChainName := ibc.Chain2.ChainName - srcChainName := ibc.Chain1.ChainName - dstChainName := ibc.Chain2.ChainName + srcPathEnd := &relayer.PathEnd{ + ChainID: a.config.Chains[srcChainName].ChainID(), + ClientID: ibc.Chain1.ClientID, + ConnectionID: ibc.Chain1.ConnectionID, + } + dstPathEnd := &relayer.PathEnd{ + ChainID: a.config.Chains[dstChainName].ChainID(), + ClientID: ibc.Chain2.ClientID, + ConnectionID: ibc.Chain2.ConnectionID, + } + newPath := &relayer.Path{ + Src: srcPathEnd, + Dst: dstPathEnd, + } + client.Close() - srcPathEnd := &relayer.PathEnd{ - ChainID: a.Config.Chains[srcChainName].ChainID(), - ClientID: ibc.Chain1.ClientID, - ConnectionID: ibc.Chain1.ConnectionID, - } - dstPathEnd := &relayer.PathEnd{ - ChainID: a.Config.Chains[dstChainName].ChainID(), - ClientID: ibc.Chain2.ClientID, - ConnectionID: ibc.Chain2.ConnectionID, - } - newPath := &relayer.Path{ - Src: srcPathEnd, - Dst: dstPathEnd, - } - client.Close() + if err = a.config.AddPath(pthName, newPath); err != nil { + return fmt.Errorf("failed to add path %s: %w", pthName, err) + } + fmt.Fprintf(cmd.ErrOrStderr(), "added: %s\n", pthName) - if err = a.Config.AddPath(pthName, newPath); err != nil { - return fmt.Errorf("failed to add path %s: %w", pthName, err) } - fmt.Fprintf(cmd.ErrOrStderr(), "added: %s\n", pthName) - - } - - if err := a.OverwriteConfig(a.Config); err != nil { - return err - } - return nil - + return nil + }) }, } - return OverwriteConfigFlag(a.Viper, cmd) + return OverwriteConfigFlag(a.viper, cmd) } diff --git a/cmd/query.go b/cmd/query.go index 9e74aa395..5540fb916 100644 --- a/cmd/query.go +++ b/cmd/query.go @@ -63,7 +63,7 @@ $ %s q ibc-denoms ibc-0`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -99,7 +99,7 @@ $ %s q denom-trace osmosis 9BBA9A1C257E971E38C1422780CE6F0B0686F0A3085E2D61118D9 appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - c, ok := a.Config.Chains[args[0]] + c, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -127,7 +127,7 @@ $ %s q tx ibc-0 A5DF8D272F1C451CFF92BA6C41942C4D29B5CF180279439ED6AB038282F956BE appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -168,7 +168,7 @@ $ %s q txs ibc-0 "message.action=transfer"`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -198,7 +198,7 @@ $ %s q txs ibc-0 "message.action=transfer"`, }, } - return paginationFlags(a.Viper, cmd, "txs") + return paginationFlags(a.viper, cmd, "txs") } func queryBalanceCmd(a *appState) *cobra.Command { @@ -213,7 +213,7 @@ $ %s query balance ibc-0 testkey`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -247,7 +247,7 @@ $ %s query balance ibc-0 testkey`, }, } - return ibcDenomFlags(a.Viper, cmd) + return ibcDenomFlags(a.viper, cmd) } func queryHeaderCmd(a *appState) *cobra.Command { @@ -261,7 +261,7 @@ $ %s query header ibc-0 1400`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -315,7 +315,7 @@ $ %s q node-state ibc-1`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -355,7 +355,7 @@ $ %s query client ibc-0 ibczeroclient --height 1205`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -392,7 +392,7 @@ $ %s query client ibc-0 ibczeroclient --height 1205`, }, } - return heightFlag(a.Viper, cmd) + return heightFlag(a.viper, cmd) } func queryClientsCmd(a *appState) *cobra.Command { @@ -407,7 +407,7 @@ $ %s query clients ibc-2 --offset 2 --limit 30`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -437,7 +437,7 @@ $ %s query clients ibc-2 --offset 2 --limit 30`, }, } - return paginationFlags(a.Viper, cmd, "client states") + return paginationFlags(a.viper, cmd, "client states") } func queryConnections(a *appState) *cobra.Command { @@ -453,7 +453,7 @@ $ %s q conns ibc-1`, appName, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -483,7 +483,7 @@ $ %s q conns ibc-1`, }, } - return paginationFlags(a.Viper, cmd, "connections on a network") + return paginationFlags(a.viper, cmd, "connections on a network") } func queryConnectionsUsingClient(a *appState) *cobra.Command { @@ -499,7 +499,7 @@ $ %s query client-connections ibc-0 ibczeroclient --height 1205`, RunE: func(cmd *cobra.Command, args []string) error { //TODO - Add pagination - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -536,7 +536,7 @@ $ %s query client-connections ibc-0 ibczeroclient --height 1205`, }, } - return heightFlag(a.Viper, cmd) + return heightFlag(a.viper, cmd) } func queryConnection(a *appState) *cobra.Command { @@ -551,7 +551,7 @@ $ %s q conn ibc-1 ibconeconn`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -595,7 +595,7 @@ $ %s query connection-channels ibc-2 ibcconnection2 --offset 2 --limit 30`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -629,7 +629,7 @@ $ %s query connection-channels ibc-2 ibcconnection2 --offset 2 --limit 30`, }, } - return paginationFlags(a.Viper, cmd, "channels associated with a connection") + return paginationFlags(a.viper, cmd, "channels associated with a connection") } func queryChannel(a *appState) *cobra.Command { @@ -643,7 +643,7 @@ $ %s query channel ibc-2 ibctwochannel transfer --height 1205`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -682,7 +682,7 @@ $ %s query channel ibc-2 ibctwochannel transfer --height 1205`, }, } - return heightFlag(a.Viper, cmd) + return heightFlag(a.viper, cmd) } // chanExtendedInfo is an intermediate type for holding additional useful @@ -880,13 +880,13 @@ $ %s query channels ibc-0 ibc-2`, appName, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } if len(args) > 1 { - dstChain, ok := a.Config.Chains[args[1]] + dstChain, ok := a.config.Chains[args[1]] if !ok { return errChainNotFound(args[1]) } @@ -902,7 +902,7 @@ $ %s query channels ibc-0 ibc-2`, }, } - return paginationFlags(a.Viper, cmd, "channels on a network") + return paginationFlags(a.viper, cmd, "channels on a network") } func queryPacketCommitment(a *appState) *cobra.Command { @@ -916,7 +916,7 @@ $ %s q packet-commit ibc-1 ibconechannel transfer 31`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - chain, ok := a.Config.Chains[args[0]] + chain, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } @@ -961,14 +961,14 @@ $ %s query unrelayed-pkts demo-path channel-0`, appName, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - path, err := a.Config.Paths.Get(args[0]) + path, err := a.config.Paths.Get(args[0]) if err != nil { return err } src, dst := path.Src.ChainID, path.Dst.ChainID - c, err := a.Config.Chains.Gets(src, dst) + c, err := a.config.Chains.Gets(src, dst) if err != nil { return err } @@ -1014,13 +1014,13 @@ $ %s query unrelayed-acks demo-path channel-0`, appName, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - path, err := a.Config.Paths.Get(args[0]) + path, err := a.config.Paths.Get(args[0]) if err != nil { return err } src, dst := path.Src.ChainID, path.Dst.ChainID - c, err := a.Config.Chains.Gets(src, dst) + c, err := a.config.Chains.Gets(src, dst) if err != nil { return err } @@ -1063,12 +1063,12 @@ $ %s query clients-expiration demo-path`, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - path, err := a.Config.Paths.Get(args[0]) + path, err := a.config.Paths.Get(args[0]) if err != nil { return err } src, dst := path.Src.ChainID, path.Dst.ChainID - c, err := a.Config.Chains.Gets(src, dst) + c, err := a.config.Chains.Gets(src, dst) if err != nil { return err } diff --git a/cmd/root.go b/cmd/root.go index a819397d5..d76360e01 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -57,9 +57,9 @@ func NewRootCmd(log *zap.Logger) *cobra.Command { // Use a local app state instance scoped to the new root command, // so that tests don't concurrently access the state. a := &appState{ - Viper: viper.New(), + viper: viper.New(), - Log: log, + log: log, } // RootCmd represents the base command when called without any subcommands @@ -78,37 +78,37 @@ func NewRootCmd(log *zap.Logger) *cobra.Command { rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { // Inside persistent pre-run because this takes effect after flags are parsed. if log == nil { - log, err := newRootLogger(a.Viper.GetString("log-format"), a.Viper.GetBool("debug")) + log, err := newRootLogger(a.viper.GetString("log-format"), a.viper.GetBool("debug")) if err != nil { return err } - a.Log = log + a.log = log } // reads `homeDir/config/config.yaml` into `a.Config` - return initConfig(rootCmd, a) + return a.loadConfigFile(rootCmd.Context()) } rootCmd.PersistentPostRun = func(cmd *cobra.Command, _ []string) { // Force syncing the logs before exit, if anything is buffered. - a.Log.Sync() + _ = a.log.Sync() } // Register --home flag - rootCmd.PersistentFlags().StringVar(&a.HomePath, flagHome, defaultHome, "set home directory") - if err := a.Viper.BindPFlag(flagHome, rootCmd.PersistentFlags().Lookup(flagHome)); err != nil { + rootCmd.PersistentFlags().StringVar(&a.homePath, flagHome, defaultHome, "set home directory") + if err := a.viper.BindPFlag(flagHome, rootCmd.PersistentFlags().Lookup(flagHome)); err != nil { panic(err) } // Register --debug flag - rootCmd.PersistentFlags().BoolVarP(&a.Debug, "debug", "d", false, "debug output") - if err := a.Viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")); err != nil { + rootCmd.PersistentFlags().BoolVarP(&a.debug, "debug", "d", false, "debug output") + if err := a.viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")); err != nil { panic(err) } rootCmd.PersistentFlags().String("log-format", "auto", "log output format (auto, logfmt, json, or console)") - if err := a.Viper.BindPFlag("log-format", rootCmd.PersistentFlags().Lookup("log-format")); err != nil { + if err := a.viper.BindPFlag("log-format", rootCmd.PersistentFlags().Lookup("log-format")); err != nil { panic(err) } diff --git a/cmd/start.go b/cmd/start.go index bc8143865..fa69d2a80 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -50,7 +50,7 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), if len(args) > 0 { for i, pathName := range args { - path := a.Config.Paths.MustGet(pathName) + path := a.config.Paths.MustGet(pathName) paths[i] = relayer.NamedPath{ Name: pathName, Path: path, @@ -61,7 +61,7 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), chains[path.Dst.ChainID] = nil } } else { - for n, path := range a.Config.Paths { + for n, path := range a.config.Paths { paths = append(paths, relayer.NamedPath{ Name: n, Path: path, @@ -79,7 +79,7 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), } // get chain configurations - chains, err := a.Config.Chains.Gets(chainIDs...) + chains, err := a.config.Chains.Gets(chainIDs...) if err != nil { return err } @@ -95,7 +95,7 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), var prometheusMetrics *processor.PrometheusMetrics - debugAddr := a.Config.Global.APIListenPort + debugAddr := a.config.Global.APIListenPort debugAddrFlag, err := cmd.Flags().GetString(flagDebugAddr) if err != nil { @@ -107,14 +107,14 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), } if debugAddr == "" { - a.Log.Info("Skipping debug server due to empty debug address flag") + a.log.Info("Skipping debug server due to empty debug address flag") } else { ln, err := net.Listen("tcp", debugAddr) if err != nil { - a.Log.Error("Failed to listen on debug address. If you have another relayer process open, use --" + flagDebugAddr + " to pick a different address.") + a.log.Error("Failed to listen on debug address. If you have another relayer process open, use --" + flagDebugAddr + " to pick a different address.") return fmt.Errorf("failed to listen on debug address %q: %w", debugAddr, err) } - log := a.Log.With(zap.String("sys", "debughttp")) + log := a.log.With(zap.String("sys", "debughttp")) log.Info("Debug server listening", zap.String("addr", debugAddr)) prometheusMetrics = processor.NewPrometheusMetrics() relaydebug.StartDebugServer(cmd.Context(), log, ln, prometheusMetrics.Registry) @@ -146,11 +146,11 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), rlyErrCh := relayer.StartRelayer( cmd.Context(), - a.Log, + a.log, chains, paths, maxTxSize, maxMsgLength, - a.Config.memo(cmd), + a.config.memo(cmd), clientUpdateThresholdTime, flushInterval, nil, @@ -164,7 +164,7 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), // so we don't want to separately monitor the ctx.Done channel, // because we would risk returning before the relayer cleans up. if err := <-rlyErrCh; err != nil && !errors.Is(err, context.Canceled) { - a.Log.Warn( + a.log.Warn( "Relayer start error", zap.Error(err), ) @@ -173,13 +173,13 @@ $ %s start demo-path2 --max-tx-size 10`, appName, appName, appName, appName)), return nil }, } - cmd = updateTimeFlags(a.Viper, cmd) - cmd = strategyFlag(a.Viper, cmd) - cmd = debugServerFlags(a.Viper, cmd) - cmd = processorFlag(a.Viper, cmd) - cmd = initBlockFlag(a.Viper, cmd) - cmd = flushIntervalFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = updateTimeFlags(a.viper, cmd) + cmd = strategyFlag(a.viper, cmd) + cmd = debugServerFlags(a.viper, cmd) + cmd = processorFlag(a.viper, cmd) + cmd = initBlockFlag(a.viper, cmd) + cmd = flushIntervalFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } diff --git a/cmd/tx.go b/cmd/tx.go index 437edbc05..1913fd34f 100644 --- a/cmd/tx.go +++ b/cmd/tx.go @@ -85,7 +85,7 @@ func createClientsCmd(a *appState) *cobra.Command { path := args[0] - c, src, dst, err := a.Config.ChainsFromPath(path) + c, src, dst, err := a.config.ChainsFromPath(path) if err != nil { return err } @@ -98,12 +98,12 @@ func createClientsCmd(a *appState) *cobra.Command { return fmt.Errorf("key %s not found on dst chain %s", c[dst].ChainProvider.Key(), c[dst].ChainID()) } - clientSrc, clientDst, err := c[src].CreateClients(cmd.Context(), c[dst], allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour, override, customClientTrustingPeriod, a.Config.memo(cmd)) + clientSrc, clientDst, err := c[src].CreateClients(cmd.Context(), c[dst], allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour, override, customClientTrustingPeriod, a.config.memo(cmd)) if err != nil { return err } if clientSrc != "" || clientDst != "" { - if err := a.OverwriteConfigOnTheFly(cmd, path, clientSrc, clientDst, "", ""); err != nil { + if err := a.updatePathConfig(cmd.Context(), path, clientSrc, clientDst, "", ""); err != nil { return err } } @@ -112,9 +112,9 @@ func createClientsCmd(a *appState) *cobra.Command { }, } - cmd = clientParameterFlags(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = clientParameterFlags(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -147,17 +147,17 @@ func createClientCmd(a *appState) *cobra.Command { return err } - src, ok := a.Config.Chains[args[0]] + src, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } - dst, ok := a.Config.Chains[args[1]] + dst, ok := a.config.Chains[args[1]] if !ok { return errChainNotFound(args[1]) } pathName := args[2] - path, err := a.Config.Paths.Get(pathName) + path, err := a.config.Paths.Get(pathName) if err != nil { return err } @@ -194,7 +194,7 @@ func createClientCmd(a *appState) *cobra.Command { } return nil }, retry.Context(cmd.Context()), relayer.RtyAtt, relayer.RtyDel, relayer.RtyErr, retry.OnRetry(func(n uint, err error) { - a.Log.Info( + a.log.Info( "Failed to get light signed header", zap.String("src_chain_id", src.ChainID()), zap.Int64("src_height", srch), @@ -209,7 +209,7 @@ func createClientCmd(a *appState) *cobra.Command { return err } - clientID, err := relayer.CreateClient(cmd.Context(), src, dst, srcUpdateHeader, dstUpdateHeader, allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour, override, customClientTrustingPeriod, a.Config.memo(cmd)) + clientID, err := relayer.CreateClient(cmd.Context(), src, dst, srcUpdateHeader, dstUpdateHeader, allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour, override, customClientTrustingPeriod, a.config.memo(cmd)) if err != nil { return err } @@ -220,7 +220,7 @@ func createClientCmd(a *appState) *cobra.Command { clientDst = clientID } if clientID != "" { - if err = a.OverwriteConfigOnTheFly(cmd, pathName, clientSrc, clientDst, "", ""); err != nil { + if err = a.updatePathConfig(cmd.Context(), pathName, clientSrc, clientDst, "", ""); err != nil { return err } } @@ -229,9 +229,9 @@ func createClientCmd(a *appState) *cobra.Command { }, } - cmd = clientParameterFlags(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = clientParameterFlags(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -245,7 +245,7 @@ corresponding update-client messages.`, Args: withUsage(cobra.ExactArgs(1)), Example: strings.TrimSpace(fmt.Sprintf(`$ %s transact update-clients demo-path`, appName)), RunE: func(cmd *cobra.Command, args []string) error { - c, src, dst, err := a.Config.ChainsFromPath(args[0]) + c, src, dst, err := a.config.ChainsFromPath(args[0]) if err != nil { return err } @@ -258,11 +258,11 @@ corresponding update-client messages.`, return fmt.Errorf("key %s not found on dst chain %s", c[dst].ChainProvider.Key(), c[dst].ChainID()) } - return relayer.UpdateClients(cmd.Context(), c[src], c[dst], a.Config.memo(cmd)) + return relayer.UpdateClients(cmd.Context(), c[src], c[dst], a.config.memo(cmd)) }, } - return memoFlag(a.Viper, cmd) + return memoFlag(a.viper, cmd) } func upgradeClientsCmd(a *appState) *cobra.Command { @@ -271,7 +271,7 @@ func upgradeClientsCmd(a *appState) *cobra.Command { Short: "upgrades IBC clients between two configured chains with a configured path and chain-id", Args: withUsage(cobra.ExactArgs(2)), RunE: func(cmd *cobra.Command, args []string) error { - c, src, dst, err := a.Config.ChainsFromPath(args[0]) + c, src, dst, err := a.config.ChainsFromPath(args[0]) if err != nil { return err } @@ -291,7 +291,7 @@ func upgradeClientsCmd(a *appState) *cobra.Command { targetChainID := args[1] - memo := a.Config.memo(cmd) + memo := a.config.memo(cmd) // send the upgrade message on the targetChainID if src == targetChainID { @@ -302,8 +302,8 @@ func upgradeClientsCmd(a *appState) *cobra.Command { }, } - cmd = heightFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = heightFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -339,7 +339,7 @@ $ %s tx conn demo-path --timeout 5s`, pathName := args[0] - c, src, dst, err := a.Config.ChainsFromPath(pathName) + c, src, dst, err := a.config.ChainsFromPath(pathName) if err != nil { return err } @@ -367,7 +367,7 @@ $ %s tx conn demo-path --timeout 5s`, return fmt.Errorf("key %s not found on dst chain %s", c[dst].ChainProvider.Key(), c[dst].ChainID()) } - memo := a.Config.memo(cmd) + memo := a.config.memo(cmd) initialBlockHistory, err := cmd.Flags().GetUint64(flagInitialBlockHistory) if err != nil { @@ -380,7 +380,7 @@ $ %s tx conn demo-path --timeout 5s`, return err } if clientSrc != "" || clientDst != "" { - if err := a.OverwriteConfigOnTheFly(cmd, pathName, clientSrc, clientDst, "", ""); err != nil { + if err := a.updatePathConfig(cmd.Context(), pathName, clientSrc, clientDst, "", ""); err != nil { return err } } @@ -390,7 +390,7 @@ $ %s tx conn demo-path --timeout 5s`, return err } if connectionSrc != "" || connectionDst != "" { - if err := a.OverwriteConfigOnTheFly(cmd, pathName, "", "", connectionSrc, connectionDst); err != nil { + if err := a.updatePathConfig(cmd.Context(), pathName, "", "", connectionSrc, connectionDst); err != nil { return err } } @@ -399,12 +399,12 @@ $ %s tx conn demo-path --timeout 5s`, }, } - cmd = timeoutFlag(a.Viper, cmd) - cmd = retryFlag(a.Viper, cmd) - cmd = clientParameterFlags(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) - cmd = initBlockFlag(a.Viper, cmd) + cmd = timeoutFlag(a.viper, cmd) + cmd = retryFlag(a.viper, cmd) + cmd = clientParameterFlags(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) + cmd = initBlockFlag(a.viper, cmd) return cmd } @@ -426,7 +426,7 @@ $ %s tx chan demo-path --timeout 5s --max-retries 10`, pathName := args[0] - c, src, dst, err := a.Config.ChainsFromPath(pathName) + c, src, dst, err := a.config.ChainsFromPath(pathName) if err != nil { return err } @@ -475,15 +475,15 @@ $ %s tx chan demo-path --timeout 5s --max-retries 10`, } // create channel if it isn't already created - return c[src].CreateOpenChannels(cmd.Context(), c[dst], retries, to, srcPort, dstPort, order, version, override, a.Config.memo(cmd), pathName) + return c[src].CreateOpenChannels(cmd.Context(), c[dst], retries, to, srcPort, dstPort, order, version, override, a.config.memo(cmd), pathName) }, } - cmd = timeoutFlag(a.Viper, cmd) - cmd = retryFlag(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = channelParameterFlags(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = timeoutFlag(a.viper, cmd) + cmd = retryFlag(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = channelParameterFlags(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -502,7 +502,7 @@ $ %s tx channel-close demo-path channel-0 transfer -o 3s`, RunE: func(cmd *cobra.Command, args []string) error { pathName := args[0] - c, src, dst, err := a.Config.ChainsFromPath(pathName) + c, src, dst, err := a.config.ChainsFromPath(pathName) if err != nil { return err } @@ -538,13 +538,13 @@ $ %s tx channel-close demo-path channel-0 transfer -o 3s`, return err } - return c[src].CloseChannel(cmd.Context(), c[dst], retries, to, channelID, portID, a.Config.memo(cmd), pathName) + return c[src].CloseChannel(cmd.Context(), c[dst], retries, to, channelID, portID, a.config.memo(cmd), pathName) }, } - cmd = timeoutFlag(a.Viper, cmd) - cmd = retryFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = timeoutFlag(a.viper, cmd) + cmd = retryFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -581,13 +581,13 @@ $ %s tx connect demo-path --src-port transfer --dst-port transfer --order unorde pathName := args[0] - pth, err := a.Config.Paths.Get(pathName) + pth, err := a.config.Paths.Get(pathName) if err != nil { return err } src, dst := pth.Src.ChainID, pth.Dst.ChainID - c, err := a.Config.Chains.Gets(src, dst) + c, err := a.config.Chains.Gets(src, dst) if err != nil { return err } @@ -638,7 +638,7 @@ $ %s tx connect demo-path --src-port transfer --dst-port transfer --order unorde return fmt.Errorf("key %s not found on dst chain %s", c[dst].ChainProvider.Key(), c[dst].ChainID()) } - memo := a.Config.memo(cmd) + memo := a.config.memo(cmd) initialBlockHistory, err := cmd.Flags().GetUint64(flagInitialBlockHistory) if err != nil { @@ -651,7 +651,7 @@ $ %s tx connect demo-path --src-port transfer --dst-port transfer --order unorde return fmt.Errorf("error creating clients: %w", err) } if clientSrc != "" || clientDst != "" { - if err := a.OverwriteConfigOnTheFly(cmd, pathName, clientSrc, clientDst, "", ""); err != nil { + if err := a.updatePathConfig(cmd.Context(), pathName, clientSrc, clientDst, "", ""); err != nil { return err } } @@ -662,7 +662,7 @@ $ %s tx connect demo-path --src-port transfer --dst-port transfer --order unorde return fmt.Errorf("error creating connections: %w", err) } if connectionSrc != "" || connectionDst != "" { - if err := a.OverwriteConfigOnTheFly(cmd, pathName, "", "", connectionSrc, connectionDst); err != nil { + if err := a.updatePathConfig(cmd.Context(), pathName, "", "", connectionSrc, connectionDst); err != nil { return err } } @@ -671,13 +671,13 @@ $ %s tx connect demo-path --src-port transfer --dst-port transfer --order unorde return c[src].CreateOpenChannels(cmd.Context(), c[dst], retries, to, srcPort, dstPort, order, version, override, memo, pathName) }, } - cmd = timeoutFlag(a.Viper, cmd) - cmd = retryFlag(a.Viper, cmd) - cmd = clientParameterFlags(a.Viper, cmd) - cmd = channelParameterFlags(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) - cmd = initBlockFlag(a.Viper, cmd) + cmd = timeoutFlag(a.viper, cmd) + cmd = retryFlag(a.viper, cmd) + cmd = clientParameterFlags(a.viper, cmd) + cmd = channelParameterFlags(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) + cmd = initBlockFlag(a.viper, cmd) return cmd } @@ -697,7 +697,7 @@ $ %s tx link-then-start demo-path --timeout 5s`, appName, appName)), lCmd := linkCmd(a) for err := lCmd.RunE(cmd, args); err != nil; err = lCmd.RunE(cmd, args) { - a.Log.Info("Error running link; retrying", zap.Error(err)) + a.log.Info("Error running link; retrying", zap.Error(err)) select { case <-time.After(time.Second): // Keep going. @@ -711,17 +711,17 @@ $ %s tx link-then-start demo-path --timeout 5s`, appName, appName)), }, } - cmd = timeoutFlag(a.Viper, cmd) - cmd = retryFlag(a.Viper, cmd) - cmd = strategyFlag(a.Viper, cmd) - cmd = clientParameterFlags(a.Viper, cmd) - cmd = channelParameterFlags(a.Viper, cmd) - cmd = overrideFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) - cmd = debugServerFlags(a.Viper, cmd) - cmd = initBlockFlag(a.Viper, cmd) - cmd = processorFlag(a.Viper, cmd) - cmd = updateTimeFlags(a.Viper, cmd) + cmd = timeoutFlag(a.viper, cmd) + cmd = retryFlag(a.viper, cmd) + cmd = strategyFlag(a.viper, cmd) + cmd = clientParameterFlags(a.viper, cmd) + cmd = channelParameterFlags(a.viper, cmd) + cmd = overrideFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) + cmd = debugServerFlags(a.viper, cmd) + cmd = initBlockFlag(a.viper, cmd) + cmd = processorFlag(a.viper, cmd) + cmd = updateTimeFlags(a.viper, cmd) return cmd } @@ -743,7 +743,7 @@ $ %s tx flush demo-path channel-0`, if len(args) > 0 { pathName := args[0] - path := a.Config.Paths.MustGet(pathName) + path := a.config.Paths.MustGet(pathName) paths = append(paths, relayer.NamedPath{ Name: pathName, Path: path, @@ -753,7 +753,7 @@ $ %s tx flush demo-path channel-0`, chains[path.Src.ChainID] = nil chains[path.Dst.ChainID] = nil } else { - for n, path := range a.Config.Paths { + for n, path := range a.config.Paths { paths = append(paths, relayer.NamedPath{ Name: n, Path: path, @@ -771,7 +771,7 @@ $ %s tx flush demo-path channel-0`, } // get chain configurations - chains, err := a.Config.Chains.Gets(chainIDs...) + chains, err := a.config.Chains.Gets(chainIDs...) if err != nil { return err } @@ -798,11 +798,11 @@ $ %s tx flush demo-path channel-0`, rlyErrCh := relayer.StartRelayer( ctx, - a.Log, + a.log, chains, paths, maxTxSize, maxMsgLength, - a.Config.memo(cmd), + a.config.memo(cmd), 0, 0, &processor.FlushLifecycle{}, @@ -816,7 +816,7 @@ $ %s tx flush demo-path channel-0`, // so we don't want to separately monitor the ctx.Done channel, // because we would risk returning before the relayer cleans up. if err := <-rlyErrCh; err != nil && !errors.Is(err, context.Canceled) { - a.Log.Warn( + a.log.Warn( "Relayer start error", zap.Error(err), ) @@ -826,8 +826,8 @@ $ %s tx flush demo-path channel-0`, }, } - cmd = strategyFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = strategyFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -843,13 +843,13 @@ $ %s tx relay-pkts demo-path channel-0`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - a.Log.Warn("This command is deprecated. Please use 'tx flush' command instead") + a.log.Warn("This command is deprecated. Please use 'tx flush' command instead") return flushCmd(a).RunE(cmd, args) }, } - cmd = strategyFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = strategyFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -865,13 +865,13 @@ $ %s tx relay-acks demo-path channel-0 -l 3 -s 6`, appName, appName, )), RunE: func(cmd *cobra.Command, args []string) error { - a.Log.Warn("This command is deprecated. Please use 'tx flush' command instead") + a.log.Warn("This command is deprecated. Please use 'tx flush' command instead") return flushCmd(a).RunE(cmd, args) }, } - cmd = strategyFlag(a.Viper, cmd) - cmd = memoFlag(a.Viper, cmd) + cmd = strategyFlag(a.viper, cmd) + cmd = memoFlag(a.viper, cmd) return cmd } @@ -889,11 +889,11 @@ $ %s tx transfer ibc-0 ibc-1 100000stake raw:non-bech32-address channel-0 --path $ %s tx raw send ibc-0 ibc-1 100000stake cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk channel-0 --path demo -c 5 `, appName, appName, appName, appName)), RunE: func(cmd *cobra.Command, args []string) error { - src, ok := a.Config.Chains[args[0]] + src, ok := a.config.Chains[args[0]] if !ok { return errChainNotFound(args[0]) } - dst, ok := a.Config.Chains[args[1]] + dst, ok := a.config.Chains[args[1]] if !ok { return errChainNotFound(args[1]) } @@ -979,16 +979,16 @@ $ %s tx raw send ibc-0 ibc-1 100000stake cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9 dstAddr = rawDstAddr } - return src.SendTransferMsg(cmd.Context(), a.Log, dst, amount, dstAddr, toHeightOffset, toTimeOffset, srcChannel) + return src.SendTransferMsg(cmd.Context(), a.log, dst, amount, dstAddr, toHeightOffset, toTimeOffset, srcChannel) }, } - return timeoutFlags(a.Viper, pathFlag(a.Viper, cmd)) + return timeoutFlags(a.viper, pathFlag(a.viper, cmd)) } func setPathsFromArgs(a *appState, src, dst *relayer.Chain, name string) (*relayer.Path, error) { // find any configured paths between the chains - paths, err := a.Config.Paths.PathsFromChains(src.ChainID(), dst.ChainID()) + paths, err := a.config.Paths.PathsFromChains(src.ChainID(), dst.ChainID()) if err != nil { return nil, err } diff --git a/cmd/version.go b/cmd/version.go index 2079685de..7f18c6519 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -76,5 +76,5 @@ $ %s v`, }, } - return jsonFlag(a.Viper, versionCmd) + return jsonFlag(a.viper, versionCmd) }