node.go 17 KB

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