github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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  	"os"
    24  	"reflect"
    25  	"unicode"
    26  
    27  	"github.com/urfave/cli/v2"
    28  
    29  	"github.com/ethereum/go-ethereum/accounts/external"
    30  	"github.com/ethereum/go-ethereum/accounts/keystore"
    31  	"github.com/ethereum/go-ethereum/accounts/scwallet"
    32  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    33  	"github.com/ethereum/go-ethereum/cmd/utils"
    34  	"github.com/ethereum/go-ethereum/core/rawdb"
    35  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    36  	"github.com/ethereum/go-ethereum/internal/ethapi"
    37  	"github.com/ethereum/go-ethereum/internal/flags"
    38  	"github.com/ethereum/go-ethereum/internal/version"
    39  	"github.com/ethereum/go-ethereum/log"
    40  	"github.com/ethereum/go-ethereum/metrics"
    41  	"github.com/ethereum/go-ethereum/node"
    42  	"github.com/ethereum/go-ethereum/params"
    43  	"github.com/naoina/toml"
    44  )
    45  
    46  var (
    47  	dumpConfigCommand = &cli.Command{
    48  		Action:      dumpConfig,
    49  		Name:        "dumpconfig",
    50  		Usage:       "Show configuration values",
    51  		ArgsUsage:   "",
    52  		Flags:       flags.Merge(nodeFlags, rpcFlags),
    53  		Description: `The dumpconfig command shows configuration values.`,
    54  	}
    55  
    56  	configFileFlag = &cli.StringFlag{
    57  		Name:     "config",
    58  		Usage:    "TOML configuration file",
    59  		Category: flags.EthCategory,
    60  	}
    61  )
    62  
    63  // These settings ensure that TOML keys use the same names as Go struct fields.
    64  var tomlSettings = toml.Config{
    65  	NormFieldName: func(rt reflect.Type, key string) string {
    66  		return key
    67  	},
    68  	FieldToKey: func(rt reflect.Type, field string) string {
    69  		return field
    70  	},
    71  	MissingField: func(rt reflect.Type, field string) error {
    72  		id := fmt.Sprintf("%s.%s", rt.String(), field)
    73  		if deprecated(id) {
    74  			log.Warn("Config field is deprecated and won't have an effect", "name", id)
    75  			return nil
    76  		}
    77  		var link string
    78  		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
    79  			link = fmt.Sprintf(", see https://godoc.org/%s#%s for available fields", rt.PkgPath(), rt.Name())
    80  		}
    81  		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
    82  	},
    83  }
    84  
    85  type ethstatsConfig struct {
    86  	URL string `toml:",omitempty"`
    87  }
    88  
    89  type gethConfig struct {
    90  	Eth      ethconfig.Config
    91  	Node     node.Config
    92  	Ethstats ethstatsConfig
    93  	Metrics  metrics.Config
    94  }
    95  
    96  func loadConfig(file string, cfg *gethConfig) error {
    97  	f, err := os.Open(file)
    98  	if err != nil {
    99  		return err
   100  	}
   101  	defer f.Close()
   102  
   103  	err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
   104  	// Add file name to errors that have a line number.
   105  	if _, ok := err.(*toml.LineError); ok {
   106  		err = errors.New(file + ", " + err.Error())
   107  	}
   108  	return err
   109  }
   110  
   111  func defaultNodeConfig() node.Config {
   112  	git, _ := version.VCS()
   113  	cfg := node.DefaultConfig
   114  	cfg.Name = clientIdentifier
   115  	cfg.Version = params.VersionWithCommit(git.Commit, git.Date)
   116  	cfg.HTTPModules = append(cfg.HTTPModules, "eth")
   117  	cfg.WSModules = append(cfg.WSModules, "eth")
   118  	cfg.IPCPath = "geth.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.String(configFileFlag.Name); file != "" {
   133  		if err := loadConfig(file, &cfg); err != nil {
   134  			utils.Fatalf("%v", err)
   135  		}
   136  	}
   137  
   138  	// Apply flags.
   139  	utils.SetNodeConfig(ctx, &cfg.Node)
   140  	stack, err := node.New(&cfg.Node)
   141  	if err != nil {
   142  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   143  	}
   144  	// Node doesn't by default populate account manager backends
   145  	if err := setAccountManagerBackends(stack); err != nil {
   146  		utils.Fatalf("Failed to set account manager backends: %v", err)
   147  	}
   148  
   149  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   150  	if ctx.IsSet(utils.EthStatsURLFlag.Name) {
   151  		cfg.Ethstats.URL = ctx.String(utils.EthStatsURLFlag.Name)
   152  	}
   153  	applyMetricConfig(ctx, &cfg)
   154  
   155  	return stack, cfg
   156  }
   157  
   158  // makeFullNode loads geth configuration and creates the Ethereum backend.
   159  func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
   160  	stack, cfg := makeConfigNode(ctx)
   161  	if ctx.IsSet(utils.OverrideTerminalTotalDifficulty.Name) {
   162  		cfg.Eth.OverrideTerminalTotalDifficulty = flags.GlobalBig(ctx, utils.OverrideTerminalTotalDifficulty.Name)
   163  	}
   164  	if ctx.IsSet(utils.OverrideTerminalTotalDifficultyPassed.Name) {
   165  		override := ctx.Bool(utils.OverrideTerminalTotalDifficultyPassed.Name)
   166  		cfg.Eth.OverrideTerminalTotalDifficultyPassed = &override
   167  	}
   168  
   169  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   170  
   171  	// Warn users to migrate if they have a legacy freezer format.
   172  	if eth != nil && !ctx.IsSet(utils.IgnoreLegacyReceiptsFlag.Name) {
   173  		firstIdx := uint64(0)
   174  		// Hack to speed up check for mainnet because we know
   175  		// the first non-empty block.
   176  		ghash := rawdb.ReadCanonicalHash(eth.ChainDb(), 0)
   177  		if cfg.Eth.NetworkId == 1 && ghash == params.MainnetGenesisHash {
   178  			firstIdx = 46147
   179  		}
   180  		isLegacy, firstLegacy, err := dbHasLegacyReceipts(eth.ChainDb(), firstIdx)
   181  		if err != nil {
   182  			log.Error("Failed to check db for legacy receipts", "err", err)
   183  		} else if isLegacy {
   184  			stack.Close()
   185  			log.Error("Database has receipts with a legacy format", "firstLegacy", firstLegacy)
   186  			utils.Fatalf("Aborting. Please run `geth db freezer-migrate`.")
   187  		}
   188  	}
   189  
   190  	// Configure log filter RPC API.
   191  	filterSystem := utils.RegisterFilterAPI(stack, backend, &cfg.Eth)
   192  
   193  	// Configure GraphQL if requested.
   194  	if ctx.IsSet(utils.GraphQLEnabledFlag.Name) {
   195  		utils.RegisterGraphQLService(stack, backend, filterSystem, &cfg.Node)
   196  	}
   197  
   198  	// Add the Ethereum Stats daemon if requested.
   199  	if cfg.Ethstats.URL != "" {
   200  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   201  	}
   202  	return stack, backend
   203  }
   204  
   205  // dumpConfig is the dumpconfig command.
   206  func dumpConfig(ctx *cli.Context) error {
   207  	_, cfg := makeConfigNode(ctx)
   208  	comment := ""
   209  
   210  	if cfg.Eth.Genesis != nil {
   211  		cfg.Eth.Genesis = nil
   212  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   213  	}
   214  
   215  	out, err := tomlSettings.Marshal(&cfg)
   216  	if err != nil {
   217  		return err
   218  	}
   219  
   220  	dump := os.Stdout
   221  	if ctx.NArg() > 0 {
   222  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   223  		if err != nil {
   224  			return err
   225  		}
   226  		defer dump.Close()
   227  	}
   228  	dump.WriteString(comment)
   229  	dump.Write(out)
   230  
   231  	return nil
   232  }
   233  
   234  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   235  	if ctx.IsSet(utils.MetricsEnabledFlag.Name) {
   236  		cfg.Metrics.Enabled = ctx.Bool(utils.MetricsEnabledFlag.Name)
   237  	}
   238  	if ctx.IsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   239  		cfg.Metrics.EnabledExpensive = ctx.Bool(utils.MetricsEnabledExpensiveFlag.Name)
   240  	}
   241  	if ctx.IsSet(utils.MetricsHTTPFlag.Name) {
   242  		cfg.Metrics.HTTP = ctx.String(utils.MetricsHTTPFlag.Name)
   243  	}
   244  	if ctx.IsSet(utils.MetricsPortFlag.Name) {
   245  		cfg.Metrics.Port = ctx.Int(utils.MetricsPortFlag.Name)
   246  	}
   247  	if ctx.IsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   248  		cfg.Metrics.EnableInfluxDB = ctx.Bool(utils.MetricsEnableInfluxDBFlag.Name)
   249  	}
   250  	if ctx.IsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   251  		cfg.Metrics.InfluxDBEndpoint = ctx.String(utils.MetricsInfluxDBEndpointFlag.Name)
   252  	}
   253  	if ctx.IsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   254  		cfg.Metrics.InfluxDBDatabase = ctx.String(utils.MetricsInfluxDBDatabaseFlag.Name)
   255  	}
   256  	if ctx.IsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   257  		cfg.Metrics.InfluxDBUsername = ctx.String(utils.MetricsInfluxDBUsernameFlag.Name)
   258  	}
   259  	if ctx.IsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   260  		cfg.Metrics.InfluxDBPassword = ctx.String(utils.MetricsInfluxDBPasswordFlag.Name)
   261  	}
   262  	if ctx.IsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   263  		cfg.Metrics.InfluxDBTags = ctx.String(utils.MetricsInfluxDBTagsFlag.Name)
   264  	}
   265  	if ctx.IsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   266  		cfg.Metrics.EnableInfluxDBV2 = ctx.Bool(utils.MetricsEnableInfluxDBV2Flag.Name)
   267  	}
   268  	if ctx.IsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   269  		cfg.Metrics.InfluxDBToken = ctx.String(utils.MetricsInfluxDBTokenFlag.Name)
   270  	}
   271  	if ctx.IsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   272  		cfg.Metrics.InfluxDBBucket = ctx.String(utils.MetricsInfluxDBBucketFlag.Name)
   273  	}
   274  	if ctx.IsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   275  		cfg.Metrics.InfluxDBOrganization = ctx.String(utils.MetricsInfluxDBOrganizationFlag.Name)
   276  	}
   277  }
   278  
   279  func deprecated(field string) bool {
   280  	switch field {
   281  	case "ethconfig.Config.EVMInterpreter":
   282  		return true
   283  	case "ethconfig.Config.EWASMInterpreter":
   284  		return true
   285  	default:
   286  		return false
   287  	}
   288  }
   289  
   290  func setAccountManagerBackends(stack *node.Node) error {
   291  	conf := stack.Config()
   292  	am := stack.AccountManager()
   293  	keydir := stack.KeyStoreDir()
   294  	scryptN := keystore.StandardScryptN
   295  	scryptP := keystore.StandardScryptP
   296  	if conf.UseLightweightKDF {
   297  		scryptN = keystore.LightScryptN
   298  		scryptP = keystore.LightScryptP
   299  	}
   300  
   301  	// Assemble the supported backends
   302  	if len(conf.ExternalSigner) > 0 {
   303  		log.Info("Using external signer", "url", conf.ExternalSigner)
   304  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   305  			am.AddBackend(extapi)
   306  			return nil
   307  		} else {
   308  			return fmt.Errorf("error connecting to external signer: %v", err)
   309  		}
   310  	}
   311  
   312  	// For now, we're using EITHER external signer OR local signers.
   313  	// If/when we implement some form of lockfile for USB and keystore wallets,
   314  	// we can have both, but it's very confusing for the user to see the same
   315  	// accounts in both externally and locally, plus very racey.
   316  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   317  	if conf.USB {
   318  		// Start a USB hub for Ledger hardware wallets
   319  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   320  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   321  		} else {
   322  			am.AddBackend(ledgerhub)
   323  		}
   324  		// Start a USB hub for Trezor hardware wallets (HID version)
   325  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   326  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   327  		} else {
   328  			am.AddBackend(trezorhub)
   329  		}
   330  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   331  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   332  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   333  		} else {
   334  			am.AddBackend(trezorhub)
   335  		}
   336  	}
   337  	if len(conf.SmartCardDaemonPath) > 0 {
   338  		// Start a smart card hub
   339  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   340  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   341  		} else {
   342  			am.AddBackend(schub)
   343  		}
   344  	}
   345  
   346  	return nil
   347  }