config.go 19 KB

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