config.go 14 KB

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