github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/eth/backend.go (about)

     1  // Copyright 2014 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 eth implements the Ethereum protocol.
    18  package eth
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"runtime"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/tacshi/go-ethereum/accounts"
    30  	"github.com/tacshi/go-ethereum/common"
    31  	"github.com/tacshi/go-ethereum/common/hexutil"
    32  	"github.com/tacshi/go-ethereum/consensus"
    33  	"github.com/tacshi/go-ethereum/consensus/beacon"
    34  	"github.com/tacshi/go-ethereum/consensus/clique"
    35  	"github.com/tacshi/go-ethereum/core"
    36  	"github.com/tacshi/go-ethereum/core/bloombits"
    37  	"github.com/tacshi/go-ethereum/core/rawdb"
    38  	"github.com/tacshi/go-ethereum/core/state/pruner"
    39  	"github.com/tacshi/go-ethereum/core/txpool"
    40  	"github.com/tacshi/go-ethereum/core/types"
    41  	"github.com/tacshi/go-ethereum/core/vm"
    42  	"github.com/tacshi/go-ethereum/eth/downloader"
    43  	"github.com/tacshi/go-ethereum/eth/ethconfig"
    44  	"github.com/tacshi/go-ethereum/eth/gasprice"
    45  	"github.com/tacshi/go-ethereum/eth/protocols/eth"
    46  	"github.com/tacshi/go-ethereum/eth/protocols/snap"
    47  	"github.com/tacshi/go-ethereum/ethdb"
    48  	"github.com/tacshi/go-ethereum/event"
    49  	"github.com/tacshi/go-ethereum/internal/ethapi"
    50  	"github.com/tacshi/go-ethereum/internal/shutdowncheck"
    51  	"github.com/tacshi/go-ethereum/log"
    52  	"github.com/tacshi/go-ethereum/miner"
    53  	"github.com/tacshi/go-ethereum/node"
    54  	"github.com/tacshi/go-ethereum/p2p"
    55  	"github.com/tacshi/go-ethereum/p2p/dnsdisc"
    56  	"github.com/tacshi/go-ethereum/p2p/enode"
    57  	"github.com/tacshi/go-ethereum/params"
    58  	"github.com/tacshi/go-ethereum/rlp"
    59  	"github.com/tacshi/go-ethereum/rpc"
    60  )
    61  
    62  // Config contains the configuration options of the ETH protocol.
    63  // Deprecated: use ethconfig.Config instead.
    64  type Config = ethconfig.Config
    65  
    66  // Ethereum implements the Ethereum full node service.
    67  type Ethereum struct {
    68  	config *ethconfig.Config
    69  
    70  	// Handlers
    71  	txPool             *txpool.TxPool
    72  	blockchain         *core.BlockChain
    73  	handler            *handler
    74  	ethDialCandidates  enode.Iterator
    75  	snapDialCandidates enode.Iterator
    76  	merger             *consensus.Merger
    77  
    78  	// DB interfaces
    79  	chainDb ethdb.Database // Block chain database
    80  
    81  	eventMux       *event.TypeMux
    82  	engine         consensus.Engine
    83  	accountManager *accounts.Manager
    84  
    85  	bloomRequests     chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
    86  	bloomIndexer      *core.ChainIndexer             // Bloom indexer operating during block imports
    87  	closeBloomHandler chan struct{}
    88  
    89  	APIBackend *EthAPIBackend
    90  
    91  	miner     *miner.Miner
    92  	gasPrice  *big.Int
    93  	etherbase common.Address
    94  
    95  	networkID     uint64
    96  	netRPCService *ethapi.NetAPI
    97  
    98  	p2pServer *p2p.Server
    99  
   100  	lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
   101  
   102  	shutdownTracker *shutdowncheck.ShutdownTracker // Tracks if and when the node has shutdown ungracefully
   103  }
   104  
   105  // New creates a new Ethereum object (including the
   106  // initialisation of the common Ethereum object)
   107  func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
   108  	// Ensure configuration values are compatible and sane
   109  	if config.SyncMode == downloader.LightSync {
   110  		return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
   111  	}
   112  	if !config.SyncMode.IsValid() {
   113  		return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
   114  	}
   115  	if config.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(common.Big0) <= 0 {
   116  		log.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", ethconfig.Defaults.Miner.GasPrice)
   117  		config.Miner.GasPrice = new(big.Int).Set(ethconfig.Defaults.Miner.GasPrice)
   118  	}
   119  	if config.NoPruning && config.TrieDirtyCache > 0 {
   120  		if config.SnapshotCache > 0 {
   121  			config.TrieCleanCache += config.TrieDirtyCache * 3 / 5
   122  			config.SnapshotCache += config.TrieDirtyCache * 2 / 5
   123  		} else {
   124  			config.TrieCleanCache += config.TrieDirtyCache
   125  		}
   126  		config.TrieDirtyCache = 0
   127  	}
   128  	log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*1024*1024, "dirty", common.StorageSize(config.TrieDirtyCache)*1024*1024)
   129  
   130  	// Assemble the Ethereum object
   131  	chainDb, err := stack.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/", false)
   132  	if err != nil {
   133  		return nil, err
   134  	}
   135  	if err := pruner.RecoverPruning(stack.ResolvePath(""), chainDb, stack.ResolvePath(config.TrieCleanCacheJournal)); err != nil {
   136  		log.Error("Failed to recover state", "error", err)
   137  	}
   138  	// Transfer mining-related config to the ethash config.
   139  	ethashConfig := config.Ethash
   140  	ethashConfig.NotifyFull = config.Miner.NotifyFull
   141  	cliqueConfig, err := core.LoadCliqueConfig(chainDb, config.Genesis)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  	engine := ethconfig.CreateConsensusEngine(stack, &ethashConfig, cliqueConfig, config.Miner.Notify, config.Miner.Noverify, chainDb)
   146  
   147  	eth := &Ethereum{
   148  		config:            config,
   149  		merger:            consensus.NewMerger(chainDb),
   150  		chainDb:           chainDb,
   151  		eventMux:          stack.EventMux(),
   152  		accountManager:    stack.AccountManager(),
   153  		engine:            engine,
   154  		closeBloomHandler: make(chan struct{}),
   155  		networkID:         config.NetworkId,
   156  		gasPrice:          config.Miner.GasPrice,
   157  		etherbase:         config.Miner.Etherbase,
   158  		bloomRequests:     make(chan chan *bloombits.Retrieval),
   159  		bloomIndexer:      core.NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
   160  		p2pServer:         stack.Server(),
   161  		shutdownTracker:   shutdowncheck.NewShutdownTracker(chainDb),
   162  	}
   163  
   164  	bcVersion := rawdb.ReadDatabaseVersion(chainDb)
   165  	var dbVer = "<nil>"
   166  	if bcVersion != nil {
   167  		dbVer = fmt.Sprintf("%d", *bcVersion)
   168  	}
   169  	log.Info("Initialising Ethereum protocol", "network", config.NetworkId, "dbversion", dbVer)
   170  
   171  	if !config.SkipBcVersionCheck {
   172  		if bcVersion != nil && *bcVersion > core.BlockChainVersion {
   173  			return nil, fmt.Errorf("database version is v%d, Geth %s only supports v%d", *bcVersion, params.VersionWithMeta, core.BlockChainVersion)
   174  		} else if bcVersion == nil || *bcVersion < core.BlockChainVersion {
   175  			if bcVersion != nil { // only print warning on upgrade, not on init
   176  				log.Warn("Upgrade blockchain database version", "from", dbVer, "to", core.BlockChainVersion)
   177  			}
   178  			rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
   179  		}
   180  	}
   181  	var (
   182  		vmConfig = vm.Config{
   183  			EnablePreimageRecording: config.EnablePreimageRecording,
   184  		}
   185  		cacheConfig = &core.CacheConfig{
   186  
   187  			// Arbitrum
   188  			TriesInMemory: 128,
   189  			TrieRetention: 30 * time.Minute,
   190  
   191  			TrieCleanLimit:      config.TrieCleanCache,
   192  			TrieCleanJournal:    stack.ResolvePath(config.TrieCleanCacheJournal),
   193  			TrieCleanRejournal:  config.TrieCleanCacheRejournal,
   194  			TrieCleanNoPrefetch: config.NoPrefetch,
   195  			TrieDirtyLimit:      config.TrieDirtyCache,
   196  			TrieDirtyDisabled:   config.NoPruning,
   197  			TrieTimeLimit:       config.TrieTimeout,
   198  			SnapshotLimit:       config.SnapshotCache,
   199  			Preimages:           config.Preimages,
   200  		}
   201  	)
   202  	// Override the chain config with provided settings.
   203  	var overrides core.ChainOverrides
   204  	if config.OverrideShanghai != nil {
   205  		overrides.OverrideShanghai = config.OverrideShanghai
   206  	}
   207  	eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, nil, config.Genesis, &overrides, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit)
   208  	if err != nil {
   209  		return nil, err
   210  	}
   211  	eth.bloomIndexer.Start(eth.blockchain)
   212  
   213  	if config.TxPool.Journal != "" {
   214  		config.TxPool.Journal = stack.ResolvePath(config.TxPool.Journal)
   215  	}
   216  	eth.txPool = txpool.NewTxPool(config.TxPool, eth.blockchain.Config(), eth.blockchain)
   217  
   218  	// Permit the downloader to use the trie cache allowance during fast sync
   219  	cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit + cacheConfig.SnapshotLimit
   220  	checkpoint := config.Checkpoint
   221  	if checkpoint == nil {
   222  		checkpoint = params.TrustedCheckpoints[eth.blockchain.Genesis().Hash()]
   223  	}
   224  	if eth.handler, err = newHandler(&handlerConfig{
   225  		Database:       chainDb,
   226  		Chain:          eth.blockchain,
   227  		TxPool:         eth.txPool,
   228  		Merger:         eth.merger,
   229  		Network:        config.NetworkId,
   230  		Sync:           config.SyncMode,
   231  		BloomCache:     uint64(cacheLimit),
   232  		EventMux:       eth.eventMux,
   233  		Checkpoint:     checkpoint,
   234  		RequiredBlocks: config.RequiredBlocks,
   235  	}); err != nil {
   236  		return nil, err
   237  	}
   238  
   239  	eth.miner = miner.New(eth, &config.Miner, eth.blockchain.Config(), eth.EventMux(), eth.engine, eth.isLocalBlock)
   240  	eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
   241  
   242  	eth.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, eth, nil}
   243  	if eth.APIBackend.allowUnprotectedTxs {
   244  		log.Info("Unprotected transactions allowed")
   245  	}
   246  	gpoParams := config.GPO
   247  	if gpoParams.Default == nil {
   248  		gpoParams.Default = config.Miner.GasPrice
   249  	}
   250  	eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
   251  
   252  	// Setup DNS discovery iterators.
   253  	dnsclient := dnsdisc.NewClient(dnsdisc.Config{})
   254  	eth.ethDialCandidates, err = dnsclient.NewIterator(eth.config.EthDiscoveryURLs...)
   255  	if err != nil {
   256  		return nil, err
   257  	}
   258  	eth.snapDialCandidates, err = dnsclient.NewIterator(eth.config.SnapDiscoveryURLs...)
   259  	if err != nil {
   260  		return nil, err
   261  	}
   262  
   263  	// Start the RPC service
   264  	eth.netRPCService = ethapi.NewNetAPI(eth.p2pServer, config.NetworkId)
   265  
   266  	// Register the backend on the node
   267  	stack.RegisterAPIs(eth.APIs())
   268  	stack.RegisterProtocols(eth.Protocols())
   269  	stack.RegisterLifecycle(eth)
   270  
   271  	// Successful startup; push a marker and check previous unclean shutdowns.
   272  	eth.shutdownTracker.MarkStartup()
   273  
   274  	return eth, nil
   275  }
   276  
   277  func makeExtraData(extra []byte) []byte {
   278  	if len(extra) == 0 {
   279  		// create default extradata
   280  		extra, _ = rlp.EncodeToBytes([]interface{}{
   281  			uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
   282  			"geth",
   283  			runtime.Version(),
   284  			runtime.GOOS,
   285  		})
   286  	}
   287  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   288  		log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
   289  		extra = nil
   290  	}
   291  	return extra
   292  }
   293  
   294  // APIs return the collection of RPC services the ethereum package offers.
   295  // NOTE, some of these services probably need to be moved to somewhere else.
   296  func (s *Ethereum) APIs() []rpc.API {
   297  	apis := ethapi.GetAPIs(s.APIBackend)
   298  
   299  	// Append any APIs exposed explicitly by the consensus engine
   300  	apis = append(apis, s.engine.APIs(s.BlockChain())...)
   301  
   302  	// Append all the local APIs and return
   303  	return append(apis, []rpc.API{
   304  		{
   305  			Namespace: "eth",
   306  			Service:   NewEthereumAPI(s),
   307  		}, {
   308  			Namespace: "miner",
   309  			Service:   NewMinerAPI(s),
   310  		}, {
   311  			Namespace: "eth",
   312  			Service:   downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux),
   313  		}, {
   314  			Namespace: "admin",
   315  			Service:   NewAdminAPI(s),
   316  		}, {
   317  			Namespace: "debug",
   318  			Service:   NewDebugAPI(s),
   319  		}, {
   320  			Namespace: "net",
   321  			Service:   s.netRPCService,
   322  		},
   323  	}...)
   324  }
   325  
   326  func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
   327  	s.blockchain.ResetWithGenesisBlock(gb)
   328  }
   329  
   330  func (s *Ethereum) Etherbase() (eb common.Address, err error) {
   331  	s.lock.RLock()
   332  	etherbase := s.etherbase
   333  	s.lock.RUnlock()
   334  
   335  	if etherbase != (common.Address{}) {
   336  		return etherbase, nil
   337  	}
   338  	return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
   339  }
   340  
   341  // isLocalBlock checks whether the specified block is mined
   342  // by local miner accounts.
   343  //
   344  // We regard two types of accounts as local miner account: etherbase
   345  // and accounts specified via `txpool.locals` flag.
   346  func (s *Ethereum) isLocalBlock(header *types.Header) bool {
   347  	author, err := s.engine.Author(header)
   348  	if err != nil {
   349  		log.Warn("Failed to retrieve block author", "number", header.Number.Uint64(), "hash", header.Hash(), "err", err)
   350  		return false
   351  	}
   352  	// Check whether the given address is etherbase.
   353  	s.lock.RLock()
   354  	etherbase := s.etherbase
   355  	s.lock.RUnlock()
   356  	if author == etherbase {
   357  		return true
   358  	}
   359  	// Check whether the given address is specified by `txpool.local`
   360  	// CLI flag.
   361  	for _, account := range s.config.TxPool.Locals {
   362  		if account == author {
   363  			return true
   364  		}
   365  	}
   366  	return false
   367  }
   368  
   369  // shouldPreserve checks whether we should preserve the given block
   370  // during the chain reorg depending on whether the author of block
   371  // is a local account.
   372  func (s *Ethereum) shouldPreserve(header *types.Header) bool {
   373  	// The reason we need to disable the self-reorg preserving for clique
   374  	// is it can be probable to introduce a deadlock.
   375  	//
   376  	// e.g. If there are 7 available signers
   377  	//
   378  	// r1   A
   379  	// r2     B
   380  	// r3       C
   381  	// r4         D
   382  	// r5   A      [X] F G
   383  	// r6    [X]
   384  	//
   385  	// In the round5, the inturn signer E is offline, so the worst case
   386  	// is A, F and G sign the block of round5 and reject the block of opponents
   387  	// and in the round6, the last available signer B is offline, the whole
   388  	// network is stuck.
   389  	if _, ok := s.engine.(*clique.Clique); ok {
   390  		return false
   391  	}
   392  	return s.isLocalBlock(header)
   393  }
   394  
   395  // SetEtherbase sets the mining reward address.
   396  func (s *Ethereum) SetEtherbase(etherbase common.Address) {
   397  	s.lock.Lock()
   398  	s.etherbase = etherbase
   399  	s.lock.Unlock()
   400  
   401  	s.miner.SetEtherbase(etherbase)
   402  }
   403  
   404  // StartMining starts the miner with the given number of CPU threads. If mining
   405  // is already running, this method adjust the number of threads allowed to use
   406  // and updates the minimum price required by the transaction pool.
   407  func (s *Ethereum) StartMining(threads int) error {
   408  	// Update the thread count within the consensus engine
   409  	type threaded interface {
   410  		SetThreads(threads int)
   411  	}
   412  	if th, ok := s.engine.(threaded); ok {
   413  		log.Info("Updated mining threads", "threads", threads)
   414  		if threads == 0 {
   415  			threads = -1 // Disable the miner from within
   416  		}
   417  		th.SetThreads(threads)
   418  	}
   419  	// If the miner was not running, initialize it
   420  	if !s.IsMining() {
   421  		// Propagate the initial price point to the transaction pool
   422  		s.lock.RLock()
   423  		price := s.gasPrice
   424  		s.lock.RUnlock()
   425  		s.txPool.SetGasPrice(price)
   426  
   427  		// Configure the local mining address
   428  		eb, err := s.Etherbase()
   429  		if err != nil {
   430  			log.Error("Cannot start mining without etherbase", "err", err)
   431  			return fmt.Errorf("etherbase missing: %v", err)
   432  		}
   433  		var cli *clique.Clique
   434  		if c, ok := s.engine.(*clique.Clique); ok {
   435  			cli = c
   436  		} else if cl, ok := s.engine.(*beacon.Beacon); ok {
   437  			if c, ok := cl.InnerEngine().(*clique.Clique); ok {
   438  				cli = c
   439  			}
   440  		}
   441  		if cli != nil {
   442  			wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
   443  			if wallet == nil || err != nil {
   444  				log.Error("Etherbase account unavailable locally", "err", err)
   445  				return fmt.Errorf("signer missing: %v", err)
   446  			}
   447  			cli.Authorize(eb, wallet.SignData)
   448  		}
   449  		// If mining is started, we can disable the transaction rejection mechanism
   450  		// introduced to speed sync times.
   451  		atomic.StoreUint32(&s.handler.acceptTxs, 1)
   452  
   453  		go s.miner.Start()
   454  	}
   455  	return nil
   456  }
   457  
   458  // StopMining terminates the miner, both at the consensus engine level as well as
   459  // at the block creation level.
   460  func (s *Ethereum) StopMining() {
   461  	// Update the thread count within the consensus engine
   462  	type threaded interface {
   463  		SetThreads(threads int)
   464  	}
   465  	if th, ok := s.engine.(threaded); ok {
   466  		th.SetThreads(-1)
   467  	}
   468  	// Stop the block creating itself
   469  	s.miner.Stop()
   470  }
   471  
   472  func (s *Ethereum) IsMining() bool      { return s.miner.Mining() }
   473  func (s *Ethereum) Miner() *miner.Miner { return s.miner }
   474  
   475  func (s *Ethereum) AccountManager() *accounts.Manager  { return s.accountManager }
   476  func (s *Ethereum) BlockChain() *core.BlockChain       { return s.blockchain }
   477  func (s *Ethereum) TxPool() *txpool.TxPool             { return s.txPool }
   478  func (s *Ethereum) EventMux() *event.TypeMux           { return s.eventMux }
   479  func (s *Ethereum) Engine() consensus.Engine           { return s.engine }
   480  func (s *Ethereum) ChainDb() ethdb.Database            { return s.chainDb }
   481  func (s *Ethereum) IsListening() bool                  { return true } // Always listening
   482  func (s *Ethereum) Downloader() *downloader.Downloader { return s.handler.downloader }
   483  func (s *Ethereum) Synced() bool                       { return atomic.LoadUint32(&s.handler.acceptTxs) == 1 }
   484  func (s *Ethereum) SetSynced()                         { atomic.StoreUint32(&s.handler.acceptTxs, 1) }
   485  func (s *Ethereum) ArchiveMode() bool                  { return s.config.NoPruning }
   486  func (s *Ethereum) BloomIndexer() *core.ChainIndexer   { return s.bloomIndexer }
   487  func (s *Ethereum) Merger() *consensus.Merger          { return s.merger }
   488  func (s *Ethereum) SyncMode() downloader.SyncMode {
   489  	mode, _ := s.handler.chainSync.modeAndLocalHead()
   490  	return mode
   491  }
   492  
   493  // Protocols returns all the currently configured
   494  // network protocols to start.
   495  func (s *Ethereum) Protocols() []p2p.Protocol {
   496  	protos := eth.MakeProtocols((*ethHandler)(s.handler), s.networkID, s.ethDialCandidates)
   497  	if s.config.SnapshotCache > 0 {
   498  		protos = append(protos, snap.MakeProtocols((*snapHandler)(s.handler), s.snapDialCandidates)...)
   499  	}
   500  	return protos
   501  }
   502  
   503  // Start implements node.Lifecycle, starting all internal goroutines needed by the
   504  // Ethereum protocol implementation.
   505  func (s *Ethereum) Start() error {
   506  	eth.StartENRUpdater(s.blockchain, s.p2pServer.LocalNode())
   507  
   508  	// Start the bloom bits servicing goroutines
   509  	s.startBloomHandlers(params.BloomBitsBlocks)
   510  
   511  	// Regularly update shutdown marker
   512  	s.shutdownTracker.Start()
   513  
   514  	// Figure out a max peers count based on the server limits
   515  	maxPeers := s.p2pServer.MaxPeers
   516  	if s.config.LightServ > 0 {
   517  		if s.config.LightPeers >= s.p2pServer.MaxPeers {
   518  			return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, s.p2pServer.MaxPeers)
   519  		}
   520  		maxPeers -= s.config.LightPeers
   521  	}
   522  	// Start the networking layer and the light server if requested
   523  	s.handler.Start(maxPeers)
   524  	return nil
   525  }
   526  
   527  // Stop implements node.Lifecycle, terminating all internal goroutines used by the
   528  // Ethereum protocol.
   529  func (s *Ethereum) Stop() error {
   530  	// Stop all the peer-related stuff first.
   531  	s.ethDialCandidates.Close()
   532  	s.snapDialCandidates.Close()
   533  	s.handler.Stop()
   534  
   535  	// Then stop everything else.
   536  	s.bloomIndexer.Close()
   537  	close(s.closeBloomHandler)
   538  	s.txPool.Stop()
   539  	s.miner.Close()
   540  	s.blockchain.Stop()
   541  	s.engine.Close()
   542  
   543  	// Clean shutdown marker as the last thing before closing db
   544  	s.shutdownTracker.Stop()
   545  
   546  	s.chainDb.Close()
   547  	s.eventMux.Stop()
   548  
   549  	return nil
   550  }