github.com/AlohaMobile/go-ethereum@v1.9.7/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 `toml:",omitempty"`
   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 `toml:",omitempty"`
   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 `toml:",omitempty"`
   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 `toml:",omitempty"`
   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 `toml:",omitempty"`
   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  	// GraphQLHost is the host interface on which to start the GraphQL server. If this
   166  	// field is empty, no GraphQL API endpoint will be started.
   167  	GraphQLHost string `toml:",omitempty"`
   168  
   169  	// GraphQLPort is the TCP port number on which to start the GraphQL server. The
   170  	// default zero value is/ valid and will pick a port number randomly (useful
   171  	// for ephemeral nodes).
   172  	GraphQLPort int `toml:",omitempty"`
   173  
   174  	// GraphQLCors is the Cross-Origin Resource Sharing header to send to requesting
   175  	// clients. Please be aware that CORS is a browser enforced security, it's fully
   176  	// useless for custom HTTP clients.
   177  	GraphQLCors []string `toml:",omitempty"`
   178  
   179  	// GraphQLVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
   180  	// This is by default {'localhost'}. Using this prevents attacks like
   181  	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
   182  	// origin. These attacks do not utilize CORS, since they are not cross-domain.
   183  	// By explicitly checking the Host-header, the server will not allow requests
   184  	// made against the server with a malicious host domain.
   185  	// Requests using ip address directly are not affected
   186  	GraphQLVirtualHosts []string `toml:",omitempty"`
   187  
   188  	// Logger is a custom logger to use with the p2p.Server.
   189  	Logger log.Logger `toml:",omitempty"`
   190  
   191  	staticNodesWarning     bool
   192  	trustedNodesWarning    bool
   193  	oldGethResourceWarning bool
   194  }
   195  
   196  // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
   197  // account the set data folders as well as the designated platform we're currently
   198  // running on.
   199  func (c *Config) IPCEndpoint() string {
   200  	// Short circuit if IPC has not been enabled
   201  	if c.IPCPath == "" {
   202  		return ""
   203  	}
   204  	// On windows we can only use plain top-level pipes
   205  	if runtime.GOOS == "windows" {
   206  		if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
   207  			return c.IPCPath
   208  		}
   209  		return `\\.\pipe\` + c.IPCPath
   210  	}
   211  	// Resolve names into the data directory full paths otherwise
   212  	if filepath.Base(c.IPCPath) == c.IPCPath {
   213  		if c.DataDir == "" {
   214  			return filepath.Join(os.TempDir(), c.IPCPath)
   215  		}
   216  		return filepath.Join(c.DataDir, c.IPCPath)
   217  	}
   218  	return c.IPCPath
   219  }
   220  
   221  // NodeDB returns the path to the discovery node database.
   222  func (c *Config) NodeDB() string {
   223  	if c.DataDir == "" {
   224  		return "" // ephemeral
   225  	}
   226  	return c.ResolvePath(datadirNodeDatabase)
   227  }
   228  
   229  // DefaultIPCEndpoint returns the IPC path used by default.
   230  func DefaultIPCEndpoint(clientIdentifier string) string {
   231  	if clientIdentifier == "" {
   232  		clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   233  		if clientIdentifier == "" {
   234  			panic("empty executable name")
   235  		}
   236  	}
   237  	config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
   238  	return config.IPCEndpoint()
   239  }
   240  
   241  // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
   242  // and port parameters.
   243  func (c *Config) HTTPEndpoint() string {
   244  	if c.HTTPHost == "" {
   245  		return ""
   246  	}
   247  	return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
   248  }
   249  
   250  // GraphQLEndpoint resolves a GraphQL endpoint based on the configured host interface
   251  // and port parameters.
   252  func (c *Config) GraphQLEndpoint() string {
   253  	if c.GraphQLHost == "" {
   254  		return ""
   255  	}
   256  	return fmt.Sprintf("%s:%d", c.GraphQLHost, c.GraphQLPort)
   257  }
   258  
   259  // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
   260  func DefaultHTTPEndpoint() string {
   261  	config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
   262  	return config.HTTPEndpoint()
   263  }
   264  
   265  // WSEndpoint resolves a websocket endpoint based on the configured host interface
   266  // and port parameters.
   267  func (c *Config) WSEndpoint() string {
   268  	if c.WSHost == "" {
   269  		return ""
   270  	}
   271  	return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
   272  }
   273  
   274  // DefaultWSEndpoint returns the websocket endpoint used by default.
   275  func DefaultWSEndpoint() string {
   276  	config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
   277  	return config.WSEndpoint()
   278  }
   279  
   280  // ExtRPCEnabled returns the indicator whether node enables the external
   281  // RPC(http, ws or graphql).
   282  func (c *Config) ExtRPCEnabled() bool {
   283  	return c.HTTPHost != "" || c.WSHost != "" || c.GraphQLHost != ""
   284  }
   285  
   286  // NodeName returns the devp2p node identifier.
   287  func (c *Config) NodeName() string {
   288  	name := c.name()
   289  	// Backwards compatibility: previous versions used title-cased "Geth", keep that.
   290  	if name == "geth" || name == "geth-testnet" {
   291  		name = "Geth"
   292  	}
   293  	if c.UserIdent != "" {
   294  		name += "/" + c.UserIdent
   295  	}
   296  	if c.Version != "" {
   297  		name += "/v" + c.Version
   298  	}
   299  	name += "/" + runtime.GOOS + "-" + runtime.GOARCH
   300  	name += "/" + runtime.Version()
   301  	return name
   302  }
   303  
   304  func (c *Config) name() string {
   305  	if c.Name == "" {
   306  		progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   307  		if progname == "" {
   308  			panic("empty executable name, set Config.Name")
   309  		}
   310  		return progname
   311  	}
   312  	return c.Name
   313  }
   314  
   315  // These resources are resolved differently for "geth" instances.
   316  var isOldGethResource = map[string]bool{
   317  	"chaindata":          true,
   318  	"nodes":              true,
   319  	"nodekey":            true,
   320  	"static-nodes.json":  false, // no warning for these because they have their
   321  	"trusted-nodes.json": false, // own separate warning.
   322  }
   323  
   324  // ResolvePath resolves path in the instance directory.
   325  func (c *Config) ResolvePath(path string) string {
   326  	if filepath.IsAbs(path) {
   327  		return path
   328  	}
   329  	if c.DataDir == "" {
   330  		return ""
   331  	}
   332  	// Backwards-compatibility: ensure that data directory files created
   333  	// by geth 1.4 are used if they exist.
   334  	if warn, isOld := isOldGethResource[path]; isOld {
   335  		oldpath := ""
   336  		if c.name() == "geth" {
   337  			oldpath = filepath.Join(c.DataDir, path)
   338  		}
   339  		if oldpath != "" && common.FileExist(oldpath) {
   340  			if warn {
   341  				c.warnOnce(&c.oldGethResourceWarning, "Using deprecated resource file %s, please move this file to the 'geth' subdirectory of datadir.", oldpath)
   342  			}
   343  			return oldpath
   344  		}
   345  	}
   346  	return filepath.Join(c.instanceDir(), path)
   347  }
   348  
   349  func (c *Config) instanceDir() string {
   350  	if c.DataDir == "" {
   351  		return ""
   352  	}
   353  	return filepath.Join(c.DataDir, c.name())
   354  }
   355  
   356  // NodeKey retrieves the currently configured private key of the node, checking
   357  // first any manually set key, falling back to the one found in the configured
   358  // data folder. If no key can be found, a new one is generated.
   359  func (c *Config) NodeKey() *ecdsa.PrivateKey {
   360  	// Use any specifically configured key.
   361  	if c.P2P.PrivateKey != nil {
   362  		return c.P2P.PrivateKey
   363  	}
   364  	// Generate ephemeral key if no datadir is being used.
   365  	if c.DataDir == "" {
   366  		key, err := crypto.GenerateKey()
   367  		if err != nil {
   368  			log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
   369  		}
   370  		return key
   371  	}
   372  
   373  	keyfile := c.ResolvePath(datadirPrivateKey)
   374  	if key, err := crypto.LoadECDSA(keyfile); err == nil {
   375  		return key
   376  	}
   377  	// No persistent key found, generate and store a new one.
   378  	key, err := crypto.GenerateKey()
   379  	if err != nil {
   380  		log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
   381  	}
   382  	instanceDir := filepath.Join(c.DataDir, c.name())
   383  	if err := os.MkdirAll(instanceDir, 0700); err != nil {
   384  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   385  		return key
   386  	}
   387  	keyfile = filepath.Join(instanceDir, datadirPrivateKey)
   388  	if err := crypto.SaveECDSA(keyfile, key); err != nil {
   389  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   390  	}
   391  	return key
   392  }
   393  
   394  // StaticNodes returns a list of node enode URLs configured as static nodes.
   395  func (c *Config) StaticNodes() []*enode.Node {
   396  	return c.parsePersistentNodes(&c.staticNodesWarning, c.ResolvePath(datadirStaticNodes))
   397  }
   398  
   399  // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
   400  func (c *Config) TrustedNodes() []*enode.Node {
   401  	return c.parsePersistentNodes(&c.trustedNodesWarning, c.ResolvePath(datadirTrustedNodes))
   402  }
   403  
   404  // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
   405  // file from within the data directory.
   406  func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node {
   407  	// Short circuit if no node config is present
   408  	if c.DataDir == "" {
   409  		return nil
   410  	}
   411  	if _, err := os.Stat(path); err != nil {
   412  		return nil
   413  	}
   414  	c.warnOnce(w, "Found deprecated node list file %s, please use the TOML config file instead.", path)
   415  
   416  	// Load the nodes from the config file.
   417  	var nodelist []string
   418  	if err := common.LoadJSON(path, &nodelist); err != nil {
   419  		log.Error(fmt.Sprintf("Can't load node list file: %v", err))
   420  		return nil
   421  	}
   422  	// Interpret the list as a discovery node array
   423  	var nodes []*enode.Node
   424  	for _, url := range nodelist {
   425  		if url == "" {
   426  			continue
   427  		}
   428  		node, err := enode.Parse(enode.ValidSchemes, url)
   429  		if err != nil {
   430  			log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
   431  			continue
   432  		}
   433  		nodes = append(nodes, node)
   434  	}
   435  	return nodes
   436  }
   437  
   438  // AccountConfig determines the settings for scrypt and keydirectory
   439  func (c *Config) AccountConfig() (int, int, string, error) {
   440  	scryptN := keystore.StandardScryptN
   441  	scryptP := keystore.StandardScryptP
   442  	if c.UseLightweightKDF {
   443  		scryptN = keystore.LightScryptN
   444  		scryptP = keystore.LightScryptP
   445  	}
   446  
   447  	var (
   448  		keydir string
   449  		err    error
   450  	)
   451  	switch {
   452  	case filepath.IsAbs(c.KeyStoreDir):
   453  		keydir = c.KeyStoreDir
   454  	case c.DataDir != "":
   455  		if c.KeyStoreDir == "" {
   456  			keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
   457  		} else {
   458  			keydir, err = filepath.Abs(c.KeyStoreDir)
   459  		}
   460  	case c.KeyStoreDir != "":
   461  		keydir, err = filepath.Abs(c.KeyStoreDir)
   462  	}
   463  	return scryptN, scryptP, keydir, err
   464  }
   465  
   466  func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
   467  	scryptN, scryptP, keydir, err := conf.AccountConfig()
   468  	var ephemeral string
   469  	if keydir == "" {
   470  		// There is no datadir.
   471  		keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
   472  		ephemeral = keydir
   473  	}
   474  
   475  	if err != nil {
   476  		return nil, "", err
   477  	}
   478  	if err := os.MkdirAll(keydir, 0700); err != nil {
   479  		return nil, "", err
   480  	}
   481  	// Assemble the account manager and supported backends
   482  	var backends []accounts.Backend
   483  	if len(conf.ExternalSigner) > 0 {
   484  		log.Info("Using external signer", "url", conf.ExternalSigner)
   485  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   486  			backends = append(backends, extapi)
   487  		} else {
   488  			return nil, "", fmt.Errorf("error connecting to external signer: %v", err)
   489  		}
   490  	}
   491  	if len(backends) == 0 {
   492  		// For now, we're using EITHER external signer OR local signers.
   493  		// If/when we implement some form of lockfile for USB and keystore wallets,
   494  		// we can have both, but it's very confusing for the user to see the same
   495  		// accounts in both externally and locally, plus very racey.
   496  		backends = append(backends, keystore.NewKeyStore(keydir, scryptN, scryptP))
   497  		if !conf.NoUSB {
   498  			// Start a USB hub for Ledger hardware wallets
   499  			if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   500  				log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   501  			} else {
   502  				backends = append(backends, ledgerhub)
   503  			}
   504  			// Start a USB hub for Trezor hardware wallets (HID version)
   505  			if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   506  				log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   507  			} else {
   508  				backends = append(backends, trezorhub)
   509  			}
   510  			// Start a USB hub for Trezor hardware wallets (WebUSB version)
   511  			if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   512  				log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   513  			} else {
   514  				backends = append(backends, trezorhub)
   515  			}
   516  		}
   517  		if len(conf.SmartCardDaemonPath) > 0 {
   518  			// Start a smart card hub
   519  			if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   520  				log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   521  			} else {
   522  				backends = append(backends, schub)
   523  			}
   524  		}
   525  	}
   526  
   527  	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}, backends...), ephemeral, nil
   528  }
   529  
   530  var warnLock sync.Mutex
   531  
   532  func (c *Config) warnOnce(w *bool, format string, args ...interface{}) {
   533  	warnLock.Lock()
   534  	defer warnLock.Unlock()
   535  
   536  	if *w {
   537  		return
   538  	}
   539  	l := c.Logger
   540  	if l == nil {
   541  		l = log.Root()
   542  	}
   543  	l.Warn(fmt.Sprintf(format, args...))
   544  	*w = true
   545  }