github.com/rayrapetyan/go-ethereum@v1.8.21/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/ethereum/go-ethereum/accounts" 30 "github.com/ethereum/go-ethereum/accounts/keystore" 31 "github.com/ethereum/go-ethereum/accounts/usbwallet" 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/log" 35 "github.com/ethereum/go-ethereum/p2p" 36 "github.com/ethereum/go-ethereum/p2p/enode" 37 "github.com/ethereum/go-ethereum/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 // WSHost is the host interface on which to start the websocket RPC server. If 129 // this field is empty, no websocket API endpoint will be started. 130 WSHost string `toml:",omitempty"` 131 132 // WSPort is the TCP port number on which to start the websocket RPC server. The 133 // default zero value is/ valid and will pick a port number randomly (useful for 134 // ephemeral nodes). 135 WSPort int `toml:",omitempty"` 136 137 // WSOrigins is the list of domain to accept websocket requests from. Please be 138 // aware that the server can only act upon the HTTP request the client sends and 139 // cannot verify the validity of the request header. 140 WSOrigins []string `toml:",omitempty"` 141 142 // WSModules is a list of API modules to expose via the websocket RPC interface. 143 // If the module list is empty, all RPC API endpoints designated public will be 144 // exposed. 145 WSModules []string `toml:",omitempty"` 146 147 // WSExposeAll exposes all API modules via the WebSocket RPC interface rather 148 // than just the public ones. 149 // 150 // *WARNING* Only set this if the node is running in a trusted network, exposing 151 // private APIs to untrusted users is a major security risk. 152 WSExposeAll bool `toml:",omitempty"` 153 154 // Logger is a custom logger to use with the p2p.Server. 155 Logger log.Logger `toml:",omitempty"` 156 157 staticNodesWarning bool 158 trustedNodesWarning bool 159 oldGethResourceWarning bool 160 } 161 162 // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into 163 // account the set data folders as well as the designated platform we're currently 164 // running on. 165 func (c *Config) IPCEndpoint() string { 166 // Short circuit if IPC has not been enabled 167 if c.IPCPath == "" { 168 return "" 169 } 170 // On windows we can only use plain top-level pipes 171 if runtime.GOOS == "windows" { 172 if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) { 173 return c.IPCPath 174 } 175 return `\\.\pipe\` + c.IPCPath 176 } 177 // Resolve names into the data directory full paths otherwise 178 if filepath.Base(c.IPCPath) == c.IPCPath { 179 if c.DataDir == "" { 180 return filepath.Join(os.TempDir(), c.IPCPath) 181 } 182 return filepath.Join(c.DataDir, c.IPCPath) 183 } 184 return c.IPCPath 185 } 186 187 // NodeDB returns the path to the discovery node database. 188 func (c *Config) NodeDB() string { 189 if c.DataDir == "" { 190 return "" // ephemeral 191 } 192 return c.ResolvePath(datadirNodeDatabase) 193 } 194 195 // DefaultIPCEndpoint returns the IPC path used by default. 196 func DefaultIPCEndpoint(clientIdentifier string) string { 197 if clientIdentifier == "" { 198 clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe") 199 if clientIdentifier == "" { 200 panic("empty executable name") 201 } 202 } 203 config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"} 204 return config.IPCEndpoint() 205 } 206 207 // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface 208 // and port parameters. 209 func (c *Config) HTTPEndpoint() string { 210 if c.HTTPHost == "" { 211 return "" 212 } 213 return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort) 214 } 215 216 // DefaultHTTPEndpoint returns the HTTP endpoint used by default. 217 func DefaultHTTPEndpoint() string { 218 config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort} 219 return config.HTTPEndpoint() 220 } 221 222 // WSEndpoint resolves a websocket endpoint based on the configured host interface 223 // and port parameters. 224 func (c *Config) WSEndpoint() string { 225 if c.WSHost == "" { 226 return "" 227 } 228 return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort) 229 } 230 231 // DefaultWSEndpoint returns the websocket endpoint used by default. 232 func DefaultWSEndpoint() string { 233 config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort} 234 return config.WSEndpoint() 235 } 236 237 // NodeName returns the devp2p node identifier. 238 func (c *Config) NodeName() string { 239 name := c.name() 240 // Backwards compatibility: previous versions used title-cased "Geth", keep that. 241 if name == "geth" || name == "geth-testnet" { 242 name = "Geth" 243 } 244 if c.UserIdent != "" { 245 name += "/" + c.UserIdent 246 } 247 if c.Version != "" { 248 name += "/v" + c.Version 249 } 250 name += "/" + runtime.GOOS + "-" + runtime.GOARCH 251 name += "/" + runtime.Version() 252 return name 253 } 254 255 func (c *Config) name() string { 256 if c.Name == "" { 257 progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe") 258 if progname == "" { 259 panic("empty executable name, set Config.Name") 260 } 261 return progname 262 } 263 return c.Name 264 } 265 266 // These resources are resolved differently for "geth" instances. 267 var isOldGethResource = map[string]bool{ 268 "chaindata": true, 269 "nodes": true, 270 "nodekey": true, 271 "static-nodes.json": false, // no warning for these because they have their 272 "trusted-nodes.json": false, // own separate warning. 273 } 274 275 // ResolvePath resolves path in the instance directory. 276 func (c *Config) ResolvePath(path string) string { 277 if filepath.IsAbs(path) { 278 return path 279 } 280 if c.DataDir == "" { 281 return "" 282 } 283 // Backwards-compatibility: ensure that data directory files created 284 // by geth 1.4 are used if they exist. 285 if warn, isOld := isOldGethResource[path]; isOld { 286 oldpath := "" 287 if c.name() == "geth" { 288 oldpath = filepath.Join(c.DataDir, path) 289 } 290 if oldpath != "" && common.FileExist(oldpath) { 291 if warn { 292 c.warnOnce(&c.oldGethResourceWarning, "Using deprecated resource file %s, please move this file to the 'geth' subdirectory of datadir.", oldpath) 293 } 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() []*enode.Node { 347 return c.parsePersistentNodes(&c.staticNodesWarning, c.ResolvePath(datadirStaticNodes)) 348 } 349 350 // TrustedNodes returns a list of node enode URLs configured as trusted nodes. 351 func (c *Config) TrustedNodes() []*enode.Node { 352 return c.parsePersistentNodes(&c.trustedNodesWarning, 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(w *bool, path string) []*enode.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 c.warnOnce(w, "Found deprecated node list file %s, please use the TOML config file instead.", path) 366 367 // Load the nodes from the config file. 368 var nodelist []string 369 if err := common.LoadJSON(path, &nodelist); err != nil { 370 log.Error(fmt.Sprintf("Can't load node list file: %v", err)) 371 return nil 372 } 373 // Interpret the list as a discovery node array 374 var nodes []*enode.Node 375 for _, url := range nodelist { 376 if url == "" { 377 continue 378 } 379 node, err := enode.ParseV4(url) 380 if err != nil { 381 log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err)) 382 continue 383 } 384 nodes = append(nodes, node) 385 } 386 return nodes 387 } 388 389 // AccountConfig determines the settings for scrypt and keydirectory 390 func (c *Config) AccountConfig() (int, int, string, error) { 391 scryptN := keystore.StandardScryptN 392 scryptP := keystore.StandardScryptP 393 if c.UseLightweightKDF { 394 scryptN = keystore.LightScryptN 395 scryptP = keystore.LightScryptP 396 } 397 398 var ( 399 keydir string 400 err error 401 ) 402 switch { 403 case filepath.IsAbs(c.KeyStoreDir): 404 keydir = c.KeyStoreDir 405 case c.DataDir != "": 406 if c.KeyStoreDir == "" { 407 keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore) 408 } else { 409 keydir, err = filepath.Abs(c.KeyStoreDir) 410 } 411 case c.KeyStoreDir != "": 412 keydir, err = filepath.Abs(c.KeyStoreDir) 413 } 414 return scryptN, scryptP, keydir, err 415 } 416 417 func makeAccountManager(conf *Config) (*accounts.Manager, string, error) { 418 scryptN, scryptP, keydir, err := conf.AccountConfig() 419 var ephemeral string 420 if keydir == "" { 421 // There is no datadir. 422 keydir, err = ioutil.TempDir("", "go-ethereum-keystore") 423 ephemeral = keydir 424 } 425 426 if err != nil { 427 return nil, "", err 428 } 429 if err := os.MkdirAll(keydir, 0700); err != nil { 430 return nil, "", err 431 } 432 // Assemble the account manager and supported backends 433 backends := []accounts.Backend{ 434 keystore.NewKeyStore(keydir, scryptN, scryptP), 435 } 436 if !conf.NoUSB { 437 // Start a USB hub for Ledger hardware wallets 438 if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil { 439 log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err)) 440 } else { 441 backends = append(backends, ledgerhub) 442 } 443 // Start a USB hub for Trezor hardware wallets 444 if trezorhub, err := usbwallet.NewTrezorHub(); err != nil { 445 log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err)) 446 } else { 447 backends = append(backends, trezorhub) 448 } 449 } 450 return accounts.NewManager(backends...), ephemeral, nil 451 } 452 453 var warnLock sync.Mutex 454 455 func (c *Config) warnOnce(w *bool, format string, args ...interface{}) { 456 warnLock.Lock() 457 defer warnLock.Unlock() 458 459 if *w { 460 return 461 } 462 l := c.Logger 463 if l == nil { 464 l = log.Root() 465 } 466 l.Warn(fmt.Sprintf(format, args...)) 467 *w = true 468 }