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