client.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2016 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 les implements the Light Ethereum Subprotocol.
  17. package les
  18. import (
  19. "fmt"
  20. "github.com/ethereum/go-ethereum/accounts"
  21. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/common/mclock"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/bloombits"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/eth"
  31. "github.com/ethereum/go-ethereum/eth/downloader"
  32. "github.com/ethereum/go-ethereum/eth/filters"
  33. "github.com/ethereum/go-ethereum/eth/gasprice"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/internal/ethapi"
  36. "github.com/ethereum/go-ethereum/light"
  37. "github.com/ethereum/go-ethereum/log"
  38. "github.com/ethereum/go-ethereum/node"
  39. "github.com/ethereum/go-ethereum/p2p"
  40. "github.com/ethereum/go-ethereum/p2p/enode"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rpc"
  43. )
  44. type LightEthereum struct {
  45. lesCommons
  46. reqDist *requestDistributor
  47. retriever *retrieveManager
  48. odr *LesOdr
  49. relay *lesTxRelay
  50. handler *clientHandler
  51. txPool *light.TxPool
  52. blockchain *light.LightChain
  53. serverPool *serverPool
  54. bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
  55. bloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports
  56. ApiBackend *LesApiBackend
  57. eventMux *event.TypeMux
  58. engine consensus.Engine
  59. accountManager *accounts.Manager
  60. netRPCService *ethapi.PublicNetAPI
  61. }
  62. func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
  63. chainDb, err := ctx.OpenDatabase("lightchaindata", config.DatabaseCache, config.DatabaseHandles, "eth/db/chaindata/")
  64. if err != nil {
  65. return nil, err
  66. }
  67. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.OverrideIstanbul)
  68. if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
  69. return nil, genesisErr
  70. }
  71. log.Info("Initialised chain configuration", "config", chainConfig)
  72. peers := newPeerSet()
  73. leth := &LightEthereum{
  74. lesCommons: lesCommons{
  75. genesis: genesisHash,
  76. config: config,
  77. chainConfig: chainConfig,
  78. iConfig: light.DefaultClientIndexerConfig,
  79. chainDb: chainDb,
  80. peers: peers,
  81. closeCh: make(chan struct{}),
  82. },
  83. eventMux: ctx.EventMux,
  84. reqDist: newRequestDistributor(peers, &mclock.System{}),
  85. accountManager: ctx.AccountManager,
  86. engine: eth.CreateConsensusEngine(ctx, chainConfig, &config.Ethash, nil, false, chainDb),
  87. bloomRequests: make(chan chan *bloombits.Retrieval),
  88. bloomIndexer: eth.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
  89. serverPool: newServerPool(chainDb, config.UltraLightServers),
  90. }
  91. leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool)
  92. leth.relay = newLesTxRelay(peers, leth.retriever)
  93. leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.retriever)
  94. leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations)
  95. leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency)
  96. leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
  97. checkpoint := config.Checkpoint
  98. if checkpoint == nil {
  99. checkpoint = params.TrustedCheckpoints[genesisHash]
  100. }
  101. // Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
  102. // indexers already set but not started yet
  103. if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil {
  104. return nil, err
  105. }
  106. leth.chainReader = leth.blockchain
  107. leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
  108. // Set up checkpoint oracle.
  109. oracle := config.CheckpointOracle
  110. if oracle == nil {
  111. oracle = params.CheckpointOracles[genesisHash]
  112. }
  113. leth.oracle = newCheckpointOracle(oracle, leth.localCheckpoint)
  114. // Note: AddChildIndexer starts the update process for the child
  115. leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
  116. leth.chtIndexer.Start(leth.blockchain)
  117. leth.bloomIndexer.Start(leth.blockchain)
  118. leth.handler = newClientHandler(config.UltraLightServers, config.UltraLightFraction, checkpoint, leth)
  119. if leth.handler.ulc != nil {
  120. log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.handler.ulc.keys), "minTrustedFraction", leth.handler.ulc.fraction)
  121. leth.blockchain.DisableCheckFreq()
  122. }
  123. // Rewind the chain in case of an incompatible config upgrade.
  124. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  125. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  126. leth.blockchain.SetHead(compat.RewindTo)
  127. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  128. }
  129. leth.ApiBackend = &LesApiBackend{ctx.ExtRPCEnabled(), leth, nil}
  130. gpoParams := config.GPO
  131. if gpoParams.Default == nil {
  132. gpoParams.Default = config.Miner.GasPrice
  133. }
  134. leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
  135. return leth, nil
  136. }
  137. type LightDummyAPI struct{}
  138. // Etherbase is the address that mining rewards will be send to
  139. func (s *LightDummyAPI) Etherbase() (common.Address, error) {
  140. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  141. }
  142. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  143. func (s *LightDummyAPI) Coinbase() (common.Address, error) {
  144. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  145. }
  146. // Hashrate returns the POW hashrate
  147. func (s *LightDummyAPI) Hashrate() hexutil.Uint {
  148. return 0
  149. }
  150. // Mining returns an indication if this node is currently mining.
  151. func (s *LightDummyAPI) Mining() bool {
  152. return false
  153. }
  154. // APIs returns the collection of RPC services the ethereum package offers.
  155. // NOTE, some of these services probably need to be moved to somewhere else.
  156. func (s *LightEthereum) APIs() []rpc.API {
  157. return append(ethapi.GetAPIs(s.ApiBackend), []rpc.API{
  158. {
  159. Namespace: "eth",
  160. Version: "1.0",
  161. Service: &LightDummyAPI{},
  162. Public: true,
  163. }, {
  164. Namespace: "eth",
  165. Version: "1.0",
  166. Service: downloader.NewPublicDownloaderAPI(s.handler.downloader, s.eventMux),
  167. Public: true,
  168. }, {
  169. Namespace: "eth",
  170. Version: "1.0",
  171. Service: filters.NewPublicFilterAPI(s.ApiBackend, true),
  172. Public: true,
  173. }, {
  174. Namespace: "net",
  175. Version: "1.0",
  176. Service: s.netRPCService,
  177. Public: true,
  178. }, {
  179. Namespace: "les",
  180. Version: "1.0",
  181. Service: NewPrivateLightAPI(&s.lesCommons),
  182. Public: false,
  183. },
  184. }...)
  185. }
  186. func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
  187. s.blockchain.ResetWithGenesisBlock(gb)
  188. }
  189. func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
  190. func (s *LightEthereum) TxPool() *light.TxPool { return s.txPool }
  191. func (s *LightEthereum) Engine() consensus.Engine { return s.engine }
  192. func (s *LightEthereum) LesVersion() int { return int(ClientProtocolVersions[0]) }
  193. func (s *LightEthereum) Downloader() *downloader.Downloader { return s.handler.downloader }
  194. func (s *LightEthereum) EventMux() *event.TypeMux { return s.eventMux }
  195. // Protocols implements node.Service, returning all the currently configured
  196. // network protocols to start.
  197. func (s *LightEthereum) Protocols() []p2p.Protocol {
  198. return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
  199. if p := s.peers.Peer(peerIdToString(id)); p != nil {
  200. return p.Info()
  201. }
  202. return nil
  203. })
  204. }
  205. // Start implements node.Service, starting all internal goroutines needed by the
  206. // light ethereum protocol implementation.
  207. func (s *LightEthereum) Start(srvr *p2p.Server) error {
  208. log.Warn("Light client mode is an experimental feature")
  209. // Start bloom request workers.
  210. s.wg.Add(bloomServiceThreads)
  211. s.startBloomHandlers(params.BloomBitsBlocksClient)
  212. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.config.NetworkId)
  213. // clients are searching for the first advertised protocol in the list
  214. protocolVersion := AdvertiseProtocolVersions[0]
  215. s.serverPool.start(srvr, lesTopic(s.blockchain.Genesis().Hash(), protocolVersion))
  216. return nil
  217. }
  218. // Stop implements node.Service, terminating all internal goroutines used by the
  219. // Ethereum protocol.
  220. func (s *LightEthereum) Stop() error {
  221. close(s.closeCh)
  222. s.peers.Close()
  223. s.reqDist.close()
  224. s.odr.Stop()
  225. s.relay.Stop()
  226. s.bloomIndexer.Close()
  227. s.chtIndexer.Close()
  228. s.blockchain.Stop()
  229. s.handler.stop()
  230. s.txPool.Stop()
  231. s.engine.Close()
  232. s.eventMux.Stop()
  233. s.serverPool.stop()
  234. s.chainDb.Close()
  235. s.wg.Wait()
  236. log.Info("Light ethereum stopped")
  237. return nil
  238. }
  239. // SetClient sets the rpc client and binds the registrar contract.
  240. func (s *LightEthereum) SetContractBackend(backend bind.ContractBackend) {
  241. if s.oracle == nil {
  242. return
  243. }
  244. s.oracle.start(backend)
  245. }