client.go 11 KB

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