node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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.Config
  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.Config{
  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 := &p2p.Server{Config: n.serverConfig}
  137. services := make(map[reflect.Type]Service)
  138. for _, constructor := range n.serviceFuncs {
  139. // Create a new context for the particular service
  140. ctx := &ServiceContext{
  141. datadir: n.datadir,
  142. services: make(map[reflect.Type]Service),
  143. EventMux: n.eventmux,
  144. }
  145. for kind, s := range services { // copy needed for threaded access
  146. ctx.services[kind] = s
  147. }
  148. // Construct and save the service
  149. service, err := constructor(ctx)
  150. if err != nil {
  151. return err
  152. }
  153. kind := reflect.TypeOf(service)
  154. if _, exists := services[kind]; exists {
  155. return &DuplicateServiceError{Kind: kind}
  156. }
  157. services[kind] = service
  158. }
  159. // Gather the protocols and start the freshly assembled P2P server
  160. for _, service := range services {
  161. running.Protocols = append(running.Protocols, service.Protocols()...)
  162. }
  163. if err := running.Start(); err != nil {
  164. if errno, ok := err.(syscall.Errno); ok && datadirInUseErrnos[uint(errno)] {
  165. return ErrDatadirUsed
  166. }
  167. return err
  168. }
  169. // Start each of the services
  170. started := []reflect.Type{}
  171. for kind, service := range services {
  172. // Start the next service, stopping all previous upon failure
  173. if err := service.Start(running); err != nil {
  174. for _, kind := range started {
  175. services[kind].Stop()
  176. }
  177. running.Stop()
  178. return err
  179. }
  180. // Mark the service started for potential cleanup
  181. started = append(started, kind)
  182. }
  183. // Lastly start the configured RPC interfaces
  184. if err := n.startRPC(services); err != nil {
  185. for _, service := range services {
  186. service.Stop()
  187. }
  188. running.Stop()
  189. return err
  190. }
  191. // Finish initializing the startup
  192. n.services = services
  193. n.server = running
  194. n.stop = make(chan struct{})
  195. return nil
  196. }
  197. // startRPC is a helper method to start all the various RPC endpoint during node
  198. // startup. It's not meant to be called at any time afterwards as it makes certain
  199. // assumptions about the state of the node.
  200. func (n *Node) startRPC(services map[reflect.Type]Service) error {
  201. // Gather all the possible APIs to surface
  202. apis := n.apis()
  203. for _, service := range services {
  204. apis = append(apis, service.APIs()...)
  205. }
  206. // Start the various API endpoints, terminating all in case of errors
  207. if err := n.startInProc(apis); err != nil {
  208. return err
  209. }
  210. if err := n.startIPC(apis); err != nil {
  211. n.stopInProc()
  212. return err
  213. }
  214. if err := n.startHTTP(n.httpEndpoint, apis, n.httpWhitelist, n.httpCors); err != nil {
  215. n.stopIPC()
  216. n.stopInProc()
  217. return err
  218. }
  219. if err := n.startWS(n.wsEndpoint, apis, n.wsWhitelist, n.wsOrigins); err != nil {
  220. n.stopHTTP()
  221. n.stopIPC()
  222. n.stopInProc()
  223. return err
  224. }
  225. // All API endpoints started successfully
  226. n.rpcAPIs = apis
  227. return nil
  228. }
  229. // startInProc initializes an in-process RPC endpoint.
  230. func (n *Node) startInProc(apis []rpc.API) error {
  231. // Register all the APIs exposed by the services
  232. handler := rpc.NewServer()
  233. for _, api := range apis {
  234. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  235. return err
  236. }
  237. glog.V(logger.Debug).Infof("InProc registered %T under '%s'", api.Service, api.Namespace)
  238. }
  239. n.inprocHandler = handler
  240. return nil
  241. }
  242. // stopInProc terminates the in-process RPC endpoint.
  243. func (n *Node) stopInProc() {
  244. if n.inprocHandler != nil {
  245. n.inprocHandler.Stop()
  246. n.inprocHandler = nil
  247. }
  248. }
  249. // startIPC initializes and starts the IPC RPC endpoint.
  250. func (n *Node) startIPC(apis []rpc.API) error {
  251. // Short circuit if the IPC endpoint isn't being exposed
  252. if n.ipcEndpoint == "" {
  253. return nil
  254. }
  255. // Register all the APIs exposed by the services
  256. handler := rpc.NewServer()
  257. for _, api := range apis {
  258. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  259. return err
  260. }
  261. glog.V(logger.Debug).Infof("IPC registered %T under '%s'", api.Service, api.Namespace)
  262. }
  263. // All APIs registered, start the IPC listener
  264. var (
  265. listener net.Listener
  266. err error
  267. )
  268. if listener, err = rpc.CreateIPCListener(n.ipcEndpoint); err != nil {
  269. return err
  270. }
  271. go func() {
  272. glog.V(logger.Info).Infof("IPC endpoint opened: %s", n.ipcEndpoint)
  273. for {
  274. conn, err := listener.Accept()
  275. if err != nil {
  276. // Terminate if the listener was closed
  277. n.lock.RLock()
  278. closed := n.ipcListener == nil
  279. n.lock.RUnlock()
  280. if closed {
  281. return
  282. }
  283. // Not closed, just some error; report and continue
  284. glog.V(logger.Error).Infof("IPC accept failed: %v", err)
  285. continue
  286. }
  287. go handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation|rpc.OptionSubscriptions)
  288. }
  289. }()
  290. // All listeners booted successfully
  291. n.ipcListener = listener
  292. n.ipcHandler = handler
  293. return nil
  294. }
  295. // stopIPC terminates the IPC RPC endpoint.
  296. func (n *Node) stopIPC() {
  297. if n.ipcListener != nil {
  298. n.ipcListener.Close()
  299. n.ipcListener = nil
  300. glog.V(logger.Info).Infof("IPC endpoint closed: %s", n.ipcEndpoint)
  301. }
  302. if n.ipcHandler != nil {
  303. n.ipcHandler.Stop()
  304. n.ipcHandler = nil
  305. }
  306. }
  307. // startHTTP initializes and starts the HTTP RPC endpoint.
  308. func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors string) error {
  309. // Short circuit if the HTTP endpoint isn't being exposed
  310. if endpoint == "" {
  311. return nil
  312. }
  313. // Generate the whitelist based on the allowed modules
  314. whitelist := make(map[string]bool)
  315. for _, module := range modules {
  316. whitelist[module] = true
  317. }
  318. // Register all the APIs exposed by the services
  319. handler := rpc.NewServer()
  320. for _, api := range apis {
  321. if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
  322. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  323. return err
  324. }
  325. glog.V(logger.Debug).Infof("HTTP registered %T under '%s'", api.Service, api.Namespace)
  326. }
  327. }
  328. // All APIs registered, start the HTTP listener
  329. var (
  330. listener net.Listener
  331. err error
  332. )
  333. if listener, err = net.Listen("tcp", endpoint); err != nil {
  334. return err
  335. }
  336. go rpc.NewHTTPServer(cors, handler).Serve(listener)
  337. glog.V(logger.Info).Infof("HTTP endpoint opened: http://%s", endpoint)
  338. // All listeners booted successfully
  339. n.httpEndpoint = endpoint
  340. n.httpListener = listener
  341. n.httpHandler = handler
  342. n.httpCors = cors
  343. return nil
  344. }
  345. // stopHTTP terminates the HTTP RPC endpoint.
  346. func (n *Node) stopHTTP() {
  347. if n.httpListener != nil {
  348. n.httpListener.Close()
  349. n.httpListener = nil
  350. glog.V(logger.Info).Infof("HTTP endpoint closed: http://%s", n.httpEndpoint)
  351. }
  352. if n.httpHandler != nil {
  353. n.httpHandler.Stop()
  354. n.httpHandler = nil
  355. }
  356. }
  357. // startWS initializes and starts the websocket RPC endpoint.
  358. func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins string) error {
  359. // Short circuit if the WS endpoint isn't being exposed
  360. if endpoint == "" {
  361. return nil
  362. }
  363. // Generate the whitelist based on the allowed modules
  364. whitelist := make(map[string]bool)
  365. for _, module := range modules {
  366. whitelist[module] = true
  367. }
  368. // Register all the APIs exposed by the services
  369. handler := rpc.NewServer()
  370. for _, api := range apis {
  371. if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
  372. if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
  373. return err
  374. }
  375. glog.V(logger.Debug).Infof("WebSocket registered %T under '%s'", api.Service, api.Namespace)
  376. }
  377. }
  378. // All APIs registered, start the HTTP listener
  379. var (
  380. listener net.Listener
  381. err error
  382. )
  383. if listener, err = net.Listen("tcp", endpoint); err != nil {
  384. return err
  385. }
  386. go rpc.NewWSServer(wsOrigins, handler).Serve(listener)
  387. glog.V(logger.Info).Infof("WebSocket endpoint opened: ws://%s", endpoint)
  388. // All listeners booted successfully
  389. n.wsEndpoint = endpoint
  390. n.wsListener = listener
  391. n.wsHandler = handler
  392. n.wsOrigins = wsOrigins
  393. return nil
  394. }
  395. // stopWS terminates the websocket RPC endpoint.
  396. func (n *Node) stopWS() {
  397. if n.wsListener != nil {
  398. n.wsListener.Close()
  399. n.wsListener = nil
  400. glog.V(logger.Info).Infof("WebSocket endpoint closed: ws://%s", n.wsEndpoint)
  401. }
  402. if n.wsHandler != nil {
  403. n.wsHandler.Stop()
  404. n.wsHandler = nil
  405. }
  406. }
  407. // Stop terminates a running node along with all it's services. In the node was
  408. // not started, an error is returned.
  409. func (n *Node) Stop() error {
  410. n.lock.Lock()
  411. defer n.lock.Unlock()
  412. // Short circuit if the node's not running
  413. if n.server == nil {
  414. return ErrNodeStopped
  415. }
  416. // Otherwise terminate the API, all services and the P2P server too
  417. n.stopWS()
  418. n.stopHTTP()
  419. n.stopIPC()
  420. n.rpcAPIs = nil
  421. failure := &StopError{
  422. Services: make(map[reflect.Type]error),
  423. }
  424. for kind, service := range n.services {
  425. if err := service.Stop(); err != nil {
  426. failure.Services[kind] = err
  427. }
  428. }
  429. n.server.Stop()
  430. n.services = nil
  431. n.server = nil
  432. close(n.stop)
  433. if len(failure.Services) > 0 {
  434. return failure
  435. }
  436. return nil
  437. }
  438. // Wait blocks the thread until the node is stopped. If the node is not running
  439. // at the time of invocation, the method immediately returns.
  440. func (n *Node) Wait() {
  441. n.lock.RLock()
  442. if n.server == nil {
  443. return
  444. }
  445. stop := n.stop
  446. n.lock.RUnlock()
  447. <-stop
  448. }
  449. // Restart terminates a running node and boots up a new one in its place. If the
  450. // node isn't running, an error is returned.
  451. func (n *Node) Restart() error {
  452. if err := n.Stop(); err != nil {
  453. return err
  454. }
  455. if err := n.Start(); err != nil {
  456. return err
  457. }
  458. return nil
  459. }
  460. // Attach creates an RPC client attached to an in-process API handler.
  461. func (n *Node) Attach() (*rpc.Client, error) {
  462. n.lock.RLock()
  463. defer n.lock.RUnlock()
  464. if n.server == nil {
  465. return nil, ErrNodeStopped
  466. }
  467. return rpc.DialInProc(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. func (n *Node) DataDir() string {
  495. return n.datadir
  496. }
  497. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  498. func (n *Node) IPCEndpoint() string {
  499. return n.ipcEndpoint
  500. }
  501. // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
  502. func (n *Node) HTTPEndpoint() string {
  503. return n.httpEndpoint
  504. }
  505. // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
  506. func (n *Node) WSEndpoint() string {
  507. return n.wsEndpoint
  508. }
  509. // EventMux retrieves the event multiplexer used by all the network services in
  510. // the current protocol stack.
  511. func (n *Node) EventMux() *event.TypeMux {
  512. return n.eventmux
  513. }
  514. // apis returns the collection of RPC descriptors this node offers.
  515. func (n *Node) apis() []rpc.API {
  516. return []rpc.API{
  517. {
  518. Namespace: "admin",
  519. Version: "1.0",
  520. Service: NewPrivateAdminAPI(n),
  521. }, {
  522. Namespace: "admin",
  523. Version: "1.0",
  524. Service: NewPublicAdminAPI(n),
  525. Public: true,
  526. }, {
  527. Namespace: "debug",
  528. Version: "1.0",
  529. Service: debug.Handler,
  530. }, {
  531. Namespace: "debug",
  532. Version: "1.0",
  533. Service: NewPublicDebugAPI(n),
  534. Public: true,
  535. }, {
  536. Namespace: "web3",
  537. Version: "1.0",
  538. Service: NewPublicWeb3API(n),
  539. Public: true,
  540. },
  541. }
  542. }