node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. // Copyright 2015 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. "errors"
  19. "fmt"
  20. "net"
  21. "os"
  22. "path/filepath"
  23. "reflect"
  24. "strings"
  25. "sync"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/internal/debug"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/rpc"
  33. "github.com/prometheus/prometheus/util/flock"
  34. )
  35. // Node is a container on which services can be registered.
  36. type Node struct {
  37. eventmux *event.TypeMux // Event multiplexer used between the services of a stack
  38. config *Config
  39. accman *accounts.Manager
  40. ephemeralKeystore string // if non-empty, the key directory that will be removed by Stop
  41. instanceDirLock flock.Releaser // prevents concurrent use of instance directory
  42. serverConfig p2p.Config
  43. server *p2p.Server // Currently running P2P networking layer
  44. serviceFuncs []ServiceConstructor // Service constructors (in dependency order)
  45. services map[reflect.Type]Service // Currently running services
  46. rpcAPIs []rpc.API // List of APIs currently provided by the node
  47. inprocHandler *rpc.Server // In-process RPC request handler to process the API requests
  48. ipcEndpoint string // IPC endpoint to listen at (empty = IPC disabled)
  49. ipcListener net.Listener // IPC RPC listener socket to serve API requests
  50. ipcHandler *rpc.Server // IPC RPC request handler to process the API requests
  51. httpEndpoint string // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled)
  52. httpWhitelist []string // HTTP RPC modules to allow through this endpoint
  53. httpListener net.Listener // HTTP RPC listener socket to server API requests
  54. httpHandler *rpc.Server // HTTP RPC request handler to process the API requests
  55. wsEndpoint string // Websocket endpoint (interface + port) to listen at (empty = websocket disabled)
  56. wsListener net.Listener // Websocket RPC listener socket to server API requests
  57. wsHandler *rpc.Server // Websocket RPC request handler to process the API requests
  58. stop chan struct{} // Channel to wait for termination notifications
  59. lock sync.RWMutex
  60. log log.Logger
  61. }
  62. // New creates a new P2P node, ready for protocol registration.
  63. func New(conf *Config) (*Node, error) {
  64. // Copy config and resolve the datadir so future changes to the current
  65. // working directory don't affect the node.
  66. confCopy := *conf
  67. conf = &confCopy
  68. if conf.DataDir != "" {
  69. absdatadir, err := filepath.Abs(conf.DataDir)
  70. if err != nil {
  71. return nil, err
  72. }
  73. conf.DataDir = absdatadir
  74. }
  75. // Ensure that the instance name doesn't cause weird conflicts with
  76. // other files in the data directory.
  77. if strings.ContainsAny(conf.Name, `/\`) {
  78. return nil, errors.New(`Config.Name must not contain '/' or '\'`)
  79. }
  80. if conf.Name == datadirDefaultKeyStore {
  81. return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`)
  82. }
  83. if strings.HasSuffix(conf.Name, ".ipc") {
  84. return nil, errors.New(`Config.Name cannot end in ".ipc"`)
  85. }
  86. // Ensure that the AccountManager method works before the node has started.
  87. // We rely on this in cmd/geth.
  88. am, ephemeralKeystore, err := makeAccountManager(conf)
  89. if err != nil {
  90. return nil, err
  91. }
  92. if conf.Logger == nil {
  93. conf.Logger = log.New()
  94. }
  95. // Note: any interaction with Config that would create/touch files
  96. // in the data directory or instance directory is delayed until Start.
  97. return &Node{
  98. accman: am,
  99. ephemeralKeystore: ephemeralKeystore,
  100. config: conf,
  101. serviceFuncs: []ServiceConstructor{},
  102. ipcEndpoint: conf.IPCEndpoint(),
  103. httpEndpoint: conf.HTTPEndpoint(),
  104. wsEndpoint: conf.WSEndpoint(),
  105. eventmux: new(event.TypeMux),
  106. log: conf.Logger,
  107. }, nil
  108. }
  109. // Register injects a new service into the node's stack. The service created by
  110. // the passed constructor must be unique in its type with regard to sibling ones.
  111. func (n *Node) Register(constructor ServiceConstructor) error {
  112. n.lock.Lock()
  113. defer n.lock.Unlock()
  114. if n.server != nil {
  115. return ErrNodeRunning
  116. }
  117. n.serviceFuncs = append(n.serviceFuncs, constructor)
  118. return nil
  119. }
  120. // Start create a live P2P node and starts running it.
  121. func (n *Node) Start() error {
  122. n.lock.Lock()
  123. defer n.lock.Unlock()
  124. // Short circuit if the node's already running
  125. if n.server != nil {
  126. return ErrNodeRunning
  127. }
  128. if err := n.openDataDir(); err != nil {
  129. return err
  130. }
  131. // Initialize the p2p server. This creates the node key and
  132. // discovery databases.
  133. n.serverConfig = n.config.P2P
  134. n.serverConfig.PrivateKey = n.config.NodeKey()
  135. n.serverConfig.Name = n.config.NodeName()
  136. n.serverConfig.Logger = n.log
  137. if n.serverConfig.StaticNodes == nil {
  138. n.serverConfig.StaticNodes = n.config.StaticNodes()
  139. }
  140. if n.serverConfig.TrustedNodes == nil {
  141. n.serverConfig.TrustedNodes = n.config.TrustedNodes()
  142. }
  143. if n.serverConfig.NodeDatabase == "" {
  144. n.serverConfig.NodeDatabase = n.config.NodeDB()
  145. }
  146. running := &p2p.Server{Config: n.serverConfig}
  147. n.log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
  148. // Otherwise copy and specialize the P2P configuration
  149. services := make(map[reflect.Type]Service)
  150. for _, constructor := range n.serviceFuncs {
  151. // Create a new context for the particular service
  152. ctx := &ServiceContext{
  153. config: n.config,
  154. services: make(map[reflect.Type]Service),
  155. EventMux: n.eventmux,
  156. AccountManager: n.accman,
  157. }
  158. for kind, s := range services { // copy needed for threaded access
  159. ctx.services[kind] = s
  160. }
  161. // Construct and save the service
  162. service, err := constructor(ctx)
  163. if err != nil {
  164. return err
  165. }
  166. kind := reflect.TypeOf(service)
  167. if _, exists := services[kind]; exists {
  168. return &DuplicateServiceError{Kind: kind}
  169. }
  170. services[kind] = service
  171. }
  172. // Gather the protocols and start the freshly assembled P2P server
  173. for _, service := range services {
  174. running.Protocols = append(running.Protocols, service.Protocols()...)
  175. }
  176. if err := running.Start(); err != nil {
  177. return convertFileLockError(err)
  178. }
  179. // Start each of the services
  180. started := []reflect.Type{}
  181. for kind, service := range services {
  182. // Start the next service, stopping all previous upon failure
  183. if err := service.Start(running); err != nil {
  184. for _, kind := range started {
  185. services[kind].Stop()
  186. }
  187. running.Stop()
  188. return err
  189. }
  190. // Mark the service started for potential cleanup
  191. started = append(started, kind)
  192. }
  193. // Lastly start the configured RPC interfaces
  194. if err := n.startRPC(services); err != nil {
  195. for _, service := range services {
  196. service.Stop()
  197. }
  198. running.Stop()
  199. return err
  200. }
  201. // Finish initializing the startup
  202. n.services = services
  203. n.server = running
  204. n.stop = make(chan struct{})
  205. return nil
  206. }
  207. func (n *Node) openDataDir() error {
  208. if n.config.DataDir == "" {
  209. return nil // ephemeral
  210. }
  211. instdir := filepath.Join(n.config.DataDir, n.config.name())
  212. if err := os.MkdirAll(instdir, 0700); err != nil {
  213. return err
  214. }
  215. // Lock the instance directory to prevent concurrent use by another instance as well as
  216. // accidental use of the instance directory as a database.
  217. release, _, err := flock.New(filepath.Join(instdir, "LOCK"))
  218. if err != nil {
  219. return convertFileLockError(err)
  220. }
  221. n.instanceDirLock = release
  222. return nil
  223. }
  224. // startRPC is a helper method to start all the various RPC endpoint during node
  225. // startup. It's not meant to be called at any time afterwards as it makes certain
  226. // assumptions about the state of the node.
  227. func (n *Node) startRPC(services map[reflect.Type]Service) error {
  228. // Gather all the possible APIs to surface
  229. apis := n.apis()
  230. for _, service := range services {
  231. apis = append(apis, service.APIs()...)
  232. }
  233. // Start the various API endpoints, terminating all in case of errors
  234. if err := n.startInProc(apis); err != nil {
  235. return err
  236. }
  237. if err := n.startIPC(apis); err != nil {
  238. n.stopInProc()
  239. return err
  240. }
  241. if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors, n.config.HTTPVirtualHosts); err != nil {
  242. n.stopIPC()
  243. n.stopInProc()
  244. return err
  245. }
  246. if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil {
  247. n.stopHTTP()
  248. n.stopIPC()
  249. n.stopInProc()
  250. return err
  251. }
  252. // All API endpoints started successfully
  253. n.rpcAPIs = apis
  254. return nil
  255. }
  256. // startInProc initializes an in-process RPC endpoint.
  257. func (n *Node) startInProc(apis []rpc.API) error {
  258. // Register all the APIs exposed by the services
  259. handler := rpc.NewServer()
  260. for _, api := range apis {
  261. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  262. return err
  263. }
  264. n.log.Debug("InProc registered", "service", api.Service, "namespace", api.Namespace)
  265. }
  266. n.inprocHandler = handler
  267. return nil
  268. }
  269. // stopInProc terminates the in-process RPC endpoint.
  270. func (n *Node) stopInProc() {
  271. if n.inprocHandler != nil {
  272. n.inprocHandler.Stop()
  273. n.inprocHandler = nil
  274. }
  275. }
  276. // startIPC initializes and starts the IPC RPC endpoint.
  277. func (n *Node) startIPC(apis []rpc.API) error {
  278. if n.ipcEndpoint == "" {
  279. return nil // IPC disabled.
  280. }
  281. listener, handler, err := rpc.StartIPCEndpoint(n.ipcEndpoint, apis)
  282. if err != nil {
  283. return err
  284. }
  285. n.ipcListener = listener
  286. n.ipcHandler = handler
  287. n.log.Info("IPC endpoint opened", "url", n.ipcEndpoint)
  288. return nil
  289. }
  290. // stopIPC terminates the IPC RPC endpoint.
  291. func (n *Node) stopIPC() {
  292. if n.ipcListener != nil {
  293. n.ipcListener.Close()
  294. n.ipcListener = nil
  295. n.log.Info("IPC endpoint closed", "endpoint", n.ipcEndpoint)
  296. }
  297. if n.ipcHandler != nil {
  298. n.ipcHandler.Stop()
  299. n.ipcHandler = nil
  300. }
  301. }
  302. // startHTTP initializes and starts the HTTP RPC endpoint.
  303. func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors []string, vhosts []string) error {
  304. // Short circuit if the HTTP endpoint isn't being exposed
  305. if endpoint == "" {
  306. return nil
  307. }
  308. listener, handler, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, cors, vhosts)
  309. if err != nil {
  310. return err
  311. }
  312. n.log.Info("HTTP endpoint opened", "url", fmt.Sprintf("http://%s", endpoint), "cors", strings.Join(cors, ","), "vhosts", strings.Join(vhosts, ","))
  313. // All listeners booted successfully
  314. n.httpEndpoint = endpoint
  315. n.httpListener = listener
  316. n.httpHandler = handler
  317. return nil
  318. }
  319. // stopHTTP terminates the HTTP RPC endpoint.
  320. func (n *Node) stopHTTP() {
  321. if n.httpListener != nil {
  322. n.httpListener.Close()
  323. n.httpListener = nil
  324. n.log.Info("HTTP endpoint closed", "url", fmt.Sprintf("http://%s", n.httpEndpoint))
  325. }
  326. if n.httpHandler != nil {
  327. n.httpHandler.Stop()
  328. n.httpHandler = nil
  329. }
  330. }
  331. // startWS initializes and starts the websocket RPC endpoint.
  332. func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
  333. // Short circuit if the WS endpoint isn't being exposed
  334. if endpoint == "" {
  335. return nil
  336. }
  337. listener, handler, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
  338. if err != nil {
  339. return err
  340. }
  341. n.log.Info("WebSocket endpoint opened", "url", fmt.Sprintf("ws://%s", listener.Addr()))
  342. // All listeners booted successfully
  343. n.wsEndpoint = endpoint
  344. n.wsListener = listener
  345. n.wsHandler = handler
  346. return nil
  347. }
  348. // stopWS terminates the websocket RPC endpoint.
  349. func (n *Node) stopWS() {
  350. if n.wsListener != nil {
  351. n.wsListener.Close()
  352. n.wsListener = nil
  353. n.log.Info("WebSocket endpoint closed", "url", fmt.Sprintf("ws://%s", n.wsEndpoint))
  354. }
  355. if n.wsHandler != nil {
  356. n.wsHandler.Stop()
  357. n.wsHandler = nil
  358. }
  359. }
  360. // Stop terminates a running node along with all it's services. In the node was
  361. // not started, an error is returned.
  362. func (n *Node) Stop() error {
  363. n.lock.Lock()
  364. defer n.lock.Unlock()
  365. // Short circuit if the node's not running
  366. if n.server == nil {
  367. return ErrNodeStopped
  368. }
  369. // Terminate the API, services and the p2p server.
  370. n.stopWS()
  371. n.stopHTTP()
  372. n.stopIPC()
  373. n.rpcAPIs = nil
  374. failure := &StopError{
  375. Services: make(map[reflect.Type]error),
  376. }
  377. for kind, service := range n.services {
  378. if err := service.Stop(); err != nil {
  379. failure.Services[kind] = err
  380. }
  381. }
  382. n.server.Stop()
  383. n.services = nil
  384. n.server = nil
  385. // Release instance directory lock.
  386. if n.instanceDirLock != nil {
  387. if err := n.instanceDirLock.Release(); err != nil {
  388. n.log.Error("Can't release datadir lock", "err", err)
  389. }
  390. n.instanceDirLock = nil
  391. }
  392. // unblock n.Wait
  393. close(n.stop)
  394. // Remove the keystore if it was created ephemerally.
  395. var keystoreErr error
  396. if n.ephemeralKeystore != "" {
  397. keystoreErr = os.RemoveAll(n.ephemeralKeystore)
  398. }
  399. if len(failure.Services) > 0 {
  400. return failure
  401. }
  402. if keystoreErr != nil {
  403. return keystoreErr
  404. }
  405. return nil
  406. }
  407. // Wait blocks the thread until the node is stopped. If the node is not running
  408. // at the time of invocation, the method immediately returns.
  409. func (n *Node) Wait() {
  410. n.lock.RLock()
  411. if n.server == nil {
  412. n.lock.RUnlock()
  413. return
  414. }
  415. stop := n.stop
  416. n.lock.RUnlock()
  417. <-stop
  418. }
  419. // Restart terminates a running node and boots up a new one in its place. If the
  420. // node isn't running, an error is returned.
  421. func (n *Node) Restart() error {
  422. if err := n.Stop(); err != nil {
  423. return err
  424. }
  425. if err := n.Start(); err != nil {
  426. return err
  427. }
  428. return nil
  429. }
  430. // Attach creates an RPC client attached to an in-process API handler.
  431. func (n *Node) Attach() (*rpc.Client, error) {
  432. n.lock.RLock()
  433. defer n.lock.RUnlock()
  434. if n.server == nil {
  435. return nil, ErrNodeStopped
  436. }
  437. return rpc.DialInProc(n.inprocHandler), nil
  438. }
  439. // RPCHandler returns the in-process RPC request handler.
  440. func (n *Node) RPCHandler() (*rpc.Server, error) {
  441. n.lock.RLock()
  442. defer n.lock.RUnlock()
  443. if n.inprocHandler == nil {
  444. return nil, ErrNodeStopped
  445. }
  446. return n.inprocHandler, nil
  447. }
  448. // Server retrieves the currently running P2P network layer. This method is meant
  449. // only to inspect fields of the currently running server, life cycle management
  450. // should be left to this Node entity.
  451. func (n *Node) Server() *p2p.Server {
  452. n.lock.RLock()
  453. defer n.lock.RUnlock()
  454. return n.server
  455. }
  456. // Service retrieves a currently running service registered of a specific type.
  457. func (n *Node) Service(service interface{}) error {
  458. n.lock.RLock()
  459. defer n.lock.RUnlock()
  460. // Short circuit if the node's not running
  461. if n.server == nil {
  462. return ErrNodeStopped
  463. }
  464. // Otherwise try to find the service to return
  465. element := reflect.ValueOf(service).Elem()
  466. if running, ok := n.services[element.Type()]; ok {
  467. element.Set(reflect.ValueOf(running))
  468. return nil
  469. }
  470. return ErrServiceUnknown
  471. }
  472. // DataDir retrieves the current datadir used by the protocol stack.
  473. // Deprecated: No files should be stored in this directory, use InstanceDir instead.
  474. func (n *Node) DataDir() string {
  475. return n.config.DataDir
  476. }
  477. // InstanceDir retrieves the instance directory used by the protocol stack.
  478. func (n *Node) InstanceDir() string {
  479. return n.config.instanceDir()
  480. }
  481. // AccountManager retrieves the account manager used by the protocol stack.
  482. func (n *Node) AccountManager() *accounts.Manager {
  483. return n.accman
  484. }
  485. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  486. func (n *Node) IPCEndpoint() string {
  487. return n.ipcEndpoint
  488. }
  489. // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
  490. func (n *Node) HTTPEndpoint() string {
  491. return n.httpEndpoint
  492. }
  493. // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
  494. func (n *Node) WSEndpoint() string {
  495. return n.wsEndpoint
  496. }
  497. // EventMux retrieves the event multiplexer used by all the network services in
  498. // the current protocol stack.
  499. func (n *Node) EventMux() *event.TypeMux {
  500. return n.eventmux
  501. }
  502. // OpenDatabase opens an existing database with the given name (or creates one if no
  503. // previous can be found) from within the node's instance directory. If the node is
  504. // ephemeral, a memory database is returned.
  505. func (n *Node) OpenDatabase(name string, cache, handles int) (ethdb.Database, error) {
  506. if n.config.DataDir == "" {
  507. return ethdb.NewMemDatabase(), nil
  508. }
  509. return ethdb.NewLDBDatabase(n.config.resolvePath(name), cache, handles)
  510. }
  511. // ResolvePath returns the absolute path of a resource in the instance directory.
  512. func (n *Node) ResolvePath(x string) string {
  513. return n.config.resolvePath(x)
  514. }
  515. // apis returns the collection of RPC descriptors this node offers.
  516. func (n *Node) apis() []rpc.API {
  517. return []rpc.API{
  518. {
  519. Namespace: "admin",
  520. Version: "1.0",
  521. Service: NewPrivateAdminAPI(n),
  522. }, {
  523. Namespace: "admin",
  524. Version: "1.0",
  525. Service: NewPublicAdminAPI(n),
  526. Public: true,
  527. }, {
  528. Namespace: "debug",
  529. Version: "1.0",
  530. Service: debug.Handler,
  531. }, {
  532. Namespace: "debug",
  533. Version: "1.0",
  534. Service: NewPublicDebugAPI(n),
  535. Public: true,
  536. }, {
  537. Namespace: "web3",
  538. Version: "1.0",
  539. Service: NewPublicWeb3API(n),
  540. Public: true,
  541. },
  542. }
  543. }