github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/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  	"bufio"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"os"
    25  	"reflect"
    26  	"time"
    27  	"unicode"
    28  
    29  	"gopkg.in/urfave/cli.v1"
    30  
    31  	"github.com/ethereum/go-ethereum/accounts/external"
    32  	"github.com/ethereum/go-ethereum/accounts/keystore"
    33  	"github.com/ethereum/go-ethereum/accounts/scwallet"
    34  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    35  	"github.com/ethereum/go-ethereum/cmd/utils"
    36  	"github.com/ethereum/go-ethereum/eth/catalyst"
    37  	"github.com/ethereum/go-ethereum/eth/downloader"
    38  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    39  	"github.com/ethereum/go-ethereum/internal/ethapi"
    40  	"github.com/ethereum/go-ethereum/log"
    41  	"github.com/ethereum/go-ethereum/metrics"
    42  	"github.com/ethereum/go-ethereum/node"
    43  	"github.com/ethereum/go-ethereum/params"
    44  	"github.com/naoina/toml"
    45  )
    46  
    47  var (
    48  	dumpConfigCommand = cli.Command{
    49  		Action:      utils.MigrateFlags(dumpConfig),
    50  		Name:        "dumpconfig",
    51  		Usage:       "Show configuration values",
    52  		ArgsUsage:   "",
    53  		Flags:       append(nodeFlags, rpcFlags...),
    54  		Category:    "MISCELLANEOUS COMMANDS",
    55  		Description: `The dumpconfig command shows configuration values.`,
    56  	}
    57  
    58  	configFileFlag = cli.StringFlag{
    59  		Name:  "config",
    60  		Usage: "TOML configuration file",
    61  	}
    62  )
    63  
    64  // These settings ensure that TOML keys use the same names as Go struct fields.
    65  var tomlSettings = toml.Config{
    66  	NormFieldName: func(rt reflect.Type, key string) string {
    67  		return key
    68  	},
    69  	FieldToKey: func(rt reflect.Type, field string) string {
    70  		return field
    71  	},
    72  	MissingField: func(rt reflect.Type, field string) error {
    73  		id := fmt.Sprintf("%s.%s", rt.String(), field)
    74  		if deprecated(id) {
    75  			log.Warn("Config field is deprecated and won't have an effect", "name", id)
    76  			return nil
    77  		}
    78  		var link string
    79  		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
    80  			link = fmt.Sprintf(", see https://godoc.org/%s#%s for available fields", rt.PkgPath(), rt.Name())
    81  		}
    82  		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
    83  	},
    84  }
    85  
    86  type ethstatsConfig struct {
    87  	URL string `toml:",omitempty"`
    88  }
    89  
    90  type gethConfig struct {
    91  	Eth      ethconfig.Config
    92  	Node     node.Config
    93  	Ethstats ethstatsConfig
    94  	Metrics  metrics.Config
    95  }
    96  
    97  func loadConfig(file string, cfg *gethConfig) error {
    98  	f, err := os.Open(file)
    99  	if err != nil {
   100  		return err
   101  	}
   102  	defer f.Close()
   103  
   104  	err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
   105  	// Add file name to errors that have a line number.
   106  	if _, ok := err.(*toml.LineError); ok {
   107  		err = errors.New(file + ", " + err.Error())
   108  	}
   109  	return err
   110  }
   111  
   112  func defaultNodeConfig() node.Config {
   113  	cfg := node.DefaultConfig
   114  	cfg.Name = clientIdentifier
   115  	cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
   116  	cfg.HTTPModules = append(cfg.HTTPModules, "eth")
   117  	cfg.WSModules = append(cfg.WSModules, "eth")
   118  	cfg.IPCPath = clientIdentifier + ".ipc"
   119  	return cfg
   120  }
   121  
   122  // makeConfigNode loads geth configuration and creates a blank node instance.
   123  func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
   124  	// Load defaults.
   125  	cfg := gethConfig{
   126  		Eth:     ethconfig.Defaults,
   127  		Node:    defaultNodeConfig(),
   128  		Metrics: metrics.DefaultConfig,
   129  	}
   130  
   131  	// Load config file.
   132  	if file := ctx.GlobalString(configFileFlag.Name); file != "" {
   133  		if err := loadConfig(file, &cfg); err != nil {
   134  			utils.Fatalf("%v", err)
   135  		}
   136  	}
   137  
   138  	if ctx.GlobalIsSet(utils.MumbaiFlag.Name) {
   139  		setDefaultMumbaiGethConfig(ctx, &cfg)
   140  	}
   141  
   142  	if ctx.GlobalIsSet(utils.BorMainnetFlag.Name) {
   143  		setDefaultBorMainnetGethConfig(ctx, &cfg)
   144  	}
   145  
   146  	// Apply flags.
   147  	utils.SetNodeConfig(ctx, &cfg.Node)
   148  	stack, err := node.New(&cfg.Node)
   149  	if err != nil {
   150  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   151  	}
   152  	// Node doesn't by default populate account manager backends
   153  	if err := setAccountManagerBackends(stack); err != nil {
   154  		utils.Fatalf("Failed to set account manager backends: %v", err)
   155  	}
   156  
   157  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   158  	if ctx.GlobalIsSet(utils.EthStatsURLFlag.Name) {
   159  		cfg.Ethstats.URL = ctx.GlobalString(utils.EthStatsURLFlag.Name)
   160  	}
   161  	applyMetricConfig(ctx, &cfg)
   162  
   163  	// Set Bor config flags
   164  	utils.SetBorConfig(ctx, &cfg.Eth)
   165  
   166  	return stack, cfg
   167  }
   168  
   169  // makeFullNode loads geth configuration and creates the Ethereum backend.
   170  func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
   171  	stack, cfg := makeConfigNode(ctx)
   172  	if ctx.GlobalIsSet(utils.OverrideLondonFlag.Name) {
   173  		cfg.Eth.OverrideLondon = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideLondonFlag.Name))
   174  	}
   175  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   176  
   177  	// Configure catalyst.
   178  	if ctx.GlobalBool(utils.CatalystFlag.Name) {
   179  		if eth == nil {
   180  			utils.Fatalf("Catalyst does not work in light client mode.")
   181  		}
   182  		if err := catalyst.Register(stack, eth); err != nil {
   183  			utils.Fatalf("%v", err)
   184  		}
   185  	}
   186  
   187  	// Configure GraphQL if requested
   188  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   189  		utils.RegisterGraphQLService(stack, backend, cfg.Node)
   190  	}
   191  	// Add the Ethereum Stats daemon if requested.
   192  	if cfg.Ethstats.URL != "" {
   193  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   194  	}
   195  	return stack, backend
   196  }
   197  
   198  // dumpConfig is the dumpconfig command.
   199  func dumpConfig(ctx *cli.Context) error {
   200  	_, cfg := makeConfigNode(ctx)
   201  	comment := ""
   202  
   203  	if cfg.Eth.Genesis != nil {
   204  		cfg.Eth.Genesis = nil
   205  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   206  	}
   207  
   208  	out, err := tomlSettings.Marshal(&cfg)
   209  	if err != nil {
   210  		return err
   211  	}
   212  
   213  	dump := os.Stdout
   214  	if ctx.NArg() > 0 {
   215  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   216  		if err != nil {
   217  			return err
   218  		}
   219  		defer dump.Close()
   220  	}
   221  	dump.WriteString(comment)
   222  	dump.Write(out)
   223  
   224  	return nil
   225  }
   226  
   227  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   228  	if ctx.GlobalIsSet(utils.MetricsEnabledFlag.Name) {
   229  		cfg.Metrics.Enabled = ctx.GlobalBool(utils.MetricsEnabledFlag.Name)
   230  	}
   231  	if ctx.GlobalIsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   232  		cfg.Metrics.EnabledExpensive = ctx.GlobalBool(utils.MetricsEnabledExpensiveFlag.Name)
   233  	}
   234  	if ctx.GlobalIsSet(utils.MetricsHTTPFlag.Name) {
   235  		cfg.Metrics.HTTP = ctx.GlobalString(utils.MetricsHTTPFlag.Name)
   236  	}
   237  	if ctx.GlobalIsSet(utils.MetricsPortFlag.Name) {
   238  		cfg.Metrics.Port = ctx.GlobalInt(utils.MetricsPortFlag.Name)
   239  	}
   240  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   241  		cfg.Metrics.EnableInfluxDB = ctx.GlobalBool(utils.MetricsEnableInfluxDBFlag.Name)
   242  	}
   243  	if ctx.GlobalIsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   244  		cfg.Metrics.InfluxDBEndpoint = ctx.GlobalString(utils.MetricsInfluxDBEndpointFlag.Name)
   245  	}
   246  	if ctx.GlobalIsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   247  		cfg.Metrics.InfluxDBDatabase = ctx.GlobalString(utils.MetricsInfluxDBDatabaseFlag.Name)
   248  	}
   249  	if ctx.GlobalIsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   250  		cfg.Metrics.InfluxDBUsername = ctx.GlobalString(utils.MetricsInfluxDBUsernameFlag.Name)
   251  	}
   252  	if ctx.GlobalIsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   253  		cfg.Metrics.InfluxDBPassword = ctx.GlobalString(utils.MetricsInfluxDBPasswordFlag.Name)
   254  	}
   255  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   256  		cfg.Metrics.InfluxDBTags = ctx.GlobalString(utils.MetricsInfluxDBTagsFlag.Name)
   257  	}
   258  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   259  		cfg.Metrics.EnableInfluxDBV2 = ctx.GlobalBool(utils.MetricsEnableInfluxDBV2Flag.Name)
   260  	}
   261  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   262  		cfg.Metrics.InfluxDBToken = ctx.GlobalString(utils.MetricsInfluxDBTokenFlag.Name)
   263  	}
   264  	if ctx.GlobalIsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   265  		cfg.Metrics.InfluxDBBucket = ctx.GlobalString(utils.MetricsInfluxDBBucketFlag.Name)
   266  	}
   267  	if ctx.GlobalIsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   268  		cfg.Metrics.InfluxDBOrganization = ctx.GlobalString(utils.MetricsInfluxDBOrganizationFlag.Name)
   269  	}
   270  }
   271  
   272  func deprecated(field string) bool {
   273  	switch field {
   274  	case "ethconfig.Config.EVMInterpreter":
   275  		return true
   276  	case "ethconfig.Config.EWASMInterpreter":
   277  		return true
   278  	default:
   279  		return false
   280  	}
   281  }
   282  
   283  func setAccountManagerBackends(stack *node.Node) error {
   284  	conf := stack.Config()
   285  	am := stack.AccountManager()
   286  	keydir := stack.KeyStoreDir()
   287  	scryptN := keystore.StandardScryptN
   288  	scryptP := keystore.StandardScryptP
   289  	if conf.UseLightweightKDF {
   290  		scryptN = keystore.LightScryptN
   291  		scryptP = keystore.LightScryptP
   292  	}
   293  
   294  	// Assemble the supported backends
   295  	if len(conf.ExternalSigner) > 0 {
   296  		log.Info("Using external signer", "url", conf.ExternalSigner)
   297  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   298  			am.AddBackend(extapi)
   299  			return nil
   300  		} else {
   301  			return fmt.Errorf("error connecting to external signer: %v", err)
   302  		}
   303  	}
   304  
   305  	// For now, we're using EITHER external signer OR local signers.
   306  	// If/when we implement some form of lockfile for USB and keystore wallets,
   307  	// we can have both, but it's very confusing for the user to see the same
   308  	// accounts in both externally and locally, plus very racey.
   309  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   310  	if conf.USB {
   311  		// Start a USB hub for Ledger hardware wallets
   312  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   313  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   314  		} else {
   315  			am.AddBackend(ledgerhub)
   316  		}
   317  		// Start a USB hub for Trezor hardware wallets (HID version)
   318  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   319  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   320  		} else {
   321  			am.AddBackend(trezorhub)
   322  		}
   323  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   324  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   325  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   326  		} else {
   327  			am.AddBackend(trezorhub)
   328  		}
   329  	}
   330  	if len(conf.SmartCardDaemonPath) > 0 {
   331  		// Start a smart card hub
   332  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   333  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   334  		} else {
   335  			am.AddBackend(schub)
   336  		}
   337  	}
   338  
   339  	return nil
   340  }
   341  
   342  func setDefaultMumbaiGethConfig(ctx *cli.Context, config *gethConfig) {
   343  	config.Node.P2P.ListenAddr = fmt.Sprintf(":%d", 30303)
   344  	config.Node.HTTPHost = "0.0.0.0"
   345  	config.Node.HTTPVirtualHosts = []string{"*"}
   346  	config.Node.HTTPCors = []string{"*"}
   347  	config.Node.HTTPPort = 8545
   348  	config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
   349  	config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
   350  	config.Eth.SyncMode = downloader.FullSync
   351  	config.Eth.NetworkId = 80001
   352  	config.Eth.Miner.GasCeil = 20000000
   353  	//--miner.gastarget is depreceated, No longed used
   354  	config.Eth.TxPool.NoLocals = true
   355  	config.Eth.TxPool.AccountSlots = 16
   356  	config.Eth.TxPool.GlobalSlots = 131072
   357  	config.Eth.TxPool.AccountQueue = 64
   358  	config.Eth.TxPool.GlobalQueue = 131072
   359  	config.Eth.TxPool.Lifetime = 90 * time.Minute
   360  	config.Node.P2P.MaxPeers = 200
   361  	config.Metrics.Enabled = true
   362  	// --pprof is enabled in 'internal/debug/flags.go'
   363  }
   364  
   365  func setDefaultBorMainnetGethConfig(ctx *cli.Context, config *gethConfig) {
   366  	config.Node.P2P.ListenAddr = fmt.Sprintf(":%d", 30303)
   367  	config.Node.HTTPHost = "0.0.0.0"
   368  	config.Node.HTTPVirtualHosts = []string{"*"}
   369  	config.Node.HTTPCors = []string{"*"}
   370  	config.Node.HTTPPort = 8545
   371  	config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
   372  	config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
   373  	config.Eth.SyncMode = downloader.FullSync
   374  	config.Eth.NetworkId = 137
   375  	config.Eth.Miner.GasCeil = 20000000
   376  	//--miner.gastarget is depreceated, No longed used
   377  	config.Eth.TxPool.NoLocals = true
   378  	config.Eth.TxPool.AccountSlots = 16
   379  	config.Eth.TxPool.GlobalSlots = 131072
   380  	config.Eth.TxPool.AccountQueue = 64
   381  	config.Eth.TxPool.GlobalQueue = 131072
   382  	config.Eth.TxPool.Lifetime = 90 * time.Minute
   383  	config.Node.P2P.MaxPeers = 200
   384  	config.Metrics.Enabled = true
   385  	// --pprof is enabled in 'internal/debug/flags.go'
   386  }