gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/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  
    28  	"github.com/ethereum/go-ethereum/accounts"
    29  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    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/clique"
    34  	"github.com/ethereum/go-ethereum/consensus/ethash"
    35  	"github.com/ethereum/go-ethereum/consensus/parlia"
    36  	"github.com/ethereum/go-ethereum/core"
    37  	"github.com/ethereum/go-ethereum/core/bloombits"
    38  	"github.com/ethereum/go-ethereum/core/rawdb"
    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/filters"
    43  	"github.com/ethereum/go-ethereum/eth/gasprice"
    44  	"github.com/ethereum/go-ethereum/ethdb"
    45  	"github.com/ethereum/go-ethereum/event"
    46  	"github.com/ethereum/go-ethereum/internal/ethapi"
    47  	"github.com/ethereum/go-ethereum/log"
    48  	"github.com/ethereum/go-ethereum/miner"
    49  	"github.com/ethereum/go-ethereum/node"
    50  	"github.com/ethereum/go-ethereum/p2p"
    51  	"github.com/ethereum/go-ethereum/p2p/enode"
    52  	"github.com/ethereum/go-ethereum/p2p/enr"
    53  	"github.com/ethereum/go-ethereum/params"
    54  	"github.com/ethereum/go-ethereum/rlp"
    55  	"github.com/ethereum/go-ethereum/rpc"
    56  )
    57  
    58  type LesServer interface {
    59  	Start(srvr *p2p.Server)
    60  	Stop()
    61  	APIs() []rpc.API
    62  	Protocols() []p2p.Protocol
    63  	SetBloomBitsIndexer(bbIndexer *core.ChainIndexer)
    64  	SetContractBackend(bind.ContractBackend)
    65  }
    66  
    67  // Ethereum implements the Ethereum full node service.
    68  type Ethereum struct {
    69  	config *Config
    70  
    71  	// Handlers
    72  	txPool          *core.TxPool
    73  	blockchain      *core.BlockChain
    74  	protocolManager *ProtocolManager
    75  	lesServer       LesServer
    76  	dialCandiates   enode.Iterator
    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  	lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
    99  }
   100  
   101  func (s *Ethereum) AddLesServer(ls LesServer) {
   102  	s.lesServer = ls
   103  	ls.SetBloomBitsIndexer(s.bloomIndexer)
   104  }
   105  
   106  // SetClient sets a rpc client which connecting to our local node.
   107  func (s *Ethereum) SetContractBackend(backend bind.ContractBackend) {
   108  	// Pass the rpc client to les server if it is enabled.
   109  	if s.lesServer != nil {
   110  		s.lesServer.SetContractBackend(backend)
   111  	}
   112  }
   113  
   114  // New creates a new Ethereum object (including the
   115  // initialisation of the common Ethereum object)
   116  func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
   117  	// Ensure configuration values are compatible and sane
   118  	if config.SyncMode == downloader.LightSync {
   119  		return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
   120  	}
   121  	if !config.SyncMode.IsValid() {
   122  		return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
   123  	}
   124  	if config.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(common.Big0) <= 0 {
   125  		log.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", DefaultConfig.Miner.GasPrice)
   126  		config.Miner.GasPrice = new(big.Int).Set(DefaultConfig.Miner.GasPrice)
   127  	}
   128  	if config.NoPruning && config.TrieDirtyCache > 0 {
   129  		config.TrieCleanCache += config.TrieDirtyCache * 3 / 5
   130  		config.SnapshotCache += config.TrieDirtyCache * 3 / 5
   131  		config.TrieDirtyCache = 0
   132  	}
   133  	log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*1024*1024, "dirty", common.StorageSize(config.TrieDirtyCache)*1024*1024)
   134  
   135  	// Assemble the Ethereum object
   136  	chainDb, err := ctx.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/")
   137  	if err != nil {
   138  		return nil, err
   139  	}
   140  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.OverrideIstanbul, config.OverrideMuirGlacier)
   141  	if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
   142  		return nil, genesisErr
   143  	}
   144  	log.Info("Initialised chain configuration", "config", chainConfig)
   145  
   146  	eth := &Ethereum{
   147  		config:            config,
   148  		chainDb:           chainDb,
   149  		eventMux:          ctx.EventMux,
   150  		accountManager:    ctx.AccountManager,
   151  		closeBloomHandler: make(chan struct{}),
   152  		networkID:         config.NetworkId,
   153  		gasPrice:          config.Miner.GasPrice,
   154  		etherbase:         config.Miner.Etherbase,
   155  		bloomRequests:     make(chan chan *bloombits.Retrieval),
   156  		bloomIndexer:      NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
   157  	}
   158  
   159  	eth.APIBackend = &EthAPIBackend{ctx.ExtRPCEnabled(), eth, nil}
   160  	ethAPI := ethapi.NewPublicBlockChainAPI(eth.APIBackend)
   161  	eth.engine = CreateConsensusEngine(ctx, chainConfig, &config.Ethash, config.Miner.Notify, config.Miner.Noverify, chainDb, ethAPI, genesisHash)
   162  
   163  	bcVersion := rawdb.ReadDatabaseVersion(chainDb)
   164  	var dbVer = "<nil>"
   165  	if bcVersion != nil {
   166  		dbVer = fmt.Sprintf("%d", *bcVersion)
   167  	}
   168  	log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId, "dbversion", dbVer)
   169  
   170  	if !config.SkipBcVersionCheck {
   171  		if bcVersion != nil && *bcVersion > core.BlockChainVersion {
   172  			return nil, fmt.Errorf("database version is v%d, Geth %s only supports v%d", *bcVersion, params.VersionWithMeta, core.BlockChainVersion)
   173  		} else if bcVersion == nil || *bcVersion < core.BlockChainVersion {
   174  			log.Warn("Upgrade blockchain database version", "from", dbVer, "to", core.BlockChainVersion)
   175  			rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
   176  		}
   177  	}
   178  	var (
   179  		vmConfig = vm.Config{
   180  			EnablePreimageRecording: config.EnablePreimageRecording,
   181  			EWASMInterpreter:        config.EWASMInterpreter,
   182  			EVMInterpreter:          config.EVMInterpreter,
   183  		}
   184  		cacheConfig = &core.CacheConfig{
   185  			TrieCleanLimit:      config.TrieCleanCache,
   186  			TrieCleanNoPrefetch: config.NoPrefetch,
   187  			TrieDirtyLimit:      config.TrieDirtyCache,
   188  			TrieDirtyDisabled:   config.NoPruning,
   189  			TrieTimeLimit:       config.TrieTimeout,
   190  			SnapshotLimit:       config.SnapshotCache,
   191  		}
   192  	)
   193  	eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, chainConfig, eth.engine, vmConfig, eth.shouldPreserve)
   194  	if err != nil {
   195  		return nil, err
   196  	}
   197  	// Rewind the chain in case of an incompatible config upgrade.
   198  	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
   199  		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
   200  		eth.blockchain.SetHead(compat.RewindTo)
   201  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   202  	}
   203  	eth.bloomIndexer.Start(eth.blockchain)
   204  
   205  	if config.TxPool.Journal != "" {
   206  		config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
   207  	}
   208  	eth.txPool = core.NewTxPool(config.TxPool, chainConfig, eth.blockchain)
   209  
   210  	// Permit the downloader to use the trie cache allowance during fast sync
   211  	cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit + cacheConfig.SnapshotLimit
   212  	checkpoint := config.Checkpoint
   213  	if checkpoint == nil {
   214  		checkpoint = params.TrustedCheckpoints[genesisHash]
   215  	}
   216  	if eth.protocolManager, err = NewProtocolManager(chainConfig, checkpoint, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist, config.DirectBroadcast); err != nil {
   217  		return nil, err
   218  	}
   219  
   220  	eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock)
   221  	eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
   222  	gpoParams := config.GPO
   223  	if gpoParams.Default == nil {
   224  		gpoParams.Default = config.Miner.GasPrice
   225  	}
   226  	eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
   227  
   228  	eth.dialCandiates, err = eth.setupDiscovery(&ctx.Config.P2P)
   229  	if err != nil {
   230  		return nil, err
   231  	}
   232  
   233  	return eth, nil
   234  }
   235  
   236  func makeExtraData(extra []byte) []byte {
   237  	if len(extra) == 0 {
   238  		// create default extradata
   239  		extra, _ = rlp.EncodeToBytes([]interface{}{
   240  			uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
   241  			"geth",
   242  			runtime.Version(),
   243  			runtime.GOOS,
   244  		})
   245  	}
   246  	if uint64(len(extra)) > params.MaximumExtraDataSize-params.ForkIDSize {
   247  		log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize-params.ForkIDSize)
   248  		extra = nil
   249  	}
   250  	return extra
   251  }
   252  
   253  // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
   254  func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, noverify bool, db ethdb.Database, ee *ethapi.PublicBlockChainAPI, genesisHash common.Hash) consensus.Engine {
   255  	makeEthash := func() *ethash.Ethash {
   256  		engine := ethash.New(ethash.Config{
   257  			CacheDir:         ctx.ResolvePath(config.CacheDir),
   258  			CachesInMem:      config.CachesInMem,
   259  			CachesOnDisk:     config.CachesOnDisk,
   260  			CachesLockMmap:   config.CachesLockMmap,
   261  			DatasetDir:       config.DatasetDir,
   262  			DatasetsInMem:    config.DatasetsInMem,
   263  			DatasetsOnDisk:   config.DatasetsOnDisk,
   264  			DatasetsLockMmap: config.DatasetsLockMmap,
   265  		}, notify, noverify)
   266  		engine.SetThreads(-1) // Disable CPU mining
   267  		return engine
   268  	}
   269  
   270  	// If proof-of-authority is requested, set it up
   271  	if chainConfig.Clique != nil {
   272  		return clique.New(chainConfig.Clique, db)
   273  	}
   274  	if chainConfig.Parlia != nil {
   275  		return parlia.New(chainConfig, db, ee, genesisHash, makeEthash)
   276  	}
   277  	// Otherwise assume proof-of-work
   278  	switch config.PowMode {
   279  	case ethash.ModeFake:
   280  		log.Warn("Ethash used in fake mode")
   281  		return ethash.NewFaker()
   282  	case ethash.ModeTest:
   283  		log.Warn("Ethash used in test mode")
   284  		return ethash.NewTester(nil, noverify)
   285  	case ethash.ModeShared:
   286  		log.Warn("Ethash used in shared mode")
   287  		return ethash.NewShared()
   288  	default:
   289  		return makeEthash()
   290  	}
   291  }
   292  
   293  // APIs return the collection of RPC services the ethereum package offers.
   294  // NOTE, some of these services probably need to be moved to somewhere else.
   295  func (s *Ethereum) APIs() []rpc.API {
   296  	apis := ethapi.GetAPIs(s.APIBackend)
   297  
   298  	// Append any APIs exposed explicitly by the les server
   299  	if s.lesServer != nil {
   300  		apis = append(apis, s.lesServer.APIs()...)
   301  	}
   302  	// Append any APIs exposed explicitly by the consensus engine
   303  	apis = append(apis, s.engine.APIs(s.BlockChain())...)
   304  
   305  	// Append any APIs exposed explicitly by the les server
   306  	if s.lesServer != nil {
   307  		apis = append(apis, s.lesServer.APIs()...)
   308  	}
   309  
   310  	// Append all the local APIs and return
   311  	return append(apis, []rpc.API{
   312  		{
   313  			Namespace: "eth",
   314  			Version:   "1.0",
   315  			Service:   NewPublicEthereumAPI(s),
   316  			Public:    true,
   317  		}, {
   318  			Namespace: "eth",
   319  			Version:   "1.0",
   320  			Service:   NewPublicMinerAPI(s),
   321  			Public:    true,
   322  		}, {
   323  			Namespace: "eth",
   324  			Version:   "1.0",
   325  			Service:   downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
   326  			Public:    true,
   327  		}, {
   328  			Namespace: "miner",
   329  			Version:   "1.0",
   330  			Service:   NewPrivateMinerAPI(s),
   331  			Public:    false,
   332  		}, {
   333  			Namespace: "eth",
   334  			Version:   "1.0",
   335  			Service:   filters.NewPublicFilterAPI(s.APIBackend, false, s.config.RangeLimit),
   336  			Public:    true,
   337  		}, {
   338  			Namespace: "admin",
   339  			Version:   "1.0",
   340  			Service:   NewPrivateAdminAPI(s),
   341  		}, {
   342  			Namespace: "debug",
   343  			Version:   "1.0",
   344  			Service:   NewPublicDebugAPI(s),
   345  			Public:    true,
   346  		}, {
   347  			Namespace: "debug",
   348  			Version:   "1.0",
   349  			Service:   NewPrivateDebugAPI(s),
   350  		}, {
   351  			Namespace: "net",
   352  			Version:   "1.0",
   353  			Service:   s.netRPCService,
   354  			Public:    true,
   355  		},
   356  	}...)
   357  }
   358  
   359  func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
   360  	s.blockchain.ResetWithGenesisBlock(gb)
   361  }
   362  
   363  func (s *Ethereum) Etherbase() (eb common.Address, err error) {
   364  	s.lock.RLock()
   365  	etherbase := s.etherbase
   366  	s.lock.RUnlock()
   367  
   368  	if etherbase != (common.Address{}) {
   369  		return etherbase, nil
   370  	}
   371  	if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
   372  		if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   373  			etherbase := accounts[0].Address
   374  
   375  			s.lock.Lock()
   376  			s.etherbase = etherbase
   377  			s.lock.Unlock()
   378  
   379  			log.Info("Etherbase automatically configured", "address", etherbase)
   380  			return etherbase, nil
   381  		}
   382  	}
   383  	return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
   384  }
   385  
   386  // isLocalBlock checks whether the specified block is mined
   387  // by local miner accounts.
   388  //
   389  // We regard two types of accounts as local miner account: etherbase
   390  // and accounts specified via `txpool.locals` flag.
   391  func (s *Ethereum) isLocalBlock(block *types.Block) bool {
   392  	author, err := s.engine.Author(block.Header())
   393  	if err != nil {
   394  		log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err)
   395  		return false
   396  	}
   397  	// Check whether the given address is etherbase.
   398  	s.lock.RLock()
   399  	etherbase := s.etherbase
   400  	s.lock.RUnlock()
   401  	if author == etherbase {
   402  		return true
   403  	}
   404  	// Check whether the given address is specified by `txpool.local`
   405  	// CLI flag.
   406  	for _, account := range s.config.TxPool.Locals {
   407  		if account == author {
   408  			return true
   409  		}
   410  	}
   411  	return false
   412  }
   413  
   414  // shouldPreserve checks whether we should preserve the given block
   415  // during the chain reorg depending on whether the author of block
   416  // is a local account.
   417  func (s *Ethereum) shouldPreserve(block *types.Block) bool {
   418  	// The reason we need to disable the self-reorg preserving for clique
   419  	// is it can be probable to introduce a deadlock.
   420  	//
   421  	// e.g. If there are 7 available signers
   422  	//
   423  	// r1   A
   424  	// r2     B
   425  	// r3       C
   426  	// r4         D
   427  	// r5   A      [X] F G
   428  	// r6    [X]
   429  	//
   430  	// In the round5, the inturn signer E is offline, so the worst case
   431  	// is A, F and G sign the block of round5 and reject the block of opponents
   432  	// and in the round6, the last available signer B is offline, the whole
   433  	// network is stuck.
   434  	if _, ok := s.engine.(*clique.Clique); ok {
   435  		return false
   436  	}
   437  	if _, ok := s.engine.(*parlia.Parlia); ok {
   438  		return false
   439  	}
   440  	return s.isLocalBlock(block)
   441  }
   442  
   443  // SetEtherbase sets the mining reward address.
   444  func (s *Ethereum) SetEtherbase(etherbase common.Address) {
   445  	s.lock.Lock()
   446  	s.etherbase = etherbase
   447  	s.lock.Unlock()
   448  
   449  	s.miner.SetEtherbase(etherbase)
   450  }
   451  
   452  // StartMining starts the miner with the given number of CPU threads. If mining
   453  // is already running, this method adjust the number of threads allowed to use
   454  // and updates the minimum price required by the transaction pool.
   455  func (s *Ethereum) StartMining(threads int) error {
   456  	// Update the thread count within the consensus engine
   457  	type threaded interface {
   458  		SetThreads(threads int)
   459  	}
   460  	if th, ok := s.engine.(threaded); ok {
   461  		log.Info("Updated mining threads", "threads", threads)
   462  		if threads == 0 {
   463  			threads = -1 // Disable the miner from within
   464  		}
   465  		th.SetThreads(threads)
   466  	}
   467  	// If the miner was not running, initialize it
   468  	if !s.IsMining() {
   469  		// Propagate the initial price point to the transaction pool
   470  		s.lock.RLock()
   471  		price := s.gasPrice
   472  		s.lock.RUnlock()
   473  		s.txPool.SetGasPrice(price)
   474  
   475  		// Configure the local mining address
   476  		eb, err := s.Etherbase()
   477  		if err != nil {
   478  			log.Error("Cannot start mining without etherbase", "err", err)
   479  			return fmt.Errorf("etherbase missing: %v", err)
   480  		}
   481  		if clique, ok := s.engine.(*clique.Clique); ok {
   482  			wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
   483  			if wallet == nil || err != nil {
   484  				log.Error("Etherbase account unavailable locally", "err", err)
   485  				return fmt.Errorf("signer missing: %v", err)
   486  			}
   487  			clique.Authorize(eb, wallet.SignData)
   488  		}
   489  		if parlia, ok := s.engine.(*parlia.Parlia); ok {
   490  			wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
   491  			if wallet == nil || err != nil {
   492  				log.Error("Etherbase account unavailable locally", "err", err)
   493  				return fmt.Errorf("signer missing: %v", err)
   494  			}
   495  
   496  			parlia.Authorize(eb, wallet.SignData, wallet.SignTx)
   497  		}
   498  		// If mining is started, we can disable the transaction rejection mechanism
   499  		// introduced to speed sync times.
   500  		atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
   501  
   502  		go s.miner.Start(eb)
   503  	}
   504  	return nil
   505  }
   506  
   507  // StopMining terminates the miner, both at the consensus engine level as well as
   508  // at the block creation level.
   509  func (s *Ethereum) StopMining() {
   510  	// Update the thread count within the consensus engine
   511  	type threaded interface {
   512  		SetThreads(threads int)
   513  	}
   514  	if th, ok := s.engine.(threaded); ok {
   515  		th.SetThreads(-1)
   516  	}
   517  	// Stop the block creating itself
   518  	s.miner.Stop()
   519  }
   520  
   521  func (s *Ethereum) IsMining() bool      { return s.miner.Mining() }
   522  func (s *Ethereum) Miner() *miner.Miner { return s.miner }
   523  
   524  func (s *Ethereum) AccountManager() *accounts.Manager  { return s.accountManager }
   525  func (s *Ethereum) BlockChain() *core.BlockChain       { return s.blockchain }
   526  func (s *Ethereum) TxPool() *core.TxPool               { return s.txPool }
   527  func (s *Ethereum) EventMux() *event.TypeMux           { return s.eventMux }
   528  func (s *Ethereum) Engine() consensus.Engine           { return s.engine }
   529  func (s *Ethereum) ChainDb() ethdb.Database            { return s.chainDb }
   530  func (s *Ethereum) IsListening() bool                  { return true } // Always listening
   531  func (s *Ethereum) EthVersion() int                    { return int(ProtocolVersions[0]) }
   532  func (s *Ethereum) NetVersion() uint64                 { return s.networkID }
   533  func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
   534  func (s *Ethereum) Synced() bool                       { return atomic.LoadUint32(&s.protocolManager.acceptTxs) == 1 }
   535  func (s *Ethereum) ArchiveMode() bool                  { return s.config.NoPruning }
   536  
   537  // Protocols implements node.Service, returning all the currently configured
   538  // network protocols to start.
   539  func (s *Ethereum) Protocols() []p2p.Protocol {
   540  	protos := make([]p2p.Protocol, len(ProtocolVersions))
   541  	for i, vsn := range ProtocolVersions {
   542  		protos[i] = s.protocolManager.makeProtocol(vsn)
   543  		protos[i].Attributes = []enr.Entry{s.currentEthEntry()}
   544  		protos[i].DialCandidates = s.dialCandiates
   545  	}
   546  	if s.lesServer != nil {
   547  		protos = append(protos, s.lesServer.Protocols()...)
   548  	}
   549  	return protos
   550  }
   551  
   552  // Start implements node.Service, starting all internal goroutines needed by the
   553  // Ethereum protocol implementation.
   554  func (s *Ethereum) Start(srvr *p2p.Server) error {
   555  	s.startEthEntryUpdate(srvr.LocalNode())
   556  
   557  	// Start the bloom bits servicing goroutines
   558  	s.startBloomHandlers(params.BloomBitsBlocks)
   559  
   560  	// Start the RPC service
   561  	s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
   562  
   563  	// Figure out a max peers count based on the server limits
   564  	maxPeers := srvr.MaxPeers
   565  	if s.config.LightServ > 0 {
   566  		if s.config.LightPeers >= srvr.MaxPeers {
   567  			return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
   568  		}
   569  		maxPeers -= s.config.LightPeers
   570  	}
   571  	// Start the networking layer and the light server if requested
   572  	s.protocolManager.Start(maxPeers)
   573  	if s.lesServer != nil {
   574  		s.lesServer.Start(srvr)
   575  	}
   576  	return nil
   577  }
   578  
   579  // Stop implements node.Service, terminating all internal goroutines used by the
   580  // Ethereum protocol.
   581  func (s *Ethereum) Stop() error {
   582  	// Stop all the peer-related stuff first.
   583  	s.protocolManager.Stop()
   584  	if s.lesServer != nil {
   585  		s.lesServer.Stop()
   586  	}
   587  
   588  	// Then stop everything else.
   589  	s.bloomIndexer.Close()
   590  	close(s.closeBloomHandler)
   591  	s.txPool.Stop()
   592  	s.miner.Stop()
   593  	s.blockchain.Stop()
   594  	s.engine.Close()
   595  	s.chainDb.Close()
   596  	s.eventMux.Stop()
   597  	return nil
   598  }