config.go 19 KB

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