client.go 13 KB

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