config.go 15 KB

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