backend.go 8.7 KB

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