node.go 18 KB

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