github.com/r8d8/go-ethereum@v5.5.2+incompatible/eth/downloader/queue.go (about)

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