backend.go 19 KB

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