github.com/ethereum/go-ethereum@v1.10.9/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  	"unicode"
    27  
    28  	"gopkg.in/urfave/cli.v1"
    29  
    30  	"github.com/ethereum/go-ethereum/accounts/external"
    31  	"github.com/ethereum/go-ethereum/accounts/keystore"
    32  	"github.com/ethereum/go-ethereum/accounts/scwallet"
    33  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    34  	"github.com/ethereum/go-ethereum/cmd/utils"
    35  	"github.com/ethereum/go-ethereum/eth/catalyst"
    36  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    37  	"github.com/ethereum/go-ethereum/internal/ethapi"
    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:      utils.MigrateFlags(dumpConfig),
    48  		Name:        "dumpconfig",
    49  		Usage:       "Show configuration values",
    50  		ArgsUsage:   "",
    51  		Flags:       append(nodeFlags, rpcFlags...),
    52  		Category:    "MISCELLANEOUS COMMANDS",
    53  		Description: `The dumpconfig command shows configuration values.`,
    54  	}
    55  
    56  	configFileFlag = cli.StringFlag{
    57  		Name:  "config",
    58  		Usage: "TOML configuration file",
    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.GlobalString(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.GlobalIsSet(utils.EthStatsURLFlag.Name) {
   149  		cfg.Ethstats.URL = ctx.GlobalString(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.GlobalIsSet(utils.OverrideLondonFlag.Name) {
   160  		cfg.Eth.OverrideLondon = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideLondonFlag.Name))
   161  	}
   162  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   163  
   164  	// Configure catalyst.
   165  	if ctx.GlobalBool(utils.CatalystFlag.Name) {
   166  		if eth == nil {
   167  			utils.Fatalf("Catalyst does not work in light client mode.")
   168  		}
   169  		if err := catalyst.Register(stack, eth); err != nil {
   170  			utils.Fatalf("%v", err)
   171  		}
   172  	}
   173  
   174  	// Configure GraphQL if requested
   175  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   176  		utils.RegisterGraphQLService(stack, backend, cfg.Node)
   177  	}
   178  	// Add the Ethereum Stats daemon if requested.
   179  	if cfg.Ethstats.URL != "" {
   180  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   181  	}
   182  	return stack, backend
   183  }
   184  
   185  // dumpConfig is the dumpconfig command.
   186  func dumpConfig(ctx *cli.Context) error {
   187  	_, cfg := makeConfigNode(ctx)
   188  	comment := ""
   189  
   190  	if cfg.Eth.Genesis != nil {
   191  		cfg.Eth.Genesis = nil
   192  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   193  	}
   194  
   195  	out, err := tomlSettings.Marshal(&cfg)
   196  	if err != nil {
   197  		return err
   198  	}
   199  
   200  	dump := os.Stdout
   201  	if ctx.NArg() > 0 {
   202  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   203  		if err != nil {
   204  			return err
   205  		}
   206  		defer dump.Close()
   207  	}
   208  	dump.WriteString(comment)
   209  	dump.Write(out)
   210  
   211  	return nil
   212  }
   213  
   214  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   215  	if ctx.GlobalIsSet(utils.MetricsEnabledFlag.Name) {
   216  		cfg.Metrics.Enabled = ctx.GlobalBool(utils.MetricsEnabledFlag.Name)
   217  	}
   218  	if ctx.GlobalIsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   219  		cfg.Metrics.EnabledExpensive = ctx.GlobalBool(utils.MetricsEnabledExpensiveFlag.Name)
   220  	}
   221  	if ctx.GlobalIsSet(utils.MetricsHTTPFlag.Name) {
   222  		cfg.Metrics.HTTP = ctx.GlobalString(utils.MetricsHTTPFlag.Name)
   223  	}
   224  	if ctx.GlobalIsSet(utils.MetricsPortFlag.Name) {
   225  		cfg.Metrics.Port = ctx.GlobalInt(utils.MetricsPortFlag.Name)
   226  	}
   227  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   228  		cfg.Metrics.EnableInfluxDB = ctx.GlobalBool(utils.MetricsEnableInfluxDBFlag.Name)
   229  	}
   230  	if ctx.GlobalIsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   231  		cfg.Metrics.InfluxDBEndpoint = ctx.GlobalString(utils.MetricsInfluxDBEndpointFlag.Name)
   232  	}
   233  	if ctx.GlobalIsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   234  		cfg.Metrics.InfluxDBDatabase = ctx.GlobalString(utils.MetricsInfluxDBDatabaseFlag.Name)
   235  	}
   236  	if ctx.GlobalIsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   237  		cfg.Metrics.InfluxDBUsername = ctx.GlobalString(utils.MetricsInfluxDBUsernameFlag.Name)
   238  	}
   239  	if ctx.GlobalIsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   240  		cfg.Metrics.InfluxDBPassword = ctx.GlobalString(utils.MetricsInfluxDBPasswordFlag.Name)
   241  	}
   242  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   243  		cfg.Metrics.InfluxDBTags = ctx.GlobalString(utils.MetricsInfluxDBTagsFlag.Name)
   244  	}
   245  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   246  		cfg.Metrics.EnableInfluxDBV2 = ctx.GlobalBool(utils.MetricsEnableInfluxDBV2Flag.Name)
   247  	}
   248  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   249  		cfg.Metrics.InfluxDBToken = ctx.GlobalString(utils.MetricsInfluxDBTokenFlag.Name)
   250  	}
   251  	if ctx.GlobalIsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   252  		cfg.Metrics.InfluxDBBucket = ctx.GlobalString(utils.MetricsInfluxDBBucketFlag.Name)
   253  	}
   254  	if ctx.GlobalIsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   255  		cfg.Metrics.InfluxDBOrganization = ctx.GlobalString(utils.MetricsInfluxDBOrganizationFlag.Name)
   256  	}
   257  }
   258  
   259  func deprecated(field string) bool {
   260  	switch field {
   261  	case "ethconfig.Config.EVMInterpreter":
   262  		return true
   263  	case "ethconfig.Config.EWASMInterpreter":
   264  		return true
   265  	default:
   266  		return false
   267  	}
   268  }
   269  
   270  func setAccountManagerBackends(stack *node.Node) error {
   271  	conf := stack.Config()
   272  	am := stack.AccountManager()
   273  	keydir := stack.KeyStoreDir()
   274  	scryptN := keystore.StandardScryptN
   275  	scryptP := keystore.StandardScryptP
   276  	if conf.UseLightweightKDF {
   277  		scryptN = keystore.LightScryptN
   278  		scryptP = keystore.LightScryptP
   279  	}
   280  
   281  	// Assemble the supported backends
   282  	if len(conf.ExternalSigner) > 0 {
   283  		log.Info("Using external signer", "url", conf.ExternalSigner)
   284  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   285  			am.AddBackend(extapi)
   286  			return nil
   287  		} else {
   288  			return fmt.Errorf("error connecting to external signer: %v", err)
   289  		}
   290  	}
   291  
   292  	// For now, we're using EITHER external signer OR local signers.
   293  	// If/when we implement some form of lockfile for USB and keystore wallets,
   294  	// we can have both, but it's very confusing for the user to see the same
   295  	// accounts in both externally and locally, plus very racey.
   296  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   297  	if conf.USB {
   298  		// Start a USB hub for Ledger hardware wallets
   299  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   300  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   301  		} else {
   302  			am.AddBackend(ledgerhub)
   303  		}
   304  		// Start a USB hub for Trezor hardware wallets (HID version)
   305  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   306  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   307  		} else {
   308  			am.AddBackend(trezorhub)
   309  		}
   310  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   311  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   312  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   313  		} else {
   314  			am.AddBackend(trezorhub)
   315  		}
   316  	}
   317  	if len(conf.SmartCardDaemonPath) > 0 {
   318  		// Start a smart card hub
   319  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   320  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   321  		} else {
   322  			am.AddBackend(schub)
   323  		}
   324  	}
   325  
   326  	return nil
   327  }