backend.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/accounts"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/common/mclock"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/bloombits"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/eth"
  32. "github.com/ethereum/go-ethereum/eth/downloader"
  33. "github.com/ethereum/go-ethereum/eth/filters"
  34. "github.com/ethereum/go-ethereum/eth/gasprice"
  35. "github.com/ethereum/go-ethereum/event"
  36. "github.com/ethereum/go-ethereum/internal/ethapi"
  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/discv5"
  42. "github.com/ethereum/go-ethereum/params"
  43. rpc "github.com/ethereum/go-ethereum/rpc"
  44. )
  45. type LightEthereum struct {
  46. lesCommons
  47. odr *LesOdr
  48. relay *LesTxRelay
  49. chainConfig *params.ChainConfig
  50. // Channel for shutting down the service
  51. shutdownChan chan bool
  52. // Handlers
  53. peers *peerSet
  54. txPool *light.TxPool
  55. blockchain *light.LightChain
  56. serverPool *serverPool
  57. reqDist *requestDistributor
  58. retriever *retrieveManager
  59. bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
  60. bloomIndexer *core.ChainIndexer
  61. ApiBackend *LesApiBackend
  62. eventMux *event.TypeMux
  63. engine consensus.Engine
  64. accountManager *accounts.Manager
  65. networkId uint64
  66. netRPCService *ethapi.PublicNetAPI
  67. wg sync.WaitGroup
  68. }
  69. func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
  70. chainDb, err := ctx.OpenDatabase("lightchaindata", config.DatabaseCache, config.DatabaseHandles, "eth/db/chaindata/")
  71. if err != nil {
  72. return nil, err
  73. }
  74. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.ConstantinopleOverride)
  75. if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
  76. return nil, genesisErr
  77. }
  78. log.Info("Initialised chain configuration", "config", chainConfig)
  79. peers := newPeerSet()
  80. quitSync := make(chan struct{})
  81. leth := &LightEthereum{
  82. lesCommons: lesCommons{
  83. chainDb: chainDb,
  84. config: config,
  85. iConfig: light.DefaultClientIndexerConfig,
  86. },
  87. chainConfig: chainConfig,
  88. eventMux: ctx.EventMux,
  89. peers: peers,
  90. reqDist: newRequestDistributor(peers, quitSync, &mclock.System{}),
  91. accountManager: ctx.AccountManager,
  92. engine: eth.CreateConsensusEngine(ctx, chainConfig, &config.Ethash, nil, false, chainDb),
  93. shutdownChan: make(chan bool),
  94. networkId: config.NetworkId,
  95. bloomRequests: make(chan chan *bloombits.Retrieval),
  96. bloomIndexer: eth.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
  97. }
  98. var trustedNodes []string
  99. if leth.config.ULC != nil {
  100. trustedNodes = leth.config.ULC.TrustedServers
  101. }
  102. leth.relay = NewLesTxRelay(peers, leth.reqDist)
  103. leth.serverPool = newServerPool(chainDb, quitSync, &leth.wg, trustedNodes)
  104. leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool)
  105. leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.retriever)
  106. leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequencyClient, params.HelperTrieConfirmations)
  107. leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency)
  108. leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
  109. // Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
  110. // indexers already set but not started yet
  111. if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine); err != nil {
  112. return nil, err
  113. }
  114. // Note: AddChildIndexer starts the update process for the child
  115. leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
  116. leth.chtIndexer.Start(leth.blockchain)
  117. leth.bloomIndexer.Start(leth.blockchain)
  118. // Rewind the chain in case of an incompatible config upgrade.
  119. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  120. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  121. leth.blockchain.SetHead(compat.RewindTo)
  122. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  123. }
  124. leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
  125. if leth.protocolManager, err = NewProtocolManager(
  126. leth.chainConfig,
  127. light.DefaultClientIndexerConfig,
  128. true,
  129. config.NetworkId,
  130. leth.eventMux,
  131. leth.engine,
  132. leth.peers,
  133. leth.blockchain,
  134. nil,
  135. chainDb,
  136. leth.odr,
  137. leth.relay,
  138. leth.serverPool,
  139. quitSync,
  140. &leth.wg,
  141. config.ULC); err != nil {
  142. return nil, err
  143. }
  144. if leth.protocolManager.isULCEnabled() {
  145. log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.protocolManager.ulc.trustedKeys), "minTrustedFraction", leth.protocolManager.ulc.minTrustedFraction)
  146. leth.blockchain.DisableCheckFreq()
  147. }
  148. leth.ApiBackend = &LesApiBackend{ctx.ExtRPCEnabled(), leth, nil}
  149. gpoParams := config.GPO
  150. if gpoParams.Default == nil {
  151. gpoParams.Default = config.MinerGasPrice
  152. }
  153. leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
  154. return leth, nil
  155. }
  156. func lesTopic(genesisHash common.Hash, protocolVersion uint) discv5.Topic {
  157. var name string
  158. switch protocolVersion {
  159. case lpv2:
  160. name = "LES2"
  161. default:
  162. panic(nil)
  163. }
  164. return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
  165. }
  166. type LightDummyAPI struct{}
  167. // Etherbase is the address that mining rewards will be send to
  168. func (s *LightDummyAPI) Etherbase() (common.Address, error) {
  169. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  170. }
  171. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  172. func (s *LightDummyAPI) Coinbase() (common.Address, error) {
  173. return common.Address{}, fmt.Errorf("mining is not supported in light mode")
  174. }
  175. // Hashrate returns the POW hashrate
  176. func (s *LightDummyAPI) Hashrate() hexutil.Uint {
  177. return 0
  178. }
  179. // Mining returns an indication if this node is currently mining.
  180. func (s *LightDummyAPI) Mining() bool {
  181. return false
  182. }
  183. // APIs returns the collection of RPC services the ethereum package offers.
  184. // NOTE, some of these services probably need to be moved to somewhere else.
  185. func (s *LightEthereum) APIs() []rpc.API {
  186. return append(ethapi.GetAPIs(s.ApiBackend), []rpc.API{
  187. {
  188. Namespace: "eth",
  189. Version: "1.0",
  190. Service: &LightDummyAPI{},
  191. Public: true,
  192. }, {
  193. Namespace: "eth",
  194. Version: "1.0",
  195. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  196. Public: true,
  197. }, {
  198. Namespace: "eth",
  199. Version: "1.0",
  200. Service: filters.NewPublicFilterAPI(s.ApiBackend, true),
  201. Public: true,
  202. }, {
  203. Namespace: "net",
  204. Version: "1.0",
  205. Service: s.netRPCService,
  206. Public: true,
  207. },
  208. }...)
  209. }
  210. func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
  211. s.blockchain.ResetWithGenesisBlock(gb)
  212. }
  213. func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
  214. func (s *LightEthereum) TxPool() *light.TxPool { return s.txPool }
  215. func (s *LightEthereum) Engine() consensus.Engine { return s.engine }
  216. func (s *LightEthereum) LesVersion() int { return int(ClientProtocolVersions[0]) }
  217. func (s *LightEthereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  218. func (s *LightEthereum) EventMux() *event.TypeMux { return s.eventMux }
  219. // Protocols implements node.Service, returning all the currently configured
  220. // network protocols to start.
  221. func (s *LightEthereum) Protocols() []p2p.Protocol {
  222. return s.makeProtocols(ClientProtocolVersions)
  223. }
  224. // Start implements node.Service, starting all internal goroutines needed by the
  225. // Ethereum protocol implementation.
  226. func (s *LightEthereum) Start(srvr *p2p.Server) error {
  227. log.Warn("Light client mode is an experimental feature")
  228. s.startBloomHandlers(params.BloomBitsBlocksClient)
  229. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId)
  230. // clients are searching for the first advertised protocol in the list
  231. protocolVersion := AdvertiseProtocolVersions[0]
  232. s.serverPool.start(srvr, lesTopic(s.blockchain.Genesis().Hash(), protocolVersion))
  233. s.protocolManager.Start(s.config.LightPeers)
  234. return nil
  235. }
  236. // Stop implements node.Service, terminating all internal goroutines used by the
  237. // Ethereum protocol.
  238. func (s *LightEthereum) Stop() error {
  239. s.odr.Stop()
  240. s.bloomIndexer.Close()
  241. s.chtIndexer.Close()
  242. s.blockchain.Stop()
  243. s.protocolManager.Stop()
  244. s.txPool.Stop()
  245. s.engine.Close()
  246. s.eventMux.Stop()
  247. time.Sleep(time.Millisecond * 200)
  248. s.chainDb.Close()
  249. close(s.shutdownChan)
  250. return nil
  251. }