backend.go 19 KB

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