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