github.com/snowblossomcoin/go-ethereum@v1.9.25/node/config.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser 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  // The go-ethereum library 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 Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package node
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"os"
    24  	"path/filepath"
    25  	"runtime"
    26  	"strings"
    27  	"sync"
    28  
    29  	"github.com/ethereum/go-ethereum/accounts"
    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/common"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/log"
    37  	"github.com/ethereum/go-ethereum/p2p"
    38  	"github.com/ethereum/go-ethereum/p2p/enode"
    39  	"github.com/ethereum/go-ethereum/rpc"
    40  )
    41  
    42  const (
    43  	datadirPrivateKey      = "nodekey"            // Path within the datadir to the node's private key
    44  	datadirDefaultKeyStore = "keystore"           // Path within the datadir to the keystore
    45  	datadirStaticNodes     = "static-nodes.json"  // Path within the datadir to the static node list
    46  	datadirTrustedNodes    = "trusted-nodes.json" // Path within the datadir to the trusted node list
    47  	datadirNodeDatabase    = "nodes"              // Path within the datadir to store the node infos
    48  )
    49  
    50  // Config represents a small collection of configuration values to fine tune the
    51  // P2P network layer of a protocol stack. These values can be further extended by
    52  // all registered services.
    53  type Config struct {
    54  	// Name sets the instance name of the node. It must not contain the / character and is
    55  	// used in the devp2p node identifier. The instance name of geth is "geth". If no
    56  	// value is specified, the basename of the current executable is used.
    57  	Name string `toml:"-"`
    58  
    59  	// UserIdent, if set, is used as an additional component in the devp2p node identifier.
    60  	UserIdent string `toml:",omitempty"`
    61  
    62  	// Version should be set to the version number of the program. It is used
    63  	// in the devp2p node identifier.
    64  	Version string `toml:"-"`
    65  
    66  	// DataDir is the file system folder the node should use for any data storage
    67  	// requirements. The configured data directory will not be directly shared with
    68  	// registered services, instead those can use utility methods to create/access
    69  	// databases or flat files. This enables ephemeral nodes which can fully reside
    70  	// in memory.
    71  	DataDir string
    72  
    73  	// Configuration of peer-to-peer networking.
    74  	P2P p2p.Config
    75  
    76  	// KeyStoreDir is the file system folder that contains private keys. The directory can
    77  	// be specified as a relative path, in which case it is resolved relative to the
    78  	// current directory.
    79  	//
    80  	// If KeyStoreDir is empty, the default location is the "keystore" subdirectory of
    81  	// DataDir. If DataDir is unspecified and KeyStoreDir is empty, an ephemeral directory
    82  	// is created by New and destroyed when the node is stopped.
    83  	KeyStoreDir string `toml:",omitempty"`
    84  
    85  	// ExternalSigner specifies an external URI for a clef-type signer
    86  	ExternalSigner string `toml:",omitempty"`
    87  
    88  	// UseLightweightKDF lowers the memory and CPU requirements of the key store
    89  	// scrypt KDF at the expense of security.
    90  	UseLightweightKDF bool `toml:",omitempty"`
    91  
    92  	// InsecureUnlockAllowed allows user to unlock accounts in unsafe http environment.
    93  	InsecureUnlockAllowed bool `toml:",omitempty"`
    94  
    95  	// NoUSB disables hardware wallet monitoring and connectivity.
    96  	NoUSB bool `toml:",omitempty"`
    97  
    98  	// SmartCardDaemonPath is the path to the smartcard daemon's socket
    99  	SmartCardDaemonPath string `toml:",omitempty"`
   100  
   101  	// IPCPath is the requested location to place the IPC endpoint. If the path is
   102  	// a simple file name, it is placed inside the data directory (or on the root
   103  	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
   104  	// relative), then that specific path is enforced. An empty path disables IPC.
   105  	IPCPath string
   106  
   107  	// HTTPHost is the host interface on which to start the HTTP RPC server. If this
   108  	// field is empty, no HTTP API endpoint will be started.
   109  	HTTPHost string
   110  
   111  	// HTTPPort is the TCP port number on which to start the HTTP RPC server. The
   112  	// default zero value is/ valid and will pick a port number randomly (useful
   113  	// for ephemeral nodes).
   114  	HTTPPort int `toml:",omitempty"`
   115  
   116  	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
   117  	// clients. Please be aware that CORS is a browser enforced security, it's fully
   118  	// useless for custom HTTP clients.
   119  	HTTPCors []string `toml:",omitempty"`
   120  
   121  	// HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
   122  	// This is by default {'localhost'}. Using this prevents attacks like
   123  	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
   124  	// origin. These attacks do not utilize CORS, since they are not cross-domain.
   125  	// By explicitly checking the Host-header, the server will not allow requests
   126  	// made against the server with a malicious host domain.
   127  	// Requests using ip address directly are not affected
   128  	HTTPVirtualHosts []string `toml:",omitempty"`
   129  
   130  	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
   131  	// If the module list is empty, all RPC API endpoints designated public will be
   132  	// exposed.
   133  	HTTPModules []string
   134  
   135  	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
   136  	// interface.
   137  	HTTPTimeouts rpc.HTTPTimeouts
   138  
   139  	// WSHost is the host interface on which to start the websocket RPC server. If
   140  	// this field is empty, no websocket API endpoint will be started.
   141  	WSHost string
   142  
   143  	// WSPort is the TCP port number on which to start the websocket RPC server. The
   144  	// default zero value is/ valid and will pick a port number randomly (useful for
   145  	// ephemeral nodes).
   146  	WSPort int `toml:",omitempty"`
   147  
   148  	// WSOrigins is the list of domain to accept websocket requests from. Please be
   149  	// aware that the server can only act upon the HTTP request the client sends and
   150  	// cannot verify the validity of the request header.
   151  	WSOrigins []string `toml:",omitempty"`
   152  
   153  	// WSModules is a list of API modules to expose via the websocket RPC interface.
   154  	// If the module list is empty, all RPC API endpoints designated public will be
   155  	// exposed.
   156  	WSModules []string
   157  
   158  	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
   159  	// than just the public ones.
   160  	//
   161  	// *WARNING* Only set this if the node is running in a trusted network, exposing
   162  	// private APIs to untrusted users is a major security risk.
   163  	WSExposeAll bool `toml:",omitempty"`
   164  
   165  	// GraphQLCors is the Cross-Origin Resource Sharing header to send to requesting
   166  	// clients. Please be aware that CORS is a browser enforced security, it's fully
   167  	// useless for custom HTTP clients.
   168  	GraphQLCors []string `toml:",omitempty"`
   169  
   170  	// GraphQLVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
   171  	// This is by default {'localhost'}. Using this prevents attacks like
   172  	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
   173  	// origin. These attacks do not utilize CORS, since they are not cross-domain.
   174  	// By explicitly checking the Host-header, the server will not allow requests
   175  	// made against the server with a malicious host domain.
   176  	// Requests using ip address directly are not affected
   177  	GraphQLVirtualHosts []string `toml:",omitempty"`
   178  
   179  	// Logger is a custom logger to use with the p2p.Server.
   180  	Logger log.Logger `toml:",omitempty"`
   181  
   182  	staticNodesWarning     bool
   183  	trustedNodesWarning    bool
   184  	oldGethResourceWarning bool
   185  }
   186  
   187  // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
   188  // account the set data folders as well as the designated platform we're currently
   189  // running on.
   190  func (c *Config) IPCEndpoint() string {
   191  	// Short circuit if IPC has not been enabled
   192  	if c.IPCPath == "" {
   193  		return ""
   194  	}
   195  	// On windows we can only use plain top-level pipes
   196  	if runtime.GOOS == "windows" {
   197  		if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
   198  			return c.IPCPath
   199  		}
   200  		return `\\.\pipe\` + c.IPCPath
   201  	}
   202  	// Resolve names into the data directory full paths otherwise
   203  	if filepath.Base(c.IPCPath) == c.IPCPath {
   204  		if c.DataDir == "" {
   205  			return filepath.Join(os.TempDir(), c.IPCPath)
   206  		}
   207  		return filepath.Join(c.DataDir, c.IPCPath)
   208  	}
   209  	return c.IPCPath
   210  }
   211  
   212  // NodeDB returns the path to the discovery node database.
   213  func (c *Config) NodeDB() string {
   214  	if c.DataDir == "" {
   215  		return "" // ephemeral
   216  	}
   217  	return c.ResolvePath(datadirNodeDatabase)
   218  }
   219  
   220  // DefaultIPCEndpoint returns the IPC path used by default.
   221  func DefaultIPCEndpoint(clientIdentifier string) string {
   222  	if clientIdentifier == "" {
   223  		clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   224  		if clientIdentifier == "" {
   225  			panic("empty executable name")
   226  		}
   227  	}
   228  	config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
   229  	return config.IPCEndpoint()
   230  }
   231  
   232  // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
   233  // and port parameters.
   234  func (c *Config) HTTPEndpoint() string {
   235  	if c.HTTPHost == "" {
   236  		return ""
   237  	}
   238  	return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
   239  }
   240  
   241  // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
   242  func DefaultHTTPEndpoint() string {
   243  	config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
   244  	return config.HTTPEndpoint()
   245  }
   246  
   247  // WSEndpoint resolves a websocket endpoint based on the configured host interface
   248  // and port parameters.
   249  func (c *Config) WSEndpoint() string {
   250  	if c.WSHost == "" {
   251  		return ""
   252  	}
   253  	return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
   254  }
   255  
   256  // DefaultWSEndpoint returns the websocket endpoint used by default.
   257  func DefaultWSEndpoint() string {
   258  	config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
   259  	return config.WSEndpoint()
   260  }
   261  
   262  // ExtRPCEnabled returns the indicator whether node enables the external
   263  // RPC(http, ws or graphql).
   264  func (c *Config) ExtRPCEnabled() bool {
   265  	return c.HTTPHost != "" || c.WSHost != ""
   266  }
   267  
   268  // NodeName returns the devp2p node identifier.
   269  func (c *Config) NodeName() string {
   270  	name := c.name()
   271  	// Backwards compatibility: previous versions used title-cased "Geth", keep that.
   272  	if name == "geth" || name == "geth-testnet" {
   273  		name = "Geth"
   274  	}
   275  	if c.UserIdent != "" {
   276  		name += "/" + c.UserIdent
   277  	}
   278  	if c.Version != "" {
   279  		name += "/v" + c.Version
   280  	}
   281  	name += "/" + runtime.GOOS + "-" + runtime.GOARCH
   282  	name += "/" + runtime.Version()
   283  	return name
   284  }
   285  
   286  func (c *Config) name() string {
   287  	if c.Name == "" {
   288  		progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   289  		if progname == "" {
   290  			panic("empty executable name, set Config.Name")
   291  		}
   292  		return progname
   293  	}
   294  	return c.Name
   295  }
   296  
   297  // These resources are resolved differently for "geth" instances.
   298  var isOldGethResource = map[string]bool{
   299  	"chaindata":          true,
   300  	"nodes":              true,
   301  	"nodekey":            true,
   302  	"static-nodes.json":  false, // no warning for these because they have their
   303  	"trusted-nodes.json": false, // own separate warning.
   304  }
   305  
   306  // ResolvePath resolves path in the instance directory.
   307  func (c *Config) ResolvePath(path string) string {
   308  	if filepath.IsAbs(path) {
   309  		return path
   310  	}
   311  	if c.DataDir == "" {
   312  		return ""
   313  	}
   314  	// Backwards-compatibility: ensure that data directory files created
   315  	// by geth 1.4 are used if they exist.
   316  	if warn, isOld := isOldGethResource[path]; isOld {
   317  		oldpath := ""
   318  		if c.name() == "geth" {
   319  			oldpath = filepath.Join(c.DataDir, path)
   320  		}
   321  		if oldpath != "" && common.FileExist(oldpath) {
   322  			if warn {
   323  				c.warnOnce(&c.oldGethResourceWarning, "Using deprecated resource file %s, please move this file to the 'geth' subdirectory of datadir.", oldpath)
   324  			}
   325  			return oldpath
   326  		}
   327  	}
   328  	return filepath.Join(c.instanceDir(), path)
   329  }
   330  
   331  func (c *Config) instanceDir() string {
   332  	if c.DataDir == "" {
   333  		return ""
   334  	}
   335  	return filepath.Join(c.DataDir, c.name())
   336  }
   337  
   338  // NodeKey retrieves the currently configured private key of the node, checking
   339  // first any manually set key, falling back to the one found in the configured
   340  // data folder. If no key can be found, a new one is generated.
   341  func (c *Config) NodeKey() *ecdsa.PrivateKey {
   342  	// Use any specifically configured key.
   343  	if c.P2P.PrivateKey != nil {
   344  		return c.P2P.PrivateKey
   345  	}
   346  	// Generate ephemeral key if no datadir is being used.
   347  	if c.DataDir == "" {
   348  		key, err := crypto.GenerateKey()
   349  		if err != nil {
   350  			log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
   351  		}
   352  		return key
   353  	}
   354  
   355  	keyfile := c.ResolvePath(datadirPrivateKey)
   356  	if key, err := crypto.LoadECDSA(keyfile); err == nil {
   357  		return key
   358  	}
   359  	// No persistent key found, generate and store a new one.
   360  	key, err := crypto.GenerateKey()
   361  	if err != nil {
   362  		log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
   363  	}
   364  	instanceDir := filepath.Join(c.DataDir, c.name())
   365  	if err := os.MkdirAll(instanceDir, 0700); err != nil {
   366  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   367  		return key
   368  	}
   369  	keyfile = filepath.Join(instanceDir, datadirPrivateKey)
   370  	if err := crypto.SaveECDSA(keyfile, key); err != nil {
   371  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   372  	}
   373  	return key
   374  }
   375  
   376  // StaticNodes returns a list of node enode URLs configured as static nodes.
   377  func (c *Config) StaticNodes() []*enode.Node {
   378  	return c.parsePersistentNodes(&c.staticNodesWarning, c.ResolvePath(datadirStaticNodes))
   379  }
   380  
   381  // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
   382  func (c *Config) TrustedNodes() []*enode.Node {
   383  	return c.parsePersistentNodes(&c.trustedNodesWarning, c.ResolvePath(datadirTrustedNodes))
   384  }
   385  
   386  // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
   387  // file from within the data directory.
   388  func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node {
   389  	// Short circuit if no node config is present
   390  	if c.DataDir == "" {
   391  		return nil
   392  	}
   393  	if _, err := os.Stat(path); err != nil {
   394  		return nil
   395  	}
   396  	c.warnOnce(w, "Found deprecated node list file %s, please use the TOML config file instead.", path)
   397  
   398  	// Load the nodes from the config file.
   399  	var nodelist []string
   400  	if err := common.LoadJSON(path, &nodelist); err != nil {
   401  		log.Error(fmt.Sprintf("Can't load node list file: %v", err))
   402  		return nil
   403  	}
   404  	// Interpret the list as a discovery node array
   405  	var nodes []*enode.Node
   406  	for _, url := range nodelist {
   407  		if url == "" {
   408  			continue
   409  		}
   410  		node, err := enode.Parse(enode.ValidSchemes, url)
   411  		if err != nil {
   412  			log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
   413  			continue
   414  		}
   415  		nodes = append(nodes, node)
   416  	}
   417  	return nodes
   418  }
   419  
   420  // AccountConfig determines the settings for scrypt and keydirectory
   421  func (c *Config) AccountConfig() (int, int, string, error) {
   422  	scryptN := keystore.StandardScryptN
   423  	scryptP := keystore.StandardScryptP
   424  	if c.UseLightweightKDF {
   425  		scryptN = keystore.LightScryptN
   426  		scryptP = keystore.LightScryptP
   427  	}
   428  
   429  	var (
   430  		keydir string
   431  		err    error
   432  	)
   433  	switch {
   434  	case filepath.IsAbs(c.KeyStoreDir):
   435  		keydir = c.KeyStoreDir
   436  	case c.DataDir != "":
   437  		if c.KeyStoreDir == "" {
   438  			keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
   439  		} else {
   440  			keydir, err = filepath.Abs(c.KeyStoreDir)
   441  		}
   442  	case c.KeyStoreDir != "":
   443  		keydir, err = filepath.Abs(c.KeyStoreDir)
   444  	}
   445  	return scryptN, scryptP, keydir, err
   446  }
   447  
   448  func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
   449  	scryptN, scryptP, keydir, err := conf.AccountConfig()
   450  	var ephemeral string
   451  	if keydir == "" {
   452  		// There is no datadir.
   453  		keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
   454  		ephemeral = keydir
   455  	}
   456  
   457  	if err != nil {
   458  		return nil, "", err
   459  	}
   460  	if err := os.MkdirAll(keydir, 0700); err != nil {
   461  		return nil, "", err
   462  	}
   463  	// Assemble the account manager and supported backends
   464  	var backends []accounts.Backend
   465  	if len(conf.ExternalSigner) > 0 {
   466  		log.Info("Using external signer", "url", conf.ExternalSigner)
   467  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   468  			backends = append(backends, extapi)
   469  		} else {
   470  			return nil, "", fmt.Errorf("error connecting to external signer: %v", err)
   471  		}
   472  	}
   473  	if len(backends) == 0 {
   474  		// For now, we're using EITHER external signer OR local signers.
   475  		// If/when we implement some form of lockfile for USB and keystore wallets,
   476  		// we can have both, but it's very confusing for the user to see the same
   477  		// accounts in both externally and locally, plus very racey.
   478  		backends = append(backends, keystore.NewKeyStore(keydir, scryptN, scryptP))
   479  		if !conf.NoUSB {
   480  			// Start a USB hub for Ledger hardware wallets
   481  			if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   482  				log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   483  			} else {
   484  				backends = append(backends, ledgerhub)
   485  			}
   486  			// Start a USB hub for Trezor hardware wallets (HID version)
   487  			if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   488  				log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   489  			} else {
   490  				backends = append(backends, trezorhub)
   491  			}
   492  			// Start a USB hub for Trezor hardware wallets (WebUSB version)
   493  			if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   494  				log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   495  			} else {
   496  				backends = append(backends, trezorhub)
   497  			}
   498  		}
   499  		if len(conf.SmartCardDaemonPath) > 0 {
   500  			// Start a smart card hub
   501  			if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   502  				log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   503  			} else {
   504  				backends = append(backends, schub)
   505  			}
   506  		}
   507  	}
   508  
   509  	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}, backends...), ephemeral, nil
   510  }
   511  
   512  var warnLock sync.Mutex
   513  
   514  func (c *Config) warnOnce(w *bool, format string, args ...interface{}) {
   515  	warnLock.Lock()
   516  	defer warnLock.Unlock()
   517  
   518  	if *w {
   519  		return
   520  	}
   521  	l := c.Logger
   522  	if l == nil {
   523  		l = log.Root()
   524  	}
   525  	l.Warn(fmt.Sprintf(format, args...))
   526  	*w = true
   527  }