backend.go 19 KB

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