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