config.go 17 KB

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