config.go 15 KB

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