github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/cmd/geth/config.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"os"
    23  	"time"
    24  
    25  	"github.com/BurntSushi/toml"
    26  	"gopkg.in/urfave/cli.v1"
    27  
    28  	"github.com/ethereum/go-ethereum/accounts/external"
    29  	"github.com/ethereum/go-ethereum/accounts/keystore"
    30  	"github.com/ethereum/go-ethereum/accounts/scwallet"
    31  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    32  	"github.com/ethereum/go-ethereum/cmd/utils"
    33  	"github.com/ethereum/go-ethereum/core/rawdb"
    34  	"github.com/ethereum/go-ethereum/eth/downloader"
    35  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    36  	"github.com/ethereum/go-ethereum/internal/ethapi"
    37  	"github.com/ethereum/go-ethereum/log"
    38  	"github.com/ethereum/go-ethereum/metrics"
    39  	"github.com/ethereum/go-ethereum/node"
    40  	"github.com/ethereum/go-ethereum/params"
    41  )
    42  
    43  var (
    44  	dumpConfigCommand = cli.Command{
    45  		Action:      utils.MigrateFlags(dumpConfig),
    46  		Name:        "dumpconfig",
    47  		Usage:       "Show configuration values",
    48  		ArgsUsage:   "",
    49  		Flags:       append(nodeFlags, rpcFlags...),
    50  		Category:    "MISCELLANEOUS COMMANDS",
    51  		Description: `The dumpconfig command shows configuration values.`,
    52  	}
    53  
    54  	configFileFlag = cli.StringFlag{
    55  		Name:  "config",
    56  		Usage: "TOML configuration file",
    57  	}
    58  )
    59  
    60  type ethstatsConfig struct {
    61  	URL string `toml:",omitempty"`
    62  }
    63  
    64  type gethConfig struct {
    65  	Eth      ethconfig.Config
    66  	Node     node.Config
    67  	Ethstats ethstatsConfig
    68  	Metrics  metrics.Config
    69  }
    70  
    71  func loadConfig(file string, cfg *gethConfig) error {
    72  	data, err := os.ReadFile(file)
    73  	if err != nil {
    74  		return err
    75  	}
    76  
    77  	tomlData := string(data)
    78  	if _, err = toml.Decode(tomlData, &cfg); err != nil {
    79  		return err
    80  	}
    81  
    82  	return nil
    83  }
    84  
    85  func defaultNodeConfig() node.Config {
    86  	cfg := node.DefaultConfig
    87  	cfg.Name = clientIdentifier
    88  	cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
    89  	cfg.HTTPModules = append(cfg.HTTPModules, "eth")
    90  	cfg.WSModules = append(cfg.WSModules, "eth")
    91  	cfg.IPCPath = clientIdentifier + ".ipc"
    92  	return cfg
    93  }
    94  
    95  // makeConfigNode loads geth configuration and creates a blank node instance.
    96  func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
    97  	// Load defaults.
    98  	cfg := gethConfig{
    99  		Eth:     ethconfig.Defaults,
   100  		Node:    defaultNodeConfig(),
   101  		Metrics: metrics.DefaultConfig,
   102  	}
   103  
   104  	// Load config file.
   105  	if file := ctx.GlobalString(configFileFlag.Name); file != "" {
   106  		if err := loadConfig(file, &cfg); err != nil {
   107  			utils.Fatalf("%v", err)
   108  		}
   109  	}
   110  
   111  	if ctx.GlobalIsSet(utils.MumbaiFlag.Name) {
   112  		setDefaultMumbaiGethConfig(ctx, &cfg)
   113  	}
   114  
   115  	if ctx.GlobalIsSet(utils.BorMainnetFlag.Name) {
   116  		setDefaultBorMainnetGethConfig(ctx, &cfg)
   117  	}
   118  
   119  	// Apply flags.
   120  	utils.SetNodeConfig(ctx, &cfg.Node)
   121  	stack, err := node.New(&cfg.Node)
   122  	if err != nil {
   123  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   124  	}
   125  	// Node doesn't by default populate account manager backends
   126  	if err := setAccountManagerBackends(stack); err != nil {
   127  		utils.Fatalf("Failed to set account manager backends: %v", err)
   128  	}
   129  
   130  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   131  	if ctx.GlobalIsSet(utils.EthStatsURLFlag.Name) {
   132  		cfg.Ethstats.URL = ctx.GlobalString(utils.EthStatsURLFlag.Name)
   133  	}
   134  	applyMetricConfig(ctx, &cfg)
   135  
   136  	// Set Bor config flags
   137  	utils.SetBorConfig(ctx, &cfg.Eth)
   138  
   139  	return stack, cfg
   140  }
   141  
   142  // makeFullNode loads geth configuration and creates the Ethereum backend.
   143  func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
   144  	stack, cfg := makeConfigNode(ctx)
   145  	if ctx.GlobalIsSet(utils.OverrideArrowGlacierFlag.Name) {
   146  		cfg.Eth.OverrideArrowGlacier = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideArrowGlacierFlag.Name))
   147  	}
   148  	if ctx.GlobalIsSet(utils.OverrideTerminalTotalDifficulty.Name) {
   149  		cfg.Eth.OverrideTerminalTotalDifficulty = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideTerminalTotalDifficulty.Name))
   150  	}
   151  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   152  	// Warn users to migrate if they have a legacy freezer format.
   153  	if eth != nil {
   154  		firstIdx := uint64(0)
   155  		// Hack to speed up check for mainnet because we know
   156  		// the first non-empty block.
   157  		ghash := rawdb.ReadCanonicalHash(eth.ChainDb(), 0)
   158  		if cfg.Eth.NetworkId == 1 && ghash == params.MainnetGenesisHash {
   159  			firstIdx = 46147
   160  		}
   161  		isLegacy, _, err := dbHasLegacyReceipts(eth.ChainDb(), firstIdx)
   162  		if err != nil {
   163  			log.Error("Failed to check db for legacy receipts", "err", err)
   164  		} else if isLegacy {
   165  			log.Warn("Database has receipts with a legacy format. Please run `geth db freezer-migrate`.")
   166  		}
   167  	}
   168  
   169  	// Configure GraphQL if requested
   170  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   171  		utils.RegisterGraphQLService(stack, backend, cfg.Node)
   172  	}
   173  	// Add the Ethereum Stats daemon if requested.
   174  	if cfg.Ethstats.URL != "" {
   175  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   176  	}
   177  	return stack, backend
   178  }
   179  
   180  // dumpConfig is the dumpconfig command.
   181  func dumpConfig(ctx *cli.Context) error {
   182  	_, cfg := makeConfigNode(ctx)
   183  	comment := ""
   184  
   185  	if cfg.Eth.Genesis != nil {
   186  		cfg.Eth.Genesis = nil
   187  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   188  	}
   189  
   190  	if err := toml.NewEncoder(os.Stdout).Encode(&cfg); err != nil {
   191  		return err
   192  	}
   193  
   194  	return nil
   195  }
   196  
   197  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   198  	if ctx.GlobalIsSet(utils.MetricsEnabledFlag.Name) {
   199  		cfg.Metrics.Enabled = ctx.GlobalBool(utils.MetricsEnabledFlag.Name)
   200  	}
   201  	if ctx.GlobalIsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   202  		cfg.Metrics.EnabledExpensive = ctx.GlobalBool(utils.MetricsEnabledExpensiveFlag.Name)
   203  	}
   204  	if ctx.GlobalIsSet(utils.MetricsHTTPFlag.Name) {
   205  		cfg.Metrics.HTTP = ctx.GlobalString(utils.MetricsHTTPFlag.Name)
   206  	}
   207  	if ctx.GlobalIsSet(utils.MetricsPortFlag.Name) {
   208  		cfg.Metrics.Port = ctx.GlobalInt(utils.MetricsPortFlag.Name)
   209  	}
   210  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   211  		cfg.Metrics.EnableInfluxDB = ctx.GlobalBool(utils.MetricsEnableInfluxDBFlag.Name)
   212  	}
   213  	if ctx.GlobalIsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   214  		cfg.Metrics.InfluxDBEndpoint = ctx.GlobalString(utils.MetricsInfluxDBEndpointFlag.Name)
   215  	}
   216  	if ctx.GlobalIsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   217  		cfg.Metrics.InfluxDBDatabase = ctx.GlobalString(utils.MetricsInfluxDBDatabaseFlag.Name)
   218  	}
   219  	if ctx.GlobalIsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   220  		cfg.Metrics.InfluxDBUsername = ctx.GlobalString(utils.MetricsInfluxDBUsernameFlag.Name)
   221  	}
   222  	if ctx.GlobalIsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   223  		cfg.Metrics.InfluxDBPassword = ctx.GlobalString(utils.MetricsInfluxDBPasswordFlag.Name)
   224  	}
   225  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   226  		cfg.Metrics.InfluxDBTags = ctx.GlobalString(utils.MetricsInfluxDBTagsFlag.Name)
   227  	}
   228  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   229  		cfg.Metrics.EnableInfluxDBV2 = ctx.GlobalBool(utils.MetricsEnableInfluxDBV2Flag.Name)
   230  	}
   231  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   232  		cfg.Metrics.InfluxDBToken = ctx.GlobalString(utils.MetricsInfluxDBTokenFlag.Name)
   233  	}
   234  	if ctx.GlobalIsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   235  		cfg.Metrics.InfluxDBBucket = ctx.GlobalString(utils.MetricsInfluxDBBucketFlag.Name)
   236  	}
   237  	if ctx.GlobalIsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   238  		cfg.Metrics.InfluxDBOrganization = ctx.GlobalString(utils.MetricsInfluxDBOrganizationFlag.Name)
   239  	}
   240  }
   241  
   242  func deprecated(field string) bool {
   243  	switch field {
   244  	case "ethconfig.Config.EVMInterpreter":
   245  		return true
   246  	case "ethconfig.Config.EWASMInterpreter":
   247  		return true
   248  	default:
   249  		return false
   250  	}
   251  }
   252  
   253  func setAccountManagerBackends(stack *node.Node) error {
   254  	conf := stack.Config()
   255  	am := stack.AccountManager()
   256  	keydir := stack.KeyStoreDir()
   257  	scryptN := keystore.StandardScryptN
   258  	scryptP := keystore.StandardScryptP
   259  	if conf.UseLightweightKDF {
   260  		scryptN = keystore.LightScryptN
   261  		scryptP = keystore.LightScryptP
   262  	}
   263  
   264  	// Assemble the supported backends
   265  	if len(conf.ExternalSigner) > 0 {
   266  		log.Info("Using external signer", "url", conf.ExternalSigner)
   267  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   268  			am.AddBackend(extapi)
   269  			return nil
   270  		} else {
   271  			return fmt.Errorf("error connecting to external signer: %v", err)
   272  		}
   273  	}
   274  
   275  	// For now, we're using EITHER external signer OR local signers.
   276  	// If/when we implement some form of lockfile for USB and keystore wallets,
   277  	// we can have both, but it's very confusing for the user to see the same
   278  	// accounts in both externally and locally, plus very racey.
   279  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   280  	if conf.USB {
   281  		// Start a USB hub for Ledger hardware wallets
   282  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   283  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   284  		} else {
   285  			am.AddBackend(ledgerhub)
   286  		}
   287  		// Start a USB hub for Trezor hardware wallets (HID version)
   288  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   289  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   290  		} else {
   291  			am.AddBackend(trezorhub)
   292  		}
   293  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   294  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   295  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   296  		} else {
   297  			am.AddBackend(trezorhub)
   298  		}
   299  	}
   300  	if len(conf.SmartCardDaemonPath) > 0 {
   301  		// Start a smart card hub
   302  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   303  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   304  		} else {
   305  			am.AddBackend(schub)
   306  		}
   307  	}
   308  
   309  	return nil
   310  }
   311  
   312  func setDefaultMumbaiGethConfig(ctx *cli.Context, config *gethConfig) {
   313  	config.Node.P2P.ListenAddr = fmt.Sprintf(":%d", 30303)
   314  	config.Node.HTTPHost = "0.0.0.0"
   315  	config.Node.HTTPVirtualHosts = []string{"*"}
   316  	config.Node.HTTPCors = []string{"*"}
   317  	config.Node.HTTPPort = 8545
   318  	config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
   319  	config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
   320  	config.Eth.SyncMode = downloader.FullSync
   321  	config.Eth.NetworkId = 80001
   322  	config.Eth.Miner.GasCeil = 20000000
   323  	//--miner.gastarget is depreceated, No longed used
   324  	config.Eth.TxPool.NoLocals = true
   325  	config.Eth.TxPool.AccountSlots = 16
   326  	config.Eth.TxPool.GlobalSlots = 131072
   327  	config.Eth.TxPool.AccountQueue = 64
   328  	config.Eth.TxPool.GlobalQueue = 131072
   329  	config.Eth.TxPool.Lifetime = 90 * time.Minute
   330  	config.Node.P2P.MaxPeers = 50
   331  	config.Metrics.Enabled = true
   332  	// --pprof is enabled in 'internal/debug/flags.go'
   333  }
   334  
   335  func setDefaultBorMainnetGethConfig(ctx *cli.Context, config *gethConfig) {
   336  	config.Node.P2P.ListenAddr = fmt.Sprintf(":%d", 30303)
   337  	config.Node.HTTPHost = "0.0.0.0"
   338  	config.Node.HTTPVirtualHosts = []string{"*"}
   339  	config.Node.HTTPCors = []string{"*"}
   340  	config.Node.HTTPPort = 8545
   341  	config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
   342  	config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
   343  	config.Eth.SyncMode = downloader.FullSync
   344  	config.Eth.NetworkId = 137
   345  	config.Eth.Miner.GasCeil = 20000000
   346  	//--miner.gastarget is depreceated, No longed used
   347  	config.Eth.TxPool.NoLocals = true
   348  	config.Eth.TxPool.AccountSlots = 16
   349  	config.Eth.TxPool.GlobalSlots = 131072
   350  	config.Eth.TxPool.AccountQueue = 64
   351  	config.Eth.TxPool.GlobalQueue = 131072
   352  	config.Eth.TxPool.Lifetime = 90 * time.Minute
   353  	config.Node.P2P.MaxPeers = 50
   354  	config.Metrics.Enabled = true
   355  	// --pprof is enabled in 'internal/debug/flags.go'
   356  }