github.com/theQRL/go-zond@v0.1.1/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  	"errors"
    22  	"strings"
    23  	"time"
    24  
    25  	"github.com/theQRL/go-zond/accounts"
    26  	"github.com/theQRL/go-zond/common"
    27  	"github.com/theQRL/go-zond/common/hexutil"
    28  	"github.com/theQRL/go-zond/common/mclock"
    29  	"github.com/theQRL/go-zond/consensus"
    30  	"github.com/theQRL/go-zond/core"
    31  	"github.com/theQRL/go-zond/core/bloombits"
    32  	"github.com/theQRL/go-zond/core/rawdb"
    33  	"github.com/theQRL/go-zond/core/types"
    34  	"github.com/theQRL/go-zond/event"
    35  	"github.com/theQRL/go-zond/internal/ethapi"
    36  	"github.com/theQRL/go-zond/internal/shutdowncheck"
    37  	"github.com/theQRL/go-zond/les/vflux"
    38  	vfc "github.com/theQRL/go-zond/les/vflux/client"
    39  	"github.com/theQRL/go-zond/light"
    40  	"github.com/theQRL/go-zond/log"
    41  	"github.com/theQRL/go-zond/node"
    42  	"github.com/theQRL/go-zond/p2p"
    43  	"github.com/theQRL/go-zond/p2p/enode"
    44  	"github.com/theQRL/go-zond/p2p/enr"
    45  	"github.com/theQRL/go-zond/params"
    46  	"github.com/theQRL/go-zond/rlp"
    47  	"github.com/theQRL/go-zond/rpc"
    48  	"github.com/theQRL/go-zond/trie"
    49  	"github.com/theQRL/go-zond/zond/ethconfig"
    50  	"github.com/theQRL/go-zond/zond/gasprice"
    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  	merger             *consensus.Merger
    67  
    68  	bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
    69  	bloomIndexer  *core.ChainIndexer             // Bloom indexer operating during block imports
    70  
    71  	ApiBackend     *LesApiBackend
    72  	eventMux       *event.TypeMux
    73  	engine         consensus.Engine
    74  	accountManager *accounts.Manager
    75  	netRPCService  *ethapi.NetAPI
    76  
    77  	p2pServer  *p2p.Server
    78  	p2pConfig  *p2p.Config
    79  	udpEnabled bool
    80  
    81  	shutdownTracker *shutdowncheck.ShutdownTracker // Tracks if and when the node has shutdown ungracefully
    82  }
    83  
    84  // New creates an instance of the light client.
    85  func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
    86  	chainDb, err := stack.OpenDatabase("lightchaindata", config.DatabaseCache, config.DatabaseHandles, "zond/db/chaindata/", false)
    87  	if err != nil {
    88  		return nil, err
    89  	}
    90  	lesDb, err := stack.OpenDatabase("les.client", 0, 0, "zond/db/lesclient/", false)
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  	var overrides core.ChainOverrides
    95  	if config.OverrideCancun != nil {
    96  		overrides.OverrideCancun = config.OverrideCancun
    97  	}
    98  	if config.OverrideVerkle != nil {
    99  		overrides.OverrideVerkle = config.OverrideVerkle
   100  	}
   101  	triedb := trie.NewDatabase(chainDb, trie.HashDefaults)
   102  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, triedb, config.Genesis, &overrides)
   103  	if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
   104  		return nil, genesisErr
   105  	}
   106  	engine, err := ethconfig.CreateConsensusEngine(chainConfig, chainDb)
   107  	if err != nil {
   108  		return nil, err
   109  	}
   110  	log.Info("")
   111  	log.Info(strings.Repeat("-", 153))
   112  	for _, line := range strings.Split(chainConfig.Description(), "\n") {
   113  		log.Info(line)
   114  	}
   115  	log.Info(strings.Repeat("-", 153))
   116  	log.Info("")
   117  
   118  	peers := newServerPeerSet()
   119  	merger := consensus.NewMerger(chainDb)
   120  	leth := &LightEthereum{
   121  		lesCommons: lesCommons{
   122  			genesis:     genesisHash,
   123  			config:      config,
   124  			chainConfig: chainConfig,
   125  			iConfig:     light.DefaultClientIndexerConfig,
   126  			chainDb:     chainDb,
   127  			lesDb:       lesDb,
   128  			closeCh:     make(chan struct{}),
   129  		},
   130  		peers:           peers,
   131  		eventMux:        stack.EventMux(),
   132  		reqDist:         newRequestDistributor(peers, &mclock.System{}),
   133  		accountManager:  stack.AccountManager(),
   134  		merger:          merger,
   135  		engine:          engine,
   136  		bloomRequests:   make(chan chan *bloombits.Retrieval),
   137  		bloomIndexer:    core.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
   138  		p2pServer:       stack.Server(),
   139  		p2pConfig:       &stack.Config().P2P,
   140  		udpEnabled:      stack.Config().P2P.DiscoveryV5,
   141  		shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb),
   142  	}
   143  
   144  	var prenegQuery vfc.QueryFunc
   145  	if leth.udpEnabled {
   146  		prenegQuery = leth.prenegQuery
   147  	}
   148  	leth.serverPool, leth.serverPoolIterator = vfc.NewServerPool(lesDb, []byte("serverpool:"), time.Second, prenegQuery, &mclock.System{}, nil, requestList)
   149  	leth.serverPool.AddMetrics(suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge, sessionValueMeter, serverDialedMeter)
   150  
   151  	leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool.GetTimeout)
   152  	leth.relay = newLesTxRelay(peers, leth.retriever)
   153  
   154  	leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.peers, leth.retriever)
   155  	leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations, config.LightNoPrune)
   156  	leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency, config.LightNoPrune)
   157  	leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
   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); 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  	// Note: AddChildIndexer starts the update process for the child
   168  	leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
   169  	leth.chtIndexer.Start(leth.blockchain)
   170  	leth.bloomIndexer.Start(leth.blockchain)
   171  
   172  	// Rewind the chain in case of an incompatible config upgrade.
   173  	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
   174  		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
   175  		if compat.RewindToTime > 0 {
   176  			leth.blockchain.SetHeadWithTimestamp(compat.RewindToTime)
   177  		} else {
   178  			leth.blockchain.SetHead(compat.RewindToBlock)
   179  		}
   180  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   181  	}
   182  
   183  	leth.ApiBackend = &LesApiBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, leth, nil}
   184  	gpoParams := config.GPO
   185  	if gpoParams.Default == nil {
   186  		gpoParams.Default = config.Miner.GasPrice
   187  	}
   188  	leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
   189  
   190  	leth.handler = newClientHandler(leth)
   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 sent to
   269  func (s *LightDummyAPI) Etherbase() (common.Address, error) {
   270  	return common.Address{}, errors.New("mining is not supported in light mode")
   271  }
   272  
   273  // Coinbase is the address that mining rewards will be sent to (alias for Etherbase)
   274  func (s *LightDummyAPI) Coinbase() (common.Address, error) {
   275  	return common.Address{}, errors.New("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: "zond",
   296  			Service:   &LightDummyAPI{},
   297  		}, {
   298  			Namespace: "net",
   299  			Service:   s.netRPCService,
   300  		}, {
   301  			Namespace: "vflux",
   302  			Service:   s.serverPool.API(),
   303  		},
   304  	}...)
   305  }
   306  
   307  func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
   308  	s.blockchain.ResetWithGenesisBlock(gb)
   309  }
   310  
   311  func (s *LightEthereum) BlockChain() *light.LightChain { return s.blockchain }
   312  func (s *LightEthereum) TxPool() *light.TxPool         { return s.txPool }
   313  func (s *LightEthereum) Engine() consensus.Engine      { return s.engine }
   314  func (s *LightEthereum) LesVersion() int               { return int(ClientProtocolVersions[0]) }
   315  func (s *LightEthereum) EventMux() *event.TypeMux      { return s.eventMux }
   316  func (s *LightEthereum) Merger() *consensus.Merger     { return s.merger }
   317  
   318  // Protocols returns all the currently configured network protocols to start.
   319  func (s *LightEthereum) Protocols() []p2p.Protocol {
   320  	return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
   321  		if p := s.peers.peer(id.String()); p != nil {
   322  			return p.Info()
   323  		}
   324  		return nil
   325  	}, s.serverPoolIterator)
   326  }
   327  
   328  // Start implements node.Lifecycle, starting all internal goroutines needed by the
   329  // light ethereum protocol implementation.
   330  func (s *LightEthereum) Start() error {
   331  	log.Warn("Light client mode is an experimental feature")
   332  
   333  	// Regularly update shutdown marker
   334  	s.shutdownTracker.Start()
   335  
   336  	if s.udpEnabled && s.p2pServer.DiscV5 == nil {
   337  		s.udpEnabled = false
   338  		log.Error("Discovery v5 is not initialized")
   339  	}
   340  	discovery, err := s.setupDiscovery()
   341  	if err != nil {
   342  		return err
   343  	}
   344  	s.serverPool.AddSource(discovery)
   345  	s.serverPool.Start()
   346  	// Start bloom request workers.
   347  	s.wg.Add(bloomServiceThreads)
   348  	s.startBloomHandlers(params.BloomBitsBlocksClient)
   349  
   350  	return nil
   351  }
   352  
   353  // Stop implements node.Lifecycle, terminating all internal goroutines used by the
   354  // Ethereum protocol.
   355  func (s *LightEthereum) Stop() error {
   356  	close(s.closeCh)
   357  	s.serverPool.Stop()
   358  	s.peers.close()
   359  	s.reqDist.close()
   360  	s.odr.Stop()
   361  	s.relay.Stop()
   362  	s.bloomIndexer.Close()
   363  	s.chtIndexer.Close()
   364  	s.blockchain.Stop()
   365  	s.handler.stop()
   366  	s.txPool.Stop()
   367  	s.engine.Close()
   368  	s.eventMux.Stop()
   369  	// Clean shutdown marker as the last thing before closing db
   370  	s.shutdownTracker.Stop()
   371  
   372  	s.chainDb.Close()
   373  	s.lesDb.Close()
   374  	s.wg.Wait()
   375  	log.Info("Light ethereum stopped")
   376  	return nil
   377  }