client.go 13 KB

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