backend.go 19 KB

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