client.go 11 KB

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