github.com/gochain-io/gochain@v2.2.26+incompatible/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  
    28  	"github.com/gochain-io/gochain/accounts"
    29  	"github.com/gochain-io/gochain/accounts/keystore"
    30  	"github.com/gochain-io/gochain/accounts/usbwallet"
    31  	"github.com/gochain-io/gochain/common"
    32  	"github.com/gochain-io/gochain/crypto"
    33  	"github.com/gochain-io/gochain/ethdb"
    34  	"github.com/gochain-io/gochain/log"
    35  	"github.com/gochain-io/gochain/p2p"
    36  	"github.com/gochain-io/gochain/p2p/discover"
    37  	"github.com/gochain-io/gochain/rpc"
    38  )
    39  
    40  const (
    41  	datadirPrivateKey      = "nodekey"            // Path within the datadir to the node's private key
    42  	datadirDefaultKeyStore = "keystore"           // Path within the datadir to the keystore
    43  	datadirStaticNodes     = "static-nodes.json"  // Path within the datadir to the static node list
    44  	datadirTrustedNodes    = "trusted-nodes.json" // Path within the datadir to the trusted node list
    45  	datadirNodeDatabase    = "nodes"              // Path within the datadir to store the node infos
    46  )
    47  
    48  // Config represents a small collection of configuration values to fine tune the
    49  // P2P network layer of a protocol stack. These values can be further extended by
    50  // all registered services.
    51  type Config struct {
    52  	// Name sets the instance name of the node. It must not contain the / character and is
    53  	// used in the devp2p node identifier. The instance name of geth is "geth". If no
    54  	// value is specified, the basename of the current executable is used.
    55  	Name string `toml:"-"`
    56  
    57  	// UserIdent, if set, is used as an additional component in the devp2p node identifier.
    58  	UserIdent string `toml:",omitempty"`
    59  
    60  	// Version should be set to the version number of the program. It is used
    61  	// in the devp2p node identifier.
    62  	Version string `toml:"-"`
    63  
    64  	// DataDir is the file system folder the node should use for any data storage
    65  	// requirements. The configured data directory will not be directly shared with
    66  	// registered services, instead those can use utility methods to create/access
    67  	// databases or flat files. This enables ephemeral nodes which can fully reside
    68  	// in memory.
    69  	DataDir string
    70  
    71  	// Configuration of peer-to-peer networking.
    72  	P2P p2p.Config
    73  
    74  	// KeyStoreDir is the file system folder that contains private keys. The directory can
    75  	// be specified as a relative path, in which case it is resolved relative to the
    76  	// current directory.
    77  	//
    78  	// If KeyStoreDir is empty, the default location is the "keystore" subdirectory of
    79  	// DataDir. If DataDir is unspecified and KeyStoreDir is empty, an ephemeral directory
    80  	// is created by New and destroyed when the node is stopped.
    81  	KeyStoreDir string `toml:",omitempty"`
    82  
    83  	// UseLightweightKDF lowers the memory and CPU requirements of the key store
    84  	// scrypt KDF at the expense of security.
    85  	UseLightweightKDF bool `toml:",omitempty"`
    86  
    87  	// NoUSB disables hardware wallet monitoring and connectivity.
    88  	NoUSB bool `toml:",omitempty"`
    89  
    90  	// IPCPath is the requested location to place the IPC endpoint. If the path is
    91  	// a simple file name, it is placed inside the data directory (or on the root
    92  	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
    93  	// relative), then that specific path is enforced. An empty path disables IPC.
    94  	IPCPath string `toml:",omitempty"`
    95  
    96  	// HTTPHost is the host interface on which to start the HTTP RPC server. If this
    97  	// field is empty, no HTTP API endpoint will be started.
    98  	HTTPHost string `toml:",omitempty"`
    99  
   100  	// HTTPPort is the TCP port number on which to start the HTTP RPC server. The
   101  	// default zero value is/ valid and will pick a port number randomly (useful
   102  	// for ephemeral nodes).
   103  	HTTPPort int `toml:",omitempty"`
   104  
   105  	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
   106  	// clients. Please be aware that CORS is a browser enforced security, it's fully
   107  	// useless for custom HTTP clients.
   108  	HTTPCors []string `toml:",omitempty"`
   109  
   110  	// HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
   111  	// This is by default {'localhost'}. Using this prevents attacks like
   112  	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
   113  	// origin. These attacks do not utilize CORS, since they are not cross-domain.
   114  	// By explicitly checking the Host-header, the server will not allow requests
   115  	// made against the server with a malicious host domain.
   116  	// Requests using ip address directly are not affected
   117  	HTTPVirtualHosts []string `toml:",omitempty"`
   118  
   119  	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
   120  	// If the module list is empty, all RPC API endpoints designated public will be
   121  	// exposed.
   122  	HTTPModules []string `toml:",omitempty"`
   123  
   124  	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
   125  	// interface.
   126  	HTTPTimeouts rpc.HTTPTimeouts
   127  
   128  	// HTTPTracing enables openconsensus tracing.
   129  	HTTPTracing bool
   130  
   131  	// WSHost is the host interface on which to start the websocket RPC server. If
   132  	// this field is empty, no websocket API endpoint will be started.
   133  	WSHost string `toml:",omitempty"`
   134  
   135  	// WSPort is the TCP port number on which to start the websocket RPC server. The
   136  	// default zero value is/ valid and will pick a port number randomly (useful for
   137  	// ephemeral nodes).
   138  	WSPort int `toml:",omitempty"`
   139  
   140  	// WSOrigins is the list of domain to accept websocket requests from. Please be
   141  	// aware that the server can only act upon the HTTP request the client sends and
   142  	// cannot verify the validity of the request header.
   143  	WSOrigins []string `toml:",omitempty"`
   144  
   145  	// WSModules is a list of API modules to expose via the websocket RPC interface.
   146  	// If the module list is empty, all RPC API endpoints designated public will be
   147  	// exposed.
   148  	WSModules []string `toml:",omitempty"`
   149  
   150  	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
   151  	// than just the public ones.
   152  	//
   153  	// *WARNING* Only set this if the node is running in a trusted network, exposing
   154  	// private APIs to untrusted users is a major security risk.
   155  	WSExposeAll bool `toml:",omitempty"`
   156  
   157  	// Logger is a custom logger to use with the p2p.Server.
   158  	Logger log.Logger `toml:",omitempty"`
   159  
   160  	// Ethdb provides db-specific settings.
   161  	Ethdb ethdb.Config `toml:,omitempty`
   162  }
   163  
   164  // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
   165  // account the set data folders as well as the designated platform we're currently
   166  // running on.
   167  func (c *Config) IPCEndpoint() string {
   168  	// Short circuit if IPC has not been enabled
   169  	if c.IPCPath == "" {
   170  		return ""
   171  	}
   172  	// On windows we can only use plain top-level pipes
   173  	if runtime.GOOS == "windows" {
   174  		if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
   175  			return c.IPCPath
   176  		}
   177  		return `\\.\pipe\` + c.IPCPath
   178  	}
   179  	// Resolve names into the data directory full paths otherwise
   180  	if filepath.Base(c.IPCPath) == c.IPCPath {
   181  		if c.DataDir == "" {
   182  			return filepath.Join(os.TempDir(), c.IPCPath)
   183  		}
   184  		return filepath.Join(c.DataDir, c.IPCPath)
   185  	}
   186  	return c.IPCPath
   187  }
   188  
   189  // NodeDB returns the path to the discovery node database.
   190  func (c *Config) NodeDB() string {
   191  	if c.DataDir == "" {
   192  		return "" // ephemeral
   193  	}
   194  	return c.resolvePath(datadirNodeDatabase)
   195  }
   196  
   197  // DefaultIPCEndpoint returns the IPC path used by default.
   198  func DefaultIPCEndpoint(clientIdentifier string) string {
   199  	if clientIdentifier == "" {
   200  		clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   201  		if clientIdentifier == "" {
   202  			panic("empty executable name")
   203  		}
   204  	}
   205  	config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
   206  	return config.IPCEndpoint()
   207  }
   208  
   209  // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
   210  // and port parameters.
   211  func (c *Config) HTTPEndpoint() string {
   212  	if c.HTTPHost == "" {
   213  		return ""
   214  	}
   215  	return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
   216  }
   217  
   218  // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
   219  func DefaultHTTPEndpoint() string {
   220  	config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
   221  	return config.HTTPEndpoint()
   222  }
   223  
   224  // WSEndpoint resolves an websocket endpoint based on the configured host interface
   225  // and port parameters.
   226  func (c *Config) WSEndpoint() string {
   227  	if c.WSHost == "" {
   228  		return ""
   229  	}
   230  	return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
   231  }
   232  
   233  // DefaultWSEndpoint returns the websocket endpoint used by default.
   234  func DefaultWSEndpoint() string {
   235  	config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
   236  	return config.WSEndpoint()
   237  }
   238  
   239  // NodeName returns the devp2p node identifier.
   240  func (c *Config) NodeName() string {
   241  	name := c.name()
   242  	// Backwards compatibility: previous versions used title-cased "GoChain", keep that.
   243  	if name == "geth" || name == "geth-testnet" {
   244  		name = "GoChain"
   245  	}
   246  	if c.UserIdent != "" {
   247  		name += "/" + c.UserIdent
   248  	}
   249  	if c.Version != "" {
   250  		name += "/v" + c.Version
   251  	}
   252  	name += "/" + runtime.GOOS + "-" + runtime.GOARCH
   253  	name += "/" + runtime.Version()
   254  	return name
   255  }
   256  
   257  func (c *Config) name() string {
   258  	if c.Name == "" {
   259  		progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
   260  		if progname == "" {
   261  			panic("empty executable name, set Config.Name")
   262  		}
   263  		return progname
   264  	}
   265  	return c.Name
   266  }
   267  
   268  // These resources are resolved differently for "geth" instances.
   269  var isOldGoChainResource = map[string]bool{
   270  	"chaindata":          true,
   271  	"nodes":              true,
   272  	"nodekey":            true,
   273  	"static-nodes.json":  true,
   274  	"trusted-nodes.json": true,
   275  }
   276  
   277  // resolvePath resolves path in the instance directory.
   278  func (c *Config) resolvePath(path string) string {
   279  	if filepath.IsAbs(path) {
   280  		return path
   281  	}
   282  	if c.DataDir == "" {
   283  		return ""
   284  	}
   285  	// Backwards-compatibility: ensure that data directory files created
   286  	// by geth 1.4 are used if they exist.
   287  	if c.name() == "geth" && isOldGoChainResource[path] {
   288  		oldpath := ""
   289  		if c.Name == "geth" {
   290  			oldpath = filepath.Join(c.DataDir, path)
   291  		}
   292  		if oldpath != "" && common.FileExist(oldpath) {
   293  			// TODO: print warning
   294  			return oldpath
   295  		}
   296  	}
   297  	return filepath.Join(c.instanceDir(), path)
   298  }
   299  
   300  func (c *Config) instanceDir() string {
   301  	if c.DataDir == "" {
   302  		return ""
   303  	}
   304  	return filepath.Join(c.DataDir, c.name())
   305  }
   306  
   307  // NodeKey retrieves the currently configured private key of the node, checking
   308  // first any manually set key, falling back to the one found in the configured
   309  // data folder. If no key can be found, a new one is generated.
   310  func (c *Config) NodeKey() *ecdsa.PrivateKey {
   311  	// Use any specifically configured key.
   312  	if c.P2P.PrivateKey != nil {
   313  		return c.P2P.PrivateKey
   314  	}
   315  	// Generate ephemeral key if no datadir is being used.
   316  	if c.DataDir == "" {
   317  		key, err := crypto.GenerateKey()
   318  		if err != nil {
   319  			log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
   320  		}
   321  		return key
   322  	}
   323  
   324  	keyfile := c.resolvePath(datadirPrivateKey)
   325  	if key, err := crypto.LoadECDSA(keyfile); err == nil {
   326  		return key
   327  	}
   328  	// No persistent key found, generate and store a new one.
   329  	key, err := crypto.GenerateKey()
   330  	if err != nil {
   331  		log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
   332  	}
   333  	instanceDir := filepath.Join(c.DataDir, c.name())
   334  	if err := os.MkdirAll(instanceDir, 0700); err != nil {
   335  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   336  		return key
   337  	}
   338  	keyfile = filepath.Join(instanceDir, datadirPrivateKey)
   339  	if err := crypto.SaveECDSA(keyfile, key); err != nil {
   340  		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
   341  	}
   342  	return key
   343  }
   344  
   345  // StaticNodes returns a list of node enode URLs configured as static nodes.
   346  func (c *Config) StaticNodes() []*discover.Node {
   347  	return c.parsePersistentNodes(c.resolvePath(datadirStaticNodes))
   348  }
   349  
   350  // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
   351  func (c *Config) TrustedNodes() []*discover.Node {
   352  	return c.parsePersistentNodes(c.resolvePath(datadirTrustedNodes))
   353  }
   354  
   355  // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
   356  // file from within the data directory.
   357  func (c *Config) parsePersistentNodes(path string) []*discover.Node {
   358  	// Short circuit if no node config is present
   359  	if c.DataDir == "" {
   360  		return nil
   361  	}
   362  	if _, err := os.Stat(path); err != nil {
   363  		return nil
   364  	}
   365  	// Load the nodes from the config file.
   366  	var nodelist []string
   367  	if err := common.LoadJSON(path, &nodelist); err != nil {
   368  		log.Error(fmt.Sprintf("Can't load node file %s: %v", path, err))
   369  		return nil
   370  	}
   371  	// Interpret the list as a discovery node array
   372  	var nodes []*discover.Node
   373  	for _, url := range nodelist {
   374  		if url == "" {
   375  			continue
   376  		}
   377  		node, err := discover.ParseNode(url)
   378  		if err != nil {
   379  			log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
   380  			continue
   381  		}
   382  		nodes = append(nodes, node)
   383  	}
   384  	return nodes
   385  }
   386  
   387  // AccountConfig determines the settings for scrypt and keydirectory
   388  func (c *Config) AccountConfig() (int, int, string, error) {
   389  	scryptN := keystore.StandardScryptN
   390  	scryptP := keystore.StandardScryptP
   391  	if c.UseLightweightKDF {
   392  		scryptN = keystore.LightScryptN
   393  		scryptP = keystore.LightScryptP
   394  	}
   395  
   396  	var (
   397  		keydir string
   398  		err    error
   399  	)
   400  	switch {
   401  	case filepath.IsAbs(c.KeyStoreDir):
   402  		keydir = c.KeyStoreDir
   403  	case c.DataDir != "":
   404  		if c.KeyStoreDir == "" {
   405  			keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
   406  		} else {
   407  			keydir, err = filepath.Abs(c.KeyStoreDir)
   408  		}
   409  	case c.KeyStoreDir != "":
   410  		keydir, err = filepath.Abs(c.KeyStoreDir)
   411  	}
   412  	return scryptN, scryptP, keydir, err
   413  }
   414  
   415  func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
   416  	scryptN, scryptP, keydir, err := conf.AccountConfig()
   417  	var ephemeral string
   418  	if keydir == "" {
   419  		// There is no datadir.
   420  		keydir, err = ioutil.TempDir("", "gochain-keystore")
   421  		ephemeral = keydir
   422  	}
   423  
   424  	if err != nil {
   425  		return nil, "", err
   426  	}
   427  	if err := os.MkdirAll(keydir, 0700); err != nil {
   428  		return nil, "", err
   429  	}
   430  	// Assemble the account manager and supported backends
   431  	backends := []accounts.Backend{
   432  		keystore.NewKeyStore(keydir, scryptN, scryptP),
   433  	}
   434  	if !conf.NoUSB {
   435  		// Start a USB hub for Ledger hardware wallets
   436  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   437  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   438  		} else {
   439  			backends = append(backends, ledgerhub)
   440  		}
   441  		// Start a USB hub for Trezor hardware wallets
   442  		if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
   443  			log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
   444  		} else {
   445  			backends = append(backends, trezorhub)
   446  		}
   447  	}
   448  	return accounts.NewManager(backends...), ephemeral, nil
   449  }