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