backend.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. TrieCleanJournal: ctx.ResolvePath(config.TrieCleanCacheJournal),
  167. TrieCleanRejournal: config.TrieCleanCacheRejournal,
  168. TrieCleanNoPrefetch: config.NoPrefetch,
  169. TrieDirtyLimit: config.TrieDirtyCache,
  170. TrieDirtyDisabled: config.NoPruning,
  171. TrieTimeLimit: config.TrieTimeout,
  172. SnapshotLimit: config.SnapshotCache,
  173. }
  174. )
  175. eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, chainConfig, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit)
  176. if err != nil {
  177. return nil, err
  178. }
  179. // Rewind the chain in case of an incompatible config upgrade.
  180. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  181. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  182. eth.blockchain.SetHead(compat.RewindTo)
  183. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  184. }
  185. eth.bloomIndexer.Start(eth.blockchain)
  186. if config.TxPool.Journal != "" {
  187. config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
  188. }
  189. eth.txPool = core.NewTxPool(config.TxPool, chainConfig, eth.blockchain)
  190. // Permit the downloader to use the trie cache allowance during fast sync
  191. cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit + cacheConfig.SnapshotLimit
  192. checkpoint := config.Checkpoint
  193. if checkpoint == nil {
  194. checkpoint = params.TrustedCheckpoints[genesisHash]
  195. }
  196. 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 {
  197. return nil, err
  198. }
  199. eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock)
  200. eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
  201. eth.APIBackend = &EthAPIBackend{ctx.ExtRPCEnabled(), eth, nil}
  202. gpoParams := config.GPO
  203. if gpoParams.Default == nil {
  204. gpoParams.Default = config.Miner.GasPrice
  205. }
  206. eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
  207. eth.dialCandidates, err = eth.setupDiscovery(&ctx.Config.P2P)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return eth, nil
  212. }
  213. func makeExtraData(extra []byte) []byte {
  214. if len(extra) == 0 {
  215. // create default extradata
  216. extra, _ = rlp.EncodeToBytes([]interface{}{
  217. uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
  218. "geth",
  219. runtime.Version(),
  220. runtime.GOOS,
  221. })
  222. }
  223. if uint64(len(extra)) > params.MaximumExtraDataSize {
  224. log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
  225. extra = nil
  226. }
  227. return extra
  228. }
  229. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  230. func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, noverify bool, db ethdb.Database) consensus.Engine {
  231. // If proof-of-authority is requested, set it up
  232. if chainConfig.Clique != nil {
  233. return clique.New(chainConfig.Clique, db)
  234. }
  235. // Otherwise assume proof-of-work
  236. switch config.PowMode {
  237. case ethash.ModeFake:
  238. log.Warn("Ethash used in fake mode")
  239. return ethash.NewFaker()
  240. case ethash.ModeTest:
  241. log.Warn("Ethash used in test mode")
  242. return ethash.NewTester(nil, noverify)
  243. case ethash.ModeShared:
  244. log.Warn("Ethash used in shared mode")
  245. return ethash.NewShared()
  246. default:
  247. engine := ethash.New(ethash.Config{
  248. CacheDir: ctx.ResolvePath(config.CacheDir),
  249. CachesInMem: config.CachesInMem,
  250. CachesOnDisk: config.CachesOnDisk,
  251. CachesLockMmap: config.CachesLockMmap,
  252. DatasetDir: config.DatasetDir,
  253. DatasetsInMem: config.DatasetsInMem,
  254. DatasetsOnDisk: config.DatasetsOnDisk,
  255. DatasetsLockMmap: config.DatasetsLockMmap,
  256. }, notify, noverify)
  257. engine.SetThreads(-1) // Disable CPU mining
  258. return engine
  259. }
  260. }
  261. // APIs return the collection of RPC services the ethereum package offers.
  262. // NOTE, some of these services probably need to be moved to somewhere else.
  263. func (s *Ethereum) APIs() []rpc.API {
  264. apis := ethapi.GetAPIs(s.APIBackend)
  265. // Append any APIs exposed explicitly by the les server
  266. if s.lesServer != nil {
  267. apis = append(apis, s.lesServer.APIs()...)
  268. }
  269. // Append any APIs exposed explicitly by the consensus engine
  270. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  271. // Append any APIs exposed explicitly by the les server
  272. if s.lesServer != nil {
  273. apis = append(apis, s.lesServer.APIs()...)
  274. }
  275. // Append all the local APIs and return
  276. return append(apis, []rpc.API{
  277. {
  278. Namespace: "eth",
  279. Version: "1.0",
  280. Service: NewPublicEthereumAPI(s),
  281. Public: true,
  282. }, {
  283. Namespace: "eth",
  284. Version: "1.0",
  285. Service: NewPublicMinerAPI(s),
  286. Public: true,
  287. }, {
  288. Namespace: "eth",
  289. Version: "1.0",
  290. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  291. Public: true,
  292. }, {
  293. Namespace: "miner",
  294. Version: "1.0",
  295. Service: NewPrivateMinerAPI(s),
  296. Public: false,
  297. }, {
  298. Namespace: "eth",
  299. Version: "1.0",
  300. Service: filters.NewPublicFilterAPI(s.APIBackend, false),
  301. Public: true,
  302. }, {
  303. Namespace: "admin",
  304. Version: "1.0",
  305. Service: NewPrivateAdminAPI(s),
  306. }, {
  307. Namespace: "debug",
  308. Version: "1.0",
  309. Service: NewPublicDebugAPI(s),
  310. Public: true,
  311. }, {
  312. Namespace: "debug",
  313. Version: "1.0",
  314. Service: NewPrivateDebugAPI(s),
  315. }, {
  316. Namespace: "net",
  317. Version: "1.0",
  318. Service: s.netRPCService,
  319. Public: true,
  320. },
  321. }...)
  322. }
  323. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  324. s.blockchain.ResetWithGenesisBlock(gb)
  325. }
  326. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  327. s.lock.RLock()
  328. etherbase := s.etherbase
  329. s.lock.RUnlock()
  330. if etherbase != (common.Address{}) {
  331. return etherbase, nil
  332. }
  333. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  334. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  335. etherbase := accounts[0].Address
  336. s.lock.Lock()
  337. s.etherbase = etherbase
  338. s.lock.Unlock()
  339. log.Info("Etherbase automatically configured", "address", etherbase)
  340. return etherbase, nil
  341. }
  342. }
  343. return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
  344. }
  345. // isLocalBlock checks whether the specified block is mined
  346. // by local miner accounts.
  347. //
  348. // We regard two types of accounts as local miner account: etherbase
  349. // and accounts specified via `txpool.locals` flag.
  350. func (s *Ethereum) isLocalBlock(block *types.Block) bool {
  351. author, err := s.engine.Author(block.Header())
  352. if err != nil {
  353. log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err)
  354. return false
  355. }
  356. // Check whether the given address is etherbase.
  357. s.lock.RLock()
  358. etherbase := s.etherbase
  359. s.lock.RUnlock()
  360. if author == etherbase {
  361. return true
  362. }
  363. // Check whether the given address is specified by `txpool.local`
  364. // CLI flag.
  365. for _, account := range s.config.TxPool.Locals {
  366. if account == author {
  367. return true
  368. }
  369. }
  370. return false
  371. }
  372. // shouldPreserve checks whether we should preserve the given block
  373. // during the chain reorg depending on whether the author of block
  374. // is a local account.
  375. func (s *Ethereum) shouldPreserve(block *types.Block) bool {
  376. // The reason we need to disable the self-reorg preserving for clique
  377. // is it can be probable to introduce a deadlock.
  378. //
  379. // e.g. If there are 7 available signers
  380. //
  381. // r1 A
  382. // r2 B
  383. // r3 C
  384. // r4 D
  385. // r5 A [X] F G
  386. // r6 [X]
  387. //
  388. // In the round5, the inturn signer E is offline, so the worst case
  389. // is A, F and G sign the block of round5 and reject the block of opponents
  390. // and in the round6, the last available signer B is offline, the whole
  391. // network is stuck.
  392. if _, ok := s.engine.(*clique.Clique); ok {
  393. return false
  394. }
  395. return s.isLocalBlock(block)
  396. }
  397. // SetEtherbase sets the mining reward address.
  398. func (s *Ethereum) SetEtherbase(etherbase common.Address) {
  399. s.lock.Lock()
  400. s.etherbase = etherbase
  401. s.lock.Unlock()
  402. s.miner.SetEtherbase(etherbase)
  403. }
  404. // StartMining starts the miner with the given number of CPU threads. If mining
  405. // is already running, this method adjust the number of threads allowed to use
  406. // and updates the minimum price required by the transaction pool.
  407. func (s *Ethereum) StartMining(threads int) error {
  408. // Update the thread count within the consensus engine
  409. type threaded interface {
  410. SetThreads(threads int)
  411. }
  412. if th, ok := s.engine.(threaded); ok {
  413. log.Info("Updated mining threads", "threads", threads)
  414. if threads == 0 {
  415. threads = -1 // Disable the miner from within
  416. }
  417. th.SetThreads(threads)
  418. }
  419. // If the miner was not running, initialize it
  420. if !s.IsMining() {
  421. // Propagate the initial price point to the transaction pool
  422. s.lock.RLock()
  423. price := s.gasPrice
  424. s.lock.RUnlock()
  425. s.txPool.SetGasPrice(price)
  426. // Configure the local mining address
  427. eb, err := s.Etherbase()
  428. if err != nil {
  429. log.Error("Cannot start mining without etherbase", "err", err)
  430. return fmt.Errorf("etherbase missing: %v", err)
  431. }
  432. if clique, ok := s.engine.(*clique.Clique); ok {
  433. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  434. if wallet == nil || err != nil {
  435. log.Error("Etherbase account unavailable locally", "err", err)
  436. return fmt.Errorf("signer missing: %v", err)
  437. }
  438. clique.Authorize(eb, wallet.SignData)
  439. }
  440. // If mining is started, we can disable the transaction rejection mechanism
  441. // introduced to speed sync times.
  442. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  443. go s.miner.Start(eb)
  444. }
  445. return nil
  446. }
  447. // StopMining terminates the miner, both at the consensus engine level as well as
  448. // at the block creation level.
  449. func (s *Ethereum) StopMining() {
  450. // Update the thread count within the consensus engine
  451. type threaded interface {
  452. SetThreads(threads int)
  453. }
  454. if th, ok := s.engine.(threaded); ok {
  455. th.SetThreads(-1)
  456. }
  457. // Stop the block creating itself
  458. s.miner.Stop()
  459. }
  460. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  461. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  462. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  463. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  464. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  465. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  466. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  467. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  468. func (s *Ethereum) IsListening() bool { return true } // Always listening
  469. func (s *Ethereum) EthVersion() int { return int(ProtocolVersions[0]) }
  470. func (s *Ethereum) NetVersion() uint64 { return s.networkID }
  471. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  472. func (s *Ethereum) Synced() bool { return atomic.LoadUint32(&s.protocolManager.acceptTxs) == 1 }
  473. func (s *Ethereum) ArchiveMode() bool { return s.config.NoPruning }
  474. // Protocols implements node.Service, returning all the currently configured
  475. // network protocols to start.
  476. func (s *Ethereum) Protocols() []p2p.Protocol {
  477. protos := make([]p2p.Protocol, len(ProtocolVersions))
  478. for i, vsn := range ProtocolVersions {
  479. protos[i] = s.protocolManager.makeProtocol(vsn)
  480. protos[i].Attributes = []enr.Entry{s.currentEthEntry()}
  481. protos[i].DialCandidates = s.dialCandidates
  482. }
  483. if s.lesServer != nil {
  484. protos = append(protos, s.lesServer.Protocols()...)
  485. }
  486. return protos
  487. }
  488. // Start implements node.Service, starting all internal goroutines needed by the
  489. // Ethereum protocol implementation.
  490. func (s *Ethereum) Start(srvr *p2p.Server) error {
  491. s.startEthEntryUpdate(srvr.LocalNode())
  492. // Start the bloom bits servicing goroutines
  493. s.startBloomHandlers(params.BloomBitsBlocks)
  494. // Start the RPC service
  495. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  496. // Figure out a max peers count based on the server limits
  497. maxPeers := srvr.MaxPeers
  498. if s.config.LightServ > 0 {
  499. if s.config.LightPeers >= srvr.MaxPeers {
  500. return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
  501. }
  502. maxPeers -= s.config.LightPeers
  503. }
  504. // Start the networking layer and the light server if requested
  505. s.protocolManager.Start(maxPeers)
  506. if s.lesServer != nil {
  507. s.lesServer.Start(srvr)
  508. }
  509. return nil
  510. }
  511. // Stop implements node.Service, terminating all internal goroutines used by the
  512. // Ethereum protocol.
  513. func (s *Ethereum) Stop() error {
  514. // Stop all the peer-related stuff first.
  515. s.protocolManager.Stop()
  516. if s.lesServer != nil {
  517. s.lesServer.Stop()
  518. }
  519. // Then stop everything else.
  520. s.bloomIndexer.Close()
  521. close(s.closeBloomHandler)
  522. s.txPool.Stop()
  523. s.miner.Stop()
  524. s.blockchain.Stop()
  525. s.engine.Close()
  526. s.chainDb.Close()
  527. s.eventMux.Stop()
  528. return nil
  529. }