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