From 00c5cf8d31fc9c526b7dc74202b22595b0add874 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 11:20:02 -0600 Subject: [PATCH 1/7] Remove the global --config flag for chia-tools config and instead use it for the config subcommand to point to the chia config --- cmd/config/config.go | 4 ++++ cmd/config/edit.go | 14 ++++++-------- cmd/root.go | 21 +++++++-------------- 3 files changed, 17 insertions(+), 22 deletions(-) diff --git a/cmd/config/config.go b/cmd/config/config.go index 3927df5..b7b1b9e 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -2,6 +2,7 @@ package config import ( "github.com/spf13/cobra" + "github.com/spf13/viper" "github.com/chia-network/chia-tools/cmd" ) @@ -13,5 +14,8 @@ var configCmd = &cobra.Command{ } func init() { + configCmd.PersistentFlags().String("config", "", "existing config file to use (default is to look in $CHIA_ROOT)") + cobra.CheckErr(viper.BindPFlag("config", configCmd.PersistentFlags().Lookup("config"))) + cmd.RootCmd.AddCommand(configCmd) } diff --git a/cmd/config/edit.go b/cmd/config/edit.go index 8cd1cf5..404bfe3 100644 --- a/cmd/config/edit.go +++ b/cmd/config/edit.go @@ -13,24 +13,22 @@ import ( var editCmd = &cobra.Command{ Use: "edit", Short: "Edit an existing chia configuration file", - Example: `chia-tools config edit ~/.chia/mainnet/config/config.yaml --set full_node.port=58444 --set full_node.target_peer_count=10 + Example: `chia-tools config edit --config ~/.chia/mainnet/config/config.yaml --set full_node.port=58444 --set full_node.target_peer_count=10 # The following version will discover the config file by inspecting CHIA_ROOT or using the default CHIA_ROOT chia-tools config edit --set full_node.port=58444 --set full_node.target_peer_count=10`, Run: func(cmd *cobra.Command, args []string) { - var cfgPath string - chiaRoot, err := config.GetChiaRootPath() if err != nil { slogs.Logr.Fatal("Unable to determine CHIA_ROOT", "error", err) } - if len(args) > 1 { + if len(args) > 0 { slogs.Logr.Fatal("Unexpected number of arguments provided") - } else if len(args) == 1 { - // Use the provided config path - cfgPath = args[0] - } else { + } + + cfgPath := viper.GetString("config") + if cfgPath == "" { // Use default chia root cfgPath = path.Join(chiaRoot, "config", "config.yaml") } diff --git a/cmd/root.go b/cmd/root.go index b1ae054..d455cf8 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -11,7 +11,6 @@ import ( "github.com/chia-network/go-modules/pkg/slogs" ) -var cfgFile string var ( gitVersion string buildTime string @@ -37,26 +36,20 @@ func init() { cobra.OnInitialize(initConfig) cobra.OnInitialize(InitLogs) - RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.chia-tools.yaml)") RootCmd.PersistentFlags().String("log-level", "info", "The log-level for the application, can be one of info, warn, error, debug.") cobra.CheckErr(viper.BindPFlag("log-level", RootCmd.PersistentFlags().Lookup("log-level"))) } // initConfig reads in config file and ENV variables if set. func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) + // Find home directory. + home, err := os.UserHomeDir() + cobra.CheckErr(err) - // Search config in home directory with name ".chia-tools" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".chia-tools") - } + // Search config in home directory with name ".chia-tools" (without extension). + viper.AddConfigPath(home) + viper.SetConfigType("yaml") + viper.SetConfigName(".chia-tools") viper.SetEnvPrefix("CHIA_TOOLS") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) From cfe4660e6452ff1aac60f75875f7320d6231a488 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 11:58:48 -0600 Subject: [PATCH 2/7] Add trusted peer command --- cmd/config/addtrustedpeer.go | 104 +++++++++++++++++++++++++++++++++++ internal/utils/confirm.go | 17 ++++++ 2 files changed, 121 insertions(+) create mode 100644 cmd/config/addtrustedpeer.go create mode 100644 internal/utils/confirm.go diff --git a/cmd/config/addtrustedpeer.go b/cmd/config/addtrustedpeer.go new file mode 100644 index 0000000..47bd710 --- /dev/null +++ b/cmd/config/addtrustedpeer.go @@ -0,0 +1,104 @@ +package config + +import ( + "encoding/hex" + "net" + "path" + + "github.com/chia-network/go-chia-libs/pkg/config" + "github.com/chia-network/go-chia-libs/pkg/peerprotocol" + "github.com/chia-network/go-modules/pkg/slogs" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/chia-network/chia-tools/internal/utils" +) + +// addTrustedPeerCmd Adds a trusted peer to the config +var addTrustedPeerCmd = &cobra.Command{ + Use: "add-trusted-peer", + Short: "Adds a trusted peer to the config file", + Example: `chia-tools config add-trusted-peer 1.2.3.4`, + Run: func(cmd *cobra.Command, args []string) { + chiaRoot, err := config.GetChiaRootPath() + if err != nil { + slogs.Logr.Fatal("Unable to determine CHIA_ROOT", "error", err) + } + + if len(args) != 1 { + slogs.Logr.Fatal("Unexpected number of arguments provided") + } + + cfgPath := viper.GetString("config") + if cfgPath == "" { + // Use default chia root + cfgPath = path.Join(chiaRoot, "config", "config.yaml") + } + + cfg, err := config.LoadConfigAtRoot(cfgPath, chiaRoot) + if err != nil { + slogs.Logr.Fatal("error loading chia config", "error", err) + } + + peer := args[0] + ip := net.ParseIP(peer) + if ip == nil { + slogs.Logr.Fatal("Invalid IP address", "id", peer) + } + slogs.Logr.Info("Attempting to get peer id", "peer", peer) + + keypair, err := cfg.FullNode.SSL.LoadPublicKeyPair(chiaRoot) + if err != nil { + slogs.Logr.Fatal("Error loading certs from CHIA_ROOT", "CHIA_ROOT", chiaRoot, "error", err) + } + if keypair == nil { + slogs.Logr.Fatal("Error loading certs from CHIA_ROOT", "CHIA_ROOT", chiaRoot, "error", "keypair was nil") + } + conn, err := peerprotocol.NewConnection( + &ip, + peerprotocol.WithPeerPort(cfg.FullNode.Port), + peerprotocol.WithNetworkID(*cfg.SelectedNetwork), + peerprotocol.WithPeerKeyPair(*keypair), + ) + if err != nil { + slogs.Logr.Fatal("Error creating connection", "error", err) + } + peerID, err := conn.PeerID() + if err != nil { + slogs.Logr.Fatal("Error getting peer id", "error", err) + } + peerIDStr := hex.EncodeToString(peerID[:]) + slogs.Logr.Info("peer id received", "peer", peerIDStr) + if !utils.ConfirmAction("Would you like trust this peer? (y/N)") { + slogs.Logr.Error("Cancelled") + } + cfg.Wallet.TrustedPeers[peerIDStr] = "Does_not_matter" + + peerToAdd := config.Peer{ + Host: ip.String(), + Port: cfg.FullNode.Port, + } + + foundPeer := false + for idx, peer := range cfg.Wallet.FullNodePeers { + if peer.Host == ip.String() { + foundPeer = true + cfg.Wallet.FullNodePeers[idx] = peerToAdd + } + } + if !foundPeer { + cfg.Wallet.FullNodePeers = append(cfg.Wallet.FullNodePeers, peerToAdd) + } + + err = cfg.Save() + if err != nil { + slogs.Logr.Fatal("error saving config", "error", err) + } + + slogs.Logr.Info("Added trusted peer. Restart your chia services for the configuration to take effect") + }, +} + +func init() { + configCmd.AddCommand(addTrustedPeerCmd) +} diff --git a/internal/utils/confirm.go b/internal/utils/confirm.go new file mode 100644 index 0000000..6fcf152 --- /dev/null +++ b/internal/utils/confirm.go @@ -0,0 +1,17 @@ +package utils + +import ( + "bufio" + "fmt" + "os" + "strings" +) + +// ConfirmAction waits for the user to confirm with "yes" or "y" +func ConfirmAction(prompt string) bool { + fmt.Printf("%s ", prompt) + reader := bufio.NewReader(os.Stdin) + response, _ := reader.ReadString('\n') + response = strings.TrimSpace(strings.ToLower(response)) + return response == "yes" || response == "y" +} From 1d26722eed5453c39c98c4d97cd61db52cf2c8bc Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 12:02:21 -0600 Subject: [PATCH 3/7] Add support for skipping confirmation with -y or --yes --- cmd/config/addtrustedpeer.go | 7 ++++++- internal/utils/confirm.go | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/cmd/config/addtrustedpeer.go b/cmd/config/addtrustedpeer.go index 47bd710..ef837e7 100644 --- a/cmd/config/addtrustedpeer.go +++ b/cmd/config/addtrustedpeer.go @@ -14,6 +14,10 @@ import ( "github.com/chia-network/chia-tools/internal/utils" ) +var ( + skipConfirm bool +) + // addTrustedPeerCmd Adds a trusted peer to the config var addTrustedPeerCmd = &cobra.Command{ Use: "add-trusted-peer", @@ -69,7 +73,7 @@ var addTrustedPeerCmd = &cobra.Command{ } peerIDStr := hex.EncodeToString(peerID[:]) slogs.Logr.Info("peer id received", "peer", peerIDStr) - if !utils.ConfirmAction("Would you like trust this peer? (y/N)") { + if !utils.ConfirmAction("Would you like trust this peer? (y/N)", skipConfirm) { slogs.Logr.Error("Cancelled") } cfg.Wallet.TrustedPeers[peerIDStr] = "Does_not_matter" @@ -100,5 +104,6 @@ var addTrustedPeerCmd = &cobra.Command{ } func init() { + addTrustedPeerCmd.Flags().BoolVarP(&skipConfirm, "yes", "y", false, "Skip confirmation") configCmd.AddCommand(addTrustedPeerCmd) } diff --git a/internal/utils/confirm.go b/internal/utils/confirm.go index 6fcf152..27a2354 100644 --- a/internal/utils/confirm.go +++ b/internal/utils/confirm.go @@ -8,7 +8,11 @@ import ( ) // ConfirmAction waits for the user to confirm with "yes" or "y" -func ConfirmAction(prompt string) bool { +func ConfirmAction(prompt string, skipConfirm bool) bool { + // Easy support for -y type flags to skip confirmation + if skipConfirm { + return true + } fmt.Printf("%s ", prompt) reader := bufio.NewReader(os.Stdin) response, _ := reader.ReadString('\n') From 0a90fce7650ec52e3ff87512a2eb0cb40ddac628 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 12:08:16 -0600 Subject: [PATCH 4/7] Allow specifying port --- cmd/config/addtrustedpeer.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/cmd/config/addtrustedpeer.go b/cmd/config/addtrustedpeer.go index ef837e7..ce81c7d 100644 --- a/cmd/config/addtrustedpeer.go +++ b/cmd/config/addtrustedpeer.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "net" "path" + "strconv" "github.com/chia-network/go-chia-libs/pkg/config" "github.com/chia-network/go-chia-libs/pkg/peerprotocol" @@ -29,7 +30,9 @@ var addTrustedPeerCmd = &cobra.Command{ slogs.Logr.Fatal("Unable to determine CHIA_ROOT", "error", err) } - if len(args) != 1 { + // 1: Peer IP + // 2: Optional, port + if len(args) < 1 || len(args) > 2 { slogs.Logr.Fatal("Unexpected number of arguments provided") } @@ -45,6 +48,16 @@ var addTrustedPeerCmd = &cobra.Command{ } peer := args[0] + port := cfg.FullNode.Port + if len(args) > 2 { + port64, err := strconv.ParseUint(args[1], 10, 16) + if err != nil { + slogs.Logr.Fatal("Invalid port provided") + } + port = uint16(port64) + } + + ip := net.ParseIP(peer) if ip == nil { slogs.Logr.Fatal("Invalid IP address", "id", peer) @@ -60,7 +73,7 @@ var addTrustedPeerCmd = &cobra.Command{ } conn, err := peerprotocol.NewConnection( &ip, - peerprotocol.WithPeerPort(cfg.FullNode.Port), + peerprotocol.WithPeerPort(port), peerprotocol.WithNetworkID(*cfg.SelectedNetwork), peerprotocol.WithPeerKeyPair(*keypair), ) @@ -80,7 +93,7 @@ var addTrustedPeerCmd = &cobra.Command{ peerToAdd := config.Peer{ Host: ip.String(), - Port: cfg.FullNode.Port, + Port: port, } foundPeer := false From cf64190c72f5ee5cd0e66f29c323ca378730a4ed Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 12:18:28 -0600 Subject: [PATCH 5/7] Fix port logic, and log the port we're using --- cmd/config/addtrustedpeer.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cmd/config/addtrustedpeer.go b/cmd/config/addtrustedpeer.go index ce81c7d..e901112 100644 --- a/cmd/config/addtrustedpeer.go +++ b/cmd/config/addtrustedpeer.go @@ -49,7 +49,7 @@ var addTrustedPeerCmd = &cobra.Command{ peer := args[0] port := cfg.FullNode.Port - if len(args) > 2 { + if len(args) > 1 { port64, err := strconv.ParseUint(args[1], 10, 16) if err != nil { slogs.Logr.Fatal("Invalid port provided") @@ -57,12 +57,11 @@ var addTrustedPeerCmd = &cobra.Command{ port = uint16(port64) } - ip := net.ParseIP(peer) if ip == nil { slogs.Logr.Fatal("Invalid IP address", "id", peer) } - slogs.Logr.Info("Attempting to get peer id", "peer", peer) + slogs.Logr.Info("Attempting to get peer id", "peer", peer, "port", port) keypair, err := cfg.FullNode.SSL.LoadPublicKeyPair(chiaRoot) if err != nil { From be764aa2e6a4fbb75ca4acfc2ef59e4b7f7889d9 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 12:28:19 -0600 Subject: [PATCH 6/7] Save wallet full_node_peers when swapping networks, and ensure we never have an empty list of peers --- cmd/network/switch.go | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/cmd/network/switch.go b/cmd/network/switch.go index 8f3d35c..1cc7557 100644 --- a/cmd/network/switch.go +++ b/cmd/network/switch.go @@ -43,10 +43,11 @@ func init() { // retainedSettings are the settings we want to keep track of when switching networks so we can swap back to them in the future type retainedSettings struct { - DNSServers []string `json:"dns_servers"` - BootstrapPeers []string `json:"bootstrap_peers"` - StaticPeers []string `json:"static_peers"` - FullNodePeers []config.Peer `json:"full_node_peers"` + DNSServers []string `json:"dns_servers"` + BootstrapPeers []string `json:"bootstrap_peers"` + StaticPeers []string `json:"static_peers"` + FullNodePeers []config.Peer `json:"full_node_peers"` + WalletFullNodePeers []config.Peer `json:"wallet_full_node_peers"` } // SwitchNetwork implements the logic to swap networks @@ -101,10 +102,11 @@ func SwitchNetwork(networkName string, checkForRunningNode bool) { } previousSettings := retainedSettings{ - DNSServers: cfg.FullNode.DNSServers, - BootstrapPeers: cfg.Seeder.BootstrapPeers, - StaticPeers: cfg.Seeder.StaticPeers, - FullNodePeers: cfg.FullNode.FullNodePeers, + DNSServers: cfg.FullNode.DNSServers, + BootstrapPeers: cfg.Seeder.BootstrapPeers, + StaticPeers: cfg.Seeder.StaticPeers, + FullNodePeers: cfg.FullNode.FullNodePeers, + WalletFullNodePeers: cfg.Wallet.FullNodePeers, } marshalled, err := json.Marshal(previousSettings) if err != nil { @@ -174,6 +176,7 @@ func SwitchNetwork(networkName string, checkForRunningNode bool) { dnsIntroducerHosts := []string{"dns-introducer.chia.net"} fullNodePort := uint16(8444) var fullnodePeers []config.Peer + var walletFullNodePeers []config.Peer peersFilePath := "db/peers.dat" walletPeersFilePath := "wallet/db/wallet_peers.dat" bootstrapPeers := []string{"node.chia.net"} @@ -202,6 +205,9 @@ func SwitchNetwork(networkName string, checkForRunningNode bool) { if len(settingsToRestore.FullNodePeers) > 0 { fullnodePeers = settingsToRestore.FullNodePeers } + if len(settingsToRestore.WalletFullNodePeers) > 0 { + walletFullNodePeers = settingsToRestore.WalletFullNodePeers + } } if introFlag := viper.GetString("switch-introducer"); introFlag != "" { @@ -247,13 +253,8 @@ func SwitchNetwork(networkName string, checkForRunningNode bool) { Port: fullNodePort, }, }, - "wallet.dns_servers": dnsIntroducerHosts, - "wallet.full_node_peers": []config.Peer{ - { - Host: "localhost", - Port: fullNodePort, - }, - }, + "wallet.dns_servers": dnsIntroducerHosts, + "wallet.full_node_peers": ensureAtLeastLocalPeer(walletFullNodePeers, fullNodePort), "wallet.introducer_peer.host": introducerHost, "wallet.introducer_peer.port": fullNodePort, "wallet.wallet_peers_file_path": walletPeersFilePath, @@ -286,6 +287,17 @@ func SwitchNetwork(networkName string, checkForRunningNode bool) { slogs.Logr.Info("Complete") } +func ensureAtLeastLocalPeer(peers []config.Peer, port uint16) []config.Peer { + if len(peers) == 0 { + peers = append(peers, config.Peer{ + Host: "localhost", + Port: port, + }) + } + + return peers +} + func isConnectionRefused(err error) bool { var netErr *net.OpError if errors.As(err, &netErr) { From 90e03c985ac76480df507872958caa827239c375 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 10 Dec 2024 12:37:09 -0600 Subject: [PATCH 7/7] Add port override example --- cmd/config/addtrustedpeer.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cmd/config/addtrustedpeer.go b/cmd/config/addtrustedpeer.go index e901112..eee780d 100644 --- a/cmd/config/addtrustedpeer.go +++ b/cmd/config/addtrustedpeer.go @@ -23,7 +23,10 @@ var ( var addTrustedPeerCmd = &cobra.Command{ Use: "add-trusted-peer", Short: "Adds a trusted peer to the config file", - Example: `chia-tools config add-trusted-peer 1.2.3.4`, + Example: `chia-tools config add-trusted-peer 1.2.3.4 + +# The following version will also override the port to use when connecting to this peer +chia-tools config add-trusted-peer 1.2.3.4 18444`, Run: func(cmd *cobra.Command, args []string) { chiaRoot, err := config.GetChiaRootPath() if err != nil {