github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/les/fetcher.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
    18  
    19  import (
    20  	"math/big"
    21  	"math/rand"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/tirogen/go-ethereum/common"
    26  	"github.com/tirogen/go-ethereum/consensus"
    27  	"github.com/tirogen/go-ethereum/core"
    28  	"github.com/tirogen/go-ethereum/core/rawdb"
    29  	"github.com/tirogen/go-ethereum/core/types"
    30  	"github.com/tirogen/go-ethereum/ethdb"
    31  	"github.com/tirogen/go-ethereum/les/fetcher"
    32  	"github.com/tirogen/go-ethereum/light"
    33  	"github.com/tirogen/go-ethereum/log"
    34  	"github.com/tirogen/go-ethereum/p2p/enode"
    35  )
    36  
    37  const (
    38  	blockDelayTimeout    = 10 * time.Second       // Timeout for retrieving the headers from the peer
    39  	gatherSlack          = 100 * time.Millisecond // Interval used to collate almost-expired requests
    40  	cachedAnnosThreshold = 64                     // The maximum queued announcements
    41  )
    42  
    43  // announce represents an new block announcement from the les server.
    44  type announce struct {
    45  	data   *announceData
    46  	trust  bool
    47  	peerid enode.ID
    48  }
    49  
    50  // request represents a record when the header request is sent.
    51  type request struct {
    52  	reqid  uint64
    53  	peerid enode.ID
    54  	sendAt time.Time
    55  	hash   common.Hash
    56  }
    57  
    58  // response represents a response packet from network as well as a channel
    59  // to return all un-requested data.
    60  type response struct {
    61  	reqid   uint64
    62  	headers []*types.Header
    63  	peerid  enode.ID
    64  	remain  chan []*types.Header
    65  }
    66  
    67  // fetcherPeer holds the fetcher-specific information for each active peer
    68  type fetcherPeer struct {
    69  	latest *announceData // The latest announcement sent from the peer
    70  
    71  	// These following two fields can track the latest announces
    72  	// from the peer with limited size for caching. We hold the
    73  	// assumption that all enqueued announces are td-monotonic.
    74  	announces map[common.Hash]*announce // Announcement map
    75  	fifo      []common.Hash             // FIFO announces list
    76  }
    77  
    78  // addAnno enqueues an new trusted announcement. If the queued announces overflow,
    79  // evict from the oldest.
    80  func (fp *fetcherPeer) addAnno(anno *announce) {
    81  	// Short circuit if the anno already exists. In normal case it should
    82  	// never happen since only monotonic anno is accepted. But the adversary
    83  	// may feed us fake announces with higher td but same hash. In this case,
    84  	// ignore the anno anyway.
    85  	hash := anno.data.Hash
    86  	if _, exist := fp.announces[hash]; exist {
    87  		return
    88  	}
    89  	fp.announces[hash] = anno
    90  	fp.fifo = append(fp.fifo, hash)
    91  
    92  	// Evict oldest if the announces are oversized.
    93  	if len(fp.fifo)-cachedAnnosThreshold > 0 {
    94  		for i := 0; i < len(fp.fifo)-cachedAnnosThreshold; i++ {
    95  			delete(fp.announces, fp.fifo[i])
    96  		}
    97  		copy(fp.fifo, fp.fifo[len(fp.fifo)-cachedAnnosThreshold:])
    98  		fp.fifo = fp.fifo[:cachedAnnosThreshold]
    99  	}
   100  }
   101  
   102  // forwardAnno removes all announces from the map with a number lower than
   103  // the provided threshold.
   104  func (fp *fetcherPeer) forwardAnno(td *big.Int) []*announce {
   105  	var (
   106  		cutset  int
   107  		evicted []*announce
   108  	)
   109  	for ; cutset < len(fp.fifo); cutset++ {
   110  		anno := fp.announces[fp.fifo[cutset]]
   111  		if anno == nil {
   112  			continue // In theory it should never ever happen
   113  		}
   114  		if anno.data.Td.Cmp(td) > 0 {
   115  			break
   116  		}
   117  		evicted = append(evicted, anno)
   118  		delete(fp.announces, anno.data.Hash)
   119  	}
   120  	if cutset > 0 {
   121  		copy(fp.fifo, fp.fifo[cutset:])
   122  		fp.fifo = fp.fifo[:len(fp.fifo)-cutset]
   123  	}
   124  	return evicted
   125  }
   126  
   127  // lightFetcher implements retrieval of newly announced headers. It reuses
   128  // the eth.BlockFetcher as the underlying fetcher but adding more additional
   129  // rules: e.g. evict "timeout" peers.
   130  type lightFetcher struct {
   131  	// Various handlers
   132  	ulc     *ulc
   133  	chaindb ethdb.Database
   134  	reqDist *requestDistributor
   135  	peerset *serverPeerSet        // The global peerset of light client which shared by all components
   136  	chain   *light.LightChain     // The local light chain which maintains the canonical header chain.
   137  	fetcher *fetcher.BlockFetcher // The underlying fetcher which takes care block header retrieval.
   138  
   139  	// Peerset maintained by fetcher
   140  	plock sync.RWMutex
   141  	peers map[enode.ID]*fetcherPeer
   142  
   143  	// Various channels
   144  	announceCh chan *announce
   145  	requestCh  chan *request
   146  	deliverCh  chan *response
   147  	syncDone   chan *types.Header
   148  
   149  	closeCh chan struct{}
   150  	wg      sync.WaitGroup
   151  
   152  	// Callback
   153  	synchronise func(peer *serverPeer)
   154  
   155  	// Test fields or hooks
   156  	newHeadHook func(*types.Header)
   157  }
   158  
   159  // newLightFetcher creates a light fetcher instance.
   160  func newLightFetcher(chain *light.LightChain, engine consensus.Engine, peers *serverPeerSet, ulc *ulc, chaindb ethdb.Database, reqDist *requestDistributor, syncFn func(p *serverPeer)) *lightFetcher {
   161  	// Construct the fetcher by offering all necessary APIs
   162  	validator := func(header *types.Header) error {
   163  		// Disable seal verification explicitly if we are running in ulc mode.
   164  		return engine.VerifyHeader(chain, header, ulc == nil)
   165  	}
   166  	heighter := func() uint64 { return chain.CurrentHeader().Number.Uint64() }
   167  	dropper := func(id string) { peers.unregister(id) }
   168  	inserter := func(headers []*types.Header) (int, error) {
   169  		// Disable PoW checking explicitly if we are running in ulc mode.
   170  		checkFreq := 1
   171  		if ulc != nil {
   172  			checkFreq = 0
   173  		}
   174  		return chain.InsertHeaderChain(headers, checkFreq)
   175  	}
   176  	f := &lightFetcher{
   177  		ulc:         ulc,
   178  		peerset:     peers,
   179  		chaindb:     chaindb,
   180  		chain:       chain,
   181  		reqDist:     reqDist,
   182  		fetcher:     fetcher.NewBlockFetcher(true, chain.GetHeaderByHash, nil, validator, nil, heighter, inserter, nil, dropper),
   183  		peers:       make(map[enode.ID]*fetcherPeer),
   184  		synchronise: syncFn,
   185  		announceCh:  make(chan *announce),
   186  		requestCh:   make(chan *request),
   187  		deliverCh:   make(chan *response),
   188  		syncDone:    make(chan *types.Header),
   189  		closeCh:     make(chan struct{}),
   190  	}
   191  	peers.subscribe(f)
   192  	return f
   193  }
   194  
   195  func (f *lightFetcher) start() {
   196  	f.wg.Add(1)
   197  	f.fetcher.Start()
   198  	go f.mainloop()
   199  }
   200  
   201  func (f *lightFetcher) stop() {
   202  	close(f.closeCh)
   203  	f.fetcher.Stop()
   204  	f.wg.Wait()
   205  }
   206  
   207  // registerPeer adds an new peer to the fetcher's peer set
   208  func (f *lightFetcher) registerPeer(p *serverPeer) {
   209  	f.plock.Lock()
   210  	defer f.plock.Unlock()
   211  
   212  	f.peers[p.ID()] = &fetcherPeer{announces: make(map[common.Hash]*announce)}
   213  }
   214  
   215  // unregisterPeer removes the specified peer from the fetcher's peer set
   216  func (f *lightFetcher) unregisterPeer(p *serverPeer) {
   217  	f.plock.Lock()
   218  	defer f.plock.Unlock()
   219  
   220  	delete(f.peers, p.ID())
   221  }
   222  
   223  // peer returns the peer from the fetcher peerset.
   224  func (f *lightFetcher) peer(id enode.ID) *fetcherPeer {
   225  	f.plock.RLock()
   226  	defer f.plock.RUnlock()
   227  
   228  	return f.peers[id]
   229  }
   230  
   231  // forEachPeer iterates the fetcher peerset, abort the iteration if the
   232  // callback returns false.
   233  func (f *lightFetcher) forEachPeer(check func(id enode.ID, p *fetcherPeer) bool) {
   234  	f.plock.RLock()
   235  	defer f.plock.RUnlock()
   236  
   237  	for id, peer := range f.peers {
   238  		if !check(id, peer) {
   239  			return
   240  		}
   241  	}
   242  }
   243  
   244  // mainloop is the main event loop of the light fetcher, which is responsible for
   245  //
   246  //   - announcement maintenance(ulc)
   247  //
   248  //     If we are running in ultra light client mode, then all announcements from
   249  //     the trusted servers are maintained. If the same announcements from trusted
   250  //     servers reach the threshold, then the relevant header is requested for retrieval.
   251  //
   252  //   - block header retrieval
   253  //     Whenever we receive announce with higher td compared with local chain, the
   254  //     request will be made for header retrieval.
   255  //
   256  //   - re-sync trigger
   257  //     If the local chain lags too much, then the fetcher will enter "synchronise"
   258  //     mode to retrieve missing headers in batch.
   259  func (f *lightFetcher) mainloop() {
   260  	defer f.wg.Done()
   261  
   262  	var (
   263  		syncInterval = uint64(1) // Interval used to trigger a light resync.
   264  		syncing      bool        // Indicator whether the client is syncing
   265  
   266  		ulc          = f.ulc != nil
   267  		headCh       = make(chan core.ChainHeadEvent, 100)
   268  		fetching     = make(map[uint64]*request)
   269  		requestTimer = time.NewTimer(0)
   270  
   271  		// Local status
   272  		localHead = f.chain.CurrentHeader()
   273  		localTd   = f.chain.GetTd(localHead.Hash(), localHead.Number.Uint64())
   274  	)
   275  	sub := f.chain.SubscribeChainHeadEvent(headCh)
   276  	defer sub.Unsubscribe()
   277  
   278  	// reset updates the local status with given header.
   279  	reset := func(header *types.Header) {
   280  		localHead = header
   281  		localTd = f.chain.GetTd(header.Hash(), header.Number.Uint64())
   282  	}
   283  	// trustedHeader returns an indicator whether the header is regarded as
   284  	// trusted. If we are running in the ulc mode, only when we receive enough
   285  	// same announcement from trusted server, the header will be trusted.
   286  	trustedHeader := func(hash common.Hash, number uint64) (bool, []enode.ID) {
   287  		var (
   288  			agreed  []enode.ID
   289  			trusted bool
   290  		)
   291  		f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool {
   292  			if anno := p.announces[hash]; anno != nil && anno.trust && anno.data.Number == number {
   293  				agreed = append(agreed, id)
   294  				if 100*len(agreed)/len(f.ulc.keys) >= f.ulc.fraction {
   295  					trusted = true
   296  					return false // abort iteration
   297  				}
   298  			}
   299  			return true
   300  		})
   301  		return trusted, agreed
   302  	}
   303  	for {
   304  		select {
   305  		case anno := <-f.announceCh:
   306  			peerid, data := anno.peerid, anno.data
   307  			log.Debug("Received new announce", "peer", peerid, "number", data.Number, "hash", data.Hash, "reorg", data.ReorgDepth)
   308  
   309  			peer := f.peer(peerid)
   310  			if peer == nil {
   311  				log.Debug("Receive announce from unknown peer", "peer", peerid)
   312  				continue
   313  			}
   314  			// Announced tds should be strictly monotonic, drop the peer if
   315  			// the announce is out-of-order.
   316  			if peer.latest != nil && data.Td.Cmp(peer.latest.Td) <= 0 {
   317  				f.peerset.unregister(peerid.String())
   318  				log.Debug("Non-monotonic td", "peer", peerid, "current", data.Td, "previous", peer.latest.Td)
   319  				continue
   320  			}
   321  			peer.latest = data
   322  
   323  			// Filter out any stale announce, the local chain is ahead of announce
   324  			if localTd != nil && data.Td.Cmp(localTd) <= 0 {
   325  				continue
   326  			}
   327  			peer.addAnno(anno)
   328  
   329  			// If we are not syncing, try to trigger a single retrieval or re-sync
   330  			if !ulc && !syncing {
   331  				// Two scenarios lead to re-sync:
   332  				// - reorg happens
   333  				// - local chain lags
   334  				// We can't retrieve the parent of the announce by single retrieval
   335  				// in both cases, so resync is necessary.
   336  				if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 {
   337  					syncing = true
   338  					go f.startSync(peerid)
   339  					log.Debug("Trigger light sync", "peer", peerid, "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash)
   340  					continue
   341  				}
   342  				f.fetcher.Notify(peerid.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(peerid), nil)
   343  				log.Debug("Trigger header retrieval", "peer", peerid, "number", data.Number, "hash", data.Hash)
   344  			}
   345  			// Keep collecting announces from trusted server even we are syncing.
   346  			if ulc && anno.trust {
   347  				// Notify underlying fetcher to retrieve header or trigger a resync if
   348  				// we have receive enough announcements from trusted server.
   349  				trusted, agreed := trustedHeader(data.Hash, data.Number)
   350  				if trusted && !syncing {
   351  					if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 {
   352  						syncing = true
   353  						go f.startSync(peerid)
   354  						log.Debug("Trigger trusted light sync", "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash)
   355  						continue
   356  					}
   357  					p := agreed[rand.Intn(len(agreed))]
   358  					f.fetcher.Notify(p.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(p), nil)
   359  					log.Debug("Trigger trusted header retrieval", "number", data.Number, "hash", data.Hash)
   360  				}
   361  			}
   362  
   363  		case req := <-f.requestCh:
   364  			fetching[req.reqid] = req // Tracking all in-flight requests for response latency statistic.
   365  			if len(fetching) == 1 {
   366  				f.rescheduleTimer(fetching, requestTimer)
   367  			}
   368  
   369  		case <-requestTimer.C:
   370  			for reqid, request := range fetching {
   371  				if time.Since(request.sendAt) > blockDelayTimeout-gatherSlack {
   372  					delete(fetching, reqid)
   373  					f.peerset.unregister(request.peerid.String())
   374  					log.Debug("Request timeout", "peer", request.peerid, "reqid", reqid)
   375  				}
   376  			}
   377  			f.rescheduleTimer(fetching, requestTimer)
   378  
   379  		case resp := <-f.deliverCh:
   380  			if req := fetching[resp.reqid]; req != nil {
   381  				delete(fetching, resp.reqid)
   382  				f.rescheduleTimer(fetching, requestTimer)
   383  
   384  				// The underlying fetcher does not check the consistency of request and response.
   385  				// The adversary can send the fake announces with invalid hash and number but always
   386  				// delivery some mismatched header. So it can't be punished by the underlying fetcher.
   387  				// We have to add two more rules here to detect.
   388  				if len(resp.headers) != 1 {
   389  					f.peerset.unregister(req.peerid.String())
   390  					log.Debug("Deliver more than requested", "peer", req.peerid, "reqid", req.reqid)
   391  					continue
   392  				}
   393  				if resp.headers[0].Hash() != req.hash {
   394  					f.peerset.unregister(req.peerid.String())
   395  					log.Debug("Deliver invalid header", "peer", req.peerid, "reqid", req.reqid)
   396  					continue
   397  				}
   398  				resp.remain <- f.fetcher.FilterHeaders(resp.peerid.String(), resp.headers, time.Now())
   399  			} else {
   400  				// Discard the entire packet no matter it's a timeout response or unexpected one.
   401  				resp.remain <- resp.headers
   402  			}
   403  
   404  		case ev := <-headCh:
   405  			// Short circuit if we are still syncing.
   406  			if syncing {
   407  				continue
   408  			}
   409  			reset(ev.Block.Header())
   410  
   411  			// Clean stale announcements from les-servers.
   412  			var droplist []enode.ID
   413  			f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool {
   414  				removed := p.forwardAnno(localTd)
   415  				for _, anno := range removed {
   416  					if header := f.chain.GetHeaderByHash(anno.data.Hash); header != nil {
   417  						if header.Number.Uint64() != anno.data.Number {
   418  							droplist = append(droplist, id)
   419  							break
   420  						}
   421  						// In theory td should exists.
   422  						td := f.chain.GetTd(anno.data.Hash, anno.data.Number)
   423  						if td != nil && td.Cmp(anno.data.Td) != 0 {
   424  							droplist = append(droplist, id)
   425  							break
   426  						}
   427  					}
   428  				}
   429  				return true
   430  			})
   431  			for _, id := range droplist {
   432  				f.peerset.unregister(id.String())
   433  				log.Debug("Kicked out peer for invalid announcement")
   434  			}
   435  			if f.newHeadHook != nil {
   436  				f.newHeadHook(localHead)
   437  			}
   438  
   439  		case origin := <-f.syncDone:
   440  			syncing = false // Reset the status
   441  
   442  			// Rewind all untrusted headers for ulc mode.
   443  			if ulc {
   444  				head := f.chain.CurrentHeader()
   445  				ancestor := rawdb.FindCommonAncestor(f.chaindb, origin, head)
   446  
   447  				// Recap the ancestor with genesis header in case the ancestor
   448  				// is not found. It can happen the original head is before the
   449  				// checkpoint while the synced headers are after it. In this
   450  				// case there is no ancestor between them.
   451  				if ancestor == nil {
   452  					ancestor = f.chain.Genesis().Header()
   453  				}
   454  				var untrusted []common.Hash
   455  				for head.Number.Cmp(ancestor.Number) > 0 {
   456  					hash, number := head.Hash(), head.Number.Uint64()
   457  					if trusted, _ := trustedHeader(hash, number); trusted {
   458  						break
   459  					}
   460  					untrusted = append(untrusted, hash)
   461  					head = f.chain.GetHeader(head.ParentHash, number-1)
   462  					if head == nil {
   463  						break // all the synced headers will be dropped
   464  					}
   465  				}
   466  				if len(untrusted) > 0 {
   467  					for i, j := 0, len(untrusted)-1; i < j; i, j = i+1, j-1 {
   468  						untrusted[i], untrusted[j] = untrusted[j], untrusted[i]
   469  					}
   470  					f.chain.Rollback(untrusted)
   471  				}
   472  			}
   473  			// Reset local status.
   474  			reset(f.chain.CurrentHeader())
   475  			if f.newHeadHook != nil {
   476  				f.newHeadHook(localHead)
   477  			}
   478  			log.Debug("light sync finished", "number", localHead.Number, "hash", localHead.Hash())
   479  
   480  		case <-f.closeCh:
   481  			return
   482  		}
   483  	}
   484  }
   485  
   486  // announce processes a new announcement message received from a peer.
   487  func (f *lightFetcher) announce(p *serverPeer, head *announceData) {
   488  	select {
   489  	case f.announceCh <- &announce{peerid: p.ID(), trust: p.trusted, data: head}:
   490  	case <-f.closeCh:
   491  		return
   492  	}
   493  }
   494  
   495  // trackRequest sends a reqID to main loop for in-flight request tracking.
   496  func (f *lightFetcher) trackRequest(peerid enode.ID, reqid uint64, hash common.Hash) {
   497  	select {
   498  	case f.requestCh <- &request{reqid: reqid, peerid: peerid, sendAt: time.Now(), hash: hash}:
   499  	case <-f.closeCh:
   500  	}
   501  }
   502  
   503  // requestHeaderByHash constructs a header retrieval request and sends it to
   504  // local request distributor.
   505  //
   506  // Note, we rely on the underlying eth/fetcher to retrieve and validate the
   507  // response, so that we have to obey the rule of eth/fetcher which only accepts
   508  // the response from given peer.
   509  func (f *lightFetcher) requestHeaderByHash(peerid enode.ID) func(common.Hash) error {
   510  	return func(hash common.Hash) error {
   511  		req := &distReq{
   512  			getCost: func(dp distPeer) uint64 { return dp.(*serverPeer).getRequestCost(GetBlockHeadersMsg, 1) },
   513  			canSend: func(dp distPeer) bool { return dp.(*serverPeer).ID() == peerid },
   514  			request: func(dp distPeer) func() {
   515  				peer, id := dp.(*serverPeer), rand.Uint64()
   516  				cost := peer.getRequestCost(GetBlockHeadersMsg, 1)
   517  				peer.fcServer.QueuedRequest(id, cost)
   518  
   519  				return func() {
   520  					f.trackRequest(peer.ID(), id, hash)
   521  					peer.requestHeadersByHash(id, hash, 1, 0, false)
   522  				}
   523  			},
   524  		}
   525  		f.reqDist.queue(req)
   526  		return nil
   527  	}
   528  }
   529  
   530  // startSync invokes synchronisation callback to start syncing.
   531  func (f *lightFetcher) startSync(id enode.ID) {
   532  	defer func(header *types.Header) {
   533  		f.syncDone <- header
   534  	}(f.chain.CurrentHeader())
   535  
   536  	peer := f.peerset.peer(id.String())
   537  	if peer == nil || peer.onlyAnnounce {
   538  		return
   539  	}
   540  	f.synchronise(peer)
   541  }
   542  
   543  // deliverHeaders delivers header download request responses for processing
   544  func (f *lightFetcher) deliverHeaders(peer *serverPeer, reqid uint64, headers []*types.Header) []*types.Header {
   545  	remain := make(chan []*types.Header, 1)
   546  	select {
   547  	case f.deliverCh <- &response{reqid: reqid, headers: headers, peerid: peer.ID(), remain: remain}:
   548  	case <-f.closeCh:
   549  		return nil
   550  	}
   551  	return <-remain
   552  }
   553  
   554  // rescheduleTimer resets the specified timeout timer to the next request timeout.
   555  func (f *lightFetcher) rescheduleTimer(requests map[uint64]*request, timer *time.Timer) {
   556  	// Short circuit if no inflight requests
   557  	if len(requests) == 0 {
   558  		timer.Stop()
   559  		return
   560  	}
   561  	// Otherwise find the earliest expiring request
   562  	earliest := time.Now()
   563  	for _, req := range requests {
   564  		if earliest.After(req.sendAt) {
   565  			earliest = req.sendAt
   566  		}
   567  	}
   568  	timer.Reset(blockDelayTimeout - time.Since(earliest))
   569  }