config.go 15 KB

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