config.go 14 KB

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