client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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/", false)
  75. if err != nil {
  76. return nil, err
  77. }
  78. lesDb, err := stack.OpenDatabase("les.client", 0, 0, "eth/db/lesclient/", false)
  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, 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. newChainFunc := light.NewLightChain
  126. if config.QuorumChainConfig.MultiTenantEnabled() {
  127. newChainFunc = light.NewMultitenantLightChain
  128. }
  129. // Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
  130. // indexers already set but not started yet
  131. if leth.blockchain, err = newChainFunc(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil {
  132. return nil, err
  133. }
  134. leth.chainReader = leth.blockchain
  135. leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
  136. // Set up checkpoint oracle.
  137. leth.oracle = leth.setupOracle(stack, genesisHash, config)
  138. // Note: AddChildIndexer starts the update process for the child
  139. leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
  140. leth.chtIndexer.Start(leth.blockchain)
  141. leth.bloomIndexer.Start(leth.blockchain)
  142. // Start a light chain pruner to delete useless historical data.
  143. leth.pruner = newPruner(chainDb, leth.chtIndexer, leth.bloomTrieIndexer)
  144. // Rewind the chain in case of an incompatible config upgrade.
  145. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  146. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  147. leth.blockchain.SetHead(compat.RewindTo)
  148. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  149. }
  150. leth.ApiBackend = &LesApiBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, leth, nil}
  151. gpoParams := config.GPO
  152. if gpoParams.Default == nil {
  153. gpoParams.Default = config.Miner.GasPrice
  154. }
  155. leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
  156. leth.handler = newClientHandler(config.UltraLightServers, config.UltraLightFraction, checkpoint, leth)
  157. if leth.handler.ulc != nil {
  158. log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.handler.ulc.keys), "minTrustedFraction", leth.handler.ulc.fraction)
  159. leth.blockchain.DisableCheckFreq()
  160. }
  161. leth.netRPCService = ethapi.NewPublicNetAPI(leth.p2pServer, leth.config.NetworkId)
  162. // Register the backend on the node
  163. stack.RegisterAPIs(leth.APIs())
  164. stack.RegisterProtocols(leth.Protocols())
  165. stack.RegisterLifecycle(leth)
  166. // Check for unclean shutdown
  167. if uncleanShutdowns, discards, err := rawdb.PushUncleanShutdownMarker(chainDb); err != nil {
  168. log.Error("Could not update unclean-shutdown-marker list", "error", err)
  169. } else {
  170. if discards > 0 {
  171. log.Warn("Old unclean shutdowns found", "count", discards)
  172. }
  173. for _, tstamp := range uncleanShutdowns {
  174. t := time.Unix(int64(tstamp), 0)
  175. log.Warn("Unclean shutdown detected", "booted", t,
  176. "age", common.PrettyAge(t))
  177. }
  178. }
  179. return leth, nil
  180. }
  181. // VfluxRequest sends a batch of requests to the given node through discv5 UDP TalkRequest and returns the responses
  182. func (s *LightEthereum) VfluxRequest(n *enode.Node, reqs vflux.Requests) vflux.Replies {
  183. if !s.udpEnabled {
  184. return nil
  185. }
  186. reqsEnc, _ := rlp.EncodeToBytes(&reqs)
  187. repliesEnc, _ := s.p2pServer.DiscV5.TalkRequest(s.serverPool.DialNode(n), "vfx", reqsEnc)
  188. var replies vflux.Replies
  189. if len(repliesEnc) == 0 || rlp.DecodeBytes(repliesEnc, &replies) != nil {
  190. return nil
  191. }
  192. return replies
  193. }
  194. // vfxVersion returns the version number of the "les" service subdomain of the vflux UDP
  195. // service, as advertised in the ENR record
  196. func (s *LightEthereum) vfxVersion(n *enode.Node) uint {
  197. if n.Seq() == 0 {
  198. var err error
  199. if !s.udpEnabled {
  200. return 0
  201. }
  202. if n, err = s.p2pServer.DiscV5.RequestENR(n); n != nil && err == nil && n.Seq() != 0 {
  203. s.serverPool.Persist(n)
  204. } else {
  205. return 0
  206. }
  207. }
  208. var les []rlp.RawValue
  209. if err := n.Load(enr.WithEntry("les", &les)); err != nil || len(les) < 1 {
  210. return 0
  211. }
  212. var version uint
  213. rlp.DecodeBytes(les[0], &version) // Ignore additional fields (for forward compatibility).
  214. return version
  215. }
  216. // prenegQuery sends a capacity query to the given server node to determine whether
  217. // a connection slot is immediately available
  218. func (s *LightEthereum) prenegQuery(n *enode.Node) int {
  219. if s.vfxVersion(n) < 1 {
  220. // UDP query not supported, always try TCP connection
  221. return 1
  222. }
  223. var requests vflux.Requests
  224. requests.Add("les", vflux.CapacityQueryName, vflux.CapacityQueryReq{
  225. Bias: 180,
  226. AddTokens: []vflux.IntOrInf{{}},
  227. })
  228. replies := s.VfluxRequest(n, requests)
  229. var cqr vflux.CapacityQueryReply
  230. if replies.Get(0, &cqr) != nil || len(cqr) != 1 { // Note: Get returns an error if replies is nil
  231. return -1
  232. }
  233. if cqr[0] > 0 {
  234. return 1
  235. }
  236. return 0
  237. }
  238. type LightDummyAPI struct{}
  239. // Etherbase is the address that mining rewards will be send to
  240. func (s *LightDummyAPI) Etherbase() (common.Address, error) {
  241. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  242. }
  243. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  244. func (s *LightDummyAPI) Coinbase() (common.Address, error) {
  245. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  246. }
  247. // Hashrate returns the POW hashrate
  248. func (s *LightDummyAPI) Hashrate() hexutil.Uint {
  249. return 0
  250. }
  251. // Mining returns an indication if this node is currently mining.
  252. func (s *LightDummyAPI) Mining() bool {
  253. return false
  254. }
  255. // APIs returns the collection of RPC services the ethereum package offers.
  256. // NOTE, some of these services probably need to be moved to somewhere else.
  257. func (s *LightEthereum) APIs() []rpc.API {
  258. apis := ethapi.GetAPIs(s.ApiBackend)
  259. apis = append(apis, s.engine.APIs(s.BlockChain().HeaderChain())...)
  260. return append(apis, []rpc.API{
  261. {
  262. Namespace: "eth",
  263. Version: "1.0",
  264. Service: &LightDummyAPI{},
  265. Public: true,
  266. }, {
  267. Namespace: "eth",
  268. Version: "1.0",
  269. Service: downloader.NewPublicDownloaderAPI(s.handler.downloader, s.eventMux),
  270. Public: true,
  271. }, {
  272. Namespace: "eth",
  273. Version: "1.0",
  274. Service: filters.NewPublicFilterAPI(s.ApiBackend, true, 5*time.Minute),
  275. Public: true,
  276. }, {
  277. Namespace: "net",
  278. Version: "1.0",
  279. Service: s.netRPCService,
  280. Public: true,
  281. }, {
  282. Namespace: "les",
  283. Version: "1.0",
  284. Service: NewPrivateLightAPI(&s.lesCommons),
  285. Public: false,
  286. }, {
  287. Namespace: "vflux",
  288. Version: "1.0",
  289. Service: s.serverPool.API(),
  290. Public: false,
  291. },
  292. }...)
  293. }
  294. func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
  295. s.blockchain.ResetWithGenesisBlock(gb)
  296. }
  297. func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
  298. func (s *LightEthereum) TxPool() *light.TxPool { return s.txPool }
  299. func (s *LightEthereum) Engine() consensus.Engine { return s.engine }
  300. func (s *LightEthereum) LesVersion() int { return int(ClientProtocolVersions[0]) }
  301. func (s *LightEthereum) Downloader() *downloader.Downloader { return s.handler.downloader }
  302. func (s *LightEthereum) EventMux() *event.TypeMux { return s.eventMux }
  303. // Protocols returns all the currently configured network protocols to start.
  304. func (s *LightEthereum) Protocols() []p2p.Protocol {
  305. return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
  306. if p := s.peers.peer(id.String()); p != nil {
  307. return p.Info()
  308. }
  309. return nil
  310. }, s.serverPoolIterator)
  311. }
  312. // Start implements node.Lifecycle, starting all internal goroutines needed by the
  313. // light ethereum protocol implementation.
  314. func (s *LightEthereum) Start() error {
  315. log.Warn("Light client mode is an experimental feature")
  316. if s.udpEnabled && s.p2pServer.DiscV5 == nil {
  317. s.udpEnabled = false
  318. log.Error("Discovery v5 is not initialized")
  319. }
  320. discovery, err := s.setupDiscovery()
  321. if err != nil {
  322. return err
  323. }
  324. s.serverPool.AddSource(discovery)
  325. s.serverPool.Start()
  326. // Start bloom request workers.
  327. s.wg.Add(bloomServiceThreads)
  328. s.startBloomHandlers(params.BloomBitsBlocksClient)
  329. s.handler.start()
  330. return nil
  331. }
  332. // Stop implements node.Lifecycle, terminating all internal goroutines used by the
  333. // Ethereum protocol.
  334. func (s *LightEthereum) Stop() error {
  335. close(s.closeCh)
  336. s.serverPool.Stop()
  337. s.peers.close()
  338. s.reqDist.close()
  339. s.odr.Stop()
  340. s.relay.Stop()
  341. s.bloomIndexer.Close()
  342. s.chtIndexer.Close()
  343. s.blockchain.Stop()
  344. s.handler.stop()
  345. s.txPool.Stop()
  346. s.engine.Close()
  347. s.pruner.close()
  348. s.eventMux.Stop()
  349. rawdb.PopUncleanShutdownMarker(s.chainDb)
  350. s.chainDb.Close()
  351. s.lesDb.Close()
  352. s.wg.Wait()
  353. log.Info("Light ethereum stopped")
  354. return nil
  355. }