client.go 10.0 KB

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