config.go 15 KB

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