github.com/jimmyx0x/go-ethereum@v1.10.28/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 crand "crypto/rand" 21 "errors" 22 "fmt" 23 "hash/crc32" 24 "net/http" 25 "os" 26 "path/filepath" 27 "reflect" 28 "strings" 29 "sync" 30 31 "github.com/ethereum/go-ethereum/accounts" 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/hexutil" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/ethdb" 36 "github.com/ethereum/go-ethereum/event" 37 "github.com/ethereum/go-ethereum/log" 38 "github.com/ethereum/go-ethereum/p2p" 39 "github.com/ethereum/go-ethereum/rpc" 40 "github.com/prometheus/tsdb/fileutil" 41 ) 42 43 // Node is a container on which services can be registered. 44 type Node struct { 45 eventmux *event.TypeMux 46 config *Config 47 accman *accounts.Manager 48 log log.Logger 49 keyDir string // key store directory 50 keyDirTemp bool // If true, key directory will be removed by Stop 51 dirLock fileutil.Releaser // prevents concurrent use of instance directory 52 stop chan struct{} // Channel to wait for termination notifications 53 server *p2p.Server // Currently running P2P networking layer 54 startStopLock sync.Mutex // Start/Stop are protected by an additional lock 55 state int // Tracks state of node lifecycle 56 57 lock sync.Mutex 58 lifecycles []Lifecycle // All registered backends, services, and auxiliary services that have a lifecycle 59 rpcAPIs []rpc.API // List of APIs currently provided by the node 60 http *httpServer // 61 ws *httpServer // 62 httpAuth *httpServer // 63 wsAuth *httpServer // 64 ipc *ipcServer // Stores information about the ipc http server 65 inprocHandler *rpc.Server // In-process RPC request handler to process the API requests 66 67 databases map[*closeTrackingDB]struct{} // All open databases 68 } 69 70 const ( 71 initializingState = iota 72 runningState 73 closedState 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 if conf.Logger == nil { 90 conf.Logger = log.New() 91 } 92 93 // Ensure that the instance name doesn't cause weird conflicts with 94 // other files in the data directory. 95 if strings.ContainsAny(conf.Name, `/\`) { 96 return nil, errors.New(`Config.Name must not contain '/' or '\'`) 97 } 98 if conf.Name == datadirDefaultKeyStore { 99 return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`) 100 } 101 if strings.HasSuffix(conf.Name, ".ipc") { 102 return nil, errors.New(`Config.Name cannot end in ".ipc"`) 103 } 104 105 node := &Node{ 106 config: conf, 107 inprocHandler: rpc.NewServer(), 108 eventmux: new(event.TypeMux), 109 log: conf.Logger, 110 stop: make(chan struct{}), 111 server: &p2p.Server{Config: conf.P2P}, 112 databases: make(map[*closeTrackingDB]struct{}), 113 } 114 115 // Register built-in APIs. 116 node.rpcAPIs = append(node.rpcAPIs, node.apis()...) 117 118 // Acquire the instance directory lock. 119 if err := node.openDataDir(); err != nil { 120 return nil, err 121 } 122 keyDir, isEphem, err := getKeyStoreDir(conf) 123 if err != nil { 124 return nil, err 125 } 126 node.keyDir = keyDir 127 node.keyDirTemp = isEphem 128 // Creates an empty AccountManager with no backends. Callers (e.g. cmd/geth) 129 // are required to add the backends later on. 130 node.accman = accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}) 131 132 // Initialize the p2p server. This creates the node key and discovery databases. 133 node.server.Config.PrivateKey = node.config.NodeKey() 134 node.server.Config.Name = node.config.NodeName() 135 node.server.Config.Logger = node.log 136 node.config.checkLegacyFiles() 137 if node.server.Config.NodeDatabase == "" { 138 node.server.Config.NodeDatabase = node.config.NodeDB() 139 } 140 141 // Check HTTP/WS prefixes are valid. 142 if err := validatePrefix("HTTP", conf.HTTPPathPrefix); err != nil { 143 return nil, err 144 } 145 if err := validatePrefix("WebSocket", conf.WSPathPrefix); err != nil { 146 return nil, err 147 } 148 149 // Configure RPC servers. 150 node.http = newHTTPServer(node.log, conf.HTTPTimeouts) 151 node.httpAuth = newHTTPServer(node.log, conf.HTTPTimeouts) 152 node.ws = newHTTPServer(node.log, rpc.DefaultHTTPTimeouts) 153 node.wsAuth = newHTTPServer(node.log, rpc.DefaultHTTPTimeouts) 154 node.ipc = newIPCServer(node.log, conf.IPCEndpoint()) 155 156 return node, nil 157 } 158 159 // Start starts all registered lifecycles, RPC services and p2p networking. 160 // Node can only be started once. 161 func (n *Node) Start() error { 162 n.startStopLock.Lock() 163 defer n.startStopLock.Unlock() 164 165 n.lock.Lock() 166 switch n.state { 167 case runningState: 168 n.lock.Unlock() 169 return ErrNodeRunning 170 case closedState: 171 n.lock.Unlock() 172 return ErrNodeStopped 173 } 174 n.state = runningState 175 // open networking and RPC endpoints 176 err := n.openEndpoints() 177 lifecycles := make([]Lifecycle, len(n.lifecycles)) 178 copy(lifecycles, n.lifecycles) 179 n.lock.Unlock() 180 181 // Check if endpoint startup failed. 182 if err != nil { 183 n.doClose(nil) 184 return err 185 } 186 // Start all registered lifecycles. 187 var started []Lifecycle 188 for _, lifecycle := range lifecycles { 189 if err = lifecycle.Start(); err != nil { 190 break 191 } 192 started = append(started, lifecycle) 193 } 194 // Check if any lifecycle failed to start. 195 if err != nil { 196 n.stopServices(started) 197 n.doClose(nil) 198 } 199 return err 200 } 201 202 // Close stops the Node and releases resources acquired in 203 // Node constructor New. 204 func (n *Node) Close() error { 205 n.startStopLock.Lock() 206 defer n.startStopLock.Unlock() 207 208 n.lock.Lock() 209 state := n.state 210 n.lock.Unlock() 211 switch state { 212 case initializingState: 213 // The node was never started. 214 return n.doClose(nil) 215 case runningState: 216 // The node was started, release resources acquired by Start(). 217 var errs []error 218 if err := n.stopServices(n.lifecycles); err != nil { 219 errs = append(errs, err) 220 } 221 return n.doClose(errs) 222 case closedState: 223 return ErrNodeStopped 224 default: 225 panic(fmt.Sprintf("node is in unknown state %d", state)) 226 } 227 } 228 229 // doClose releases resources acquired by New(), collecting errors. 230 func (n *Node) doClose(errs []error) error { 231 // Close databases. This needs the lock because it needs to 232 // synchronize with OpenDatabase*. 233 n.lock.Lock() 234 n.state = closedState 235 errs = append(errs, n.closeDatabases()...) 236 n.lock.Unlock() 237 238 if err := n.accman.Close(); err != nil { 239 errs = append(errs, err) 240 } 241 if n.keyDirTemp { 242 if err := os.RemoveAll(n.keyDir); err != nil { 243 errs = append(errs, err) 244 } 245 } 246 247 // Release instance directory lock. 248 n.closeDataDir() 249 250 // Unblock n.Wait. 251 close(n.stop) 252 253 // Report any errors that might have occurred. 254 switch len(errs) { 255 case 0: 256 return nil 257 case 1: 258 return errs[0] 259 default: 260 return fmt.Errorf("%v", errs) 261 } 262 } 263 264 // openEndpoints starts all network and RPC endpoints. 265 func (n *Node) openEndpoints() error { 266 // start networking endpoints 267 n.log.Info("Starting peer-to-peer node", "instance", n.server.Name) 268 if err := n.server.Start(); err != nil { 269 return convertFileLockError(err) 270 } 271 // start RPC endpoints 272 err := n.startRPC() 273 if err != nil { 274 n.stopRPC() 275 n.server.Stop() 276 } 277 return err 278 } 279 280 // containsLifecycle checks if 'lfs' contains 'l'. 281 func containsLifecycle(lfs []Lifecycle, l Lifecycle) bool { 282 for _, obj := range lfs { 283 if obj == l { 284 return true 285 } 286 } 287 return false 288 } 289 290 // stopServices terminates running services, RPC and p2p networking. 291 // It is the inverse of Start. 292 func (n *Node) stopServices(running []Lifecycle) error { 293 n.stopRPC() 294 295 // Stop running lifecycles in reverse order. 296 failure := &StopError{Services: make(map[reflect.Type]error)} 297 for i := len(running) - 1; i >= 0; i-- { 298 if err := running[i].Stop(); err != nil { 299 failure.Services[reflect.TypeOf(running[i])] = err 300 } 301 } 302 303 // Stop p2p networking. 304 n.server.Stop() 305 306 if len(failure.Services) > 0 { 307 return failure 308 } 309 return nil 310 } 311 312 func (n *Node) openDataDir() error { 313 if n.config.DataDir == "" { 314 return nil // ephemeral 315 } 316 317 instdir := filepath.Join(n.config.DataDir, n.config.name()) 318 if err := os.MkdirAll(instdir, 0700); err != nil { 319 return err 320 } 321 // Lock the instance directory to prevent concurrent use by another instance as well as 322 // accidental use of the instance directory as a database. 323 release, _, err := fileutil.Flock(filepath.Join(instdir, "LOCK")) 324 if err != nil { 325 return convertFileLockError(err) 326 } 327 n.dirLock = release 328 return nil 329 } 330 331 func (n *Node) closeDataDir() { 332 // Release instance directory lock. 333 if n.dirLock != nil { 334 if err := n.dirLock.Release(); err != nil { 335 n.log.Error("Can't release datadir lock", "err", err) 336 } 337 n.dirLock = nil 338 } 339 } 340 341 // obtainJWTSecret loads the jwt-secret, either from the provided config, 342 // or from the default location. If neither of those are present, it generates 343 // a new secret and stores to the default location. 344 func (n *Node) obtainJWTSecret(cliParam string) ([]byte, error) { 345 fileName := cliParam 346 if len(fileName) == 0 { 347 // no path provided, use default 348 fileName = n.ResolvePath(datadirJWTKey) 349 } 350 // try reading from file 351 if data, err := os.ReadFile(fileName); err == nil { 352 jwtSecret := common.FromHex(strings.TrimSpace(string(data))) 353 if len(jwtSecret) == 32 { 354 log.Info("Loaded JWT secret file", "path", fileName, "crc32", fmt.Sprintf("%#x", crc32.ChecksumIEEE(jwtSecret))) 355 return jwtSecret, nil 356 } 357 log.Error("Invalid JWT secret", "path", fileName, "length", len(jwtSecret)) 358 return nil, errors.New("invalid JWT secret") 359 } 360 // Need to generate one 361 jwtSecret := make([]byte, 32) 362 crand.Read(jwtSecret) 363 // if we're in --dev mode, don't bother saving, just show it 364 if fileName == "" { 365 log.Info("Generated ephemeral JWT secret", "secret", hexutil.Encode(jwtSecret)) 366 return jwtSecret, nil 367 } 368 if err := os.WriteFile(fileName, []byte(hexutil.Encode(jwtSecret)), 0600); err != nil { 369 return nil, err 370 } 371 log.Info("Generated JWT secret", "path", fileName) 372 return jwtSecret, nil 373 } 374 375 // startRPC is a helper method to configure all the various RPC endpoints during node 376 // startup. It's not meant to be called at any time afterwards as it makes certain 377 // assumptions about the state of the node. 378 func (n *Node) startRPC() error { 379 if err := n.startInProc(); err != nil { 380 return err 381 } 382 383 // Configure IPC. 384 if n.ipc.endpoint != "" { 385 if err := n.ipc.start(n.rpcAPIs); err != nil { 386 return err 387 } 388 } 389 var ( 390 servers []*httpServer 391 openAPIs, allAPIs = n.getAPIs() 392 ) 393 394 initHttp := func(server *httpServer, port int) error { 395 if err := server.setListenAddr(n.config.HTTPHost, port); err != nil { 396 return err 397 } 398 if err := server.enableRPC(openAPIs, httpConfig{ 399 CorsAllowedOrigins: n.config.HTTPCors, 400 Vhosts: n.config.HTTPVirtualHosts, 401 Modules: n.config.HTTPModules, 402 prefix: n.config.HTTPPathPrefix, 403 }); err != nil { 404 return err 405 } 406 servers = append(servers, server) 407 return nil 408 } 409 410 initWS := func(port int) error { 411 server := n.wsServerForPort(port, false) 412 if err := server.setListenAddr(n.config.WSHost, port); err != nil { 413 return err 414 } 415 if err := server.enableWS(openAPIs, wsConfig{ 416 Modules: n.config.WSModules, 417 Origins: n.config.WSOrigins, 418 prefix: n.config.WSPathPrefix, 419 }); err != nil { 420 return err 421 } 422 servers = append(servers, server) 423 return nil 424 } 425 426 initAuth := func(port int, secret []byte) error { 427 // Enable auth via HTTP 428 server := n.httpAuth 429 if err := server.setListenAddr(n.config.AuthAddr, port); err != nil { 430 return err 431 } 432 if err := server.enableRPC(allAPIs, httpConfig{ 433 CorsAllowedOrigins: DefaultAuthCors, 434 Vhosts: n.config.AuthVirtualHosts, 435 Modules: DefaultAuthModules, 436 prefix: DefaultAuthPrefix, 437 jwtSecret: secret, 438 }); err != nil { 439 return err 440 } 441 servers = append(servers, server) 442 // Enable auth via WS 443 server = n.wsServerForPort(port, true) 444 if err := server.setListenAddr(n.config.AuthAddr, port); err != nil { 445 return err 446 } 447 if err := server.enableWS(allAPIs, wsConfig{ 448 Modules: DefaultAuthModules, 449 Origins: DefaultAuthOrigins, 450 prefix: DefaultAuthPrefix, 451 jwtSecret: secret, 452 }); err != nil { 453 return err 454 } 455 servers = append(servers, server) 456 return nil 457 } 458 459 // Set up HTTP. 460 if n.config.HTTPHost != "" { 461 // Configure legacy unauthenticated HTTP. 462 if err := initHttp(n.http, n.config.HTTPPort); err != nil { 463 return err 464 } 465 } 466 // Configure WebSocket. 467 if n.config.WSHost != "" { 468 // legacy unauthenticated 469 if err := initWS(n.config.WSPort); err != nil { 470 return err 471 } 472 } 473 // Configure authenticated API 474 if len(openAPIs) != len(allAPIs) { 475 jwtSecret, err := n.obtainJWTSecret(n.config.JWTSecret) 476 if err != nil { 477 return err 478 } 479 if err := initAuth(n.config.AuthPort, jwtSecret); err != nil { 480 return err 481 } 482 } 483 // Start the servers 484 for _, server := range servers { 485 if err := server.start(); err != nil { 486 return err 487 } 488 } 489 return nil 490 } 491 492 func (n *Node) wsServerForPort(port int, authenticated bool) *httpServer { 493 httpServer, wsServer := n.http, n.ws 494 if authenticated { 495 httpServer, wsServer = n.httpAuth, n.wsAuth 496 } 497 if n.config.HTTPHost == "" || httpServer.port == port { 498 return httpServer 499 } 500 return wsServer 501 } 502 503 func (n *Node) stopRPC() { 504 n.http.stop() 505 n.ws.stop() 506 n.httpAuth.stop() 507 n.wsAuth.stop() 508 n.ipc.stop() 509 n.stopInProc() 510 } 511 512 // startInProc registers all RPC APIs on the inproc server. 513 func (n *Node) startInProc() error { 514 for _, api := range n.rpcAPIs { 515 if err := n.inprocHandler.RegisterName(api.Namespace, api.Service); err != nil { 516 return err 517 } 518 } 519 return nil 520 } 521 522 // stopInProc terminates the in-process RPC endpoint. 523 func (n *Node) stopInProc() { 524 n.inprocHandler.Stop() 525 } 526 527 // Wait blocks until the node is closed. 528 func (n *Node) Wait() { 529 <-n.stop 530 } 531 532 // RegisterLifecycle registers the given Lifecycle on the node. 533 func (n *Node) RegisterLifecycle(lifecycle Lifecycle) { 534 n.lock.Lock() 535 defer n.lock.Unlock() 536 537 if n.state != initializingState { 538 panic("can't register lifecycle on running/stopped node") 539 } 540 if containsLifecycle(n.lifecycles, lifecycle) { 541 panic(fmt.Sprintf("attempt to register lifecycle %T more than once", lifecycle)) 542 } 543 n.lifecycles = append(n.lifecycles, lifecycle) 544 } 545 546 // RegisterProtocols adds backend's protocols to the node's p2p server. 547 func (n *Node) RegisterProtocols(protocols []p2p.Protocol) { 548 n.lock.Lock() 549 defer n.lock.Unlock() 550 551 if n.state != initializingState { 552 panic("can't register protocols on running/stopped node") 553 } 554 n.server.Protocols = append(n.server.Protocols, protocols...) 555 } 556 557 // RegisterAPIs registers the APIs a service provides on the node. 558 func (n *Node) RegisterAPIs(apis []rpc.API) { 559 n.lock.Lock() 560 defer n.lock.Unlock() 561 562 if n.state != initializingState { 563 panic("can't register APIs on running/stopped node") 564 } 565 n.rpcAPIs = append(n.rpcAPIs, apis...) 566 } 567 568 // getAPIs return two sets of APIs, both the ones that do not require 569 // authentication, and the complete set 570 func (n *Node) getAPIs() (unauthenticated, all []rpc.API) { 571 for _, api := range n.rpcAPIs { 572 if !api.Authenticated { 573 unauthenticated = append(unauthenticated, api) 574 } 575 } 576 return unauthenticated, n.rpcAPIs 577 } 578 579 // RegisterHandler mounts a handler on the given path on the canonical HTTP server. 580 // 581 // The name of the handler is shown in a log message when the HTTP server starts 582 // and should be a descriptive term for the service provided by the handler. 583 func (n *Node) RegisterHandler(name, path string, handler http.Handler) { 584 n.lock.Lock() 585 defer n.lock.Unlock() 586 587 if n.state != initializingState { 588 panic("can't register HTTP handler on running/stopped node") 589 } 590 591 n.http.mux.Handle(path, handler) 592 n.http.handlerNames[path] = name 593 } 594 595 // Attach creates an RPC client attached to an in-process API handler. 596 func (n *Node) Attach() (*rpc.Client, error) { 597 return rpc.DialInProc(n.inprocHandler), nil 598 } 599 600 // RPCHandler returns the in-process RPC request handler. 601 func (n *Node) RPCHandler() (*rpc.Server, error) { 602 n.lock.Lock() 603 defer n.lock.Unlock() 604 605 if n.state == closedState { 606 return nil, ErrNodeStopped 607 } 608 return n.inprocHandler, nil 609 } 610 611 // Config returns the configuration of node. 612 func (n *Node) Config() *Config { 613 return n.config 614 } 615 616 // Server retrieves the currently running P2P network layer. This method is meant 617 // only to inspect fields of the currently running server. Callers should not 618 // start or stop the returned server. 619 func (n *Node) Server() *p2p.Server { 620 n.lock.Lock() 621 defer n.lock.Unlock() 622 623 return n.server 624 } 625 626 // DataDir retrieves the current datadir used by the protocol stack. 627 // Deprecated: No files should be stored in this directory, use InstanceDir instead. 628 func (n *Node) DataDir() string { 629 return n.config.DataDir 630 } 631 632 // InstanceDir retrieves the instance directory used by the protocol stack. 633 func (n *Node) InstanceDir() string { 634 return n.config.instanceDir() 635 } 636 637 // KeyStoreDir retrieves the key directory 638 func (n *Node) KeyStoreDir() string { 639 return n.keyDir 640 } 641 642 // AccountManager retrieves the account manager used by the protocol stack. 643 func (n *Node) AccountManager() *accounts.Manager { 644 return n.accman 645 } 646 647 // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack. 648 func (n *Node) IPCEndpoint() string { 649 return n.ipc.endpoint 650 } 651 652 // HTTPEndpoint returns the URL of the HTTP server. Note that this URL does not 653 // contain the JSON-RPC path prefix set by HTTPPathPrefix. 654 func (n *Node) HTTPEndpoint() string { 655 return "http://" + n.http.listenAddr() 656 } 657 658 // WSEndpoint returns the current JSON-RPC over WebSocket endpoint. 659 func (n *Node) WSEndpoint() string { 660 if n.http.wsAllowed() { 661 return "ws://" + n.http.listenAddr() + n.http.wsConfig.prefix 662 } 663 return "ws://" + n.ws.listenAddr() + n.ws.wsConfig.prefix 664 } 665 666 // HTTPAuthEndpoint returns the URL of the authenticated HTTP server. 667 func (n *Node) HTTPAuthEndpoint() string { 668 return "http://" + n.httpAuth.listenAddr() 669 } 670 671 // WSAuthEndpoint returns the current authenticated JSON-RPC over WebSocket endpoint. 672 func (n *Node) WSAuthEndpoint() string { 673 if n.httpAuth.wsAllowed() { 674 return "ws://" + n.httpAuth.listenAddr() + n.httpAuth.wsConfig.prefix 675 } 676 return "ws://" + n.wsAuth.listenAddr() + n.wsAuth.wsConfig.prefix 677 } 678 679 // EventMux retrieves the event multiplexer used by all the network services in 680 // the current protocol stack. 681 func (n *Node) EventMux() *event.TypeMux { 682 return n.eventmux 683 } 684 685 // OpenDatabase opens an existing database with the given name (or creates one if no 686 // previous can be found) from within the node's instance directory. If the node is 687 // ephemeral, a memory database is returned. 688 func (n *Node) OpenDatabase(name string, cache, handles int, namespace string, readonly bool) (ethdb.Database, error) { 689 n.lock.Lock() 690 defer n.lock.Unlock() 691 if n.state == closedState { 692 return nil, ErrNodeStopped 693 } 694 695 var db ethdb.Database 696 var err error 697 if n.config.DataDir == "" { 698 db = rawdb.NewMemoryDatabase() 699 } else { 700 db, err = rawdb.NewLevelDBDatabase(n.ResolvePath(name), cache, handles, namespace, readonly) 701 } 702 703 if err == nil { 704 db = n.wrapDatabase(db) 705 } 706 return db, err 707 } 708 709 // OpenDatabaseWithFreezer opens an existing database with the given name (or 710 // creates one if no previous can be found) from within the node's data directory, 711 // also attaching a chain freezer to it that moves ancient chain data from the 712 // database to immutable append-only files. If the node is an ephemeral one, a 713 // memory database is returned. 714 func (n *Node) OpenDatabaseWithFreezer(name string, cache, handles int, ancient string, namespace string, readonly bool) (ethdb.Database, error) { 715 n.lock.Lock() 716 defer n.lock.Unlock() 717 if n.state == closedState { 718 return nil, ErrNodeStopped 719 } 720 721 var db ethdb.Database 722 var err error 723 if n.config.DataDir == "" { 724 db = rawdb.NewMemoryDatabase() 725 } else { 726 db, err = rawdb.NewLevelDBDatabaseWithFreezer(n.ResolvePath(name), cache, handles, n.ResolveAncient(name, ancient), namespace, readonly) 727 } 728 729 if err == nil { 730 db = n.wrapDatabase(db) 731 } 732 return db, err 733 } 734 735 // ResolvePath returns the absolute path of a resource in the instance directory. 736 func (n *Node) ResolvePath(x string) string { 737 return n.config.ResolvePath(x) 738 } 739 740 // ResolveAncient returns the absolute path of the root ancient directory. 741 func (n *Node) ResolveAncient(name string, ancient string) string { 742 switch { 743 case ancient == "": 744 ancient = filepath.Join(n.ResolvePath(name), "ancient") 745 case !filepath.IsAbs(ancient): 746 ancient = n.ResolvePath(ancient) 747 } 748 return ancient 749 } 750 751 // closeTrackingDB wraps the Close method of a database. When the database is closed by the 752 // service, the wrapper removes it from the node's database map. This ensures that Node 753 // won't auto-close the database if it is closed by the service that opened it. 754 type closeTrackingDB struct { 755 ethdb.Database 756 n *Node 757 } 758 759 func (db *closeTrackingDB) Close() error { 760 db.n.lock.Lock() 761 delete(db.n.databases, db) 762 db.n.lock.Unlock() 763 return db.Database.Close() 764 } 765 766 // wrapDatabase ensures the database will be auto-closed when Node is closed. 767 func (n *Node) wrapDatabase(db ethdb.Database) ethdb.Database { 768 wrapper := &closeTrackingDB{db, n} 769 n.databases[wrapper] = struct{}{} 770 return wrapper 771 } 772 773 // closeDatabases closes all open databases. 774 func (n *Node) closeDatabases() (errors []error) { 775 for db := range n.databases { 776 delete(n.databases, db) 777 if err := db.Database.Close(); err != nil { 778 errors = append(errors, err) 779 } 780 } 781 return errors 782 }