config.go 14 KB

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