config.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "encoding/json"
  20. "fmt"
  21. "io/ioutil"
  22. "net"
  23. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strings"
  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. datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list
  37. datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list
  38. datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos
  39. )
  40. // Config represents a small collection of configuration values to fine tune the
  41. // P2P network layer of a protocol stack. These values can be further extended by
  42. // all registered services.
  43. type Config struct {
  44. // DataDir is the file system folder the node should use for any data storage
  45. // requirements. The configured data directory will not be directly shared with
  46. // registered services, instead those can use utility methods to create/access
  47. // databases or flat files. This enables ephemeral nodes which can fully reside
  48. // in memory.
  49. DataDir string
  50. // IPCPath is the requested location to place the IPC endpoint. If the path is
  51. // a simple file name, it is placed inside the data directory (or on the root
  52. // pipe path on Windows), whereas if it's a resolvable path name (absolute or
  53. // relative), then that specific path is enforced. An empty path disables IPC.
  54. IPCPath string
  55. // This field should be a valid secp256k1 private key that will be used for both
  56. // remote peer identification as well as network traffic encryption. If no key
  57. // is configured, the preset one is loaded from the data dir, generating it if
  58. // needed.
  59. PrivateKey *ecdsa.PrivateKey
  60. // Name sets the node name of this server. Use common.MakeName to create a name
  61. // that follows existing conventions.
  62. Name string
  63. // NoDiscovery specifies whether the peer discovery mechanism should be started
  64. // or not. Disabling is usually useful for protocol debugging (manual topology).
  65. NoDiscovery bool
  66. // Bootstrap nodes used to establish connectivity with the rest of the network.
  67. BootstrapNodes []*discover.Node
  68. // Network interface address on which the node should listen for inbound peers.
  69. ListenAddr string
  70. // If set to a non-nil value, the given NAT port mapper is used to make the
  71. // listening port available to the Internet.
  72. NAT nat.Interface
  73. // If Dialer is set to a non-nil value, the given Dialer is used to dial outbound
  74. // peer connections.
  75. Dialer *net.Dialer
  76. // If NoDial is true, the node will not dial any peers.
  77. NoDial bool
  78. // MaxPeers is the maximum number of peers that can be connected. If this is
  79. // set to zero, then only the configured static and trusted peers can connect.
  80. MaxPeers int
  81. // MaxPendingPeers is the maximum number of peers that can be pending in the
  82. // handshake phase, counted separately for inbound and outbound connections.
  83. // Zero defaults to preset values.
  84. MaxPendingPeers int
  85. // HTTPHost is the host interface on which to start the HTTP RPC server. If this
  86. // field is empty, no HTTP API endpoint will be started.
  87. HTTPHost string
  88. // HTTPPort is the TCP port number on which to start the HTTP RPC server. The
  89. // default zero value is/ valid and will pick a port number randomly (useful
  90. // for ephemeral nodes).
  91. HTTPPort int
  92. // HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
  93. // clients. Please be aware that CORS is a browser enforced security, it's fully
  94. // useless for custom HTTP clients.
  95. HTTPCors string
  96. // HTTPModules is a list of API modules to expose via the HTTP RPC interface.
  97. // If the module list is empty, all RPC API endpoints designated public will be
  98. // exposed.
  99. HTTPModules []string
  100. // WSHost is the host interface on which to start the websocket RPC server. If
  101. // this field is empty, no websocket API endpoint will be started.
  102. WSHost string
  103. // WSPort is the TCP port number on which to start the websocket RPC server. The
  104. // default zero value is/ valid and will pick a port number randomly (useful for
  105. // ephemeral nodes).
  106. WSPort int
  107. // WSOrigins is the list of domain to accept websocket requests from. Please be
  108. // aware that the server can only act upon the HTTP request the client sends and
  109. // cannot verify the validity of the request header.
  110. WSOrigins string
  111. // WSModules is a list of API modules to expose via the websocket RPC interface.
  112. // If the module list is empty, all RPC API endpoints designated public will be
  113. // exposed.
  114. WSModules []string
  115. }
  116. // IPCEndpoint resolves an IPC endpoint based on a configured value, taking into
  117. // account the set data folders as well as the designated platform we're currently
  118. // running on.
  119. func (c *Config) IPCEndpoint() string {
  120. // Short circuit if IPC has not been enabled
  121. if c.IPCPath == "" {
  122. return ""
  123. }
  124. // On windows we can only use plain top-level pipes
  125. if runtime.GOOS == "windows" {
  126. if strings.HasPrefix(c.IPCPath, `\\.\pipe\`) {
  127. return c.IPCPath
  128. }
  129. return `\\.\pipe\` + c.IPCPath
  130. }
  131. // Resolve names into the data directory full paths otherwise
  132. if filepath.Base(c.IPCPath) == c.IPCPath {
  133. if c.DataDir == "" {
  134. return filepath.Join(os.TempDir(), c.IPCPath)
  135. }
  136. return filepath.Join(c.DataDir, c.IPCPath)
  137. }
  138. return c.IPCPath
  139. }
  140. // DefaultIPCEndpoint returns the IPC path used by default.
  141. func DefaultIPCEndpoint() string {
  142. config := &Config{DataDir: common.DefaultDataDir(), IPCPath: common.DefaultIPCSocket}
  143. return config.IPCEndpoint()
  144. }
  145. // HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
  146. // and port parameters.
  147. func (c *Config) HTTPEndpoint() string {
  148. if c.HTTPHost == "" {
  149. return ""
  150. }
  151. return fmt.Sprintf("%s:%d", c.HTTPHost, c.HTTPPort)
  152. }
  153. // DefaultHTTPEndpoint returns the HTTP endpoint used by default.
  154. func DefaultHTTPEndpoint() string {
  155. config := &Config{HTTPHost: common.DefaultHTTPHost, HTTPPort: common.DefaultHTTPPort}
  156. return config.HTTPEndpoint()
  157. }
  158. // WSEndpoint resolves an websocket endpoint based on the configured host interface
  159. // and port parameters.
  160. func (c *Config) WSEndpoint() string {
  161. if c.WSHost == "" {
  162. return ""
  163. }
  164. return fmt.Sprintf("%s:%d", c.WSHost, c.WSPort)
  165. }
  166. // DefaultWSEndpoint returns the websocket endpoint used by default.
  167. func DefaultWSEndpoint() string {
  168. config := &Config{WSHost: common.DefaultWSHost, WSPort: common.DefaultWSPort}
  169. return config.WSEndpoint()
  170. }
  171. // NodeKey retrieves the currently configured private key of the node, checking
  172. // first any manually set key, falling back to the one found in the configured
  173. // data folder. If no key can be found, a new one is generated.
  174. func (c *Config) NodeKey() *ecdsa.PrivateKey {
  175. // Use any specifically configured key
  176. if c.PrivateKey != nil {
  177. return c.PrivateKey
  178. }
  179. // Generate ephemeral key if no datadir is being used
  180. if c.DataDir == "" {
  181. key, err := crypto.GenerateKey()
  182. if err != nil {
  183. glog.Fatalf("Failed to generate ephemeral node key: %v", err)
  184. }
  185. return key
  186. }
  187. // Fall back to persistent key from the data directory
  188. keyfile := filepath.Join(c.DataDir, datadirPrivateKey)
  189. if key, err := crypto.LoadECDSA(keyfile); err == nil {
  190. return key
  191. }
  192. // No persistent key found, generate and store a new one
  193. key, err := crypto.GenerateKey()
  194. if err != nil {
  195. glog.Fatalf("Failed to generate node key: %v", err)
  196. }
  197. if err := crypto.SaveECDSA(keyfile, key); err != nil {
  198. glog.V(logger.Error).Infof("Failed to persist node key: %v", err)
  199. }
  200. return key
  201. }
  202. // StaticNodes returns a list of node enode URLs configured as static nodes.
  203. func (c *Config) StaticNodes() []*discover.Node {
  204. return c.parsePersistentNodes(datadirStaticNodes)
  205. }
  206. // TrusterNodes returns a list of node enode URLs configured as trusted nodes.
  207. func (c *Config) TrusterNodes() []*discover.Node {
  208. return c.parsePersistentNodes(datadirTrustedNodes)
  209. }
  210. // parsePersistentNodes parses a list of discovery node URLs loaded from a .json
  211. // file from within the data directory.
  212. func (c *Config) parsePersistentNodes(file string) []*discover.Node {
  213. // Short circuit if no node config is present
  214. if c.DataDir == "" {
  215. return nil
  216. }
  217. path := filepath.Join(c.DataDir, file)
  218. if _, err := os.Stat(path); err != nil {
  219. return nil
  220. }
  221. // Load the nodes from the config file
  222. blob, err := ioutil.ReadFile(path)
  223. if err != nil {
  224. glog.V(logger.Error).Infof("Failed to access nodes: %v", err)
  225. return nil
  226. }
  227. nodelist := []string{}
  228. if err := json.Unmarshal(blob, &nodelist); err != nil {
  229. glog.V(logger.Error).Infof("Failed to load nodes: %v", err)
  230. return nil
  231. }
  232. // Interpret the list as a discovery node array
  233. var nodes []*discover.Node
  234. for _, url := range nodelist {
  235. if url == "" {
  236. continue
  237. }
  238. node, err := discover.ParseNode(url)
  239. if err != nil {
  240. glog.V(logger.Error).Infof("Node URL %s: %v\n", url, err)
  241. continue
  242. }
  243. nodes = append(nodes, node)
  244. }
  245. return nodes
  246. }