backend.go 19 KB

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