node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 represents the Ethereum protocol stack container.
  17. package node
  18. import (
  19. "errors"
  20. "net"
  21. "os"
  22. "path/filepath"
  23. "reflect"
  24. "sync"
  25. "syscall"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/ethereum/go-ethereum/internal/debug"
  28. "github.com/ethereum/go-ethereum/logger"
  29. "github.com/ethereum/go-ethereum/logger/glog"
  30. "github.com/ethereum/go-ethereum/p2p"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. )
  33. var (
  34. ErrDatadirUsed = errors.New("datadir already used")
  35. ErrNodeStopped = errors.New("node not started")
  36. ErrNodeRunning = errors.New("node already running")
  37. ErrServiceUnknown = errors.New("unknown service")
  38. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  39. )
  40. // Node represents a P2P node into which arbitrary (uniquely typed) services might
  41. // be registered.
  42. type Node struct {
  43. datadir string // Path to the currently used data directory
  44. eventmux *event.TypeMux // Event multiplexer used between the services of a stack
  45. serverConfig *p2p.Server // Configuration of the underlying P2P networking layer
  46. server *p2p.Server // Currently running P2P networking layer
  47. serviceFuncs []ServiceConstructor // Service constructors (in dependency order)
  48. services map[reflect.Type]Service // Currently running services
  49. rpcAPIs []rpc.API // List of APIs currently provided by the node
  50. inprocHandler *rpc.Server // In-process RPC request handler to process the API requests
  51. ipcEndpoint string // IPC endpoint to listen at (empty = IPC disabled)
  52. ipcListener net.Listener // IPC RPC listener socket to serve API requests
  53. ipcHandler *rpc.Server // IPC RPC request handler to process the API requests
  54. httpHost string // HTTP hostname
  55. httpPort int // HTTP post
  56. httpEndpoint string // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled)
  57. httpWhitelist []string // HTTP RPC modules to allow through this endpoint
  58. httpCors string // HTTP RPC Cross-Origin Resource Sharing header
  59. httpListener net.Listener // HTTP RPC listener socket to server API requests
  60. httpHandler *rpc.Server // HTTP RPC request handler to process the API requests
  61. wsHost string // Websocket host
  62. wsPort int // Websocket post
  63. wsEndpoint string // Websocket endpoint (interface + port) to listen at (empty = websocket disabled)
  64. wsWhitelist []string // Websocket RPC modules to allow through this endpoint
  65. wsOrigins string // Websocket RPC allowed origin domains
  66. wsListener net.Listener // Websocket RPC listener socket to server API requests
  67. wsHandler *rpc.Server // Websocket RPC request handler to process the API requests
  68. stop chan struct{} // Channel to wait for termination notifications
  69. lock sync.RWMutex
  70. }
  71. // New creates a new P2P node, ready for protocol registration.
  72. func New(conf *Config) (*Node, error) {
  73. // Ensure the data directory exists, failing if it cannot be created
  74. if conf.DataDir != "" {
  75. if err := os.MkdirAll(conf.DataDir, 0700); err != nil {
  76. return nil, err
  77. }
  78. }
  79. // Assemble the networking layer and the node itself
  80. nodeDbPath := ""
  81. if conf.DataDir != "" {
  82. nodeDbPath = filepath.Join(conf.DataDir, datadirNodeDatabase)
  83. }
  84. return &Node{
  85. datadir: conf.DataDir,
  86. serverConfig: &p2p.Server{
  87. PrivateKey: conf.NodeKey(),
  88. Name: conf.Name,
  89. Discovery: !conf.NoDiscovery,
  90. BootstrapNodes: conf.BootstrapNodes,
  91. StaticNodes: conf.StaticNodes(),
  92. TrustedNodes: conf.TrusterNodes(),
  93. NodeDatabase: nodeDbPath,
  94. ListenAddr: conf.ListenAddr,
  95. NAT: conf.NAT,
  96. Dialer: conf.Dialer,
  97. NoDial: conf.NoDial,
  98. MaxPeers: conf.MaxPeers,
  99. MaxPendingPeers: conf.MaxPendingPeers,
  100. },
  101. serviceFuncs: []ServiceConstructor{},
  102. ipcEndpoint: conf.IPCEndpoint(),
  103. httpHost: conf.HTTPHost,
  104. httpPort: conf.HTTPPort,
  105. httpEndpoint: conf.HTTPEndpoint(),
  106. httpWhitelist: conf.HTTPModules,
  107. httpCors: conf.HTTPCors,
  108. wsHost: conf.WSHost,
  109. wsPort: conf.WSPort,
  110. wsEndpoint: conf.WSEndpoint(),
  111. wsWhitelist: conf.WSModules,
  112. wsOrigins: conf.WSOrigins,
  113. eventmux: new(event.TypeMux),
  114. }, nil
  115. }
  116. // Register injects a new service into the node's stack. The service created by
  117. // the passed constructor must be unique in its type with regard to sibling ones.
  118. func (n *Node) Register(constructor ServiceConstructor) error {
  119. n.lock.Lock()
  120. defer n.lock.Unlock()
  121. if n.server != nil {
  122. return ErrNodeRunning
  123. }
  124. n.serviceFuncs = append(n.serviceFuncs, constructor)
  125. return nil
  126. }
  127. // Start create a live P2P node and starts running it.
  128. func (n *Node) Start() error {
  129. n.lock.Lock()
  130. defer n.lock.Unlock()
  131. // Short circuit if the node's already running
  132. if n.server != nil {
  133. return ErrNodeRunning
  134. }
  135. // Otherwise copy and specialize the P2P configuration
  136. running := new(p2p.Server)
  137. *running = *n.serverConfig
  138. services := make(map[reflect.Type]Service)
  139. for _, constructor := range n.serviceFuncs {
  140. // Create a new context for the particular service
  141. ctx := &ServiceContext{
  142. datadir: n.datadir,
  143. services: make(map[reflect.Type]Service),
  144. EventMux: n.eventmux,
  145. }
  146. for kind, s := range services { // copy needed for threaded access
  147. ctx.services[kind] = s
  148. }
  149. // Construct and save the service
  150. service, err := constructor(ctx)
  151. if err != nil {
  152. return err
  153. }
  154. kind := reflect.TypeOf(service)
  155. if _, exists := services[kind]; exists {
  156. return &DuplicateServiceError{Kind: kind}
  157. }
  158. services[kind] = service
  159. }
  160. // Gather the protocols and start the freshly assembled P2P server
  161. for _, service := range services {
  162. running.Protocols = append(running.Protocols, service.Protocols()...)
  163. }
  164. if err := running.Start(); err != nil {
  165. if errno, ok := err.(syscall.Errno); ok && datadirInUseErrnos[uint(errno)] {
  166. return ErrDatadirUsed
  167. }
  168. return err
  169. }
  170. // Start each of the services
  171. started := []reflect.Type{}
  172. for kind, service := range services {
  173. // Start the next service, stopping all previous upon failure
  174. if err := service.Start(running); err != nil {
  175. for _, kind := range started {
  176. services[kind].Stop()
  177. }
  178. running.Stop()
  179. return err
  180. }
  181. // Mark the service started for potential cleanup
  182. started = append(started, kind)
  183. }
  184. // Lastly start the configured RPC interfaces
  185. if err := n.startRPC(services); err != nil {
  186. for _, service := range services {
  187. service.Stop()
  188. }
  189. running.Stop()
  190. return err
  191. }
  192. // Finish initializing the startup
  193. n.services = services
  194. n.server = running
  195. n.stop = make(chan struct{})
  196. return nil
  197. }
  198. // startRPC is a helper method to start all the various RPC endpoint during node
  199. // startup. It's not meant to be called at any time afterwards as it makes certain
  200. // assumptions about the state of the node.
  201. func (n *Node) startRPC(services map[reflect.Type]Service) error {
  202. // Gather all the possible APIs to surface
  203. apis := n.apis()
  204. for _, service := range services {
  205. apis = append(apis, service.APIs()...)
  206. }
  207. // Start the various API endpoints, terminating all in case of errors
  208. if err := n.startInProc(apis); err != nil {
  209. return err
  210. }
  211. if err := n.startIPC(apis); err != nil {
  212. n.stopInProc()
  213. return err
  214. }
  215. if err := n.startHTTP(n.httpEndpoint, apis, n.httpWhitelist, n.httpCors); err != nil {
  216. n.stopIPC()
  217. n.stopInProc()
  218. return err
  219. }
  220. if err := n.startWS(n.wsEndpoint, apis, n.wsWhitelist, n.wsOrigins); err != nil {
  221. n.stopHTTP()
  222. n.stopIPC()
  223. n.stopInProc()
  224. return err
  225. }
  226. // All API endpoints started successfully
  227. n.rpcAPIs = apis
  228. return nil
  229. }
  230. // startInProc initializes an in-process RPC endpoint.
  231. func (n *Node) startInProc(apis []rpc.API) error {
  232. // Register all the APIs exposed by the services
  233. handler := rpc.NewServer()
  234. for _, api := range apis {
  235. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  236. return err
  237. }
  238. glog.V(logger.Debug).Infof("InProc registered %T under '%s'", api.Service, api.Namespace)
  239. }
  240. n.inprocHandler = handler
  241. return nil
  242. }
  243. // stopInProc terminates the in-process RPC endpoint.
  244. func (n *Node) stopInProc() {
  245. if n.inprocHandler != nil {
  246. n.inprocHandler.Stop()
  247. n.inprocHandler = nil
  248. }
  249. }
  250. // startIPC initializes and starts the IPC RPC endpoint.
  251. func (n *Node) startIPC(apis []rpc.API) error {
  252. // Short circuit if the IPC endpoint isn't being exposed
  253. if n.ipcEndpoint == "" {
  254. return nil
  255. }
  256. // Register all the APIs exposed by the services
  257. handler := rpc.NewServer()
  258. for _, api := range apis {
  259. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  260. return err
  261. }
  262. glog.V(logger.Debug).Infof("IPC registered %T under '%s'", api.Service, api.Namespace)
  263. }
  264. // All APIs registered, start the IPC listener
  265. var (
  266. listener net.Listener
  267. err error
  268. )
  269. if listener, err = rpc.CreateIPCListener(n.ipcEndpoint); err != nil {
  270. return err
  271. }
  272. go func() {
  273. glog.V(logger.Info).Infof("IPC endpoint opened: %s", n.ipcEndpoint)
  274. for {
  275. conn, err := listener.Accept()
  276. if err != nil {
  277. // Terminate if the listener was closed
  278. n.lock.RLock()
  279. closed := n.ipcListener == nil
  280. n.lock.RUnlock()
  281. if closed {
  282. return
  283. }
  284. // Not closed, just some error; report and continue
  285. glog.V(logger.Error).Infof("IPC accept failed: %v", err)
  286. continue
  287. }
  288. go handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation | rpc.OptionSubscriptions)
  289. }
  290. }()
  291. // All listeners booted successfully
  292. n.ipcListener = listener
  293. n.ipcHandler = handler
  294. return nil
  295. }
  296. // stopIPC terminates the IPC RPC endpoint.
  297. func (n *Node) stopIPC() {
  298. if n.ipcListener != nil {
  299. n.ipcListener.Close()
  300. n.ipcListener = nil
  301. glog.V(logger.Info).Infof("IPC endpoint closed: %s", n.ipcEndpoint)
  302. }
  303. if n.ipcHandler != nil {
  304. n.ipcHandler.Stop()
  305. n.ipcHandler = nil
  306. }
  307. }
  308. // startHTTP initializes and starts the HTTP RPC endpoint.
  309. func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors string) error {
  310. // Short circuit if the HTTP endpoint isn't being exposed
  311. if endpoint == "" {
  312. return nil
  313. }
  314. // Generate the whitelist based on the allowed modules
  315. whitelist := make(map[string]bool)
  316. for _, module := range modules {
  317. whitelist[module] = true
  318. }
  319. // Register all the APIs exposed by the services
  320. handler := rpc.NewServer()
  321. for _, api := range apis {
  322. if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
  323. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  324. return err
  325. }
  326. glog.V(logger.Debug).Infof("HTTP registered %T under '%s'", api.Service, api.Namespace)
  327. }
  328. }
  329. // All APIs registered, start the HTTP listener
  330. var (
  331. listener net.Listener
  332. err error
  333. )
  334. if listener, err = net.Listen("tcp", endpoint); err != nil {
  335. return err
  336. }
  337. go rpc.NewHTTPServer(cors, handler).Serve(listener)
  338. glog.V(logger.Info).Infof("HTTP endpoint opened: http://%s", endpoint)
  339. // All listeners booted successfully
  340. n.httpEndpoint = endpoint
  341. n.httpListener = listener
  342. n.httpHandler = handler
  343. n.httpCors = cors
  344. return nil
  345. }
  346. // stopHTTP terminates the HTTP RPC endpoint.
  347. func (n *Node) stopHTTP() {
  348. if n.httpListener != nil {
  349. n.httpListener.Close()
  350. n.httpListener = nil
  351. glog.V(logger.Info).Infof("HTTP endpoint closed: http://%s", n.httpEndpoint)
  352. }
  353. if n.httpHandler != nil {
  354. n.httpHandler.Stop()
  355. n.httpHandler = nil
  356. }
  357. }
  358. // startWS initializes and starts the websocket RPC endpoint.
  359. func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins string) error {
  360. // Short circuit if the WS endpoint isn't being exposed
  361. if endpoint == "" {
  362. return nil
  363. }
  364. // Generate the whitelist based on the allowed modules
  365. whitelist := make(map[string]bool)
  366. for _, module := range modules {
  367. whitelist[module] = true
  368. }
  369. // Register all the APIs exposed by the services
  370. handler := rpc.NewServer()
  371. for _, api := range apis {
  372. if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
  373. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  374. return err
  375. }
  376. glog.V(logger.Debug).Infof("WebSocket registered %T under '%s'", api.Service, api.Namespace)
  377. }
  378. }
  379. // All APIs registered, start the HTTP listener
  380. var (
  381. listener net.Listener
  382. err error
  383. )
  384. if listener, err = net.Listen("tcp", endpoint); err != nil {
  385. return err
  386. }
  387. go rpc.NewWSServer(wsOrigins, handler).Serve(listener)
  388. glog.V(logger.Info).Infof("WebSocket endpoint opened: ws://%s", endpoint)
  389. // All listeners booted successfully
  390. n.wsEndpoint = endpoint
  391. n.wsListener = listener
  392. n.wsHandler = handler
  393. n.wsOrigins = wsOrigins
  394. return nil
  395. }
  396. // stopWS terminates the websocket RPC endpoint.
  397. func (n *Node) stopWS() {
  398. if n.wsListener != nil {
  399. n.wsListener.Close()
  400. n.wsListener = nil
  401. glog.V(logger.Info).Infof("WebSocket endpoint closed: ws://%s", n.wsEndpoint)
  402. }
  403. if n.wsHandler != nil {
  404. n.wsHandler.Stop()
  405. n.wsHandler = nil
  406. }
  407. }
  408. // Stop terminates a running node along with all it's services. In the node was
  409. // not started, an error is returned.
  410. func (n *Node) Stop() error {
  411. n.lock.Lock()
  412. defer n.lock.Unlock()
  413. // Short circuit if the node's not running
  414. if n.server == nil {
  415. return ErrNodeStopped
  416. }
  417. // Otherwise terminate the API, all services and the P2P server too
  418. n.stopWS()
  419. n.stopHTTP()
  420. n.stopIPC()
  421. n.rpcAPIs = nil
  422. failure := &StopError{
  423. Services: make(map[reflect.Type]error),
  424. }
  425. for kind, service := range n.services {
  426. if err := service.Stop(); err != nil {
  427. failure.Services[kind] = err
  428. }
  429. }
  430. n.server.Stop()
  431. n.services = nil
  432. n.server = nil
  433. close(n.stop)
  434. if len(failure.Services) > 0 {
  435. return failure
  436. }
  437. return nil
  438. }
  439. // Wait blocks the thread until the node is stopped. If the node is not running
  440. // at the time of invocation, the method immediately returns.
  441. func (n *Node) Wait() {
  442. n.lock.RLock()
  443. if n.server == nil {
  444. return
  445. }
  446. stop := n.stop
  447. n.lock.RUnlock()
  448. <-stop
  449. }
  450. // Restart terminates a running node and boots up a new one in its place. If the
  451. // node isn't running, an error is returned.
  452. func (n *Node) Restart() error {
  453. if err := n.Stop(); err != nil {
  454. return err
  455. }
  456. if err := n.Start(); err != nil {
  457. return err
  458. }
  459. return nil
  460. }
  461. // Attach creates an RPC client attached to an in-process API handler.
  462. func (n *Node) Attach() (rpc.Client, error) {
  463. n.lock.RLock()
  464. defer n.lock.RUnlock()
  465. // Short circuit if the node's not running
  466. if n.server == nil {
  467. return nil, ErrNodeStopped
  468. }
  469. // Otherwise attach to the API and return
  470. return rpc.NewInProcRPCClient(n.inprocHandler), nil
  471. }
  472. // Server retrieves the currently running P2P network layer. This method is meant
  473. // only to inspect fields of the currently running server, life cycle management
  474. // should be left to this Node entity.
  475. func (n *Node) Server() *p2p.Server {
  476. n.lock.RLock()
  477. defer n.lock.RUnlock()
  478. return n.server
  479. }
  480. // Service retrieves a currently running service registered of a specific type.
  481. func (n *Node) Service(service interface{}) error {
  482. n.lock.RLock()
  483. defer n.lock.RUnlock()
  484. // Short circuit if the node's not running
  485. if n.server == nil {
  486. return ErrNodeStopped
  487. }
  488. // Otherwise try to find the service to return
  489. element := reflect.ValueOf(service).Elem()
  490. if running, ok := n.services[element.Type()]; ok {
  491. element.Set(reflect.ValueOf(running))
  492. return nil
  493. }
  494. return ErrServiceUnknown
  495. }
  496. // DataDir retrieves the current datadir used by the protocol stack.
  497. func (n *Node) DataDir() string {
  498. return n.datadir
  499. }
  500. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  501. func (n *Node) IPCEndpoint() string {
  502. return n.ipcEndpoint
  503. }
  504. // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
  505. func (n *Node) HTTPEndpoint() string {
  506. return n.httpEndpoint
  507. }
  508. // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
  509. func (n *Node) WSEndpoint() string {
  510. return n.wsEndpoint
  511. }
  512. // EventMux retrieves the event multiplexer used by all the network services in
  513. // the current protocol stack.
  514. func (n *Node) EventMux() *event.TypeMux {
  515. return n.eventmux
  516. }
  517. // apis returns the collection of RPC descriptors this node offers.
  518. func (n *Node) apis() []rpc.API {
  519. return []rpc.API{
  520. {
  521. Namespace: "admin",
  522. Version: "1.0",
  523. Service: NewPrivateAdminAPI(n),
  524. }, {
  525. Namespace: "admin",
  526. Version: "1.0",
  527. Service: NewPublicAdminAPI(n),
  528. Public: true,
  529. }, {
  530. Namespace: "debug",
  531. Version: "1.0",
  532. Service: debug.Handler,
  533. }, {
  534. Namespace: "debug",
  535. Version: "1.0",
  536. Service: NewPublicDebugAPI(n),
  537. Public: true,
  538. }, {
  539. Namespace: "web3",
  540. Version: "1.0",
  541. Service: NewPublicWeb3API(n),
  542. Public: true,
  543. },
  544. }
  545. }