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