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