config.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. "github.com/ethereum/go-ethereum/rpc"
  34. )
  35. const (
  36. datadirPrivateKey = "nodekey" // Path within the datadir to the node's private key
  37. datadirDefaultKeyStore = "keystore" // Path within the datadir to the keystore
  38. datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list
  39. datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list
  40. datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos
  41. )
  42. // Config represents a small collection of configuration values to fine tune the
  43. // P2P network layer of a protocol stack. These values can be further extended by
  44. // all registered services.
  45. type Config struct {
  46. // Name sets the instance name of the node. It must not contain the / character and is
  47. // used in the devp2p node identifier. The instance name of geth is "geth". If no
  48. // value is specified, the basename of the current executable is used.
  49. Name string `toml:"-"`
  50. // UserIdent, if set, is used as an additional component in the devp2p node identifier.
  51. UserIdent string `toml:",omitempty"`
  52. // Version should be set to the version number of the program. It is used
  53. // in the devp2p node identifier.
  54. Version string `toml:"-"`
  55. // DataDir is the file system folder the node should use for any data storage
  56. // requirements. The configured data directory will not be directly shared with
  57. // registered services, instead those can use utility methods to create/access
  58. // databases or flat files. This enables ephemeral nodes which can fully reside
  59. // in memory.
  60. DataDir string
  61. // Configuration of peer-to-peer networking.
  62. P2P p2p.Config
  63. // KeyStoreDir is the file system folder that contains private keys. The directory can
  64. // be specified as a relative path, in which case it is resolved relative to the
  65. // current directory.
  66. //
  67. // If KeyStoreDir is empty, the default location is the "keystore" subdirectory of
  68. // DataDir. If DataDir is unspecified and KeyStoreDir is empty, an ephemeral directory
  69. // is created by New and destroyed when the node is stopped.
  70. KeyStoreDir string `toml:",omitempty"`
  71. // UseLightweightKDF lowers the memory and CPU requirements of the key store
  72. // scrypt KDF at the expense of security.
  73. UseLightweightKDF bool `toml:",omitempty"`
  74. // NoUSB disables hardware wallet monitoring and connectivity.
  75. NoUSB bool `toml:",omitempty"`
  76. // IPCPath is the requested location to place the IPC endpoint. If the path is
  77. // a simple file name, it is placed inside the data directory (or on the root
  78. // pipe path on Windows), whereas if it's a resolvable path name (absolute or
  79. // relative), then that specific path is enforced. An empty path disables IPC.
  80. IPCPath string `toml:",omitempty"`
  81. // HTTPHost is the host interface on which to start the HTTP RPC server. If this
  82. // field is empty, no HTTP API endpoint will be started.
  83. HTTPHost string `toml:",omitempty"`
  84. // HTTPPort is the TCP port number on which to start the HTTP RPC server. The
  85. // default zero value is/ valid and will pick a port number randomly (useful
  86. // for ephemeral nodes).
  87. HTTPPort int `toml:",omitempty"`
  88. // HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
  89. // clients. Please be aware that CORS is a browser enforced security, it's fully
  90. // useless for custom HTTP clients.
  91. HTTPCors []string `toml:",omitempty"`
  92. // HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
  93. // This is by default {'localhost'}. Using this prevents attacks like
  94. // DNS rebinding, which bypasses SOP by simply masquerading as being within the same
  95. // origin. These attacks do not utilize CORS, since they are not cross-domain.
  96. // By explicitly checking the Host-header, the server will not allow requests
  97. // made against the server with a malicious host domain.
  98. // Requests using ip address directly are not affected
  99. HTTPVirtualHosts []string `toml:",omitempty"`
  100. // HTTPModules is a list of API modules to expose via the HTTP RPC interface.
  101. // If the module list is empty, all RPC API endpoints designated public will be
  102. // exposed.
  103. HTTPModules []string `toml:",omitempty"`
  104. // HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
  105. // interface.
  106. HTTPTimeouts rpc.HTTPTimeouts
  107. // WSHost is the host interface on which to start the websocket RPC server. If
  108. // this field is empty, no websocket API endpoint will be started.
  109. WSHost string `toml:",omitempty"`
  110. // WSPort is the TCP port number on which to start the websocket RPC server. The
  111. // default zero value is/ valid and will pick a port number randomly (useful for
  112. // ephemeral nodes).
  113. WSPort int `toml:",omitempty"`
  114. // WSOrigins is the list of domain to accept websocket requests from. Please be
  115. // aware that the server can only act upon the HTTP request the client sends and
  116. // cannot verify the validity of the request header.
  117. WSOrigins []string `toml:",omitempty"`
  118. // WSModules is a list of API modules to expose via the websocket RPC interface.
  119. // If the module list is empty, all RPC API endpoints designated public will be
  120. // exposed.
  121. WSModules []string `toml:",omitempty"`
  122. // WSExposeAll exposes all API modules via the WebSocket RPC interface rather
  123. // than just the public ones.
  124. //
  125. // *WARNING* Only set this if the node is running in a trusted network, exposing
  126. // private APIs to untrusted users is a major security risk.
  127. WSExposeAll bool `toml:",omitempty"`
  128. // Logger is a custom logger to use with the p2p.Server.
  129. Logger log.Logger `toml:",omitempty"`
  130. }
  131. // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
  132. // account the set data folders as well as the designated platform we're currently
  133. // running on.
  134. func (c *Config) IPCEndpoint() string {
  135. // Short circuit if IPC has not been enabled
  136. if c.IPCPath == "" {
  137. return ""
  138. }
  139. // On windows we can only use plain top-level pipes
  140. if runtime.GOOS == "windows" {
  141. if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
  142. return c.IPCPath
  143. }
  144. return `\\.\pipe\` + c.IPCPath
  145. }
  146. // Resolve names into the data directory full paths otherwise
  147. if filepath.Base(c.IPCPath) == c.IPCPath {
  148. if c.DataDir == "" {
  149. return filepath.Join(os.TempDir(), c.IPCPath)
  150. }
  151. return filepath.Join(c.DataDir, c.IPCPath)
  152. }
  153. return c.IPCPath
  154. }
  155. // NodeDB returns the path to the discovery node database.
  156. func (c *Config) NodeDB() string {
  157. if c.DataDir == "" {
  158. return "" // ephemeral
  159. }
  160. return c.ResolvePath(datadirNodeDatabase)
  161. }
  162. // DefaultIPCEndpoint returns the IPC path used by default.
  163. func DefaultIPCEndpoint(clientIdentifier string) string {
  164. if clientIdentifier == "" {
  165. clientIdentifier = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
  166. if clientIdentifier == "" {
  167. panic("empty executable name")
  168. }
  169. }
  170. config := &Config{DataDir: DefaultDataDir(), IPCPath: clientIdentifier + ".ipc"}
  171. return config.IPCEndpoint()
  172. }
  173. // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
  174. // and port parameters.
  175. func (c *Config) HTTPEndpoint() string {
  176. if c.HTTPHost == "" {
  177. return ""
  178. }
  179. return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
  180. }
  181. // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
  182. func DefaultHTTPEndpoint() string {
  183. config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
  184. return config.HTTPEndpoint()
  185. }
  186. // WSEndpoint resolves a websocket endpoint based on the configured host interface
  187. // and port parameters.
  188. func (c *Config) WSEndpoint() string {
  189. if c.WSHost == "" {
  190. return ""
  191. }
  192. return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
  193. }
  194. // DefaultWSEndpoint returns the websocket endpoint used by default.
  195. func DefaultWSEndpoint() string {
  196. config := &Config{WSHost: DefaultWSHost, WSPort: DefaultWSPort}
  197. return config.WSEndpoint()
  198. }
  199. // NodeName returns the devp2p node identifier.
  200. func (c *Config) NodeName() string {
  201. name := c.name()
  202. // Backwards compatibility: previous versions used title-cased "Geth", keep that.
  203. if name == "geth" || name == "geth-testnet" {
  204. name = "Geth"
  205. }
  206. if c.UserIdent != "" {
  207. name += "/" + c.UserIdent
  208. }
  209. if c.Version != "" {
  210. name += "/v" + c.Version
  211. }
  212. name += "/" + runtime.GOOS + "-" + runtime.GOARCH
  213. name += "/" + runtime.Version()
  214. return name
  215. }
  216. func (c *Config) name() string {
  217. if c.Name == "" {
  218. progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
  219. if progname == "" {
  220. panic("empty executable name, set Config.Name")
  221. }
  222. return progname
  223. }
  224. return c.Name
  225. }
  226. // These resources are resolved differently for "geth" instances.
  227. var isOldGethResource = map[string]bool{
  228. "chaindata": true,
  229. "nodes": true,
  230. "nodekey": true,
  231. "static-nodes.json": true,
  232. "trusted-nodes.json": true,
  233. }
  234. // ResolvePath resolves path in the instance directory.
  235. func (c *Config) ResolvePath(path string) string {
  236. if filepath.IsAbs(path) {
  237. return path
  238. }
  239. if c.DataDir == "" {
  240. return ""
  241. }
  242. // Backwards-compatibility: ensure that data directory files created
  243. // by geth 1.4 are used if they exist.
  244. if c.name() == "geth" && isOldGethResource[path] {
  245. oldpath := ""
  246. if c.Name == "geth" {
  247. oldpath = filepath.Join(c.DataDir, path)
  248. }
  249. if oldpath != "" && common.FileExist(oldpath) {
  250. // TODO: print warning
  251. return oldpath
  252. }
  253. }
  254. return filepath.Join(c.instanceDir(), path)
  255. }
  256. func (c *Config) instanceDir() string {
  257. if c.DataDir == "" {
  258. return ""
  259. }
  260. return filepath.Join(c.DataDir, c.name())
  261. }
  262. // NodeKey retrieves the currently configured private key of the node, checking
  263. // first any manually set key, falling back to the one found in the configured
  264. // data folder. If no key can be found, a new one is generated.
  265. func (c *Config) NodeKey() *ecdsa.PrivateKey {
  266. // Use any specifically configured key.
  267. if c.P2P.PrivateKey != nil {
  268. return c.P2P.PrivateKey
  269. }
  270. // Generate ephemeral key if no datadir is being used.
  271. if c.DataDir == "" {
  272. key, err := crypto.GenerateKey()
  273. if err != nil {
  274. log.Crit(fmt.Sprintf("Failed to generate ephemeral node key: %v", err))
  275. }
  276. return key
  277. }
  278. keyfile := c.ResolvePath(datadirPrivateKey)
  279. if key, err := crypto.LoadECDSA(keyfile); err == nil {
  280. return key
  281. }
  282. // No persistent key found, generate and store a new one.
  283. key, err := crypto.GenerateKey()
  284. if err != nil {
  285. log.Crit(fmt.Sprintf("Failed to generate node key: %v", err))
  286. }
  287. instanceDir := filepath.Join(c.DataDir, c.name())
  288. if err := os.MkdirAll(instanceDir, 0700); err != nil {
  289. log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
  290. return key
  291. }
  292. keyfile = filepath.Join(instanceDir, datadirPrivateKey)
  293. if err := crypto.SaveECDSA(keyfile, key); err != nil {
  294. log.Error(fmt.Sprintf("Failed to persist node key: %v", err))
  295. }
  296. return key
  297. }
  298. // StaticNodes returns a list of node enode URLs configured as static nodes.
  299. func (c *Config) StaticNodes() []*discover.Node {
  300. return c.parsePersistentNodes(c.ResolvePath(datadirStaticNodes))
  301. }
  302. // TrustedNodes returns a list of node enode URLs configured as trusted nodes.
  303. func (c *Config) TrustedNodes() []*discover.Node {
  304. return c.parsePersistentNodes(c.ResolvePath(datadirTrustedNodes))
  305. }
  306. // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
  307. // file from within the data directory.
  308. func (c *Config) parsePersistentNodes(path string) []*discover.Node {
  309. // Short circuit if no node config is present
  310. if c.DataDir == "" {
  311. return nil
  312. }
  313. if _, err := os.Stat(path); err != nil {
  314. return nil
  315. }
  316. // Load the nodes from the config file.
  317. var nodelist []string
  318. if err := common.LoadJSON(path, &nodelist); err != nil {
  319. log.Error(fmt.Sprintf("Can't load node file %s: %v", path, err))
  320. return nil
  321. }
  322. // Interpret the list as a discovery node array
  323. var nodes []*discover.Node
  324. for _, url := range nodelist {
  325. if url == "" {
  326. continue
  327. }
  328. node, err := discover.ParseNode(url)
  329. if err != nil {
  330. log.Error(fmt.Sprintf("Node URL %s: %v\n", url, err))
  331. continue
  332. }
  333. nodes = append(nodes, node)
  334. }
  335. return nodes
  336. }
  337. // AccountConfig determines the settings for scrypt and keydirectory
  338. func (c *Config) AccountConfig() (int, int, string, error) {
  339. scryptN := keystore.StandardScryptN
  340. scryptP := keystore.StandardScryptP
  341. if c.UseLightweightKDF {
  342. scryptN = keystore.LightScryptN
  343. scryptP = keystore.LightScryptP
  344. }
  345. var (
  346. keydir string
  347. err error
  348. )
  349. switch {
  350. case filepath.IsAbs(c.KeyStoreDir):
  351. keydir = c.KeyStoreDir
  352. case c.DataDir != "":
  353. if c.KeyStoreDir == "" {
  354. keydir = filepath.Join(c.DataDir, datadirDefaultKeyStore)
  355. } else {
  356. keydir, err = filepath.Abs(c.KeyStoreDir)
  357. }
  358. case c.KeyStoreDir != "":
  359. keydir, err = filepath.Abs(c.KeyStoreDir)
  360. }
  361. return scryptN, scryptP, keydir, err
  362. }
  363. func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
  364. scryptN, scryptP, keydir, err := conf.AccountConfig()
  365. var ephemeral string
  366. if keydir == "" {
  367. // There is no datadir.
  368. keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
  369. ephemeral = keydir
  370. }
  371. if err != nil {
  372. return nil, "", err
  373. }
  374. if err := os.MkdirAll(keydir, 0700); err != nil {
  375. return nil, "", err
  376. }
  377. // Assemble the account manager and supported backends
  378. backends := []accounts.Backend{
  379. keystore.NewKeyStore(keydir, scryptN, scryptP),
  380. }
  381. if !conf.NoUSB {
  382. // Start a USB hub for Ledger hardware wallets
  383. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  384. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  385. } else {
  386. backends = append(backends, ledgerhub)
  387. }
  388. // Start a USB hub for Trezor hardware wallets
  389. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  390. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  391. } else {
  392. backends = append(backends, trezorhub)
  393. }
  394. }
  395. return accounts.NewManager(backends...), ephemeral, nil
  396. }