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