github.com/daethereum/go-dae@v2.2.3+incompatible/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/daethereum/go-dae/accounts"
    26  	"github.com/daethereum/go-dae/common"
    27  	"github.com/daethereum/go-dae/common/hexutil"
    28  	"github.com/daethereum/go-dae/common/mclock"
    29  	"github.com/daethereum/go-dae/consensus"
    30  	"github.com/daethereum/go-dae/core"
    31  	"github.com/daethereum/go-dae/core/bloombits"
    32  	"github.com/daethereum/go-dae/core/rawdb"
    33  	"github.com/daethereum/go-dae/core/types"
    34  	"github.com/daethereum/go-dae/eth/ethconfig"
    35  	"github.com/daethereum/go-dae/eth/filters"
    36  	"github.com/daethereum/go-dae/eth/gasprice"
    37  	"github.com/daethereum/go-dae/event"
    38  	"github.com/daethereum/go-dae/internal/ethapi"
    39  	"github.com/daethereum/go-dae/internal/shutdowncheck"
    40  	"github.com/daethereum/go-dae/les/downloader"
    41  	"github.com/daethereum/go-dae/les/vflux"
    42  	vfc "github.com/daethereum/go-dae/les/vflux/client"
    43  	"github.com/daethereum/go-dae/light"
    44  	"github.com/daethereum/go-dae/log"
    45  	"github.com/daethereum/go-dae/node"
    46  	"github.com/daethereum/go-dae/p2p"
    47  	"github.com/daethereum/go-dae/p2p/enode"
    48  	"github.com/daethereum/go-dae/p2p/enr"
    49  	"github.com/daethereum/go-dae/params"
    50  	"github.com/daethereum/go-dae/rlp"
    51  	"github.com/daethereum/go-dae/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.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  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.OverrideGrayGlacier, config.OverrideTerminalTotalDifficulty)
    97  	if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
    98  		return nil, genesisErr
    99  	}
   100  	log.Info("")
   101  	log.Info(strings.Repeat("-", 153))
   102  	for _, line := range strings.Split(chainConfig.String(), "\n") {
   103  		log.Info(line)
   104  	}
   105  	log.Info(strings.Repeat("-", 153))
   106  	log.Info("")
   107  
   108  	peers := newServerPeerSet()
   109  	merger := consensus.NewMerger(chainDb)
   110  	leth := &LightEthereum{
   111  		lesCommons: lesCommons{
   112  			genesis:     genesisHash,
   113  			config:      config,
   114  			chainConfig: chainConfig,
   115  			iConfig:     light.DefaultClientIndexerConfig,
   116  			chainDb:     chainDb,
   117  			lesDb:       lesDb,
   118  			closeCh:     make(chan struct{}),
   119  		},
   120  		peers:           peers,
   121  		eventMux:        stack.EventMux(),
   122  		reqDist:         newRequestDistributor(peers, &mclock.System{}),
   123  		accountManager:  stack.AccountManager(),
   124  		merger:          merger,
   125  		engine:          ethconfig.CreateConsensusEngine(stack, chainConfig, &config.Ethash, nil, false, chainDb),
   126  		bloomRequests:   make(chan chan *bloombits.Retrieval),
   127  		bloomIndexer:    core.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
   128  		p2pServer:       stack.Server(),
   129  		p2pConfig:       &stack.Config().P2P,
   130  		udpEnabled:      stack.Config().P2P.DiscoveryV5,
   131  		shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb),
   132  	}
   133  
   134  	var prenegQuery vfc.QueryFunc
   135  	if leth.udpEnabled {
   136  		prenegQuery = leth.prenegQuery
   137  	}
   138  	leth.serverPool, leth.serverPoolIterator = vfc.NewServerPool(lesDb, []byte("serverpool:"), time.Second, prenegQuery, &mclock.System{}, config.UltraLightServers, requestList)
   139  	leth.serverPool.AddMetrics(suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge, sessionValueMeter, serverDialedMeter)
   140  
   141  	leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool.GetTimeout)
   142  	leth.relay = newLesTxRelay(peers, leth.retriever)
   143  
   144  	leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.peers, leth.retriever)
   145  	leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations, config.LightNoPrune)
   146  	leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency, config.LightNoPrune)
   147  	leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
   148  
   149  	checkpoint := config.Checkpoint
   150  	if checkpoint == nil {
   151  		checkpoint = params.TrustedCheckpoints[genesisHash]
   152  	}
   153  	// Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
   154  	// indexers already set but not started yet
   155  	if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil {
   156  		return nil, err
   157  	}
   158  	leth.chainReader = leth.blockchain
   159  	leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
   160  
   161  	// Set up checkpoint oracle.
   162  	leth.oracle = leth.setupOracle(stack, genesisHash, config)
   163  
   164  	// Note: AddChildIndexer starts the update process for the child
   165  	leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
   166  	leth.chtIndexer.Start(leth.blockchain)
   167  	leth.bloomIndexer.Start(leth.blockchain)
   168  
   169  	// Start a light chain pruner to delete useless historical data.
   170  	leth.pruner = newPruner(chainDb, leth.chtIndexer, leth.bloomTrieIndexer)
   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  		leth.blockchain.SetHead(compat.RewindTo)
   176  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   177  	}
   178  
   179  	leth.ApiBackend = &LesApiBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, leth, nil}
   180  	gpoParams := config.GPO
   181  	if gpoParams.Default == nil {
   182  		gpoParams.Default = config.Miner.GasPrice
   183  	}
   184  	leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
   185  
   186  	leth.handler = newClientHandler(config.UltraLightServers, config.UltraLightFraction, checkpoint, leth)
   187  	if leth.handler.ulc != nil {
   188  		log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.handler.ulc.keys), "minTrustedFraction", leth.handler.ulc.fraction)
   189  		leth.blockchain.DisableCheckFreq()
   190  	}
   191  
   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: "eth",
   303  			Service:   filters.NewFilterAPI(s.ApiBackend, true, 5*time.Minute),
   304  		}, {
   305  			Namespace: "net",
   306  			Service:   s.netRPCService,
   307  		}, {
   308  			Namespace: "les",
   309  			Service:   NewLightAPI(&s.lesCommons),
   310  		}, {
   311  			Namespace: "vflux",
   312  			Service:   s.serverPool.API(),
   313  		},
   314  	}...)
   315  }
   316  
   317  func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
   318  	s.blockchain.ResetWithGenesisBlock(gb)
   319  }
   320  
   321  func (s *LightEthereum) BlockChain() *light.LightChain      { return s.blockchain }
   322  func (s *LightEthereum) TxPool() *light.TxPool              { return s.txPool }
   323  func (s *LightEthereum) Engine() consensus.Engine           { return s.engine }
   324  func (s *LightEthereum) LesVersion() int                    { return int(ClientProtocolVersions[0]) }
   325  func (s *LightEthereum) Downloader() *downloader.Downloader { return s.handler.downloader }
   326  func (s *LightEthereum) EventMux() *event.TypeMux           { return s.eventMux }
   327  func (s *LightEthereum) Merger() *consensus.Merger          { return s.merger }
   328  
   329  // Protocols returns all the currently configured network protocols to start.
   330  func (s *LightEthereum) Protocols() []p2p.Protocol {
   331  	return s.makeProtocols(ClientProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
   332  		if p := s.peers.peer(id.String()); p != nil {
   333  			return p.Info()
   334  		}
   335  		return nil
   336  	}, s.serverPoolIterator)
   337  }
   338  
   339  // Start implements node.Lifecycle, starting all internal goroutines needed by the
   340  // light ethereum protocol implementation.
   341  func (s *LightEthereum) Start() error {
   342  	log.Warn("Light client mode is an experimental feature")
   343  
   344  	// Regularly update shutdown marker
   345  	s.shutdownTracker.Start()
   346  
   347  	if s.udpEnabled && s.p2pServer.DiscV5 == nil {
   348  		s.udpEnabled = false
   349  		log.Error("Discovery v5 is not initialized")
   350  	}
   351  	discovery, err := s.setupDiscovery()
   352  	if err != nil {
   353  		return err
   354  	}
   355  	s.serverPool.AddSource(discovery)
   356  	s.serverPool.Start()
   357  	// Start bloom request workers.
   358  	s.wg.Add(bloomServiceThreads)
   359  	s.startBloomHandlers(params.BloomBitsBlocksClient)
   360  	s.handler.start()
   361  
   362  	return nil
   363  }
   364  
   365  // Stop implements node.Lifecycle, terminating all internal goroutines used by the
   366  // Ethereum protocol.
   367  func (s *LightEthereum) Stop() error {
   368  	close(s.closeCh)
   369  	s.serverPool.Stop()
   370  	s.peers.close()
   371  	s.reqDist.close()
   372  	s.odr.Stop()
   373  	s.relay.Stop()
   374  	s.bloomIndexer.Close()
   375  	s.chtIndexer.Close()
   376  	s.blockchain.Stop()
   377  	s.handler.stop()
   378  	s.txPool.Stop()
   379  	s.engine.Close()
   380  	s.pruner.close()
   381  	s.eventMux.Stop()
   382  	// Clean shutdown marker as the last thing before closing db
   383  	s.shutdownTracker.Stop()
   384  
   385  	s.chainDb.Close()
   386  	s.lesDb.Close()
   387  	s.wg.Wait()
   388  	log.Info("Light ethereum stopped")
   389  	return nil
   390  }