github.com/aquanetwork/aquachain@v1.7.8/aqua/downloader/queue.go (about)

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