github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/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/unicornultrafoundation/go-u2u/accounts"
    30  	"github.com/unicornultrafoundation/go-u2u/accounts/external"
    31  	"github.com/unicornultrafoundation/go-u2u/accounts/keystore"
    32  	"github.com/unicornultrafoundation/go-u2u/accounts/scwallet"
    33  	"github.com/unicornultrafoundation/go-u2u/accounts/usbwallet"
    34  	"github.com/unicornultrafoundation/go-u2u/common"
    35  	"github.com/unicornultrafoundation/go-u2u/crypto"
    36  	"github.com/unicornultrafoundation/go-u2u/log"
    37  	"github.com/unicornultrafoundation/go-u2u/p2p"
    38  	"github.com/unicornultrafoundation/go-u2u/p2p/enode"
    39  	"github.com/unicornultrafoundation/go-u2u/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  	// USB enables hardware wallet monitoring and connectivity.
    99  	USB bool `toml:",omitempty"`
   100  
   101  	// SmartCardDaemonPath is the path to the smartcard daemon's socket
   102  	SmartCardDaemonPath string `toml:",omitempty"`
   103  
   104  	// IPCPath is the requested location to place the IPC endpoint. If the path is
   105  	// a simple file name, it is placed inside the data directory (or on the root
   106  	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
   107  	// relative), then that specific path is enforced. An empty path disables IPC.
   108  	IPCPath string
   109  
   110  	// HTTPHost is the host interface on which to start the HTTP RPC server. If this
   111  	// field is empty, no HTTP API endpoint will be started.
   112  	HTTPHost string
   113  
   114  	// HTTPPort is the TCP port number on which to start the HTTP RPC server. The
   115  	// default zero value is/ valid and will pick a port number randomly (useful
   116  	// for ephemeral nodes).
   117  	HTTPPort int `toml:",omitempty"`
   118  
   119  	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
   120  	// clients. Please be aware that CORS is a browser enforced security, it's fully
   121  	// useless for custom HTTP clients.
   122  	HTTPCors []string `toml:",omitempty"`
   123  
   124  	// HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
   125  	// This is by default {'localhost'}. Using this prevents attacks like
   126  	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
   127  	// origin. These attacks do not utilize CORS, since they are not cross-domain.
   128  	// By explicitly checking the Host-header, the server will not allow requests
   129  	// made against the server with a malicious host domain.
   130  	// Requests using ip address directly are not affected
   131  	HTTPVirtualHosts []string `toml:",omitempty"`
   132  
   133  	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
   134  	// If the module list is empty, all RPC API endpoints designated public will be
   135  	// exposed.
   136  	HTTPModules []string
   137  
   138  	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
   139  	// interface.
   140  	HTTPTimeouts rpc.HTTPTimeouts
   141  
   142  	// HTTPPathPrefix specifies a path prefix on which http-rpc is to be served.
   143  	HTTPPathPrefix string `toml:",omitempty"`
   144  
   145  	// WSHost is the host interface on which to start the websocket RPC server. If
   146  	// this field is empty, no websocket API endpoint will be started.
   147  	WSHost string
   148  
   149  	// WSPort is the TCP port number on which to start the websocket RPC server. The
   150  	// default zero value is/ valid and will pick a port number randomly (useful for
   151  	// ephemeral nodes).
   152  	WSPort int `toml:",omitempty"`
   153  
   154  	// WSPathPrefix specifies a path prefix on which ws-rpc is to be served.
   155  	WSPathPrefix string `toml:",omitempty"`
   156  
   157  	// WSOrigins is the list of domain to accept websocket requests from. Please be
   158  	// aware that the server can only act upon the HTTP request the client sends and
   159  	// cannot verify the validity of the request header.
   160  	WSOrigins []string `toml:",omitempty"`
   161  
   162  	// WSModules is a list of API modules to expose via the websocket RPC interface.
   163  	// If the module list is empty, all RPC API endpoints designated public will be
   164  	// exposed.
   165  	WSModules []string
   166  
   167  	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
   168  	// than just the public ones.
   169  	//
   170  	// *WARNING* Only set this if the node is running in a trusted network, exposing
   171  	// private APIs to untrusted users is a major security risk.
   172  	WSExposeAll bool `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  
   194  	// AllowUnprotectedTxs allows non EIP-155 protected transactions to be send over RPC.
   195  	AllowUnprotectedTxs bool `toml:",omitempty"`
   196  }
   197  
   198  // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
   199  // account the set data folders as well as the designated platform we're currently
   200  // running on.
   201  func (c *Config) IPCEndpoint() string {
   202  	// Short circuit if IPC has not been enabled
   203  	if c.IPCPath == "" {
   204  		return ""
   205  	}
   206  	// On windows we can only use plain top-level pipes
   207  	if runtime.GOOS == "windows" {
   208  		if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
   209  			return c.IPCPath
   210  		}
   211  		return `\\.\pipe\` + c.IPCPath
   212  	}
   213  	// Resolve names into the data directory full paths otherwise
   214  	if filepath.Base(c.IPCPath) == c.IPCPath {
   215  		if c.DataDir == "" {
   216  			return filepath.Join(os.TempDir(), c.IPCPath)
   217  		}
   218  		return filepath.Join(c.DataDir, c.IPCPath)
   219  	}
   220  	return c.IPCPath
   221  }
   222  
   223  // NodeDB returns the path to the discovery node database.
   224  func (c *Config) NodeDB() string {
   225  	if c.DataDir == "" {
   226  		return "" // ephemeral
   227  	}
   228  	return c.ResolvePath(datadirNodeDatabase)
   229  }
   230  
   231  // DefaultIPCEndpoint returns the IPC path used by default.
   232  func DefaultIPCEndpoint(clientIdentifier string) string {
   233  	if clientIdentifier == "" {
   234  		clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   235  		if clientIdentifier == "" {
   236  			panic("empty executable name")
   237  		}
   238  	}
   239  	config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
   240  	return config.IPCEndpoint()
   241  }
   242  
   243  // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
   244  // and port parameters.
   245  func (c *Config) HTTPEndpoint() string {
   246  	if c.HTTPHost == "" {
   247  		return ""
   248  	}
   249  	return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
   250  }
   251  
   252  // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
   253  func DefaultHTTPEndpoint() string {
   254  	config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
   255  	return config.HTTPEndpoint()
   256  }
   257  
   258  // WSEndpoint resolves a websocket endpoint based on the configured host interface
   259  // and port parameters.
   260  func (c *Config) WSEndpoint() string {
   261  	if c.WSHost == "" {
   262  		return ""
   263  	}
   264  	return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
   265  }
   266  
   267  // DefaultWSEndpoint returns the websocket endpoint used by default.
   268  func DefaultWSEndpoint() string {
   269  	config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
   270  	return config.WSEndpoint()
   271  }
   272  
   273  // ExtRPCEnabled returns the indicator whether node enables the external
   274  // RPC(http, ws or graphql).
   275  func (c *Config) ExtRPCEnabled() bool {
   276  	return c.HTTPHost != "" || c.WSHost != ""
   277  }
   278  
   279  // NodeName returns the devp2p node identifier.
   280  func (c *Config) NodeName() string {
   281  	name := c.name()
   282  	// Backwards compatibility: previous versions used title-cased "Geth", keep that.
   283  	if name == "geth" || name == "geth-testnet" {
   284  		name = "Geth"
   285  	}
   286  	if c.UserIdent != "" {
   287  		name += "/" + c.UserIdent
   288  	}
   289  	if c.Version != "" {
   290  		name += "/v" + c.Version
   291  	}
   292  	name += "/" + runtime.GOOS + "-" + runtime.GOARCH
   293  	name += "/" + runtime.Version()
   294  	return name
   295  }
   296  
   297  func (c *Config) name() string {
   298  	if c.Name == "" {
   299  		progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   300  		if progname == "" {
   301  			panic("empty executable name, set Config.Name")
   302  		}
   303  		return progname
   304  	}
   305  	return c.Name
   306  }
   307  
   308  // ResolvePath resolves path in the instance directory.
   309  func (c *Config) ResolvePath(path string) string {
   310  	if filepath.IsAbs(path) {
   311  		return path
   312  	}
   313  	if c.DataDir == "" {
   314  		return ""
   315  	}
   316  	return filepath.Join(c.instanceDir(), path)
   317  }
   318  
   319  func (c *Config) instanceDir() string {
   320  	if c.DataDir == "" {
   321  		return ""
   322  	}
   323  	return filepath.Join(c.DataDir, c.name())
   324  }
   325  
   326  // NodeKey retrieves the currently configured private key of the node, checking
   327  // first any manually set key, falling back to the one found in the configured
   328  // data folder. If no key can be found, a new one is generated.
   329  func (c *Config) NodeKey() *ecdsa.PrivateKey {
   330  	// Use any specifically configured key.
   331  	if c.P2P.PrivateKey != nil {
   332  		return c.P2P.PrivateKey
   333  	}
   334  	// Generate ephemeral key if no datadir is being used.
   335  	if c.DataDir == "" {
   336  		key, err := crypto.GenerateKey()
   337  		if err != nil {
   338  			log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
   339  		}
   340  		return key
   341  	}
   342  
   343  	keyfile := c.ResolvePath(datadirPrivateKey)
   344  	if key, err := crypto.LoadECDSA(keyfile); err == nil {
   345  		return key
   346  	}
   347  	// No persistent key found, generate and store a new one.
   348  	key, err := crypto.GenerateKey()
   349  	if err != nil {
   350  		log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
   351  	}
   352  	instanceDir := filepath.Join(c.DataDir, c.name())
   353  	if err := os.MkdirAll(instanceDir, 0700); err != nil {
   354  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   355  		return key
   356  	}
   357  	keyfile = filepath.Join(instanceDir, datadirPrivateKey)
   358  	if err := crypto.SaveECDSA(keyfile, key); err != nil {
   359  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   360  	}
   361  	return key
   362  }
   363  
   364  // StaticNodes returns a list of node enode URLs configured as static nodes.
   365  func (c *Config) StaticNodes() []*enode.Node {
   366  	return c.parsePersistentNodes(&c.staticNodesWarning, c.ResolvePath(datadirStaticNodes))
   367  }
   368  
   369  // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
   370  func (c *Config) TrustedNodes() []*enode.Node {
   371  	return c.parsePersistentNodes(&c.trustedNodesWarning, c.ResolvePath(datadirTrustedNodes))
   372  }
   373  
   374  func (c *Config) PrivateNodes() []*enode.Node {
   375  	return c.P2P.PrivateNodes
   376  }
   377  
   378  // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
   379  // file from within the data directory.
   380  func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node {
   381  	// Short circuit if no node config is present
   382  	if c.DataDir == "" {
   383  		return nil
   384  	}
   385  	if _, err := os.Stat(path); err != nil {
   386  		return nil
   387  	}
   388  	c.warnOnce(w, "Found deprecated node list file %s, please use the TOML config file instead.", path)
   389  
   390  	// Load the nodes from the config file.
   391  	var nodelist []string
   392  	if err := common.LoadJSON(path, &nodelist); err != nil {
   393  		log.Error(fmt.Sprintf("Can't load node list file: %v", err))
   394  		return nil
   395  	}
   396  	// Interpret the list as a discovery node array
   397  	var nodes []*enode.Node
   398  	for _, url := range nodelist {
   399  		if url == "" {
   400  			continue
   401  		}
   402  		node, err := enode.Parse(enode.ValidSchemes, url)
   403  		if err != nil {
   404  			log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
   405  			continue
   406  		}
   407  		nodes = append(nodes, node)
   408  	}
   409  	return nodes
   410  }
   411  
   412  // AccountConfig determines the settings for scrypt and keydirectory
   413  func (c *Config) AccountConfig() (int, int, string, error) {
   414  	scryptN := keystore.StandardScryptN
   415  	scryptP := keystore.StandardScryptP
   416  	if c.UseLightweightKDF {
   417  		scryptN = keystore.LightScryptN
   418  		scryptP = keystore.LightScryptP
   419  	}
   420  
   421  	var (
   422  		keydir string
   423  		err    error
   424  	)
   425  	switch {
   426  	case filepath.IsAbs(c.KeyStoreDir):
   427  		keydir = c.KeyStoreDir
   428  	case c.DataDir != "":
   429  		if c.KeyStoreDir == "" {
   430  			keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
   431  		} else {
   432  			keydir, err = filepath.Abs(c.KeyStoreDir)
   433  		}
   434  	case c.KeyStoreDir != "":
   435  		keydir, err = filepath.Abs(c.KeyStoreDir)
   436  	}
   437  	return scryptN, scryptP, keydir, err
   438  }
   439  
   440  func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
   441  	scryptN, scryptP, keydir, err := conf.AccountConfig()
   442  	var ephemeral string
   443  	if keydir == "" {
   444  		// There is no datadir.
   445  		keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
   446  		ephemeral = keydir
   447  	}
   448  
   449  	if err != nil {
   450  		return nil, "", err
   451  	}
   452  	if err := os.MkdirAll(keydir, 0700); err != nil {
   453  		return nil, "", err
   454  	}
   455  	// Assemble the account manager and supported backends
   456  	var backends []accounts.Backend
   457  	if len(conf.ExternalSigner) > 0 {
   458  		log.Info("Using external signer", "url", conf.ExternalSigner)
   459  		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
   460  			backends = append(backends, extapi)
   461  		} else {
   462  			return nil, "", fmt.Errorf("error connecting to external signer: %v", err)
   463  		}
   464  	}
   465  	if len(backends) == 0 {
   466  		// For now, we're using EITHER external signer OR local signers.
   467  		// If/when we implement some form of lockfile for USB and keystore wallets,
   468  		// we can have both, but it's very confusing for the user to see the same
   469  		// accounts in both externally and locally, plus very racey.
   470  		backends = append(backends, keystore.NewKeyStore(keydir, scryptN, scryptP))
   471  		if conf.USB {
   472  			// Start a USB hub for Ledger hardware wallets
   473  			if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   474  				log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   475  			} else {
   476  				backends = append(backends, ledgerhub)
   477  			}
   478  			// Start a USB hub for Trezor hardware wallets (HID version)
   479  			if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   480  				log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   481  			} else {
   482  				backends = append(backends, trezorhub)
   483  			}
   484  			// Start a USB hub for Trezor hardware wallets (WebUSB version)
   485  			if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   486  				log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   487  			} else {
   488  				backends = append(backends, trezorhub)
   489  			}
   490  		}
   491  		if len(conf.SmartCardDaemonPath) > 0 {
   492  			// Start a smart card hub
   493  			if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
   494  				log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   495  			} else {
   496  				backends = append(backends, schub)
   497  			}
   498  		}
   499  	}
   500  
   501  	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}, backends...), ephemeral, nil
   502  }
   503  
   504  var warnLock sync.Mutex
   505  
   506  func (c *Config) warnOnce(w *bool, format string, args ...interface{}) {
   507  	warnLock.Lock()
   508  	defer warnLock.Unlock()
   509  
   510  	if *w {
   511  		return
   512  	}
   513  	l := c.Logger
   514  	if l == nil {
   515  		l = log.Root()
   516  	}
   517  	l.Warn(fmt.Sprintf(format, args...))
   518  	*w = true
   519  }