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