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