github.com/daethereum/go-dae@v2.2.3+incompatible/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  	"github.com/urfave/cli/v2"
    29  
    30  	"github.com/daethereum/go-dae/accounts/external"
    31  	"github.com/daethereum/go-dae/accounts/keystore"
    32  	"github.com/daethereum/go-dae/accounts/scwallet"
    33  	"github.com/daethereum/go-dae/accounts/usbwallet"
    34  	"github.com/daethereum/go-dae/cmd/utils"
    35  	"github.com/daethereum/go-dae/core/rawdb"
    36  	"github.com/daethereum/go-dae/eth/ethconfig"
    37  	"github.com/daethereum/go-dae/internal/ethapi"
    38  	"github.com/daethereum/go-dae/internal/flags"
    39  	"github.com/daethereum/go-dae/log"
    40  	"github.com/daethereum/go-dae/metrics"
    41  	"github.com/daethereum/go-dae/node"
    42  	"github.com/daethereum/go-dae/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  	cfg := node.DefaultConfig
   113  	cfg.Name = clientIdentifier
   114  	cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
   115  	cfg.HTTPModules = append(cfg.HTTPModules, "eth")
   116  	cfg.WSModules = append(cfg.WSModules, "eth")
   117  	cfg.IPCPath = "geth.ipc"
   118  	return cfg
   119  }
   120  
   121  // makeConfigNode loads geth configuration and creates a blank node instance.
   122  func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
   123  	// Load defaults.
   124  	cfg := gethConfig{
   125  		Eth:     ethconfig.Defaults,
   126  		Node:    defaultNodeConfig(),
   127  		Metrics: metrics.DefaultConfig,
   128  	}
   129  
   130  	// Load config file.
   131  	if file := ctx.String(configFileFlag.Name); file != "" {
   132  		if err := loadConfig(file, &cfg); err != nil {
   133  			utils.Fatalf("%v", err)
   134  		}
   135  	}
   136  
   137  	// Apply flags.
   138  	utils.SetNodeConfig(ctx, &cfg.Node)
   139  	stack, err := node.New(&cfg.Node)
   140  	if err != nil {
   141  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   142  	}
   143  	// Node doesn't by default populate account manager backends
   144  	if err := setAccountManagerBackends(stack); err != nil {
   145  		utils.Fatalf("Failed to set account manager backends: %v", err)
   146  	}
   147  
   148  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   149  	if ctx.IsSet(utils.EthStatsURLFlag.Name) {
   150  		cfg.Ethstats.URL = ctx.String(utils.EthStatsURLFlag.Name)
   151  	}
   152  	applyMetricConfig(ctx, &cfg)
   153  
   154  	return stack, cfg
   155  }
   156  
   157  // makeFullNode loads geth configuration and creates the Ethereum backend.
   158  func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
   159  	stack, cfg := makeConfigNode(ctx)
   160  	if ctx.IsSet(utils.OverrideGrayGlacierFlag.Name) {
   161  		cfg.Eth.OverrideGrayGlacier = new(big.Int).SetUint64(ctx.Uint64(utils.OverrideGrayGlacierFlag.Name))
   162  	}
   163  	if ctx.IsSet(utils.OverrideTerminalTotalDifficulty.Name) {
   164  		cfg.Eth.OverrideTerminalTotalDifficulty = flags.GlobalBig(ctx, utils.OverrideTerminalTotalDifficulty.Name)
   165  	}
   166  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   167  	// Warn users to migrate if they have a legacy freezer format.
   168  	if eth != nil && !ctx.IsSet(utils.IgnoreLegacyReceiptsFlag.Name) {
   169  		firstIdx := uint64(0)
   170  		// Hack to speed up check for mainnet because we know
   171  		// the first non-empty block.
   172  		ghash := rawdb.ReadCanonicalHash(eth.ChainDb(), 0)
   173  		if cfg.Eth.NetworkId == 1 && ghash == params.MainnetGenesisHash {
   174  			firstIdx = 46147
   175  		}
   176  		isLegacy, _, err := dbHasLegacyReceipts(eth.ChainDb(), firstIdx)
   177  		if err != nil {
   178  			log.Error("Failed to check db for legacy receipts", "err", err)
   179  		} else if isLegacy {
   180  			stack.Close()
   181  			utils.Fatalf("Database has receipts with a legacy format. Please run `geth db freezer-migrate`.")
   182  		}
   183  	}
   184  
   185  	// Configure GraphQL if requested
   186  	if ctx.IsSet(utils.GraphQLEnabledFlag.Name) {
   187  		utils.RegisterGraphQLService(stack, backend, cfg.Node)
   188  	}
   189  	// Add the Ethereum Stats daemon if requested.
   190  	if cfg.Ethstats.URL != "" {
   191  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   192  	}
   193  	return stack, backend
   194  }
   195  
   196  // dumpConfig is the dumpconfig command.
   197  func dumpConfig(ctx *cli.Context) error {
   198  	_, cfg := makeConfigNode(ctx)
   199  	comment := ""
   200  
   201  	if cfg.Eth.Genesis != nil {
   202  		cfg.Eth.Genesis = nil
   203  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   204  	}
   205  
   206  	out, err := tomlSettings.Marshal(&cfg)
   207  	if err != nil {
   208  		return err
   209  	}
   210  
   211  	dump := os.Stdout
   212  	if ctx.NArg() > 0 {
   213  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   214  		if err != nil {
   215  			return err
   216  		}
   217  		defer dump.Close()
   218  	}
   219  	dump.WriteString(comment)
   220  	dump.Write(out)
   221  
   222  	return nil
   223  }
   224  
   225  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   226  	if ctx.IsSet(utils.MetricsEnabledFlag.Name) {
   227  		cfg.Metrics.Enabled = ctx.Bool(utils.MetricsEnabledFlag.Name)
   228  	}
   229  	if ctx.IsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   230  		cfg.Metrics.EnabledExpensive = ctx.Bool(utils.MetricsEnabledExpensiveFlag.Name)
   231  	}
   232  	if ctx.IsSet(utils.MetricsHTTPFlag.Name) {
   233  		cfg.Metrics.HTTP = ctx.String(utils.MetricsHTTPFlag.Name)
   234  	}
   235  	if ctx.IsSet(utils.MetricsPortFlag.Name) {
   236  		cfg.Metrics.Port = ctx.Int(utils.MetricsPortFlag.Name)
   237  	}
   238  	if ctx.IsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   239  		cfg.Metrics.EnableInfluxDB = ctx.Bool(utils.MetricsEnableInfluxDBFlag.Name)
   240  	}
   241  	if ctx.IsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   242  		cfg.Metrics.InfluxDBEndpoint = ctx.String(utils.MetricsInfluxDBEndpointFlag.Name)
   243  	}
   244  	if ctx.IsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   245  		cfg.Metrics.InfluxDBDatabase = ctx.String(utils.MetricsInfluxDBDatabaseFlag.Name)
   246  	}
   247  	if ctx.IsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   248  		cfg.Metrics.InfluxDBUsername = ctx.String(utils.MetricsInfluxDBUsernameFlag.Name)
   249  	}
   250  	if ctx.IsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   251  		cfg.Metrics.InfluxDBPassword = ctx.String(utils.MetricsInfluxDBPasswordFlag.Name)
   252  	}
   253  	if ctx.IsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   254  		cfg.Metrics.InfluxDBTags = ctx.String(utils.MetricsInfluxDBTagsFlag.Name)
   255  	}
   256  	if ctx.IsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   257  		cfg.Metrics.EnableInfluxDBV2 = ctx.Bool(utils.MetricsEnableInfluxDBV2Flag.Name)
   258  	}
   259  	if ctx.IsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   260  		cfg.Metrics.InfluxDBToken = ctx.String(utils.MetricsInfluxDBTokenFlag.Name)
   261  	}
   262  	if ctx.IsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   263  		cfg.Metrics.InfluxDBBucket = ctx.String(utils.MetricsInfluxDBBucketFlag.Name)
   264  	}
   265  	if ctx.IsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   266  		cfg.Metrics.InfluxDBOrganization = ctx.String(utils.MetricsInfluxDBOrganizationFlag.Name)
   267  	}
   268  }
   269  
   270  func deprecated(field string) bool {
   271  	switch field {
   272  	case "ethconfig.Config.EVMInterpreter":
   273  		return true
   274  	case "ethconfig.Config.EWASMInterpreter":
   275  		return true
   276  	default:
   277  		return false
   278  	}
   279  }
   280  
   281  func setAccountManagerBackends(stack *node.Node) error {
   282  	conf := stack.Config()
   283  	am := stack.AccountManager()
   284  	keydir := stack.KeyStoreDir()
   285  	scryptN := keystore.StandardScryptN
   286  	scryptP := keystore.StandardScryptP
   287  	if conf.UseLightweightKDF {
   288  		scryptN = keystore.LightScryptN
   289  		scryptP = keystore.LightScryptP
   290  	}
   291  
   292  	// Assemble the supported backends
   293  	if len(conf.ExternalSigner) > 0 {
   294  		log.Info("Using external signer", "url", conf.ExternalSigner)
   295  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   296  			am.AddBackend(extapi)
   297  			return nil
   298  		} else {
   299  			return fmt.Errorf("error connecting to external signer: %v", err)
   300  		}
   301  	}
   302  
   303  	// For now, we're using EITHER external signer OR local signers.
   304  	// If/when we implement some form of lockfile for USB and keystore wallets,
   305  	// we can have both, but it's very confusing for the user to see the same
   306  	// accounts in both externally and locally, plus very racey.
   307  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   308  	if conf.USB {
   309  		// Start a USB hub for Ledger hardware wallets
   310  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   311  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   312  		} else {
   313  			am.AddBackend(ledgerhub)
   314  		}
   315  		// Start a USB hub for Trezor hardware wallets (HID version)
   316  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   317  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   318  		} else {
   319  			am.AddBackend(trezorhub)
   320  		}
   321  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   322  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   323  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   324  		} else {
   325  			am.AddBackend(trezorhub)
   326  		}
   327  	}
   328  	if len(conf.SmartCardDaemonPath) > 0 {
   329  		// Start a smart card hub
   330  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   331  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   332  		} else {
   333  			am.AddBackend(schub)
   334  		}
   335  	}
   336  
   337  	return nil
   338  }