backend.go 9.0 KB

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