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