github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/les/client.go (about)

     1  // Copyright 2019 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  	"strings"
    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/ethconfig"
    35  	"github.com/ethereum/go-ethereum/eth/gasprice"
    36  	"github.com/ethereum/go-ethereum/event"
    37  	"github.com/ethereum/go-ethereum/internal/ethapi"
    38  	"github.com/ethereum/go-ethereum/internal/shutdowncheck"
    39  	"github.com/ethereum/go-ethereum/les/downloader"
    40  	"github.com/ethereum/go-ethereum/les/vflux"
    41  	vfc "github.com/ethereum/go-ethereum/les/vflux/client"
    42  	"github.com/ethereum/go-ethereum/light"
    43  	"github.com/ethereum/go-ethereum/log"
    44  	"github.com/ethereum/go-ethereum/node"
    45  	"github.com/ethereum/go-ethereum/p2p"
    46  	"github.com/ethereum/go-ethereum/p2p/enode"
    47  	"github.com/ethereum/go-ethereum/p2p/enr"
    48  	"github.com/ethereum/go-ethereum/params"
    49  	"github.com/ethereum/go-ethereum/rlp"
    50  	"github.com/ethereum/go-ethereum/rpc"
    51  )
    52  
    53  type LightEthereum struct {
    54  	lesCommons
    55  
    56  	peers              *serverPeerSet
    57  	reqDist            *requestDistributor
    58  	retriever          *retrieveManager
    59  	odr                *LesOdr
    60  	relay              *lesTxRelay
    61  	handler            *clientHandler
    62  	txPool             *light.TxPool
    63  	blockchain         *light.LightChain
    64  	serverPool         *vfc.ServerPool
    65  	serverPoolIterator enode.Iterator
    66  	pruner             *pruner
    67  	merger             *consensus.Merger
    68  
    69  	bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
    70  	bloomIndexer  *core.ChainIndexer             // Bloom indexer operating during block imports
    71  
    72  	ApiBackend     *LesApiBackend
    73  	eventMux       *event.TypeMux
    74  	engine         consensus.Engine
    75  	accountManager *accounts.Manager
    76  	netRPCService  *ethapi.NetAPI
    77  
    78  	p2pServer  *p2p.Server
    79  	p2pConfig  *p2p.Config
    80  	udpEnabled bool
    81  
    82  	shutdownTracker *shutdowncheck.ShutdownTracker // Tracks if and when the node has shutdown ungracefully
    83  }
    84  
    85  // New creates an instance of the light client.
    86  func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
    87  	chainDb, err := stack.OpenDatabase("lightchaindata", config.DatabaseCache, config.DatabaseHandles, "eth/db/chaindata/", false)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	lesDb, err := stack.OpenDatabase("les.client", 0, 0, "eth/db/lesclient/", false)
    92  	if err != nil {
    93  		return nil, err
    94  	}
    95  	var overrides core.ChainOverrides
    96  	if config.OverrideTerminalTotalDifficulty != nil {
    97  		overrides.OverrideTerminalTotalDifficulty = config.OverrideTerminalTotalDifficulty
    98  	}
    99  	if config.OverrideTerminalTotalDifficultyPassed != nil {
   100  		overrides.OverrideTerminalTotalDifficultyPassed = config.OverrideTerminalTotalDifficultyPassed
   101  	}
   102  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, &overrides)
   103  	if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
   104  		return nil, genesisErr
   105  	}
   106  	log.Info("")
   107  	log.Info(strings.Repeat("-", 153))
   108  	for _, line := range strings.Split(chainConfig.Description(), "\n") {
   109  		log.Info(line)
   110  	}
   111  	log.Info(strings.Repeat("-", 153))
   112  	log.Info("")
   113  
   114  	peers := newServerPeerSet()
   115  	merger := consensus.NewMerger(chainDb)
   116  	leth := &LightEthereum{
   117  		lesCommons: lesCommons{
   118  			genesis:     genesisHash,
   119  			config:      config,
   120  			chainConfig: chainConfig,
   121  			iConfig:     light.DefaultClientIndexerConfig,
   122  			chainDb:     chainDb,
   123  			lesDb:       lesDb,
   124  			closeCh:     make(chan struct{}),
   125  		},
   126  		peers:           peers,
   127  		eventMux:        stack.EventMux(),
   128  		reqDist:         newRequestDistributor(peers, &mclock.System{}),
   129  		accountManager:  stack.AccountManager(),
   130  		merger:          merger,
   131  		engine:          ethconfig.CreateConsensusEngine(stack, &config.Ethash, chainConfig.Clique, nil, false, chainDb),
   132  		bloomRequests:   make(chan chan *bloombits.Retrieval),
   133  		bloomIndexer:    core.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
   134  		p2pServer:       stack.Server(),
   135  		p2pConfig:       &stack.Config().P2P,
   136  		udpEnabled:      stack.Config().P2P.DiscoveryV5,
   137  		shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb),
   138  	}
   139  
   140  	var prenegQuery vfc.QueryFunc
   141  	if leth.udpEnabled {
   142  		prenegQuery = leth.prenegQuery
   143  	}
   144  	leth.serverPool, leth.serverPoolIterator = vfc.NewServerPool(lesDb, []byte("serverpool:"), time.Second, prenegQuery, &mclock.System{}, config.UltraLightServers, requestList)
   145  	leth.serverPool.AddMetrics(suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge, sessionValueMeter, serverDialedMeter)
   146  
   147  	leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool.GetTimeout)
   148  	leth.relay = newLesTxRelay(peers, leth.retriever)
   149  
   150  	leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.peers, leth.retriever)
   151  	leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations, config.LightNoPrune)
   152  	leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency, config.LightNoPrune)
   153  	leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
   154  
   155  	checkpoint := config.Checkpoint
   156  	if checkpoint == nil {
   157  		checkpoint = params.TrustedCheckpoints[genesisHash]
   158  	}
   159  	// Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
   160  	// indexers already set but not started yet
   161  	if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil {
   162  		return nil, err
   163  	}
   164  	leth.chainReader = leth.blockchain
   165  	leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
   166  
   167  	// Set up checkpoint oracle.
   168  	leth.oracle = leth.setupOracle(stack, genesisHash, config)
   169  
   170  	// Note: AddChildIndexer starts the update process for the child
   171  	leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
   172  	leth.chtIndexer.Start(leth.blockchain)
   173  	leth.bloomIndexer.Start(leth.blockchain)
   174  
   175  	// Start a light chain pruner to delete useless historical data.
   176  	leth.pruner = newPruner(chainDb, leth.chtIndexer, leth.bloomTrieIndexer)
   177  
   178  	// Rewind the chain in case of an incompatible config upgrade.
   179  	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
   180  		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
   181  		leth.blockchain.SetHead(compat.RewindTo)
   182  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   183  	}
   184  
   185  	leth.ApiBackend = &LesApiBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, leth, nil}
   186  	gpoParams := config.GPO
   187  	if gpoParams.Default == nil {
   188  		gpoParams.Default = config.Miner.GasPrice
   189  	}
   190  	leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
   191  
   192  	leth.handler = newClientHandler(config.UltraLightServers, config.UltraLightFraction, checkpoint, leth)
   193  	if leth.handler.ulc != nil {
   194  		log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.handler.ulc.keys), "minTrustedFraction", leth.handler.ulc.fraction)
   195  		leth.blockchain.DisableCheckFreq()
   196  	}
   197  
   198  	leth.netRPCService = ethapi.NewNetAPI(leth.p2pServer, leth.config.NetworkId)
   199  
   200  	// Register the backend on the node
   201  	stack.RegisterAPIs(leth.APIs())
   202  	stack.RegisterProtocols(leth.Protocols())
   203  	stack.RegisterLifecycle(leth)
   204  
   205  	// Successful startup; push a marker and check previous unclean shutdowns.
   206  	leth.shutdownTracker.MarkStartup()
   207  
   208  	return leth, nil
   209  }
   210  
   211  // VfluxRequest sends a batch of requests to the given node through discv5 UDP TalkRequest and returns the responses
   212  func (s *LightEthereum) VfluxRequest(n *enode.Node, reqs vflux.Requests) vflux.Replies {
   213  	if !s.udpEnabled {
   214  		return nil
   215  	}
   216  	reqsEnc, _ := rlp.EncodeToBytes(&reqs)
   217  	repliesEnc, _ := s.p2pServer.DiscV5.TalkRequest(s.serverPool.DialNode(n), "vfx", reqsEnc)
   218  	var replies vflux.Replies
   219  	if len(repliesEnc) == 0 || rlp.DecodeBytes(repliesEnc, &replies) != nil {
   220  		return nil
   221  	}
   222  	return replies
   223  }
   224  
   225  // vfxVersion returns the version number of the "les" service subdomain of the vflux UDP
   226  // service, as advertised in the ENR record
   227  func (s *LightEthereum) vfxVersion(n *enode.Node) uint {
   228  	if n.Seq() == 0 {
   229  		var err error
   230  		if !s.udpEnabled {
   231  			return 0
   232  		}
   233  		if n, err = s.p2pServer.DiscV5.RequestENR(n); n != nil && err == nil && n.Seq() != 0 {
   234  			s.serverPool.Persist(n)
   235  		} else {
   236  			return 0
   237  		}
   238  	}
   239  
   240  	var les []rlp.RawValue
   241  	if err := n.Load(enr.WithEntry("les", &les)); err != nil || len(les) < 1 {
   242  		return 0
   243  	}
   244  	var version uint
   245  	rlp.DecodeBytes(les[0], &version) // Ignore additional fields (for forward compatibility).
   246  	return version
   247  }
   248  
   249  // prenegQuery sends a capacity query to the given server node to determine whether
   250  // a connection slot is immediately available
   251  func (s *LightEthereum) prenegQuery(n *enode.Node) int {
   252  	if s.vfxVersion(n) < 1 {
   253  		// UDP query not supported, always try TCP connection
   254  		return 1
   255  	}
   256  
   257  	var requests vflux.Requests
   258  	requests.Add("les", vflux.CapacityQueryName, vflux.CapacityQueryReq{
   259  		Bias:      180,
   260  		AddTokens: []vflux.IntOrInf{{}},
   261  	})
   262  	replies := s.VfluxRequest(n, requests)
   263  	var cqr vflux.CapacityQueryReply
   264  	if replies.Get(0, &cqr) != nil || len(cqr) != 1 { // Note: Get returns an error if replies is nil
   265  		return -1
   266  	}
   267  	if cqr[0] > 0 {
   268  		return 1
   269  	}
   270  	return 0
   271  }
   272  
   273  type LightDummyAPI struct{}
   274  
   275  // Etherbase is the address that mining rewards will be send to
   276  func (s *LightDummyAPI) Etherbase() (common.Address, error) {
   277  	return common.Address{}, fmt.Errorf("mining is not supported in light mode")
   278  }
   279  
   280  // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
   281  func (s *LightDummyAPI) Coinbase() (common.Address, error) {
   282  	return common.Address{}, fmt.Errorf("mining is not supported in light mode")
   283  }
   284  
   285  // Hashrate returns the POW hashrate
   286  func (s *LightDummyAPI) Hashrate() hexutil.Uint {
   287  	return 0
   288  }
   289  
   290  // Mining returns an indication if this node is currently mining.
   291  func (s *LightDummyAPI) Mining() bool {
   292  	return false
   293  }
   294  
   295  // APIs returns the collection of RPC services the ethereum package offers.
   296  // NOTE, some of these services probably need to be moved to somewhere else.
   297  func (s *LightEthereum) APIs() []rpc.API {
   298  	apis := ethapi.GetAPIs(s.ApiBackend)
   299  	apis = append(apis, s.engine.APIs(s.BlockChain().HeaderChain())...)
   300  	return append(apis, []rpc.API{
   301  		{
   302  			Namespace: "eth",
   303  			Service:   &LightDummyAPI{},
   304  		}, {
   305  			Namespace: "eth",
   306  			Service:   downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux),
   307  		}, {
   308  			Namespace: "net",
   309  			Service:   s.netRPCService,
   310  		}, {
   311  			Namespace: "les",
   312  			Service:   NewLightAPI(&s.lesCommons),
   313  		}, {
   314  			Namespace: "vflux",
   315  			Service:   s.serverPool.API(),
   316  		},
   317  	}...)
   318  }
   319  
   320  func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
   321  	s.blockchain.ResetWithGenesisBlock(gb)
   322  }
   323  
   324  func (s *LightEthereum) BlockChain() *light.LightChain      { return s.blockchain }
   325  func (s *LightEthereum) TxPool() *light.TxPool              { return s.txPool }
   326  func (s *LightEthereum) Engine() consensus.Engine           { return s.engine }
   327  func (s *LightEthereum) LesVersion() int                    { return int(ClientProtocolVersions[0]) }
   328  func (s *LightEthereum) Downloader() *downloader.Downloader { return s.handler.downloader }
   329  func (s *LightEthereum) EventMux() *event.TypeMux           { return s.eventMux }
   330  func (s *LightEthereum) Merger() *consensus.Merger          { return s.merger }
   331  
   332  // Protocols returns all the currently configured network protocols to start.
   333  func (s *LightEthereum) Protocols() []p2p.Protocol {
   334  	return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
   335  		if p := s.peers.peer(id.String()); p != nil {
   336  			return p.Info()
   337  		}
   338  		return nil
   339  	}, s.serverPoolIterator)
   340  }
   341  
   342  // Start implements node.Lifecycle, starting all internal goroutines needed by the
   343  // light ethereum protocol implementation.
   344  func (s *LightEthereum) Start() error {
   345  	log.Warn("Light client mode is an experimental feature")
   346  
   347  	// Regularly update shutdown marker
   348  	s.shutdownTracker.Start()
   349  
   350  	if s.udpEnabled && s.p2pServer.DiscV5 == nil {
   351  		s.udpEnabled = false
   352  		log.Error("Discovery v5 is not initialized")
   353  	}
   354  	discovery, err := s.setupDiscovery()
   355  	if err != nil {
   356  		return err
   357  	}
   358  	s.serverPool.AddSource(discovery)
   359  	s.serverPool.Start()
   360  	// Start bloom request workers.
   361  	s.wg.Add(bloomServiceThreads)
   362  	s.startBloomHandlers(params.BloomBitsBlocksClient)
   363  	s.handler.start()
   364  
   365  	return nil
   366  }
   367  
   368  // Stop implements node.Lifecycle, terminating all internal goroutines used by the
   369  // Ethereum protocol.
   370  func (s *LightEthereum) Stop() error {
   371  	close(s.closeCh)
   372  	s.serverPool.Stop()
   373  	s.peers.close()
   374  	s.reqDist.close()
   375  	s.odr.Stop()
   376  	s.relay.Stop()
   377  	s.bloomIndexer.Close()
   378  	s.chtIndexer.Close()
   379  	s.blockchain.Stop()
   380  	s.handler.stop()
   381  	s.txPool.Stop()
   382  	s.engine.Close()
   383  	s.pruner.close()
   384  	s.eventMux.Stop()
   385  	// Clean shutdown marker as the last thing before closing db
   386  	s.shutdownTracker.Stop()
   387  
   388  	s.chainDb.Close()
   389  	s.lesDb.Close()
   390  	s.wg.Wait()
   391  	log.Info("Light ethereum stopped")
   392  	return nil
   393  }