backend.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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/types"
  28. "github.com/ethereum/go-ethereum/eth"
  29. "github.com/ethereum/go-ethereum/eth/downloader"
  30. "github.com/ethereum/go-ethereum/eth/filters"
  31. "github.com/ethereum/go-ethereum/eth/gasprice"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/light"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/node"
  38. "github.com/ethereum/go-ethereum/p2p"
  39. "github.com/ethereum/go-ethereum/p2p/discv5"
  40. "github.com/ethereum/go-ethereum/params"
  41. rpc "github.com/ethereum/go-ethereum/rpc"
  42. )
  43. type LightEthereum struct {
  44. odr *LesOdr
  45. relay *LesTxRelay
  46. chainConfig *params.ChainConfig
  47. // Channel for shutting down the service
  48. shutdownChan chan bool
  49. // Handlers
  50. peers *peerSet
  51. txPool *light.TxPool
  52. blockchain *light.LightChain
  53. protocolManager *ProtocolManager
  54. serverPool *serverPool
  55. reqDist *requestDistributor
  56. retriever *retrieveManager
  57. // DB interfaces
  58. chainDb ethdb.Database // Block chain database
  59. ApiBackend *LesApiBackend
  60. eventMux *event.TypeMux
  61. engine consensus.Engine
  62. accountManager *accounts.Manager
  63. networkId uint64
  64. netRPCService *ethapi.PublicNetAPI
  65. wg sync.WaitGroup
  66. }
  67. func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
  68. chainDb, err := eth.CreateDB(ctx, config, "lightchaindata")
  69. if err != nil {
  70. return nil, err
  71. }
  72. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  73. if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
  74. return nil, genesisErr
  75. }
  76. log.Info("Initialised chain configuration", "config", chainConfig)
  77. peers := newPeerSet()
  78. quitSync := make(chan struct{})
  79. eth := &LightEthereum{
  80. chainConfig: chainConfig,
  81. chainDb: chainDb,
  82. eventMux: ctx.EventMux,
  83. peers: peers,
  84. reqDist: newRequestDistributor(peers, quitSync),
  85. accountManager: ctx.AccountManager,
  86. engine: eth.CreateConsensusEngine(ctx, config, chainConfig, chainDb),
  87. shutdownChan: make(chan bool),
  88. networkId: config.NetworkId,
  89. }
  90. eth.relay = NewLesTxRelay(peers, eth.reqDist)
  91. eth.serverPool = newServerPool(chainDb, quitSync, &eth.wg)
  92. eth.retriever = newRetrieveManager(peers, eth.reqDist, eth.serverPool)
  93. eth.odr = NewLesOdr(chainDb, eth.retriever)
  94. if eth.blockchain, err = light.NewLightChain(eth.odr, eth.chainConfig, eth.engine); err != nil {
  95. return nil, err
  96. }
  97. // Rewind the chain in case of an incompatible config upgrade.
  98. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  99. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  100. eth.blockchain.SetHead(compat.RewindTo)
  101. core.WriteChainConfig(chainDb, genesisHash, chainConfig)
  102. }
  103. eth.txPool = light.NewTxPool(eth.chainConfig, eth.blockchain, eth.relay)
  104. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, true, config.NetworkId, eth.eventMux, eth.engine, eth.peers, eth.blockchain, nil, chainDb, eth.odr, eth.relay, quitSync, &eth.wg); err != nil {
  105. return nil, err
  106. }
  107. eth.ApiBackend = &LesApiBackend{eth, nil}
  108. gpoParams := config.GPO
  109. if gpoParams.Default == nil {
  110. gpoParams.Default = config.GasPrice
  111. }
  112. eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams)
  113. return eth, nil
  114. }
  115. func lesTopic(genesisHash common.Hash) discv5.Topic {
  116. return discv5.Topic("LES@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
  117. }
  118. type LightDummyAPI struct{}
  119. // Etherbase is the address that mining rewards will be send to
  120. func (s *LightDummyAPI) Etherbase() (common.Address, error) {
  121. return common.Address{}, fmt.Errorf("not supported")
  122. }
  123. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  124. func (s *LightDummyAPI) Coinbase() (common.Address, error) {
  125. return common.Address{}, fmt.Errorf("not supported")
  126. }
  127. // Hashrate returns the POW hashrate
  128. func (s *LightDummyAPI) Hashrate() hexutil.Uint {
  129. return 0
  130. }
  131. // Mining returns an indication if this node is currently mining.
  132. func (s *LightDummyAPI) Mining() bool {
  133. return false
  134. }
  135. // APIs returns the collection of RPC services the ethereum package offers.
  136. // NOTE, some of these services probably need to be moved to somewhere else.
  137. func (s *LightEthereum) APIs() []rpc.API {
  138. return append(ethapi.GetAPIs(s.ApiBackend), []rpc.API{
  139. {
  140. Namespace: "eth",
  141. Version: "1.0",
  142. Service: &LightDummyAPI{},
  143. Public: true,
  144. }, {
  145. Namespace: "eth",
  146. Version: "1.0",
  147. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  148. Public: true,
  149. }, {
  150. Namespace: "eth",
  151. Version: "1.0",
  152. Service: filters.NewPublicFilterAPI(s.ApiBackend, true),
  153. Public: true,
  154. }, {
  155. Namespace: "net",
  156. Version: "1.0",
  157. Service: s.netRPCService,
  158. Public: true,
  159. },
  160. }...)
  161. }
  162. func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
  163. s.blockchain.ResetWithGenesisBlock(gb)
  164. }
  165. func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
  166. func (s *LightEthereum) TxPool() *light.TxPool { return s.txPool }
  167. func (s *LightEthereum) Engine() consensus.Engine { return s.engine }
  168. func (s *LightEthereum) LesVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  169. func (s *LightEthereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  170. func (s *LightEthereum) EventMux() *event.TypeMux { return s.eventMux }
  171. // Protocols implements node.Service, returning all the currently configured
  172. // network protocols to start.
  173. func (s *LightEthereum) Protocols() []p2p.Protocol {
  174. return s.protocolManager.SubProtocols
  175. }
  176. // Start implements node.Service, starting all internal goroutines needed by the
  177. // Ethereum protocol implementation.
  178. func (s *LightEthereum) Start(srvr *p2p.Server) error {
  179. log.Warn("Light client mode is an experimental feature")
  180. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId)
  181. s.serverPool.start(srvr, lesTopic(s.blockchain.Genesis().Hash()))
  182. s.protocolManager.Start()
  183. return nil
  184. }
  185. // Stop implements node.Service, terminating all internal goroutines used by the
  186. // Ethereum protocol.
  187. func (s *LightEthereum) Stop() error {
  188. s.odr.Stop()
  189. s.blockchain.Stop()
  190. s.protocolManager.Stop()
  191. s.txPool.Stop()
  192. s.eventMux.Stop()
  193. time.Sleep(time.Millisecond * 200)
  194. s.chainDb.Close()
  195. close(s.shutdownChan)
  196. return nil
  197. }