config.go 14 KB

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