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