backend.go 21 KB

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