github.com/newbtp/btp@v0.0.0-20190709081714-e4aafa07224e/btp/backend.go (about)

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