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