config.go 18.9 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package node

import (
	"crypto/ecdsa"
21
	"fmt"
22 23 24
	"io/ioutil"
	"os"
	"path/filepath"
25 26
	"runtime"
	"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 44 45 46 47
	datadirPrivateKey      = "nodekey"            // Path within the datadir to the node's private key
	datadirDefaultKeyStore = "keystore"           // Path within the datadir to the keystore
	datadirStaticNodes     = "static-nodes.json"  // Path within the datadir to the static node list
	datadirTrustedNodes    = "trusted-nodes.json" // Path within the datadir to the trusted node list
	datadirNodeDatabase    = "nodes"              // Path within the datadir to store the node infos
48 49 50 51 52 53
)

// Config represents a small collection of configuration values to fine tune the
// P2P network layer of a protocol stack. These values can be further extended by
// all registered services.
type Config struct {
54 55 56
	// Name sets the instance name of the node. It must not contain the / character and is
	// used in the devp2p node identifier. The instance name of geth is "geth". If no
	// 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 63

	// Version should be set to the version number of the program. It is used
	// in the devp2p node identifier.
64
	Version string `toml:"-"`
65

66 67 68 69 70 71 72
	// DataDir is the file system folder the node should use for any data storage
	// requirements. The configured data directory will not be directly shared with
	// registered services, instead those can use utility methods to create/access
	// databases or flat files. This enables ephemeral nodes which can fully reside
	// in memory.
	DataDir string

73 74 75
	// Configuration of peer-to-peer networking.
	P2P p2p.Config

76 77 78 79 80 81 82
	// KeyStoreDir is the file system folder that contains private keys. The directory can
	// be specified as a relative path, in which case it is resolved relative to the
	// current directory.
	//
	// If KeyStoreDir is empty, the default location is the "keystore" subdirectory of
	// DataDir. If DataDir is unspecified and KeyStoreDir is empty, an ephemeral directory
	// is created by New and destroyed when the node is stopped.
83
	KeyStoreDir string `toml:",omitempty"`
84

85 86 87
	// ExternalSigner specifies an external URI for a clef-type signer
	ExternalSigner string `toml:"omitempty"`

88 89
	// UseLightweightKDF lowers the memory and CPU requirements of the key store
	// scrypt KDF at the expense of security.
90
	UseLightweightKDF bool `toml:",omitempty"`
91

92 93 94
	// InsecureUnlockAllowed allows user to unlock accounts in unsafe http environment.
	InsecureUnlockAllowed bool `toml:",omitempty"`

95 96 97
	// NoUSB disables hardware wallet monitoring and connectivity.
	NoUSB bool `toml:",omitempty"`

98 99 100
	// SmartCardDaemonPath is the path to the smartcard daemon's socket
	SmartCardDaemonPath string `toml:",omitempty"`

101
	// IPCPath is the requested location to place the IPC endpoint. If the path is
102 103 104
	// a simple file name, it is placed inside the data directory (or on the root
	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
	// 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 113
	// default zero value is/ valid and will pick a port number randomly (useful
	// for ephemeral nodes).
114
	HTTPPort int `toml:",omitempty"`
115

116
	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
117 118
	// clients. Please be aware that CORS is a browser enforced security, it's fully
	// useless for custom HTTP clients.
119
	HTTPCors []string `toml:",omitempty"`
120

121 122 123 124 125 126 127 128 129
	// HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
	// This is by default {'localhost'}. Using this prevents attacks like
	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
	// origin. These attacks do not utilize CORS, since they are not cross-domain.
	// By explicitly checking the Host-header, the server will not allow requests
	// made against the server with a malicious host domain.
	// Requests using ip address directly are not affected
	HTTPVirtualHosts []string `toml:",omitempty"`

130
	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
131 132
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
133
	HTTPModules []string `toml:",omitempty"`
134

135 136 137 138
	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
	// interface.
	HTTPTimeouts rpc.HTTPTimeouts

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 145
	// default zero value is/ valid and will pick a port number randomly (useful for
	// ephemeral nodes).
146
	WSPort int `toml:",omitempty"`
147

148
	// WSOrigins is the list of domain to accept websocket requests from. Please be
149 150
	// aware that the server can only act upon the HTTP request the client sends and
	// 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 155
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
156
	WSModules []string `toml:",omitempty"`
157 158 159 160 161 162 163

	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
	// than just the public ones.
	//
	// *WARNING* Only set this if the node is running in a trusted network, exposing
	// private APIs to untrusted users is a major security risk.
	WSExposeAll bool `toml:",omitempty"`
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
	// GraphQLHost is the host interface on which to start the GraphQL server. If this
	// field is empty, no GraphQL API endpoint will be started.
	GraphQLHost string `toml:",omitempty"`

	// GraphQLPort is the TCP port number on which to start the GraphQL server. The
	// default zero value is/ valid and will pick a port number randomly (useful
	// for ephemeral nodes).
	GraphQLPort int `toml:",omitempty"`

	// GraphQLCors is the Cross-Origin Resource Sharing header to send to requesting
	// clients. Please be aware that CORS is a browser enforced security, it's fully
	// useless for custom HTTP clients.
	GraphQLCors []string `toml:",omitempty"`

	// GraphQLVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
	// This is by default {'localhost'}. Using this prevents attacks like
	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
	// origin. These attacks do not utilize CORS, since they are not cross-domain.
	// By explicitly checking the Host-header, the server will not allow requests
	// made against the server with a malicious host domain.
	// Requests using ip address directly are not affected
	GraphQLVirtualHosts []string `toml:",omitempty"`

188
	// Logger is a custom logger to use with the p2p.Server.
189
	Logger log.Logger `toml:",omitempty"`
190 191 192 193

	staticNodesWarning     bool
	trustedNodesWarning    bool
	oldGethResourceWarning bool
194 195
}

196
// IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
197 198
// account the set data folders as well as the designated platform we're currently
// running on.
199
func (c *Config) IPCEndpoint() string {
200
	// Short circuit if IPC has not been enabled
201
	if c.IPCPath == "" {
202 203 204 205
		return ""
	}
	// On windows we can only use plain top-level pipes
	if runtime.GOOS == "windows" {
206 207
		if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
			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 222 223 224 225
// NodeDB returns the path to the discovery node database.
func (c *Config) NodeDB() string {
	if c.DataDir == "" {
		return "" // ephemeral
	}
226
	return c.ResolvePath(datadirNodeDatabase)
227 228
}

229
// DefaultIPCEndpoint returns the IPC path used by default.
230 231 232 233 234 235 236
func DefaultIPCEndpoint(clientIdentifier string) string {
	if clientIdentifier == "" {
		clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
		if clientIdentifier == "" {
			panic("empty executable name")
		}
	}
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 244
func (c *Config) HTTPEndpoint() string {
	if c.HTTPHost == "" {
245 246
		return ""
	}
247
	return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
248 249
}

250 251 252 253 254 255 256 257 258
// GraphQLEndpoint resolves a GraphQL endpoint based on the configured host interface
// and port parameters.
func (c *Config) GraphQLEndpoint() string {
	if c.GraphQLHost == "" {
		return ""
	}
	return fmt.Sprintf("%s:%d", c.GraphQLHost, c.GraphQLPort)
}

259 260
// DefaultHTTPEndpoint returns the HTTP endpoint used by default.
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 268
func (c *Config) WSEndpoint() string {
	if c.WSHost == "" {
269 270
		return ""
	}
271
	return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
272 273
}

274 275
// DefaultWSEndpoint returns the websocket endpoint used by default.
func DefaultWSEndpoint() string {
276
	config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
277
	return config.WSEndpoint()
278 279
}

280 281 282 283 284 285
// ExtRPCEnabled returns the indicator whether node enables the external
// RPC(http, ws or graphql).
func (c *Config) ExtRPCEnabled() bool {
	return c.HTTPHost != "" || c.WSHost != "" || c.GraphQLHost != ""
}

286 287 288 289 290 291 292 293 294 295 296 297 298
// NodeName returns the devp2p node identifier.
func (c *Config) NodeName() string {
	name := c.name()
	// Backwards compatibility: previous versions used title-cased "Geth", keep that.
	if name == "geth" || name == "geth-testnet" {
		name = "Geth"
	}
	if c.UserIdent != "" {
		name += "/" + c.UserIdent
	}
	if c.Version != "" {
		name += "/v" + c.Version
	}
299
	name += "/" + runtime.GOOS + "-" + runtime.GOARCH
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	name += "/" + runtime.Version()
	return name
}

func (c *Config) name() string {
	if c.Name == "" {
		progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
		if progname == "" {
			panic("empty executable name, set Config.Name")
		}
		return progname
	}
	return c.Name
}

315
// These resources are resolved differently for "geth" instances.
316 317 318 319
var isOldGethResource = map[string]bool{
	"chaindata":          true,
	"nodes":              true,
	"nodekey":            true,
320 321
	"static-nodes.json":  false, // no warning for these because they have their
	"trusted-nodes.json": false, // own separate warning.
322 323
}

324 325
// ResolvePath resolves path in the instance directory.
func (c *Config) ResolvePath(path string) string {
326 327 328 329 330 331 332 333
	if filepath.IsAbs(path) {
		return path
	}
	if c.DataDir == "" {
		return ""
	}
	// Backwards-compatibility: ensure that data directory files created
	// by geth 1.4 are used if they exist.
334
	if warn, isOld := isOldGethResource[path]; isOld {
335
		oldpath := ""
336
		if c.name() == "geth" {
337 338 339
			oldpath = filepath.Join(c.DataDir, path)
		}
		if oldpath != "" && common.FileExist(oldpath) {
340 341 342
			if warn {
				c.warnOnce(&c.oldGethResourceWarning, "Using deprecated resource file %s, please move this file to the 'geth' subdirectory of datadir.", oldpath)
			}
343 344 345
			return oldpath
		}
	}
346 347 348 349 350 351 352 353
	return filepath.Join(c.instanceDir(), path)
}

func (c *Config) instanceDir() string {
	if c.DataDir == "" {
		return ""
	}
	return filepath.Join(c.DataDir, c.name())
354 355
}

356 357 358 359
// NodeKey retrieves the currently configured private key of the node, checking
// first any manually set key, falling back to the one found in the configured
// data folder. If no key can be found, a new one is generated.
func (c *Config) NodeKey() *ecdsa.PrivateKey {
360
	// Use any specifically configured key.
361 362
	if c.P2P.PrivateKey != nil {
		return c.P2P.PrivateKey
363
	}
364
	// Generate ephemeral key if no datadir is being used.
365 366 367
	if c.DataDir == "" {
		key, err := crypto.GenerateKey()
		if err != nil {
368
			log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
369 370 371
		}
		return key
	}
372

373
	keyfile := c.ResolvePath(datadirPrivateKey)
374 375 376
	if key, err := crypto.LoadECDSA(keyfile); err == nil {
		return key
	}
377
	// No persistent key found, generate and store a new one.
378 379
	key, err := crypto.GenerateKey()
	if err != nil {
380
		log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
381
	}
382 383
	instanceDir := filepath.Join(c.DataDir, c.name())
	if err := os.MkdirAll(instanceDir, 0700); err != nil {
384
		log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
385 386 387
		return key
	}
	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 392 393 394
	}
	return key
}

// 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 405
}

// parsePersistentNodes parses a list of discovery node URLs loaded from a .json
// file from within the data directory.
406
func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node {
407 408 409 410 411 412 413
	// Short circuit if no node config is present
	if c.DataDir == "" {
		return nil
	}
	if _, err := os.Stat(path); err != nil {
		return nil
	}
414 415
	c.warnOnce(w, "Found deprecated node list file %s, please use the TOML config file instead.", path)

416 417 418
	// Load the nodes from the config file.
	var nodelist []string
	if err := common.LoadJSON(path, &nodelist); err != nil {
419
		log.Error(fmt.Sprintf("Can't load node list file: %v", err))
420 421 422
		return nil
	}
	// Interpret the list as a discovery node array
423
	var nodes []*enode.Node
424 425 426 427
	for _, url := range nodelist {
		if url == "" {
			continue
		}
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 432 433 434 435 436
			continue
		}
		nodes = append(nodes, node)
	}
	return nodes
}
437

438 439
// AccountConfig determines the settings for scrypt and keydirectory
func (c *Config) AccountConfig() (int, int, string, error) {
440 441
	scryptN := keystore.StandardScryptN
	scryptP := keystore.StandardScryptP
442
	if c.UseLightweightKDF {
443 444
		scryptN = keystore.LightScryptN
		scryptP = keystore.LightScryptP
445 446
	}

447
	var (
448 449
		keydir string
		err    error
450
	)
451
	switch {
452 453 454 455 456
	case filepath.IsAbs(c.KeyStoreDir):
		keydir = c.KeyStoreDir
	case c.DataDir != "":
		if c.KeyStoreDir == "" {
			keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
457
		} else {
458
			keydir, err = filepath.Abs(c.KeyStoreDir)
459
		}
460 461 462 463 464 465 466 467 468 469
	case c.KeyStoreDir != "":
		keydir, err = filepath.Abs(c.KeyStoreDir)
	}
	return scryptN, scryptP, keydir, err
}

func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
	scryptN, scryptP, keydir, err := conf.AccountConfig()
	var ephemeral string
	if keydir == "" {
470 471
		// There is no datadir.
		keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
472
		ephemeral = keydir
473
	}
474

475 476 477 478 479 480
	if err != nil {
		return nil, "", err
	}
	if err := os.MkdirAll(keydir, 0700); err != nil {
		return nil, "", err
	}
481
	// Assemble the account manager and supported backends
482
	var backends []accounts.Backend
483 484 485 486
	if len(conf.ExternalSigner) > 0 {
		log.Info("Using external signer", "url", conf.ExternalSigner)
		if extapi, err := external.NewExternalBackend(conf.ExternalSigner); err == nil {
			backends = append(backends, extapi)
487
		} else {
488
			return nil, "", fmt.Errorf("error connecting to external signer: %v", err)
489
		}
490 491 492 493 494 495 496 497 498 499 500 501 502 503
	}
	if len(backends) == 0 {
		// For now, we're using EITHER external signer OR local signers.
		// If/when we implement some form of lockfile for USB and keystore wallets,
		// we can have both, but it's very confusing for the user to see the same
		// accounts in both externally and locally, plus very racey.
		backends = append(backends, keystore.NewKeyStore(keydir, scryptN, scryptP))
		if !conf.NoUSB {
			// Start a USB hub for Ledger hardware wallets
			if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
				log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
			} else {
				backends = append(backends, ledgerhub)
			}
504 505 506
			// Start a USB hub for Trezor hardware wallets (HID version)
			if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
				log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
507 508 509
			} else {
				backends = append(backends, trezorhub)
			}
510
			// Start a USB hub for Trezor hardware wallets (WebUSB version)
511 512
			if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
				log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
513 514 515
			} else {
				backends = append(backends, trezorhub)
			}
516
		}
517 518 519 520 521 522 523
		if len(conf.SmartCardDaemonPath) > 0 {
			// Start a smart card hub
			if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil {
				log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
			} else {
				backends = append(backends, schub)
			}
524
		}
525
	}
526

527
	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}, backends...), ephemeral, nil
528
}
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

var warnLock sync.Mutex

func (c *Config) warnOnce(w *bool, format string, args ...interface{}) {
	warnLock.Lock()
	defer warnLock.Unlock()

	if *w {
		return
	}
	l := c.Logger
	if l == nil {
		l = log.Root()
	}
	l.Warn(fmt.Sprintf(format, args...))
	*w = true
}