client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // Copyright 2019 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. "strings"
  21. "time"
  22. "github.com/ethereum/go-ethereum/accounts"
  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/ethconfig"
  32. "github.com/ethereum/go-ethereum/eth/gasprice"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/internal/shutdowncheck"
  36. "github.com/ethereum/go-ethereum/les/downloader"
  37. "github.com/ethereum/go-ethereum/les/vflux"
  38. vfc "github.com/ethereum/go-ethereum/les/vflux/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/p2p/enr"
  45. "github.com/ethereum/go-ethereum/params"
  46. "github.com/ethereum/go-ethereum/rlp"
  47. "github.com/ethereum/go-ethereum/rpc"
  48. )
  49. type LightEthereum struct {
  50. lesCommons
  51. peers *serverPeerSet
  52. reqDist *requestDistributor
  53. retriever *retrieveManager
  54. odr *LesOdr
  55. relay *lesTxRelay
  56. handler *clientHandler
  57. txPool *light.TxPool
  58. blockchain *light.LightChain
  59. serverPool *vfc.ServerPool
  60. serverPoolIterator enode.Iterator
  61. pruner *pruner
  62. merger *consensus.Merger
  63. bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
  64. bloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports
  65. ApiBackend *LesApiBackend
  66. eventMux *event.TypeMux
  67. engine consensus.Engine
  68. accountManager *accounts.Manager
  69. netRPCService *ethapi.NetAPI
  70. p2pServer *p2p.Server
  71. p2pConfig *p2p.Config
  72. udpEnabled bool
  73. shutdownTracker *shutdowncheck.ShutdownTracker // Tracks if and when the node has shutdown ungracefully
  74. }
  75. // New creates an instance of the light client.
  76. func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
  77. chainDb, err := stack.OpenDatabase("lightchaindata", config.DatabaseCache, config.DatabaseHandles, "eth/db/chaindata/", false)
  78. if err != nil {
  79. return nil, err
  80. }
  81. lesDb, err := stack.OpenDatabase("les.client", 0, 0, "eth/db/lesclient/", false)
  82. if err != nil {
  83. return nil, err
  84. }
  85. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.OverrideTerminalTotalDifficulty, config.OverrideTerminalTotalDifficultyPassed)
  86. if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
  87. return nil, genesisErr
  88. }
  89. log.Info("")
  90. log.Info(strings.Repeat("-", 153))
  91. for _, line := range strings.Split(chainConfig.String(), "\n") {
  92. log.Info(line)
  93. }
  94. log.Info(strings.Repeat("-", 153))
  95. log.Info("")
  96. if !config.IsNetworkIdSet && chainConfig != nil {
  97. if chainConfig.ChainID_ALT != nil && chainConfig.EthPoWForkSupport {
  98. config.NetworkId = chainConfig.ChainID_ALT.Uint64()
  99. }
  100. }
  101. peers := newServerPeerSet()
  102. merger := consensus.NewMerger(chainDb)
  103. leth := &LightEthereum{
  104. lesCommons: lesCommons{
  105. genesis: genesisHash,
  106. config: config,
  107. chainConfig: chainConfig,
  108. iConfig: light.DefaultClientIndexerConfig,
  109. chainDb: chainDb,
  110. lesDb: lesDb,
  111. closeCh: make(chan struct{}),
  112. },
  113. peers: peers,
  114. eventMux: stack.EventMux(),
  115. reqDist: newRequestDistributor(peers, &mclock.System{}),
  116. accountManager: stack.AccountManager(),
  117. merger: merger,
  118. engine: ethconfig.CreateConsensusEngine(stack, chainConfig, &config.Ethash, nil, false, chainDb),
  119. bloomRequests: make(chan chan *bloombits.Retrieval),
  120. bloomIndexer: core.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
  121. p2pServer: stack.Server(),
  122. p2pConfig: &stack.Config().P2P,
  123. udpEnabled: stack.Config().P2P.DiscoveryV5,
  124. shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb),
  125. }
  126. var prenegQuery vfc.QueryFunc
  127. if leth.udpEnabled {
  128. prenegQuery = leth.prenegQuery
  129. }
  130. leth.serverPool, leth.serverPoolIterator = vfc.NewServerPool(lesDb, []byte("serverpool:"), time.Second, prenegQuery, &mclock.System{}, config.UltraLightServers, requestList)
  131. leth.serverPool.AddMetrics(suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge, sessionValueMeter, serverDialedMeter)
  132. leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool.GetTimeout)
  133. leth.relay = newLesTxRelay(peers, leth.retriever)
  134. leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.peers, leth.retriever)
  135. leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations, config.LightNoPrune)
  136. leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency, config.LightNoPrune)
  137. leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
  138. checkpoint := config.Checkpoint
  139. if checkpoint == nil {
  140. checkpoint = params.TrustedCheckpoints[genesisHash]
  141. }
  142. // Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
  143. // indexers already set but not started yet
  144. if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil {
  145. return nil, err
  146. }
  147. leth.chainReader = leth.blockchain
  148. leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
  149. // Set up checkpoint oracle.
  150. leth.oracle = leth.setupOracle(stack, genesisHash, config)
  151. // Note: AddChildIndexer starts the update process for the child
  152. leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
  153. leth.chtIndexer.Start(leth.blockchain)
  154. leth.bloomIndexer.Start(leth.blockchain)
  155. // Start a light chain pruner to delete useless historical data.
  156. leth.pruner = newPruner(chainDb, leth.chtIndexer, leth.bloomTrieIndexer)
  157. // Rewind the chain in case of an incompatible config upgrade.
  158. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  159. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  160. leth.blockchain.SetHead(compat.RewindTo)
  161. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  162. }
  163. leth.ApiBackend = &LesApiBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, leth, nil}
  164. gpoParams := config.GPO
  165. if gpoParams.Default == nil {
  166. gpoParams.Default = config.Miner.GasPrice
  167. }
  168. leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
  169. leth.handler = newClientHandler(config.UltraLightServers, config.UltraLightFraction, checkpoint, leth)
  170. if leth.handler.ulc != nil {
  171. log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.handler.ulc.keys), "minTrustedFraction", leth.handler.ulc.fraction)
  172. leth.blockchain.DisableCheckFreq()
  173. }
  174. leth.netRPCService = ethapi.NewNetAPI(leth.p2pServer, leth.config.NetworkId)
  175. // Register the backend on the node
  176. stack.RegisterAPIs(leth.APIs())
  177. stack.RegisterProtocols(leth.Protocols())
  178. stack.RegisterLifecycle(leth)
  179. // Successful startup; push a marker and check previous unclean shutdowns.
  180. leth.shutdownTracker.MarkStartup()
  181. return leth, nil
  182. }
  183. // VfluxRequest sends a batch of requests to the given node through discv5 UDP TalkRequest and returns the responses
  184. func (s *LightEthereum) VfluxRequest(n *enode.Node, reqs vflux.Requests) vflux.Replies {
  185. if !s.udpEnabled {
  186. return nil
  187. }
  188. reqsEnc, _ := rlp.EncodeToBytes(&reqs)
  189. repliesEnc, _ := s.p2pServer.DiscV5.TalkRequest(s.serverPool.DialNode(n), "vfx", reqsEnc)
  190. var replies vflux.Replies
  191. if len(repliesEnc) == 0 || rlp.DecodeBytes(repliesEnc, &replies) != nil {
  192. return nil
  193. }
  194. return replies
  195. }
  196. // vfxVersion returns the version number of the "les" service subdomain of the vflux UDP
  197. // service, as advertised in the ENR record
  198. func (s *LightEthereum) vfxVersion(n *enode.Node) uint {
  199. if n.Seq() == 0 {
  200. var err error
  201. if !s.udpEnabled {
  202. return 0
  203. }
  204. if n, err = s.p2pServer.DiscV5.RequestENR(n); n != nil && err == nil && n.Seq() != 0 {
  205. s.serverPool.Persist(n)
  206. } else {
  207. return 0
  208. }
  209. }
  210. var les []rlp.RawValue
  211. if err := n.Load(enr.WithEntry("les", &les)); err != nil || len(les) < 1 {
  212. return 0
  213. }
  214. var version uint
  215. rlp.DecodeBytes(les[0], &version) // Ignore additional fields (for forward compatibility).
  216. return version
  217. }
  218. // prenegQuery sends a capacity query to the given server node to determine whether
  219. // a connection slot is immediately available
  220. func (s *LightEthereum) prenegQuery(n *enode.Node) int {
  221. if s.vfxVersion(n) < 1 {
  222. // UDP query not supported, always try TCP connection
  223. return 1
  224. }
  225. var requests vflux.Requests
  226. requests.Add("les", vflux.CapacityQueryName, vflux.CapacityQueryReq{
  227. Bias: 180,
  228. AddTokens: []vflux.IntOrInf{{}},
  229. })
  230. replies := s.VfluxRequest(n, requests)
  231. var cqr vflux.CapacityQueryReply
  232. if replies.Get(0, &cqr) != nil || len(cqr) != 1 { // Note: Get returns an error if replies is nil
  233. return -1
  234. }
  235. if cqr[0] > 0 {
  236. return 1
  237. }
  238. return 0
  239. }
  240. type LightDummyAPI struct{}
  241. // Etherbase is the address that mining rewards will be send to
  242. func (s *LightDummyAPI) Etherbase() (common.Address, error) {
  243. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  244. }
  245. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  246. func (s *LightDummyAPI) Coinbase() (common.Address, error) {
  247. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  248. }
  249. // Hashrate returns the POW hashrate
  250. func (s *LightDummyAPI) Hashrate() hexutil.Uint {
  251. return 0
  252. }
  253. // Mining returns an indication if this node is currently mining.
  254. func (s *LightDummyAPI) Mining() bool {
  255. return false
  256. }
  257. // APIs returns the collection of RPC services the ethereum package offers.
  258. // NOTE, some of these services probably need to be moved to somewhere else.
  259. func (s *LightEthereum) APIs() []rpc.API {
  260. apis := ethapi.GetAPIs(s.ApiBackend, nil)
  261. apis = append(apis, s.engine.APIs(s.BlockChain().HeaderChain())...)
  262. return append(apis, []rpc.API{
  263. {
  264. Namespace: "eth",
  265. Service: &LightDummyAPI{},
  266. }, {
  267. Namespace: "eth",
  268. Service: downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux),
  269. }, {
  270. Namespace: "net",
  271. Service: s.netRPCService,
  272. }, {
  273. Namespace: "les",
  274. Service: NewLightAPI(&s.lesCommons),
  275. }, {
  276. Namespace: "vflux",
  277. Service: s.serverPool.API(),
  278. },
  279. }...)
  280. }
  281. func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
  282. s.blockchain.ResetWithGenesisBlock(gb)
  283. }
  284. func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
  285. func (s *LightEthereum) TxPool() *light.TxPool { return s.txPool }
  286. func (s *LightEthereum) Engine() consensus.Engine { return s.engine }
  287. func (s *LightEthereum) LesVersion() int { return int(ClientProtocolVersions[0]) }
  288. func (s *LightEthereum) Downloader() *downloader.Downloader { return s.handler.downloader }
  289. func (s *LightEthereum) EventMux() *event.TypeMux { return s.eventMux }
  290. func (s *LightEthereum) Merger() *consensus.Merger { return s.merger }
  291. // Protocols returns all the currently configured network protocols to start.
  292. func (s *LightEthereum) Protocols() []p2p.Protocol {
  293. return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
  294. if p := s.peers.peer(id.String()); p != nil {
  295. return p.Info()
  296. }
  297. return nil
  298. }, s.serverPoolIterator)
  299. }
  300. // Start implements node.Lifecycle, starting all internal goroutines needed by the
  301. // light ethereum protocol implementation.
  302. func (s *LightEthereum) Start() error {
  303. log.Warn("Light client mode is an experimental feature")
  304. // Regularly update shutdown marker
  305. s.shutdownTracker.Start()
  306. if s.udpEnabled && s.p2pServer.DiscV5 == nil {
  307. s.udpEnabled = false
  308. log.Error("Discovery v5 is not initialized")
  309. }
  310. discovery, err := s.setupDiscovery()
  311. if err != nil {
  312. return err
  313. }
  314. s.serverPool.AddSource(discovery)
  315. s.serverPool.Start()
  316. // Start bloom request workers.
  317. s.wg.Add(bloomServiceThreads)
  318. s.startBloomHandlers(params.BloomBitsBlocksClient)
  319. s.handler.start()
  320. return nil
  321. }
  322. // Stop implements node.Lifecycle, terminating all internal goroutines used by the
  323. // Ethereum protocol.
  324. func (s *LightEthereum) Stop() error {
  325. close(s.closeCh)
  326. s.serverPool.Stop()
  327. s.peers.close()
  328. s.reqDist.close()
  329. s.odr.Stop()
  330. s.relay.Stop()
  331. s.bloomIndexer.Close()
  332. s.chtIndexer.Close()
  333. s.blockchain.Stop()
  334. s.handler.stop()
  335. s.txPool.Stop()
  336. s.engine.Close()
  337. s.pruner.close()
  338. s.eventMux.Stop()
  339. // Clean shutdown marker as the last thing before closing db
  340. s.shutdownTracker.Stop()
  341. s.chainDb.Close()
  342. s.lesDb.Close()
  343. s.wg.Wait()
  344. log.Info("Light ethereum stopped")
  345. return nil
  346. }