backend.go 19 KB

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