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