github.com/electroneum/electroneum-sc@v0.0.0-20230105223411-3bc1d078281e/cmd/etn-sc/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/electroneum/electroneum-sc/accounts/external"
    31  	"github.com/electroneum/electroneum-sc/accounts/keystore"
    32  	"github.com/electroneum/electroneum-sc/accounts/scwallet"
    33  	"github.com/electroneum/electroneum-sc/accounts/usbwallet"
    34  	"github.com/electroneum/electroneum-sc/cmd/utils"
    35  	"github.com/electroneum/electroneum-sc/eth"
    36  	"github.com/electroneum/electroneum-sc/eth/ethconfig"
    37  	"github.com/electroneum/electroneum-sc/internal/ethapi"
    38  	"github.com/electroneum/electroneum-sc/log"
    39  	"github.com/electroneum/electroneum-sc/metrics"
    40  	"github.com/electroneum/electroneum-sc/node"
    41  	"github.com/electroneum/electroneum-sc/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:       utils.GroupFlags(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 = "etn-sc.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.OverrideArrowGlacierFlag.Name) {
   160  		cfg.Eth.OverrideArrowGlacier = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideArrowGlacierFlag.Name))
   161  	}
   162  	if ctx.GlobalIsSet(utils.OverrideTerminalTotalDifficulty.Name) {
   163  		cfg.Eth.OverrideTerminalTotalDifficulty = utils.GlobalBig(ctx, utils.OverrideTerminalTotalDifficulty.Name)
   164  	}
   165  	backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
   166  	// Warn users to migrate if they have a legacy freezer format.
   167  	if eth != nil {
   168  		isLegacy, _, err := dbHasLegacyReceipts(eth.ChainDb(), uint64(0))
   169  		if err != nil {
   170  			log.Error("Failed to check db for legacy receipts", "err", err)
   171  		} else if isLegacy {
   172  			log.Warn("Database has receipts with a legacy format. Please run `geth db freezer-migrate`.")
   173  		}
   174  	}
   175  
   176  	// Configure GraphQL if requested
   177  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   178  		utils.RegisterGraphQLService(stack, backend, cfg.Node)
   179  	}
   180  	// Add the Ethereum Stats daemon if requested.
   181  	if cfg.Ethstats.URL != "" {
   182  		utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)
   183  	}
   184  	return stack, backend
   185  }
   186  
   187  // dumpConfig is the dumpconfig command.
   188  func dumpConfig(ctx *cli.Context) error {
   189  	_, cfg := makeConfigNode(ctx)
   190  	comment := ""
   191  
   192  	if cfg.Eth.Genesis != nil {
   193  		cfg.Eth.Genesis = nil
   194  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   195  	}
   196  
   197  	out, err := tomlSettings.Marshal(&cfg)
   198  	if err != nil {
   199  		return err
   200  	}
   201  
   202  	dump := os.Stdout
   203  	if ctx.NArg() > 0 {
   204  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   205  		if err != nil {
   206  			return err
   207  		}
   208  		defer dump.Close()
   209  	}
   210  	dump.WriteString(comment)
   211  	dump.Write(out)
   212  
   213  	return nil
   214  }
   215  
   216  func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) {
   217  	if ctx.GlobalIsSet(utils.MetricsEnabledFlag.Name) {
   218  		cfg.Metrics.Enabled = ctx.GlobalBool(utils.MetricsEnabledFlag.Name)
   219  	}
   220  	if ctx.GlobalIsSet(utils.MetricsEnabledExpensiveFlag.Name) {
   221  		cfg.Metrics.EnabledExpensive = ctx.GlobalBool(utils.MetricsEnabledExpensiveFlag.Name)
   222  	}
   223  	if ctx.GlobalIsSet(utils.MetricsHTTPFlag.Name) {
   224  		cfg.Metrics.HTTP = ctx.GlobalString(utils.MetricsHTTPFlag.Name)
   225  	}
   226  	if ctx.GlobalIsSet(utils.MetricsPortFlag.Name) {
   227  		cfg.Metrics.Port = ctx.GlobalInt(utils.MetricsPortFlag.Name)
   228  	}
   229  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBFlag.Name) {
   230  		cfg.Metrics.EnableInfluxDB = ctx.GlobalBool(utils.MetricsEnableInfluxDBFlag.Name)
   231  	}
   232  	if ctx.GlobalIsSet(utils.MetricsInfluxDBEndpointFlag.Name) {
   233  		cfg.Metrics.InfluxDBEndpoint = ctx.GlobalString(utils.MetricsInfluxDBEndpointFlag.Name)
   234  	}
   235  	if ctx.GlobalIsSet(utils.MetricsInfluxDBDatabaseFlag.Name) {
   236  		cfg.Metrics.InfluxDBDatabase = ctx.GlobalString(utils.MetricsInfluxDBDatabaseFlag.Name)
   237  	}
   238  	if ctx.GlobalIsSet(utils.MetricsInfluxDBUsernameFlag.Name) {
   239  		cfg.Metrics.InfluxDBUsername = ctx.GlobalString(utils.MetricsInfluxDBUsernameFlag.Name)
   240  	}
   241  	if ctx.GlobalIsSet(utils.MetricsInfluxDBPasswordFlag.Name) {
   242  		cfg.Metrics.InfluxDBPassword = ctx.GlobalString(utils.MetricsInfluxDBPasswordFlag.Name)
   243  	}
   244  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTagsFlag.Name) {
   245  		cfg.Metrics.InfluxDBTags = ctx.GlobalString(utils.MetricsInfluxDBTagsFlag.Name)
   246  	}
   247  	if ctx.GlobalIsSet(utils.MetricsEnableInfluxDBV2Flag.Name) {
   248  		cfg.Metrics.EnableInfluxDBV2 = ctx.GlobalBool(utils.MetricsEnableInfluxDBV2Flag.Name)
   249  	}
   250  	if ctx.GlobalIsSet(utils.MetricsInfluxDBTokenFlag.Name) {
   251  		cfg.Metrics.InfluxDBToken = ctx.GlobalString(utils.MetricsInfluxDBTokenFlag.Name)
   252  	}
   253  	if ctx.GlobalIsSet(utils.MetricsInfluxDBBucketFlag.Name) {
   254  		cfg.Metrics.InfluxDBBucket = ctx.GlobalString(utils.MetricsInfluxDBBucketFlag.Name)
   255  	}
   256  	if ctx.GlobalIsSet(utils.MetricsInfluxDBOrganizationFlag.Name) {
   257  		cfg.Metrics.InfluxDBOrganization = ctx.GlobalString(utils.MetricsInfluxDBOrganizationFlag.Name)
   258  	}
   259  }
   260  
   261  // ibftValidateEthService checks ibft features that depend on the ethereum service
   262  func ibftValidateEthService(stack *node.Node) {
   263  	var ethereum *eth.Ethereum
   264  
   265  	err := stack.Lifecycle(&ethereum)
   266  	if err != nil {
   267  		utils.Fatalf("Error retrieving Ethereum service: %v", err)
   268  	}
   269  
   270  	ibftValidateConsensus(ethereum)
   271  }
   272  
   273  // ibftValidateConsensus checks if a consensus was used. The node is killed if consensus was not used
   274  func ibftValidateConsensus(ethereum *eth.Ethereum) {
   275  	if ethereum.BlockChain().Config().IBFT == nil && ethereum.BlockChain().Config().Clique == nil {
   276  		utils.Fatalf("Consensus not specified. Exiting!!")
   277  	}
   278  }
   279  
   280  func deprecated(field string) bool {
   281  	switch field {
   282  	case "ethconfig.Config.EVMInterpreter":
   283  		return true
   284  	case "ethconfig.Config.EWASMInterpreter":
   285  		return true
   286  	default:
   287  		return false
   288  	}
   289  }
   290  
   291  func setAccountManagerBackends(stack *node.Node) error {
   292  	conf := stack.Config()
   293  	am := stack.AccountManager()
   294  	keydir := stack.KeyStoreDir()
   295  	scryptN := keystore.StandardScryptN
   296  	scryptP := keystore.StandardScryptP
   297  	if conf.UseLightweightKDF {
   298  		scryptN = keystore.LightScryptN
   299  		scryptP = keystore.LightScryptP
   300  	}
   301  
   302  	// Assemble the supported backends
   303  	if len(conf.ExternalSigner) > 0 {
   304  		log.Info("Using external signer", "url", conf.ExternalSigner)
   305  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   306  			am.AddBackend(extapi)
   307  			return nil
   308  		} else {
   309  			return fmt.Errorf("error connecting to external signer: %v", err)
   310  		}
   311  	}
   312  
   313  	// For now, we're using EITHER external signer OR local signers.
   314  	// If/when we implement some form of lockfile for USB and keystore wallets,
   315  	// we can have both, but it's very confusing for the user to see the same
   316  	// accounts in both externally and locally, plus very racey.
   317  	am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP))
   318  	if conf.USB {
   319  		// Start a USB hub for Ledger hardware wallets
   320  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   321  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   322  		} else {
   323  			am.AddBackend(ledgerhub)
   324  		}
   325  		// Start a USB hub for Trezor hardware wallets (HID version)
   326  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   327  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   328  		} else {
   329  			am.AddBackend(trezorhub)
   330  		}
   331  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   332  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   333  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   334  		} else {
   335  			am.AddBackend(trezorhub)
   336  		}
   337  	}
   338  	if len(conf.SmartCardDaemonPath) > 0 {
   339  		// Start a smart card hub
   340  		if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   341  			log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   342  		} else {
   343  			am.AddBackend(schub)
   344  		}
   345  	}
   346  
   347  	return nil
   348  }