backend.go 19 KB

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