backend.go 20 KB

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