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