github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/node/config.go (about)

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