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