backend.go 19 KB

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