github.com/theQRL/go-zond@v0.2.1/zond/downloader/queue.go (about)

     1  // Copyright 2015 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  // Contains the block download scheduler to collect download tasks and schedule
    18  // them in an ordered, and throttled way.
    19  
    20  package downloader
    21  
    22  import (
    23  	"errors"
    24  	"fmt"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/theQRL/go-zond/common"
    30  	"github.com/theQRL/go-zond/common/prque"
    31  	"github.com/theQRL/go-zond/core/types"
    32  	"github.com/theQRL/go-zond/log"
    33  	"github.com/theQRL/go-zond/metrics"
    34  )
    35  
    36  const (
    37  	bodyType    = uint(0)
    38  	receiptType = uint(1)
    39  )
    40  
    41  var (
    42  	blockCacheMaxItems     = 8192              // Maximum number of blocks to cache before throttling the download
    43  	blockCacheInitialItems = 2048              // Initial number of blocks to start fetching, before we know the sizes of the blocks
    44  	blockCacheMemory       = 256 * 1024 * 1024 // Maximum amount of memory to use for block caching
    45  	blockCacheSizeWeight   = 0.1               // Multiplier to approximate the average block size based on past ones
    46  )
    47  
    48  var (
    49  	errNoFetchesPending = errors.New("no fetches pending")
    50  	errStaleDelivery    = errors.New("stale delivery")
    51  )
    52  
    53  // fetchRequest is a currently running data retrieval operation.
    54  type fetchRequest struct {
    55  	Peer    *peerConnection // Peer to which the request was sent
    56  	From    uint64          // Requested chain element index (used for skeleton fills only)
    57  	Headers []*types.Header // Requested headers, sorted by request order
    58  	Time    time.Time       // Time when the request was made
    59  }
    60  
    61  // fetchResult is a struct collecting partial results from data fetchers until
    62  // all outstanding pieces complete and the result as a whole can be processed.
    63  type fetchResult struct {
    64  	pending atomic.Int32 // Flag telling what deliveries are outstanding
    65  
    66  	Header       *types.Header
    67  	Transactions types.Transactions
    68  	Receipts     types.Receipts
    69  	Withdrawals  types.Withdrawals
    70  }
    71  
    72  func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
    73  	item := &fetchResult{
    74  		Header: header,
    75  	}
    76  	if !header.EmptyBody() {
    77  		item.pending.Store(item.pending.Load() | (1 << bodyType))
    78  	} else if header.WithdrawalsHash != nil {
    79  		item.Withdrawals = make(types.Withdrawals, 0)
    80  	}
    81  	if fastSync && !header.EmptyReceipts() {
    82  		item.pending.Store(item.pending.Load() | (1 << receiptType))
    83  	}
    84  	return item
    85  }
    86  
    87  // body returns a representation of the fetch result as a types.Body object.
    88  func (f *fetchResult) body() types.Body {
    89  	return types.Body{
    90  		Transactions: f.Transactions,
    91  		Withdrawals:  f.Withdrawals,
    92  	}
    93  }
    94  
    95  // SetBodyDone flags the body as finished.
    96  func (f *fetchResult) SetBodyDone() {
    97  	if v := f.pending.Load(); (v & (1 << bodyType)) != 0 {
    98  		f.pending.Add(-1)
    99  	}
   100  }
   101  
   102  // AllDone checks if item is done.
   103  func (f *fetchResult) AllDone() bool {
   104  	return f.pending.Load() == 0
   105  }
   106  
   107  // SetReceiptsDone flags the receipts as finished.
   108  func (f *fetchResult) SetReceiptsDone() {
   109  	if v := f.pending.Load(); (v & (1 << receiptType)) != 0 {
   110  		f.pending.Add(-2)
   111  	}
   112  }
   113  
   114  // Done checks if the given type is done already
   115  func (f *fetchResult) Done(kind uint) bool {
   116  	v := f.pending.Load()
   117  	return v&(1<<kind) == 0
   118  }
   119  
   120  // queue represents hashes that are either need fetching or are being fetched
   121  type queue struct {
   122  	mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
   123  
   124  	// Headers are "special", they download in batches, supported by a skeleton chain
   125  	headerHead      common.Hash                    // Hash of the last queued header to verify order
   126  	headerTaskPool  map[uint64]*types.Header       // Pending header retrieval tasks, mapping starting indexes to skeleton headers
   127  	headerTaskQueue *prque.Prque[int64, uint64]    // Priority queue of the skeleton indexes to fetch the filling headers for
   128  	headerPeerMiss  map[string]map[uint64]struct{} // Set of per-peer header batches known to be unavailable
   129  	headerPendPool  map[string]*fetchRequest       // Currently pending header retrieval operations
   130  	headerResults   []*types.Header                // Result cache accumulating the completed headers
   131  	headerHashes    []common.Hash                  // Result cache accumulating the completed header hashes
   132  	headerProced    int                            // Number of headers already processed from the results
   133  	headerOffset    uint64                         // Number of the first header in the result cache
   134  	headerContCh    chan bool                      // Channel to notify when header download finishes
   135  
   136  	// All data retrievals below are based on an already assembles header chain
   137  	blockTaskPool  map[common.Hash]*types.Header      // Pending block (body) retrieval tasks, mapping hashes to headers
   138  	blockTaskQueue *prque.Prque[int64, *types.Header] // Priority queue of the headers to fetch the blocks (bodies) for
   139  	blockPendPool  map[string]*fetchRequest           // Currently pending block (body) retrieval operations
   140  	blockWakeCh    chan bool                          // Channel to notify the block fetcher of new tasks
   141  
   142  	receiptTaskPool  map[common.Hash]*types.Header      // Pending receipt retrieval tasks, mapping hashes to headers
   143  	receiptTaskQueue *prque.Prque[int64, *types.Header] // Priority queue of the headers to fetch the receipts for
   144  	receiptPendPool  map[string]*fetchRequest           // Currently pending receipt retrieval operations
   145  	receiptWakeCh    chan bool                          // Channel to notify when receipt fetcher of new tasks
   146  
   147  	resultCache *resultStore       // Downloaded but not yet delivered fetch results
   148  	resultSize  common.StorageSize // Approximate size of a block (exponential moving average)
   149  
   150  	lock   *sync.RWMutex
   151  	active *sync.Cond
   152  	closed bool
   153  
   154  	logTime time.Time // Time instance when status was last reported
   155  }
   156  
   157  // newQueue creates a new download queue for scheduling block retrieval.
   158  func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
   159  	lock := new(sync.RWMutex)
   160  	q := &queue{
   161  		headerContCh:     make(chan bool, 1),
   162  		blockTaskQueue:   prque.New[int64, *types.Header](nil),
   163  		blockWakeCh:      make(chan bool, 1),
   164  		receiptTaskQueue: prque.New[int64, *types.Header](nil),
   165  		receiptWakeCh:    make(chan bool, 1),
   166  		active:           sync.NewCond(lock),
   167  		lock:             lock,
   168  	}
   169  	q.Reset(blockCacheLimit, thresholdInitialSize)
   170  	return q
   171  }
   172  
   173  // Reset clears out the queue contents.
   174  func (q *queue) Reset(blockCacheLimit int, thresholdInitialSize int) {
   175  	q.lock.Lock()
   176  	defer q.lock.Unlock()
   177  
   178  	q.closed = false
   179  	q.mode = FullSync
   180  
   181  	q.headerHead = common.Hash{}
   182  	q.headerPendPool = make(map[string]*fetchRequest)
   183  
   184  	q.blockTaskPool = make(map[common.Hash]*types.Header)
   185  	q.blockTaskQueue.Reset()
   186  	q.blockPendPool = make(map[string]*fetchRequest)
   187  
   188  	q.receiptTaskPool = make(map[common.Hash]*types.Header)
   189  	q.receiptTaskQueue.Reset()
   190  	q.receiptPendPool = make(map[string]*fetchRequest)
   191  
   192  	q.resultCache = newResultStore(blockCacheLimit)
   193  	q.resultCache.SetThrottleThreshold(uint64(thresholdInitialSize))
   194  }
   195  
   196  // Close marks the end of the sync, unblocking Results.
   197  // It may be called even if the queue is already closed.
   198  func (q *queue) Close() {
   199  	q.lock.Lock()
   200  	q.closed = true
   201  	q.active.Signal()
   202  	q.lock.Unlock()
   203  }
   204  
   205  // PendingHeaders retrieves the number of header requests pending for retrieval.
   206  func (q *queue) PendingHeaders() int {
   207  	q.lock.Lock()
   208  	defer q.lock.Unlock()
   209  
   210  	return q.headerTaskQueue.Size()
   211  }
   212  
   213  // PendingBodies retrieves the number of block body requests pending for retrieval.
   214  func (q *queue) PendingBodies() int {
   215  	q.lock.Lock()
   216  	defer q.lock.Unlock()
   217  
   218  	return q.blockTaskQueue.Size()
   219  }
   220  
   221  // PendingReceipts retrieves the number of block receipts pending for retrieval.
   222  func (q *queue) PendingReceipts() int {
   223  	q.lock.Lock()
   224  	defer q.lock.Unlock()
   225  
   226  	return q.receiptTaskQueue.Size()
   227  }
   228  
   229  // InFlightBlocks retrieves whether there are block fetch requests currently in
   230  // flight.
   231  func (q *queue) InFlightBlocks() bool {
   232  	q.lock.Lock()
   233  	defer q.lock.Unlock()
   234  
   235  	return len(q.blockPendPool) > 0
   236  }
   237  
   238  // InFlightReceipts retrieves whether there are receipt fetch requests currently
   239  // in flight.
   240  func (q *queue) InFlightReceipts() bool {
   241  	q.lock.Lock()
   242  	defer q.lock.Unlock()
   243  
   244  	return len(q.receiptPendPool) > 0
   245  }
   246  
   247  // Idle returns if the queue is fully idle or has some data still inside.
   248  func (q *queue) Idle() bool {
   249  	q.lock.Lock()
   250  	defer q.lock.Unlock()
   251  
   252  	queued := q.blockTaskQueue.Size() + q.receiptTaskQueue.Size()
   253  	pending := len(q.blockPendPool) + len(q.receiptPendPool)
   254  
   255  	return (queued + pending) == 0
   256  }
   257  
   258  // ScheduleSkeleton adds a batch of header retrieval tasks to the queue to fill
   259  // up an already retrieved header skeleton.
   260  func (q *queue) ScheduleSkeleton(from uint64, skeleton []*types.Header) {
   261  	q.lock.Lock()
   262  	defer q.lock.Unlock()
   263  
   264  	// No skeleton retrieval can be in progress, fail hard if so (huge implementation bug)
   265  	if q.headerResults != nil {
   266  		panic("skeleton assembly already in progress")
   267  	}
   268  	// Schedule all the header retrieval tasks for the skeleton assembly
   269  	q.headerTaskPool = make(map[uint64]*types.Header)
   270  	q.headerTaskQueue = prque.New[int64, uint64](nil)
   271  	q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
   272  	q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
   273  	q.headerHashes = make([]common.Hash, len(skeleton)*MaxHeaderFetch)
   274  	q.headerProced = 0
   275  	q.headerOffset = from
   276  	q.headerContCh = make(chan bool, 1)
   277  
   278  	for i, header := range skeleton {
   279  		index := from + uint64(i*MaxHeaderFetch)
   280  
   281  		q.headerTaskPool[index] = header
   282  		q.headerTaskQueue.Push(index, -int64(index))
   283  	}
   284  }
   285  
   286  // RetrieveHeaders retrieves the header chain assemble based on the scheduled
   287  // skeleton.
   288  func (q *queue) RetrieveHeaders() ([]*types.Header, []common.Hash, int) {
   289  	q.lock.Lock()
   290  	defer q.lock.Unlock()
   291  
   292  	headers, hashes, proced := q.headerResults, q.headerHashes, q.headerProced
   293  	q.headerResults, q.headerHashes, q.headerProced = nil, nil, 0
   294  
   295  	return headers, hashes, proced
   296  }
   297  
   298  // Schedule adds a set of headers for the download queue for scheduling, returning
   299  // the new headers encountered.
   300  func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uint64) []*types.Header {
   301  	q.lock.Lock()
   302  	defer q.lock.Unlock()
   303  
   304  	// Insert all the headers prioritised by the contained block number
   305  	inserts := make([]*types.Header, 0, len(headers))
   306  	for i, header := range headers {
   307  		// Make sure chain order is honoured and preserved throughout
   308  		hash := hashes[i]
   309  		if header.Number == nil || header.Number.Uint64() != from {
   310  			log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
   311  			break
   312  		}
   313  		if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
   314  			log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
   315  			break
   316  		}
   317  		// Make sure no duplicate requests are executed
   318  		// We cannot skip this, even if the block is empty, since this is
   319  		// what triggers the fetchResult creation.
   320  		if _, ok := q.blockTaskPool[hash]; ok {
   321  			log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash)
   322  		} else {
   323  			q.blockTaskPool[hash] = header
   324  			q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
   325  		}
   326  		// Queue for receipt retrieval
   327  		if q.mode == SnapSync && !header.EmptyReceipts() {
   328  			if _, ok := q.receiptTaskPool[hash]; ok {
   329  				log.Warn("Header already scheduled for receipt fetch", "number", header.Number, "hash", hash)
   330  			} else {
   331  				q.receiptTaskPool[hash] = header
   332  				q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
   333  			}
   334  		}
   335  		inserts = append(inserts, header)
   336  		q.headerHead = hash
   337  		from++
   338  	}
   339  	return inserts
   340  }
   341  
   342  // Results retrieves and permanently removes a batch of fetch results from
   343  // the cache. the result slice will be empty if the queue has been closed.
   344  // Results can be called concurrently with Deliver and Schedule,
   345  // but assumes that there are not two simultaneous callers to Results
   346  func (q *queue) Results(block bool) []*fetchResult {
   347  	// Abort early if there are no items and non-blocking requested
   348  	if !block && !q.resultCache.HasCompletedItems() {
   349  		return nil
   350  	}
   351  	closed := false
   352  	for !closed && !q.resultCache.HasCompletedItems() {
   353  		// In order to wait on 'active', we need to obtain the lock.
   354  		// That may take a while, if someone is delivering at the same
   355  		// time, so after obtaining the lock, we check again if there
   356  		// are any results to fetch.
   357  		// Also, in-between we ask for the lock and the lock is obtained,
   358  		// someone can have closed the queue. In that case, we should
   359  		// return the available results and stop blocking
   360  		q.lock.Lock()
   361  		if q.resultCache.HasCompletedItems() || q.closed {
   362  			q.lock.Unlock()
   363  			break
   364  		}
   365  		// No items available, and not closed
   366  		q.active.Wait()
   367  		closed = q.closed
   368  		q.lock.Unlock()
   369  	}
   370  	// Regardless if closed or not, we can still deliver whatever we have
   371  	results := q.resultCache.GetCompleted(maxResultsProcess)
   372  	for _, result := range results {
   373  		// Recalculate the result item weights to prevent memory exhaustion
   374  		size := result.Header.Size()
   375  		for _, receipt := range result.Receipts {
   376  			size += receipt.Size()
   377  		}
   378  		for _, tx := range result.Transactions {
   379  			size += common.StorageSize(tx.Size())
   380  		}
   381  		q.resultSize = common.StorageSize(blockCacheSizeWeight)*size +
   382  			(1-common.StorageSize(blockCacheSizeWeight))*q.resultSize
   383  	}
   384  	// Using the newly calibrated resultsize, figure out the new throttle limit
   385  	// on the result cache
   386  	throttleThreshold := uint64((common.StorageSize(blockCacheMemory) + q.resultSize - 1) / q.resultSize)
   387  	throttleThreshold = q.resultCache.SetThrottleThreshold(throttleThreshold)
   388  
   389  	// With results removed from the cache, wake throttled fetchers
   390  	for _, ch := range []chan bool{q.blockWakeCh, q.receiptWakeCh} {
   391  		select {
   392  		case ch <- true:
   393  		default:
   394  		}
   395  	}
   396  	// Log some info at certain times
   397  	if time.Since(q.logTime) >= 60*time.Second {
   398  		q.logTime = time.Now()
   399  
   400  		info := q.Stats()
   401  		info = append(info, "throttle", throttleThreshold)
   402  		log.Debug("Downloader queue stats", info...)
   403  	}
   404  	return results
   405  }
   406  
   407  func (q *queue) Stats() []interface{} {
   408  	q.lock.RLock()
   409  	defer q.lock.RUnlock()
   410  
   411  	return q.stats()
   412  }
   413  
   414  func (q *queue) stats() []interface{} {
   415  	return []interface{}{
   416  		"receiptTasks", q.receiptTaskQueue.Size(),
   417  		"blockTasks", q.blockTaskQueue.Size(),
   418  		"itemSize", q.resultSize,
   419  	}
   420  }
   421  
   422  // ReserveHeaders reserves a set of headers for the given peer, skipping any
   423  // previously failed batches.
   424  func (q *queue) ReserveHeaders(p *peerConnection, count int) *fetchRequest {
   425  	q.lock.Lock()
   426  	defer q.lock.Unlock()
   427  
   428  	// Short circuit if the peer's already downloading something (sanity check to
   429  	// not corrupt state)
   430  	if _, ok := q.headerPendPool[p.id]; ok {
   431  		return nil
   432  	}
   433  	// Retrieve a batch of hashes, skipping previously failed ones
   434  	send, skip := uint64(0), []uint64{}
   435  	for send == 0 && !q.headerTaskQueue.Empty() {
   436  		from, _ := q.headerTaskQueue.Pop()
   437  		if q.headerPeerMiss[p.id] != nil {
   438  			if _, ok := q.headerPeerMiss[p.id][from]; ok {
   439  				skip = append(skip, from)
   440  				continue
   441  			}
   442  		}
   443  		send = from
   444  	}
   445  	// Merge all the skipped batches back
   446  	for _, from := range skip {
   447  		q.headerTaskQueue.Push(from, -int64(from))
   448  	}
   449  	// Assemble and return the block download request
   450  	if send == 0 {
   451  		return nil
   452  	}
   453  	request := &fetchRequest{
   454  		Peer: p,
   455  		From: send,
   456  		Time: time.Now(),
   457  	}
   458  	q.headerPendPool[p.id] = request
   459  	return request
   460  }
   461  
   462  // ReserveBodies reserves a set of body fetches for the given peer, skipping any
   463  // previously failed downloads. Beside the next batch of needed fetches, it also
   464  // returns a flag whether empty blocks were queued requiring processing.
   465  func (q *queue) ReserveBodies(p *peerConnection, count int) (*fetchRequest, bool, bool) {
   466  	q.lock.Lock()
   467  	defer q.lock.Unlock()
   468  
   469  	return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, bodyType)
   470  }
   471  
   472  // ReserveReceipts reserves a set of receipt fetches for the given peer, skipping
   473  // any previously failed downloads. Beside the next batch of needed fetches, it
   474  // also returns a flag whether empty receipts were queued requiring importing.
   475  func (q *queue) ReserveReceipts(p *peerConnection, count int) (*fetchRequest, bool, bool) {
   476  	q.lock.Lock()
   477  	defer q.lock.Unlock()
   478  
   479  	return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, receiptType)
   480  }
   481  
   482  // reserveHeaders reserves a set of data download operations for a given peer,
   483  // skipping any previously failed ones. This method is a generic version used
   484  // by the individual special reservation functions.
   485  //
   486  // Note, this method expects the queue lock to be already held for writing. The
   487  // reason the lock is not obtained in here is because the parameters already need
   488  // to access the queue, so they already need a lock anyway.
   489  //
   490  // Returns:
   491  //
   492  //	item     - the fetchRequest
   493  //	progress - whether any progress was made
   494  //	throttle - if the caller should throttle for a while
   495  func (q *queue) reserveHeaders(p *peerConnection, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque[int64, *types.Header],
   496  	pendPool map[string]*fetchRequest, kind uint) (*fetchRequest, bool, bool) {
   497  	// Short circuit if the pool has been depleted, or if the peer's already
   498  	// downloading something (sanity check not to corrupt state)
   499  	if taskQueue.Empty() {
   500  		return nil, false, true
   501  	}
   502  	if _, ok := pendPool[p.id]; ok {
   503  		return nil, false, false
   504  	}
   505  	// Retrieve a batch of tasks, skipping previously failed ones
   506  	send := make([]*types.Header, 0, count)
   507  	skip := make([]*types.Header, 0)
   508  	progress := false
   509  	throttled := false
   510  	for proc := 0; len(send) < count && !taskQueue.Empty(); proc++ {
   511  		// the task queue will pop items in order, so the highest prio block
   512  		// is also the lowest block number.
   513  		header, _ := taskQueue.Peek()
   514  
   515  		// we can ask the resultcache if this header is within the
   516  		// "prioritized" segment of blocks. If it is not, we need to throttle
   517  
   518  		stale, throttle, item, err := q.resultCache.AddFetch(header, q.mode == SnapSync)
   519  		if stale {
   520  			// Don't put back in the task queue, this item has already been
   521  			// delivered upstream
   522  			taskQueue.PopItem()
   523  			progress = true
   524  			delete(taskPool, header.Hash())
   525  			proc = proc - 1
   526  			log.Error("Fetch reservation already delivered", "number", header.Number.Uint64())
   527  			continue
   528  		}
   529  		if throttle {
   530  			// There are no resultslots available. Leave it in the task queue
   531  			// However, if there are any left as 'skipped', we should not tell
   532  			// the caller to throttle, since we still want some other
   533  			// peer to fetch those for us
   534  			throttled = len(skip) == 0
   535  			break
   536  		}
   537  		if err != nil {
   538  			// this most definitely should _not_ happen
   539  			log.Warn("Failed to reserve headers", "err", err)
   540  			// There are no resultslots available. Leave it in the task queue
   541  			break
   542  		}
   543  		if item.Done(kind) {
   544  			// If it's a noop, we can skip this task
   545  			delete(taskPool, header.Hash())
   546  			taskQueue.PopItem()
   547  			proc = proc - 1
   548  			progress = true
   549  			continue
   550  		}
   551  		// Remove it from the task queue
   552  		taskQueue.PopItem()
   553  		// Otherwise unless the peer is known not to have the data, add to the retrieve list
   554  		if p.Lacks(header.Hash()) {
   555  			skip = append(skip, header)
   556  		} else {
   557  			send = append(send, header)
   558  		}
   559  	}
   560  	// Merge all the skipped headers back
   561  	for _, header := range skip {
   562  		taskQueue.Push(header, -int64(header.Number.Uint64()))
   563  	}
   564  	if q.resultCache.HasCompletedItems() {
   565  		// Wake Results, resultCache was modified
   566  		q.active.Signal()
   567  	}
   568  	// Assemble and return the block download request
   569  	if len(send) == 0 {
   570  		return nil, progress, throttled
   571  	}
   572  	request := &fetchRequest{
   573  		Peer:    p,
   574  		Headers: send,
   575  		Time:    time.Now(),
   576  	}
   577  	pendPool[p.id] = request
   578  	return request, progress, throttled
   579  }
   580  
   581  // Revoke cancels all pending requests belonging to a given peer. This method is
   582  // meant to be called during a peer drop to quickly reassign owned data fetches
   583  // to remaining nodes.
   584  func (q *queue) Revoke(peerID string) {
   585  	q.lock.Lock()
   586  	defer q.lock.Unlock()
   587  
   588  	if request, ok := q.headerPendPool[peerID]; ok {
   589  		q.headerTaskQueue.Push(request.From, -int64(request.From))
   590  		delete(q.headerPendPool, peerID)
   591  	}
   592  	if request, ok := q.blockPendPool[peerID]; ok {
   593  		for _, header := range request.Headers {
   594  			q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
   595  		}
   596  		delete(q.blockPendPool, peerID)
   597  	}
   598  	if request, ok := q.receiptPendPool[peerID]; ok {
   599  		for _, header := range request.Headers {
   600  			q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
   601  		}
   602  		delete(q.receiptPendPool, peerID)
   603  	}
   604  }
   605  
   606  // ExpireHeaders cancels a request that timed out and moves the pending fetch
   607  // task back into the queue for rescheduling.
   608  func (q *queue) ExpireHeaders(peer string) int {
   609  	q.lock.Lock()
   610  	defer q.lock.Unlock()
   611  
   612  	headerTimeoutMeter.Mark(1)
   613  	return q.expire(peer, q.headerPendPool, q.headerTaskQueue)
   614  }
   615  
   616  // ExpireBodies checks for in flight block body requests that exceeded a timeout
   617  // allowance, canceling them and returning the responsible peers for penalisation.
   618  func (q *queue) ExpireBodies(peer string) int {
   619  	q.lock.Lock()
   620  	defer q.lock.Unlock()
   621  
   622  	bodyTimeoutMeter.Mark(1)
   623  	return q.expire(peer, q.blockPendPool, q.blockTaskQueue)
   624  }
   625  
   626  // ExpireReceipts checks for in flight receipt requests that exceeded a timeout
   627  // allowance, canceling them and returning the responsible peers for penalisation.
   628  func (q *queue) ExpireReceipts(peer string) int {
   629  	q.lock.Lock()
   630  	defer q.lock.Unlock()
   631  
   632  	receiptTimeoutMeter.Mark(1)
   633  	return q.expire(peer, q.receiptPendPool, q.receiptTaskQueue)
   634  }
   635  
   636  // expire is the generic check that moves a specific expired task from a pending
   637  // pool back into a task pool. The syntax on the passed taskQueue is a bit weird
   638  // as we would need a generic expire method to handle both types, but that is not
   639  // supported at the moment at least (Go 1.19).
   640  //
   641  // Note, this method expects the queue lock to be already held. The reason the
   642  // lock is not obtained in here is that the parameters already need to access
   643  // the queue, so they already need a lock anyway.
   644  func (q *queue) expire(peer string, pendPool map[string]*fetchRequest, taskQueue interface{}) int {
   645  	// Retrieve the request being expired and log an error if it's non-existent,
   646  	// as there's no order of events that should lead to such expirations.
   647  	req := pendPool[peer]
   648  	if req == nil {
   649  		log.Error("Expired request does not exist", "peer", peer)
   650  		return 0
   651  	}
   652  	delete(pendPool, peer)
   653  
   654  	// Return any non-satisfied requests to the pool
   655  	if req.From > 0 {
   656  		taskQueue.(*prque.Prque[int64, uint64]).Push(req.From, -int64(req.From))
   657  	}
   658  	for _, header := range req.Headers {
   659  		taskQueue.(*prque.Prque[int64, *types.Header]).Push(header, -int64(header.Number.Uint64()))
   660  	}
   661  	return len(req.Headers)
   662  }
   663  
   664  // DeliverHeaders injects a header retrieval response into the header results
   665  // cache. This method either accepts all headers it received, or none of them
   666  // if they do not map correctly to the skeleton.
   667  //
   668  // If the headers are accepted, the method makes an attempt to deliver the set
   669  // of ready headers to the processor to keep the pipeline full. However, it will
   670  // not block to prevent stalling other pending deliveries.
   671  func (q *queue) DeliverHeaders(id string, headers []*types.Header, hashes []common.Hash, headerProcCh chan *headerTask) (int, error) {
   672  	q.lock.Lock()
   673  	defer q.lock.Unlock()
   674  
   675  	var logger log.Logger
   676  	if len(id) < 16 {
   677  		// Tests use short IDs, don't choke on them
   678  		logger = log.New("peer", id)
   679  	} else {
   680  		logger = log.New("peer", id[:16])
   681  	}
   682  	// Short circuit if the data was never requested
   683  	request := q.headerPendPool[id]
   684  	if request == nil {
   685  		headerDropMeter.Mark(int64(len(headers)))
   686  		return 0, errNoFetchesPending
   687  	}
   688  	delete(q.headerPendPool, id)
   689  
   690  	headerReqTimer.UpdateSince(request.Time)
   691  	headerInMeter.Mark(int64(len(headers)))
   692  
   693  	// Ensure headers can be mapped onto the skeleton chain
   694  	target := q.headerTaskPool[request.From].Hash()
   695  
   696  	accepted := len(headers) == MaxHeaderFetch
   697  	if accepted {
   698  		if headers[0].Number.Uint64() != request.From {
   699  			logger.Trace("First header broke chain ordering", "number", headers[0].Number, "hash", hashes[0], "expected", request.From)
   700  			accepted = false
   701  		} else if hashes[len(headers)-1] != target {
   702  			logger.Trace("Last header broke skeleton structure ", "number", headers[len(headers)-1].Number, "hash", hashes[len(headers)-1], "expected", target)
   703  			accepted = false
   704  		}
   705  	}
   706  	if accepted {
   707  		parentHash := hashes[0]
   708  		for i, header := range headers[1:] {
   709  			hash := hashes[i+1]
   710  			if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
   711  				logger.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", want)
   712  				accepted = false
   713  				break
   714  			}
   715  			if parentHash != header.ParentHash {
   716  				logger.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
   717  				accepted = false
   718  				break
   719  			}
   720  			// Set-up parent hash for next round
   721  			parentHash = hash
   722  		}
   723  	}
   724  	// If the batch of headers wasn't accepted, mark as unavailable
   725  	if !accepted {
   726  		logger.Trace("Skeleton filling not accepted", "from", request.From)
   727  		headerDropMeter.Mark(int64(len(headers)))
   728  
   729  		miss := q.headerPeerMiss[id]
   730  		if miss == nil {
   731  			q.headerPeerMiss[id] = make(map[uint64]struct{})
   732  			miss = q.headerPeerMiss[id]
   733  		}
   734  		miss[request.From] = struct{}{}
   735  
   736  		q.headerTaskQueue.Push(request.From, -int64(request.From))
   737  		return 0, errors.New("delivery not accepted")
   738  	}
   739  	// Clean up a successful fetch and try to deliver any sub-results
   740  	copy(q.headerResults[request.From-q.headerOffset:], headers)
   741  	copy(q.headerHashes[request.From-q.headerOffset:], hashes)
   742  
   743  	delete(q.headerTaskPool, request.From)
   744  
   745  	ready := 0
   746  	for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
   747  		ready += MaxHeaderFetch
   748  	}
   749  	if ready > 0 {
   750  		// Headers are ready for delivery, gather them and push forward (non blocking)
   751  		processHeaders := make([]*types.Header, ready)
   752  		copy(processHeaders, q.headerResults[q.headerProced:q.headerProced+ready])
   753  
   754  		processHashes := make([]common.Hash, ready)
   755  		copy(processHashes, q.headerHashes[q.headerProced:q.headerProced+ready])
   756  
   757  		select {
   758  		case headerProcCh <- &headerTask{
   759  			headers: processHeaders,
   760  			hashes:  processHashes,
   761  		}:
   762  			logger.Trace("Pre-scheduled new headers", "count", len(processHeaders), "from", processHeaders[0].Number)
   763  			q.headerProced += len(processHeaders)
   764  		default:
   765  		}
   766  	}
   767  	// Check for termination and return
   768  	if len(q.headerTaskPool) == 0 {
   769  		q.headerContCh <- false
   770  	}
   771  	return len(headers), nil
   772  }
   773  
   774  // DeliverBodies injects a block body retrieval response into the results queue.
   775  // The method returns the number of blocks bodies accepted from the delivery and
   776  // also wakes any threads waiting for data delivery.
   777  func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, txListHashes []common.Hash,
   778  	withdrawalLists [][]*types.Withdrawal, withdrawalListHashes []common.Hash) (int, error) {
   779  	q.lock.Lock()
   780  	defer q.lock.Unlock()
   781  
   782  	validate := func(index int, header *types.Header) error {
   783  		if txListHashes[index] != header.TxHash {
   784  			return errInvalidBody
   785  		}
   786  		if header.WithdrawalsHash == nil {
   787  			// nil hash means that withdrawals should not be present in body
   788  			if withdrawalLists[index] != nil {
   789  				return errInvalidBody
   790  			}
   791  		} else { // non-nil hash: body must have withdrawals
   792  			if withdrawalLists[index] == nil {
   793  				return errInvalidBody
   794  			}
   795  			if withdrawalListHashes[index] != *header.WithdrawalsHash {
   796  				return errInvalidBody
   797  			}
   798  		}
   799  
   800  		return nil
   801  	}
   802  
   803  	reconstruct := func(index int, result *fetchResult) {
   804  		result.Transactions = txLists[index]
   805  		result.Withdrawals = withdrawalLists[index]
   806  		result.SetBodyDone()
   807  	}
   808  	return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool,
   809  		bodyReqTimer, bodyInMeter, bodyDropMeter, len(txLists), validate, reconstruct)
   810  }
   811  
   812  // DeliverReceipts injects a receipt retrieval response into the results queue.
   813  // The method returns the number of transaction receipts accepted from the delivery
   814  // and also wakes any threads waiting for data delivery.
   815  func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt, receiptListHashes []common.Hash) (int, error) {
   816  	q.lock.Lock()
   817  	defer q.lock.Unlock()
   818  
   819  	validate := func(index int, header *types.Header) error {
   820  		if receiptListHashes[index] != header.ReceiptHash {
   821  			return errInvalidReceipt
   822  		}
   823  		return nil
   824  	}
   825  	reconstruct := func(index int, result *fetchResult) {
   826  		result.Receipts = receiptList[index]
   827  		result.SetReceiptsDone()
   828  	}
   829  	return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool,
   830  		receiptReqTimer, receiptInMeter, receiptDropMeter, len(receiptList), validate, reconstruct)
   831  }
   832  
   833  // deliver injects a data retrieval response into the results queue.
   834  //
   835  // Note, this method expects the queue lock to be already held for writing. The
   836  // reason this lock is not obtained in here is because the parameters already need
   837  // to access the queue, so they already need a lock anyway.
   838  func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
   839  	taskQueue *prque.Prque[int64, *types.Header], pendPool map[string]*fetchRequest,
   840  	reqTimer metrics.Timer, resInMeter metrics.Meter, resDropMeter metrics.Meter,
   841  	results int, validate func(index int, header *types.Header) error,
   842  	reconstruct func(index int, result *fetchResult)) (int, error) {
   843  	// Short circuit if the data was never requested
   844  	request := pendPool[id]
   845  	if request == nil {
   846  		resDropMeter.Mark(int64(results))
   847  		return 0, errNoFetchesPending
   848  	}
   849  	delete(pendPool, id)
   850  
   851  	reqTimer.UpdateSince(request.Time)
   852  	resInMeter.Mark(int64(results))
   853  
   854  	// If no data items were retrieved, mark them as unavailable for the origin peer
   855  	if results == 0 {
   856  		for _, header := range request.Headers {
   857  			request.Peer.MarkLacking(header.Hash())
   858  		}
   859  	}
   860  	// Assemble each of the results with their headers and retrieved data parts
   861  	var (
   862  		accepted int
   863  		failure  error
   864  		i        int
   865  		hashes   []common.Hash
   866  	)
   867  	for _, header := range request.Headers {
   868  		// Short circuit assembly if no more fetch results are found
   869  		if i >= results {
   870  			break
   871  		}
   872  		// Validate the fields
   873  		if err := validate(i, header); err != nil {
   874  			failure = err
   875  			break
   876  		}
   877  		hashes = append(hashes, header.Hash())
   878  		i++
   879  	}
   880  
   881  	for _, header := range request.Headers[:i] {
   882  		if res, stale, err := q.resultCache.GetDeliverySlot(header.Number.Uint64()); err == nil && !stale {
   883  			reconstruct(accepted, res)
   884  		} else {
   885  			// else: between here and above, some other peer filled this result,
   886  			// or it was indeed a no-op. This should not happen, but if it does it's
   887  			// not something to panic about
   888  			log.Error("Delivery stale", "stale", stale, "number", header.Number.Uint64(), "err", err)
   889  			failure = errStaleDelivery
   890  		}
   891  		// Clean up a successful fetch
   892  		delete(taskPool, hashes[accepted])
   893  		accepted++
   894  	}
   895  	resDropMeter.Mark(int64(results - accepted))
   896  
   897  	// Return all failed or missing fetches to the queue
   898  	for _, header := range request.Headers[accepted:] {
   899  		taskQueue.Push(header, -int64(header.Number.Uint64()))
   900  	}
   901  	// Wake up Results
   902  	if accepted > 0 {
   903  		q.active.Signal()
   904  	}
   905  	if failure == nil {
   906  		return accepted, nil
   907  	}
   908  	// If none of the data was good, it's a stale delivery
   909  	if accepted > 0 {
   910  		return accepted, fmt.Errorf("partial failure: %v", failure)
   911  	}
   912  	return accepted, fmt.Errorf("%w: %v", failure, errStaleDelivery)
   913  }
   914  
   915  // Prepare configures the result cache to allow accepting and caching inbound
   916  // fetch results.
   917  func (q *queue) Prepare(offset uint64, mode SyncMode) {
   918  	q.lock.Lock()
   919  	defer q.lock.Unlock()
   920  
   921  	// Prepare the queue for sync results
   922  	q.resultCache.Prepare(offset)
   923  	q.mode = mode
   924  }