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