github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/eth/downloader/queue.go (about)

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