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