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