From c636358ee322444328e99e95f6b19730b7fb2e12 Mon Sep 17 00:00:00 2001 From: wizeguyy Date: Mon, 3 Jun 2024 12:13:07 -0500 Subject: [PATCH 1/4] Remove obsolete 'send' command --- cmd/go-quai/send.go | 203 -------------------------------------------- 1 file changed, 203 deletions(-) delete mode 100644 cmd/go-quai/send.go diff --git a/cmd/go-quai/send.go b/cmd/go-quai/send.go deleted file mode 100644 index 3d91fe0aa1..0000000000 --- a/cmd/go-quai/send.go +++ /dev/null @@ -1,203 +0,0 @@ -/* -Copyright © 2023 NAME HERE -*/ -package main - -import ( - "bufio" - "context" - "os" - "os/signal" - "path/filepath" - "runtime/debug" - "syscall" - "time" - - "github.com/pkg/errors" - - "github.com/libp2p/go-libp2p/core/peer" - "github.com/libp2p/go-libp2p/core/protocol" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/dominant-strategies/go-quai/cmd/utils" - "github.com/dominant-strategies/go-quai/common" - "github.com/dominant-strategies/go-quai/log" - "github.com/dominant-strategies/go-quai/p2p/node" - quaiprotocol "github.com/dominant-strategies/go-quai/p2p/protocol" -) - -// In your cmd package where you define Cobra commands - -var sendCmd = &cobra.Command{ - Use: "send", - Short: "Send a message using the Quai protocol", - Long: `Send a message to a specific peer using the Quai protocol for testing purposes.`, - RunE: runSend, - PreRunE: sendCmdPreRun, - SilenceUsage: true, -} - -var targetPeer string -var message string -var sendInterval time.Duration -var protocolID string - -func init() { - startCmd.AddCommand(sendCmd) - - sendCmd.Flags().StringVar(&targetPeer, "target", "", "Target peer multiaddress. If not provided, will use the default bootnode.") - sendCmd.Flags().StringVarP(&message, "message", "m", "", "Message to send") - sendCmd.Flags().DurationVar(&sendInterval, "interval", 0, "Interval between messages, i.e. '5s' (Set to 0 for a one-time send).") - // add flag to read the protocol id from the command line - sendCmd.Flags().StringVar(&protocolID, "protocol", string(quaiprotocol.ProtocolVersion), "Protocol ID, i.e. '/quai/1.0.0'") - - sendCmd.MarkFlagRequired("message") // Ensure that message flag is provided -} - -func sendCmdPreRun(cmd *cobra.Command, args []string) error { - // duplicated from cmd/start.go - // set keyfile path - if viper.GetString(utils.KeyFileFlag.Name) == "" { - configDir := cmd.Flag(utils.ConfigDirFlag.Name).Value.String() - viper.Set(utils.KeyFileFlag.Name, filepath.Join(configDir, "private.key")) - } - - // if no bootstrap peers are provided, use the default ones defined in config/bootnodes.go - if bootstrapPeers := viper.GetStringSlice(utils.BootPeersFlag.Name); len(bootstrapPeers) == 0 { - log.Global.Debugf("no bootstrap peers provided. Using default ones: %v", common.BootstrapPeers) - viper.Set(utils.BootPeersFlag.Name, common.BootstrapPeers) - } - return nil -} - -func runSend(cmd *cobra.Command, args []string) error { - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - // create a new p2p node - node, err := node.NewNode(ctx, nil) - if err != nil { - log.Global.Fatalf("error creating node: %s", err) - } - - // Ensure target peer is set, or use a default - if targetPeer == "" { - log.Global.Warnf("no target peer provided. Using default bootnode: %s", common.BootstrapPeers[0]) - targetPeer = common.BootstrapPeers[0] - } - - // Convert targetPeer string to peer.AddrInfo - targetAddrInfo, err := peer.AddrInfoFromString(targetPeer) - if err != nil { - return err - } - - // start node - if err := node.Start(); err != nil { - log.Global.Fatalf("error starting node: %s", err) - } - - // Connect to the target peer - if err := node.GetPeerManager().GetHost().Connect(ctx, *targetAddrInfo); err != nil { - log.Global.Errorf("error connecting to target peer: %+v, error: %s", targetAddrInfo.ID, err) - return err - } - - // Function to send a message - sendMessage := func() error { - stream, err := node.GetPeerManager().GetHost().NewStream(ctx, targetAddrInfo.ID, protocol.ID(protocolID)) - if err != nil { - log.Global.Errorf("error opening stream: %s", err) - return err - } - defer stream.Close() - - _, err = stream.Write([]byte(message + "\n")) - if err != nil { - log.Global.Errorf("error writing to stream: %s", err) - return err - } - - log.Global.Debugf("Sent message: '%s'. Waiting for response...", message) - - // Read the response from host2 - buf := bufio.NewReader(stream) - // response, err := buf.ReadString('\n') - response, err := readWithTimeout(buf, ctx) - if err != nil { - log.Global.Errorf("error reading from stream: %s", err) - return err - } - log.Global.Debugf("Received response: '%s'", response) - return nil - } - - if sendInterval > 0 { - // Send periodically - ticker := time.NewTicker(sendInterval) - defer ticker.Stop() - // wait for a SIGINT or SIGTERM signal - ch := make(chan os.Signal, 1) - signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) - for { - select { - case <-ticker.C: - if err := sendMessage(); err != nil { - log.Global.Errorf("Error sending message: %s", err) - } - case <-ch: - log.Global.Warnf("Received 'stop' signal, shutting down gracefully...") - cancel() - if err := node.Stop(); err != nil { - panic(err) - } - log.Global.Warnf("Node is offline") - return nil - case <-ctx.Done(): - return ctx.Err() - } - } - } else { - // Send once - return sendMessage() - } -} - -// readWithTimeout reads from the bufio.Reader with a 5 seconds timeout. -func readWithTimeout(buf *bufio.Reader, ctx context.Context) (string, error) { - resultChan := make(chan string, 1) - errChan := make(chan error, 1) - - timer := time.NewTimer(5 * time.Second) - defer timer.Stop() - - go func() { - defer func() { - if r := recover(); r != nil { - log.Global.WithFields(log.Fields{ - "error": r, - "stacktrace": string(debug.Stack()), - }).Fatal("Go-Quai Panicked") - } - }() - response, err := buf.ReadString('\n') - if err != nil { - errChan <- err - return - } - resultChan <- response - }() - - select { - case <-ctx.Done(): - return "", ctx.Err() - case response := <-resultChan: - return response, nil - case err := <-errChan: - return "", err - case <-timer.C: - return "", errors.New("timeout waiting for response") - } -} From 861cc981678320da9f46c72f416916f28450ccd3 Mon Sep 17 00:00:00 2001 From: wizeguyy Date: Mon, 3 Jun 2024 09:40:09 -0500 Subject: [PATCH 2/4] Remove unused SaveConfig() method --- cmd/utils/utils.go | 42 ----------------------------------------- cmd/utils/utils_test.go | 34 --------------------------------- 2 files changed, 76 deletions(-) diff --git a/cmd/utils/utils.go b/cmd/utils/utils.go index ec277805ba..ca62c5aea0 100644 --- a/cmd/utils/utils.go +++ b/cmd/utils/utils.go @@ -3,7 +3,6 @@ package utils import ( "errors" "io/fs" - "os" "github.com/spf13/viper" @@ -35,44 +34,3 @@ func InitConfig() { viper.SetEnvPrefix(constants.ENV_PREFIX) viper.AutomaticEnv() } - -// saves the config file with the current config parameters. -// -// If the config file does not exist, it creates it. -// -// If the config file exists, it creates a backup copy ending with .bak -// and overwrites the existing config file. -// TODO: consider using one single utility function to save/update/append files throughout the codebase -func SaveConfig() error { - // check if config file exists - configFile := viper.ConfigFileUsed() - log.Global.Debugf("saving/updating config file: %s", configFile) - if _, err := os.Stat(configFile); err == nil { - // config file exists, create backup copy - err := os.Rename(configFile, configFile+".bak") - if err != nil { - return err - } - } else if os.IsNotExist(err) { - // config file does not exist, create directory if it does not exist - if _, err := os.Stat(configFile); os.IsNotExist(err) { - configDir := viper.GetString(ConfigDirFlag.Name) - if err := os.MkdirAll(configDir, 0755); err != nil { - return err - } - } - _, err := os.Create(configFile) - if err != nil { - return err - } - } else { - return err - } - - // write config file - err := viper.WriteConfigAs(configFile) - if err != nil { - return err - } - return nil -} diff --git a/cmd/utils/utils_test.go b/cmd/utils/utils_test.go index ec98f198c3..8d9a1192ae 100644 --- a/cmd/utils/utils_test.go +++ b/cmd/utils/utils_test.go @@ -11,40 +11,6 @@ import ( "github.com/stretchr/testify/require" ) -// Verifies that the config file is saved or updated with the current config parameters. -func TestSaveConfig(t *testing.T) { - // set configPath to a temporary mocked XDG config folder - mockConfigPath := "/tmp/xdg_config_home/" - tempFile := createMockXDGConfigFile(t, mockConfigPath) - defer tempFile.Close() - defer os.RemoveAll(mockConfigPath) - // write LOG_LEVEL config to mock config.yaml file - _, err := tempFile.WriteString(LogLevelFlag.Name + " : " + "debug\n") - require.NoError(t, err) - // Clear viper instance to simulate a fresh start - viper.Reset() - - // Set config path to the temporary config directory - viper.SetConfigFile(tempFile.Name()) - - // Set PORT to 8080 as environment variable - err = os.Setenv("GO_QUAI_PORT", "8080") - require.NoError(t, err) - defer os.Unsetenv("GO_QUAI_PORT") - InitConfig() - // Save config file - err = SaveConfig() - require.NoError(t, err) - // Load config from mock file into viper and assert that the new config parameters were saved - err = viper.ReadInConfig() - require.NoError(t, err) - assert.Equal(t, "8080", viper.GetString(P2PPortFlag.Name)) - // Assert a .bak config file was created - backupFile, err := os.Stat(mockConfigPath + constants.CONFIG_FILE_NAME + ".bak") - assert.False(t, os.IsNotExist(err)) - assert.Equal(t, constants.CONFIG_FILE_NAME+".bak", backupFile.Name()) -} - // testXDGConfigLoading tests the loading of the config file from the XDG config home // and verifies values are correctly set in viper. // This test is nested within the TestCobraFlagConfigLoading test. From 4d4c927569cdfc6f9bac962f69a2906654fa6ee0 Mon Sep 17 00:00:00 2001 From: wizeguyy Date: Mon, 3 Jun 2024 10:38:42 -0500 Subject: [PATCH 3/4] Fix default network and bootpeer selection --- cmd/go-quai/start.go | 7 ------- cmd/utils/flags.go | 7 +++++-- cmd/utils/utils.go | 7 +++++++ common/bootnodes.go | 12 +++++++----- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/cmd/go-quai/start.go b/cmd/go-quai/start.go index 5f790ef670..81eb75921b 100644 --- a/cmd/go-quai/start.go +++ b/cmd/go-quai/start.go @@ -15,7 +15,6 @@ import ( "github.com/spf13/viper" "github.com/dominant-strategies/go-quai/cmd/utils" - "github.com/dominant-strategies/go-quai/common" "github.com/dominant-strategies/go-quai/log" "github.com/dominant-strategies/go-quai/metrics_config" "github.com/dominant-strategies/go-quai/p2p/node" @@ -63,12 +62,6 @@ func startCmdPreRun(cmd *cobra.Command, args []string) error { configDir := cmd.Flag(utils.ConfigDirFlag.Name).Value.String() viper.Set(utils.KeyFileFlag.Name, filepath.Join(configDir, "private.key")) } - - // if no bootstrap peers are provided, use the default ones defined in config/bootnodes.go - if bootstrapPeers := viper.GetStringSlice(utils.BootPeersFlag.Name); len(bootstrapPeers) == 0 { - log.Global.Debugf("no bootstrap peers provided. Using default ones: %v", common.BootstrapPeers) - viper.Set(utils.BootPeersFlag.Name, common.BootstrapPeers) - } return nil } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 83216812bd..59aad95b46 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -533,7 +533,7 @@ var ( EnvironmentFlag = Flag{ Name: c_NodeFlagPrefix + "environment", - Value: params.LocalName, + Value: params.ColosseumName, Usage: "environment to run in (local, colosseum, garden, orchard, lighthouse, dev)" + generateEnvDoc(c_NodeFlagPrefix+"environment"), } @@ -1522,7 +1522,7 @@ func addFlagsToCategory(flags []Flag) { } } -// Write a function to write the default values of each flag to a file +// Write the default values of each flag to a file func WriteDefaultConfigFile(configDir string, configFileName string, configType string) error { if configDir == "" { log.Global.Fatalf("No config file path provided") @@ -1560,6 +1560,9 @@ func WriteDefaultConfigFile(configDir string, configFileName string, configType addFlagsToCategory(RPCFlags) addFlagsToCategory(MetricsFlags) + // Remove bootpeers data from the configData to be written. + delete(configData["node"], "bootpeers") + var output []byte var marshalErr error diff --git a/cmd/utils/utils.go b/cmd/utils/utils.go index ca62c5aea0..d3e95bb9e8 100644 --- a/cmd/utils/utils.go +++ b/cmd/utils/utils.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/viper" + "github.com/dominant-strategies/go-quai/common" "github.com/dominant-strategies/go-quai/common/constants" "github.com/dominant-strategies/go-quai/log" ) @@ -29,6 +30,12 @@ func InitConfig() { panic(err) } } + if !viper.IsSet(BootPeersFlag.Name) { + network := viper.GetString(EnvironmentFlag.Name) + bootpeers := common.BootstrapPeers[network] + log.Global.Debugf("No bootpeers specified. Using defaults for %s: %s", network, bootpeers) + viper.Set(BootPeersFlag.Name, bootpeers) + } log.Global.Infof("Loading config from environment variables with prefix: '%s_'", constants.ENV_PREFIX) viper.SetEnvPrefix(constants.ENV_PREFIX) diff --git a/common/bootnodes.go b/common/bootnodes.go index ef49876e7f..91ced0eee0 100644 --- a/common/bootnodes.go +++ b/common/bootnodes.go @@ -1,10 +1,12 @@ package common var ( - BootstrapPeers = []string{ - "/ip4/146.148.66.22/tcp/4001/p2p/12D3KooWRQrLVEeJtfyKoJDYWYjryBKR8qxkDooMMzyf2ZpLaZRR", - "/ip4/35.190.147.237/tcp/4001/p2p/12D3KooWSb49ccXFWPCsvi7rzCbqBUK2xfuRC2xbo6KnUZk3YaVg", - "/ip4/35.194.7.78/tcp/4001/p2p/12D3KooWR3xMB6sCpsowQcvtdMKmKbTaiDcDFAXuWABdZVPWaVuo", - "/ip4/34.136.140.151/tcp/4001/p2p/12D3KooWJnWmBukEbZtGPPJvT1r4tQ97CRSGmnjHewcrjNB8oRxU", + BootstrapPeers = map[string][]string{ + "garden": { + "/ip4/146.148.66.22/tcp/4001/p2p/12D3KooWRQrLVEeJtfyKoJDYWYjryBKR8qxkDooMMzyf2ZpLaZRR", + "/ip4/35.190.147.237/tcp/4001/p2p/12D3KooWSb49ccXFWPCsvi7rzCbqBUK2xfuRC2xbo6KnUZk3YaVg", + "/ip4/35.194.7.78/tcp/4001/p2p/12D3KooWR3xMB6sCpsowQcvtdMKmKbTaiDcDFAXuWABdZVPWaVuo", + "/ip4/34.136.140.151/tcp/4001/p2p/12D3KooWJnWmBukEbZtGPPJvT1r4tQ97CRSGmnjHewcrjNB8oRxU", + }, } ) From 3a9098fdc4d021d51a7860645a2840b06bb4c225 Mon Sep 17 00:00:00 2001 From: wizeguyy Date: Tue, 4 Jun 2024 10:46:27 -0500 Subject: [PATCH 4/4] Print network name at start --- cmd/go-quai/start.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/go-quai/start.go b/cmd/go-quai/start.go index 81eb75921b..fe9b78af66 100644 --- a/cmd/go-quai/start.go +++ b/cmd/go-quai/start.go @@ -66,7 +66,8 @@ func startCmdPreRun(cmd *cobra.Command, args []string) error { } func runStart(cmd *cobra.Command, args []string) error { - log.Global.Info("Starting go-quai") + network := viper.GetString(utils.EnvironmentFlag.Name) + log.Global.Infof("Starting go-quai on the %s network", network) ctx, cancel := context.WithCancel(context.Background()) defer cancel()