client.go 12 KB

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