config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. const (
  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. // WSExposeAll exposes all API modules via the WebSocket RPC interface rather
  111. // than just the public ones.
  112. //
  113. // *WARNING* Only set this if the node is running in a trusted network, exposing
  114. // private APIs to untrusted users is a major security risk.
  115. WSExposeAll bool `toml:",omitempty"`
  116. }
  117. // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
  118. // account the set data folders as well as the designated platform we're currently
  119. // running on.
  120. func (c *Config) IPCEndpoint() string {
  121. // Short circuit if IPC has not been enabled
  122. if c.IPCPath == "" {
  123. return ""
  124. }
  125. // On windows we can only use plain top-level pipes
  126. if runtime.GOOS == "windows" {
  127. if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
  128. return c.IPCPath
  129. }
  130. return `\\.\pipe\` + c.IPCPath
  131. }
  132. // Resolve names into the data directory full paths otherwise
  133. if filepath.Base(c.IPCPath) == c.IPCPath {
  134. if c.DataDir == "" {
  135. return filepath.Join(os.TempDir(), c.IPCPath)
  136. }
  137. return filepath.Join(c.DataDir, c.IPCPath)
  138. }
  139. return c.IPCPath
  140. }
  141. // NodeDB returns the path to the discovery node database.
  142. func (c *Config) NodeDB() string {
  143. if c.DataDir == "" {
  144. return "" // ephemeral
  145. }
  146. return c.resolvePath(datadirNodeDatabase)
  147. }
  148. // DefaultIPCEndpoint returns the IPC path used by default.
  149. func DefaultIPCEndpoint(clientIdentifier string) string {
  150. if clientIdentifier == "" {
  151. clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
  152. if clientIdentifier == "" {
  153. panic("empty executable name")
  154. }
  155. }
  156. config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
  157. return config.IPCEndpoint()
  158. }
  159. // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
  160. // and port parameters.
  161. func (c *Config) HTTPEndpoint() string {
  162. if c.HTTPHost == "" {
  163. return ""
  164. }
  165. return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
  166. }
  167. // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
  168. func DefaultHTTPEndpoint() string {
  169. config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
  170. return config.HTTPEndpoint()
  171. }
  172. // WSEndpoint resolves an websocket endpoint based on the configured host interface
  173. // and port parameters.
  174. func (c *Config) WSEndpoint() string {
  175. if c.WSHost == "" {
  176. return ""
  177. }
  178. return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
  179. }
  180. // DefaultWSEndpoint returns the websocket endpoint used by default.
  181. func DefaultWSEndpoint() string {
  182. config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
  183. return config.WSEndpoint()
  184. }
  185. // NodeName returns the devp2p node identifier.
  186. func (c *Config) NodeName() string {
  187. name := c.name()
  188. // Backwards compatibility: previous versions used title-cased "Geth", keep that.
  189. if name == "geth" || name == "geth-testnet" {
  190. name = "Geth"
  191. }
  192. if c.UserIdent != "" {
  193. name += "/" + c.UserIdent
  194. }
  195. if c.Version != "" {
  196. name += "/v" + c.Version
  197. }
  198. name += "/" + runtime.GOOS + "-" + runtime.GOARCH
  199. name += "/" + runtime.Version()
  200. return name
  201. }
  202. func (c *Config) name() string {
  203. if c.Name == "" {
  204. progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
  205. if progname == "" {
  206. panic("empty executable name, set Config.Name")
  207. }
  208. return progname
  209. }
  210. return c.Name
  211. }
  212. // These resources are resolved differently for "geth" instances.
  213. var isOldGethResource = map[string]bool{
  214. "chaindata": true,
  215. "nodes": true,
  216. "nodekey": true,
  217. "static-nodes.json": true,
  218. "trusted-nodes.json": true,
  219. }
  220. // resolvePath resolves path in the instance directory.
  221. func (c *Config) resolvePath(path string) string {
  222. if filepath.IsAbs(path) {
  223. return path
  224. }
  225. if c.DataDir == "" {
  226. return ""
  227. }
  228. // Backwards-compatibility: ensure that data directory files created
  229. // by geth 1.4 are used if they exist.
  230. if c.name() == "geth" && isOldGethResource[path] {
  231. oldpath := ""
  232. if c.Name == "geth" {
  233. oldpath = filepath.Join(c.DataDir, path)
  234. }
  235. if oldpath != "" && common.FileExist(oldpath) {
  236. // TODO: print warning
  237. return oldpath
  238. }
  239. }
  240. return filepath.Join(c.instanceDir(), path)
  241. }
  242. func (c *Config) instanceDir() string {
  243. if c.DataDir == "" {
  244. return ""
  245. }
  246. return filepath.Join(c.DataDir, c.name())
  247. }
  248. // NodeKey retrieves the currently configured private key of the node, checking
  249. // first any manually set key, falling back to the one found in the configured
  250. // data folder. If no key can be found, a new one is generated.
  251. func (c *Config) NodeKey() *ecdsa.PrivateKey {
  252. // Use any specifically configured key.
  253. if c.P2P.PrivateKey != nil {
  254. return c.P2P.PrivateKey
  255. }
  256. // Generate ephemeral key if no datadir is being used.
  257. if c.DataDir == "" {
  258. key, err := crypto.GenerateKey()
  259. if err != nil {
  260. log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
  261. }
  262. return key
  263. }
  264. keyfile := c.resolvePath(datadirPrivateKey)
  265. if key, err := crypto.LoadECDSA(keyfile); err == nil {
  266. return key
  267. }
  268. // No persistent key found, generate and store a new one.
  269. key, err := crypto.GenerateKey()
  270. if err != nil {
  271. log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
  272. }
  273. instanceDir := filepath.Join(c.DataDir, c.name())
  274. if err := os.MkdirAll(instanceDir, 0700); err != nil {
  275. log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
  276. return key
  277. }
  278. keyfile = filepath.Join(instanceDir, datadirPrivateKey)
  279. if err := crypto.SaveECDSA(keyfile, key); err != nil {
  280. log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
  281. }
  282. return key
  283. }
  284. // StaticNodes returns a list of node enode URLs configured as static nodes.
  285. func (c *Config) StaticNodes() []*discover.Node {
  286. return c.parsePersistentNodes(c.resolvePath(datadirStaticNodes))
  287. }
  288. // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
  289. func (c *Config) TrustedNodes() []*discover.Node {
  290. return c.parsePersistentNodes(c.resolvePath(datadirTrustedNodes))
  291. }
  292. // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
  293. // file from within the data directory.
  294. func (c *Config) parsePersistentNodes(path string) []*discover.Node {
  295. // Short circuit if no node config is present
  296. if c.DataDir == "" {
  297. return nil
  298. }
  299. if _, err := os.Stat(path); err != nil {
  300. return nil
  301. }
  302. // Load the nodes from the config file.
  303. var nodelist []string
  304. if err := common.LoadJSON(path, &nodelist); err != nil {
  305. log.Error(fmt.Sprintf("Can't load node file %s: %v", path, err))
  306. return nil
  307. }
  308. // Interpret the list as a discovery node array
  309. var nodes []*discover.Node
  310. for _, url := range nodelist {
  311. if url == "" {
  312. continue
  313. }
  314. node, err := discover.ParseNode(url)
  315. if err != nil {
  316. log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
  317. continue
  318. }
  319. nodes = append(nodes, node)
  320. }
  321. return nodes
  322. }
  323. // AccountConfig determines the settings for scrypt and keydirectory
  324. func (c *Config) AccountConfig() (int, int, string, error) {
  325. scryptN := keystore.StandardScryptN
  326. scryptP := keystore.StandardScryptP
  327. if c.UseLightweightKDF {
  328. scryptN = keystore.LightScryptN
  329. scryptP = keystore.LightScryptP
  330. }
  331. var (
  332. keydir string
  333. err error
  334. )
  335. switch {
  336. case filepath.IsAbs(c.KeyStoreDir):
  337. keydir = c.KeyStoreDir
  338. case c.DataDir != "":
  339. if c.KeyStoreDir == "" {
  340. keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
  341. } else {
  342. keydir, err = filepath.Abs(c.KeyStoreDir)
  343. }
  344. case c.KeyStoreDir != "":
  345. keydir, err = filepath.Abs(c.KeyStoreDir)
  346. }
  347. return scryptN, scryptP, keydir, err
  348. }
  349. func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
  350. scryptN, scryptP, keydir, err := conf.AccountConfig()
  351. var ephemeral string
  352. if keydir == "" {
  353. // There is no datadir.
  354. keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
  355. ephemeral = keydir
  356. }
  357. if err != nil {
  358. return nil, "", err
  359. }
  360. if err := os.MkdirAll(keydir, 0700); err != nil {
  361. return nil, "", err
  362. }
  363. // Assemble the account manager and supported backends
  364. backends := []accounts.Backend{
  365. keystore.NewKeyStore(keydir, scryptN, scryptP),
  366. }
  367. if !conf.NoUSB {
  368. // Start a USB hub for Ledger hardware wallets
  369. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  370. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  371. } else {
  372. backends = append(backends, ledgerhub)
  373. }
  374. // Start a USB hub for Trezor hardware wallets
  375. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  376. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  377. } else {
  378. backends = append(backends, trezorhub)
  379. }
  380. }
  381. return accounts.NewManager(backends...), ephemeral, nil
  382. }