node.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. // Close stops the Node and releases resources acquired in
  110. // Node constructor New.
  111. func (n *Node) Close() error {
  112. var errs []error
  113. // Terminate all subsystems and collect any errors
  114. if err := n.Stop(); err != nil && err != ErrNodeStopped {
  115. errs = append(errs, err)
  116. }
  117. if err := n.accman.Close(); err != nil {
  118. errs = append(errs, err)
  119. }
  120. // Report any errors that might have occurred
  121. switch len(errs) {
  122. case 0:
  123. return nil
  124. case 1:
  125. return errs[0]
  126. default:
  127. return fmt.Errorf("%v", errs)
  128. }
  129. }
  130. // Register injects a new service into the node's stack. The service created by
  131. // the passed constructor must be unique in its type with regard to sibling ones.
  132. func (n *Node) Register(constructor ServiceConstructor) error {
  133. n.lock.Lock()
  134. defer n.lock.Unlock()
  135. if n.server != nil {
  136. return ErrNodeRunning
  137. }
  138. n.serviceFuncs = append(n.serviceFuncs, constructor)
  139. return nil
  140. }
  141. // Start create a live P2P node and starts running it.
  142. func (n *Node) Start() error {
  143. n.lock.Lock()
  144. defer n.lock.Unlock()
  145. // Short circuit if the node's already running
  146. if n.server != nil {
  147. return ErrNodeRunning
  148. }
  149. if err := n.openDataDir(); err != nil {
  150. return err
  151. }
  152. // Initialize the p2p server. This creates the node key and
  153. // discovery databases.
  154. n.serverConfig = n.config.P2P
  155. n.serverConfig.PrivateKey = n.config.NodeKey()
  156. n.serverConfig.Name = n.config.NodeName()
  157. n.serverConfig.Logger = n.log
  158. if n.serverConfig.StaticNodes == nil {
  159. n.serverConfig.StaticNodes = n.config.StaticNodes()
  160. }
  161. if n.serverConfig.TrustedNodes == nil {
  162. n.serverConfig.TrustedNodes = n.config.TrustedNodes()
  163. }
  164. if n.serverConfig.NodeDatabase == "" {
  165. n.serverConfig.NodeDatabase = n.config.NodeDB()
  166. }
  167. running := &p2p.Server{Config: n.serverConfig}
  168. n.log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
  169. // Otherwise copy and specialize the P2P configuration
  170. services := make(map[reflect.Type]Service)
  171. for _, constructor := range n.serviceFuncs {
  172. // Create a new context for the particular service
  173. ctx := &ServiceContext{
  174. config: n.config,
  175. services: make(map[reflect.Type]Service),
  176. EventMux: n.eventmux,
  177. AccountManager: n.accman,
  178. }
  179. for kind, s := range services { // copy needed for threaded access
  180. ctx.services[kind] = s
  181. }
  182. // Construct and save the service
  183. service, err := constructor(ctx)
  184. if err != nil {
  185. return err
  186. }
  187. kind := reflect.TypeOf(service)
  188. if _, exists := services[kind]; exists {
  189. return &DuplicateServiceError{Kind: kind}
  190. }
  191. services[kind] = service
  192. }
  193. // Gather the protocols and start the freshly assembled P2P server
  194. for _, service := range services {
  195. running.Protocols = append(running.Protocols, service.Protocols()...)
  196. }
  197. if err := running.Start(); err != nil {
  198. return convertFileLockError(err)
  199. }
  200. // Start each of the services
  201. started := []reflect.Type{}
  202. for kind, service := range services {
  203. // Start the next service, stopping all previous upon failure
  204. if err := service.Start(running); err != nil {
  205. for _, kind := range started {
  206. services[kind].Stop()
  207. }
  208. running.Stop()
  209. return err
  210. }
  211. // Mark the service started for potential cleanup
  212. started = append(started, kind)
  213. }
  214. // Lastly start the configured RPC interfaces
  215. if err := n.startRPC(services); err != nil {
  216. for _, service := range services {
  217. service.Stop()
  218. }
  219. running.Stop()
  220. return err
  221. }
  222. // Finish initializing the startup
  223. n.services = services
  224. n.server = running
  225. n.stop = make(chan struct{})
  226. return nil
  227. }
  228. func (n *Node) openDataDir() error {
  229. if n.config.DataDir == "" {
  230. return nil // ephemeral
  231. }
  232. instdir := filepath.Join(n.config.DataDir, n.config.name())
  233. if err := os.MkdirAll(instdir, 0700); err != nil {
  234. return err
  235. }
  236. // Lock the instance directory to prevent concurrent use by another instance as well as
  237. // accidental use of the instance directory as a database.
  238. release, _, err := flock.New(filepath.Join(instdir, "LOCK"))
  239. if err != nil {
  240. return convertFileLockError(err)
  241. }
  242. n.instanceDirLock = release
  243. return nil
  244. }
  245. // startRPC is a helper method to start all the various RPC endpoint during node
  246. // startup. It's not meant to be called at any time afterwards as it makes certain
  247. // assumptions about the state of the node.
  248. func (n *Node) startRPC(services map[reflect.Type]Service) error {
  249. // Gather all the possible APIs to surface
  250. apis := n.apis()
  251. for _, service := range services {
  252. apis = append(apis, service.APIs()...)
  253. }
  254. // Start the various API endpoints, terminating all in case of errors
  255. if err := n.startInProc(apis); err != nil {
  256. return err
  257. }
  258. if err := n.startIPC(apis); err != nil {
  259. n.stopInProc()
  260. return err
  261. }
  262. if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors, n.config.HTTPVirtualHosts, n.config.HTTPTimeouts); err != nil {
  263. n.stopIPC()
  264. n.stopInProc()
  265. return err
  266. }
  267. if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil {
  268. n.stopHTTP()
  269. n.stopIPC()
  270. n.stopInProc()
  271. return err
  272. }
  273. // All API endpoints started successfully
  274. n.rpcAPIs = apis
  275. return nil
  276. }
  277. // startInProc initializes an in-process RPC endpoint.
  278. func (n *Node) startInProc(apis []rpc.API) error {
  279. // Register all the APIs exposed by the services
  280. handler := rpc.NewServer()
  281. for _, api := range apis {
  282. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  283. return err
  284. }
  285. n.log.Debug("InProc registered", "namespace", api.Namespace)
  286. }
  287. n.inprocHandler = handler
  288. return nil
  289. }
  290. // stopInProc terminates the in-process RPC endpoint.
  291. func (n *Node) stopInProc() {
  292. if n.inprocHandler != nil {
  293. n.inprocHandler.Stop()
  294. n.inprocHandler = nil
  295. }
  296. }
  297. // startIPC initializes and starts the IPC RPC endpoint.
  298. func (n *Node) startIPC(apis []rpc.API) error {
  299. if n.ipcEndpoint == "" {
  300. return nil // IPC disabled.
  301. }
  302. listener, handler, err := rpc.StartIPCEndpoint(n.ipcEndpoint, apis)
  303. if err != nil {
  304. return err
  305. }
  306. n.ipcListener = listener
  307. n.ipcHandler = handler
  308. n.log.Info("IPC endpoint opened", "url", n.ipcEndpoint)
  309. return nil
  310. }
  311. // stopIPC terminates the IPC RPC endpoint.
  312. func (n *Node) stopIPC() {
  313. if n.ipcListener != nil {
  314. n.ipcListener.Close()
  315. n.ipcListener = nil
  316. n.log.Info("IPC endpoint closed", "url", n.ipcEndpoint)
  317. }
  318. if n.ipcHandler != nil {
  319. n.ipcHandler.Stop()
  320. n.ipcHandler = nil
  321. }
  322. }
  323. // startHTTP initializes and starts the HTTP RPC endpoint.
  324. func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors []string, vhosts []string, timeouts rpc.HTTPTimeouts) error {
  325. // Short circuit if the HTTP endpoint isn't being exposed
  326. if endpoint == "" {
  327. return nil
  328. }
  329. listener, handler, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, cors, vhosts, timeouts)
  330. if err != nil {
  331. return err
  332. }
  333. n.log.Info("HTTP endpoint opened", "url", fmt.Sprintf("http://%s", endpoint), "cors", strings.Join(cors, ","), "vhosts", strings.Join(vhosts, ","))
  334. // All listeners booted successfully
  335. n.httpEndpoint = endpoint
  336. n.httpListener = listener
  337. n.httpHandler = handler
  338. return nil
  339. }
  340. // stopHTTP terminates the HTTP RPC endpoint.
  341. func (n *Node) stopHTTP() {
  342. if n.httpListener != nil {
  343. n.httpListener.Close()
  344. n.httpListener = nil
  345. n.log.Info("HTTP endpoint closed", "url", fmt.Sprintf("http://%s", n.httpEndpoint))
  346. }
  347. if n.httpHandler != nil {
  348. n.httpHandler.Stop()
  349. n.httpHandler = nil
  350. }
  351. }
  352. // startWS initializes and starts the websocket RPC endpoint.
  353. func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
  354. // Short circuit if the WS endpoint isn't being exposed
  355. if endpoint == "" {
  356. return nil
  357. }
  358. listener, handler, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
  359. if err != nil {
  360. return err
  361. }
  362. n.log.Info("WebSocket endpoint opened", "url", fmt.Sprintf("ws://%s", listener.Addr()))
  363. // All listeners booted successfully
  364. n.wsEndpoint = endpoint
  365. n.wsListener = listener
  366. n.wsHandler = handler
  367. return nil
  368. }
  369. // stopWS terminates the websocket RPC endpoint.
  370. func (n *Node) stopWS() {
  371. if n.wsListener != nil {
  372. n.wsListener.Close()
  373. n.wsListener = nil
  374. n.log.Info("WebSocket endpoint closed", "url", fmt.Sprintf("ws://%s", n.wsEndpoint))
  375. }
  376. if n.wsHandler != nil {
  377. n.wsHandler.Stop()
  378. n.wsHandler = nil
  379. }
  380. }
  381. // Stop terminates a running node along with all it's services. In the node was
  382. // not started, an error is returned.
  383. func (n *Node) Stop() error {
  384. n.lock.Lock()
  385. defer n.lock.Unlock()
  386. // Short circuit if the node's not running
  387. if n.server == nil {
  388. return ErrNodeStopped
  389. }
  390. // Terminate the API, services and the p2p server.
  391. n.stopWS()
  392. n.stopHTTP()
  393. n.stopIPC()
  394. n.rpcAPIs = nil
  395. failure := &StopError{
  396. Services: make(map[reflect.Type]error),
  397. }
  398. for kind, service := range n.services {
  399. if err := service.Stop(); err != nil {
  400. failure.Services[kind] = err
  401. }
  402. }
  403. n.server.Stop()
  404. n.services = nil
  405. n.server = nil
  406. // Release instance directory lock.
  407. if n.instanceDirLock != nil {
  408. if err := n.instanceDirLock.Release(); err != nil {
  409. n.log.Error("Can't release datadir lock", "err", err)
  410. }
  411. n.instanceDirLock = nil
  412. }
  413. // unblock n.Wait
  414. close(n.stop)
  415. // Remove the keystore if it was created ephemerally.
  416. var keystoreErr error
  417. if n.ephemeralKeystore != "" {
  418. keystoreErr = os.RemoveAll(n.ephemeralKeystore)
  419. }
  420. if len(failure.Services) > 0 {
  421. return failure
  422. }
  423. if keystoreErr != nil {
  424. return keystoreErr
  425. }
  426. return nil
  427. }
  428. // Wait blocks the thread until the node is stopped. If the node is not running
  429. // at the time of invocation, the method immediately returns.
  430. func (n *Node) Wait() {
  431. n.lock.RLock()
  432. if n.server == nil {
  433. n.lock.RUnlock()
  434. return
  435. }
  436. stop := n.stop
  437. n.lock.RUnlock()
  438. <-stop
  439. }
  440. // Restart terminates a running node and boots up a new one in its place. If the
  441. // node isn't running, an error is returned.
  442. func (n *Node) Restart() error {
  443. if err := n.Stop(); err != nil {
  444. return err
  445. }
  446. if err := n.Start(); err != nil {
  447. return err
  448. }
  449. return nil
  450. }
  451. // Attach creates an RPC client attached to an in-process API handler.
  452. func (n *Node) Attach() (*rpc.Client, error) {
  453. n.lock.RLock()
  454. defer n.lock.RUnlock()
  455. if n.server == nil {
  456. return nil, ErrNodeStopped
  457. }
  458. return rpc.DialInProc(n.inprocHandler), nil
  459. }
  460. // RPCHandler returns the in-process RPC request handler.
  461. func (n *Node) RPCHandler() (*rpc.Server, error) {
  462. n.lock.RLock()
  463. defer n.lock.RUnlock()
  464. if n.inprocHandler == nil {
  465. return nil, ErrNodeStopped
  466. }
  467. return n.inprocHandler, nil
  468. }
  469. // Server retrieves the currently running P2P network layer. This method is meant
  470. // only to inspect fields of the currently running server, life cycle management
  471. // should be left to this Node entity.
  472. func (n *Node) Server() *p2p.Server {
  473. n.lock.RLock()
  474. defer n.lock.RUnlock()
  475. return n.server
  476. }
  477. // Service retrieves a currently running service registered of a specific type.
  478. func (n *Node) Service(service interface{}) error {
  479. n.lock.RLock()
  480. defer n.lock.RUnlock()
  481. // Short circuit if the node's not running
  482. if n.server == nil {
  483. return ErrNodeStopped
  484. }
  485. // Otherwise try to find the service to return
  486. element := reflect.ValueOf(service).Elem()
  487. if running, ok := n.services[element.Type()]; ok {
  488. element.Set(reflect.ValueOf(running))
  489. return nil
  490. }
  491. return ErrServiceUnknown
  492. }
  493. // DataDir retrieves the current datadir used by the protocol stack.
  494. // Deprecated: No files should be stored in this directory, use InstanceDir instead.
  495. func (n *Node) DataDir() string {
  496. return n.config.DataDir
  497. }
  498. // InstanceDir retrieves the instance directory used by the protocol stack.
  499. func (n *Node) InstanceDir() string {
  500. return n.config.instanceDir()
  501. }
  502. // AccountManager retrieves the account manager used by the protocol stack.
  503. func (n *Node) AccountManager() *accounts.Manager {
  504. return n.accman
  505. }
  506. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  507. func (n *Node) IPCEndpoint() string {
  508. return n.ipcEndpoint
  509. }
  510. // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
  511. func (n *Node) HTTPEndpoint() string {
  512. n.lock.Lock()
  513. defer n.lock.Unlock()
  514. if n.httpListener != nil {
  515. return n.httpListener.Addr().String()
  516. }
  517. return n.httpEndpoint
  518. }
  519. // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
  520. func (n *Node) WSEndpoint() string {
  521. n.lock.Lock()
  522. defer n.lock.Unlock()
  523. if n.wsListener != nil {
  524. return n.wsListener.Addr().String()
  525. }
  526. return n.wsEndpoint
  527. }
  528. // EventMux retrieves the event multiplexer used by all the network services in
  529. // the current protocol stack.
  530. func (n *Node) EventMux() *event.TypeMux {
  531. return n.eventmux
  532. }
  533. // OpenDatabase opens an existing database with the given name (or creates one if no
  534. // previous can be found) from within the node's instance directory. If the node is
  535. // ephemeral, a memory database is returned.
  536. func (n *Node) OpenDatabase(name string, cache, handles int) (ethdb.Database, error) {
  537. if n.config.DataDir == "" {
  538. return ethdb.NewMemDatabase(), nil
  539. }
  540. return ethdb.NewLDBDatabase(n.config.ResolvePath(name), cache, handles)
  541. }
  542. // ResolvePath returns the absolute path of a resource in the instance directory.
  543. func (n *Node) ResolvePath(x string) string {
  544. return n.config.ResolvePath(x)
  545. }
  546. // apis returns the collection of RPC descriptors this node offers.
  547. func (n *Node) apis() []rpc.API {
  548. return []rpc.API{
  549. {
  550. Namespace: "admin",
  551. Version: "1.0",
  552. Service: NewPrivateAdminAPI(n),
  553. }, {
  554. Namespace: "admin",
  555. Version: "1.0",
  556. Service: NewPublicAdminAPI(n),
  557. Public: true,
  558. }, {
  559. Namespace: "debug",
  560. Version: "1.0",
  561. Service: debug.Handler,
  562. }, {
  563. Namespace: "debug",
  564. Version: "1.0",
  565. Service: NewPublicDebugAPI(n),
  566. Public: true,
  567. }, {
  568. Namespace: "web3",
  569. Version: "1.0",
  570. Service: NewPublicWeb3API(n),
  571. Public: true,
  572. },
  573. }
  574. }