config.go 14 KB

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