config.go 13 KB

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