2015-07-07 03:54:22 +03:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 19:48:40 +03:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-07 03:54:22 +03:00
|
|
|
//
|
2015-07-23 19:35:11 +03:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-07 03:54:22 +03:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 19:48:40 +03:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-07 03:54:22 +03:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 19:48:40 +03:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-07 03:54:22 +03:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 19:48:40 +03:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-07 03:54:22 +03:00
|
|
|
|
2015-05-11 14:26:20 +03:00
|
|
|
// Contains the block download scheduler to collect download tasks and schedule
|
|
|
|
// them in an ordered, and throttled way.
|
|
|
|
|
2015-04-12 13:38:25 +03:00
|
|
|
package downloader
|
|
|
|
|
|
|
|
import (
|
2015-05-06 15:32:53 +03:00
|
|
|
"errors"
|
2015-05-03 15:11:00 +03:00
|
|
|
"fmt"
|
2015-04-12 13:38:25 +03:00
|
|
|
"sync"
|
2020-07-24 10:46:26 +03:00
|
|
|
"sync/atomic"
|
2015-04-12 13:38:25 +03:00
|
|
|
"time"
|
|
|
|
|
2015-04-13 17:38:32 +03:00
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2018-09-03 18:33:21 +03:00
|
|
|
"github.com/ethereum/go-ethereum/common/prque"
|
2015-04-12 13:38:25 +03:00
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
2017-02-22 15:10:07 +03:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2018-02-23 12:56:08 +03:00
|
|
|
"github.com/ethereum/go-ethereum/metrics"
|
2020-08-21 15:10:40 +03:00
|
|
|
"github.com/ethereum/go-ethereum/trie"
|
2015-04-12 13:38:25 +03:00
|
|
|
)
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
const (
|
|
|
|
bodyType = uint(0)
|
|
|
|
receiptType = uint(1)
|
|
|
|
)
|
|
|
|
|
2018-02-05 19:40:32 +03:00
|
|
|
var (
|
2020-09-02 12:01:46 +03:00
|
|
|
blockCacheMaxItems = 8192 // Maximum number of blocks to cache before throttling the download
|
|
|
|
blockCacheInitialItems = 2048 // Initial number of blocks to start fetching, before we know the sizes of the blocks
|
|
|
|
blockCacheMemory = 64 * 1024 * 1024 // Maximum amount of memory to use for block caching
|
|
|
|
blockCacheSizeWeight = 0.1 // Multiplier to approximate the average block size based on past ones
|
2018-02-05 19:40:32 +03:00
|
|
|
)
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2015-06-05 12:37:48 +03:00
|
|
|
var (
|
|
|
|
errNoFetchesPending = errors.New("no fetches pending")
|
|
|
|
errStaleDelivery = errors.New("stale delivery")
|
|
|
|
)
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// fetchRequest is a currently running data retrieval operation.
|
2015-05-06 15:32:53 +03:00
|
|
|
type fetchRequest struct {
|
2018-02-05 19:40:32 +03:00
|
|
|
Peer *peerConnection // Peer to which the request was sent
|
|
|
|
From uint64 // [eth/62] Requested chain element index (used for skeleton fills only)
|
|
|
|
Headers []*types.Header // [eth/62] Requested headers, sorted by request order
|
|
|
|
Time time.Time // Time when the request was made
|
2015-05-06 15:32:53 +03:00
|
|
|
}
|
|
|
|
|
2015-10-13 12:04:25 +03:00
|
|
|
// fetchResult is a struct collecting partial results from data fetchers until
|
|
|
|
// all outstanding pieces complete and the result as a whole can be processed.
|
2015-09-28 19:27:31 +03:00
|
|
|
type fetchResult struct {
|
2020-07-24 10:46:26 +03:00
|
|
|
pending int32 // Flag telling what deliveries are outstanding
|
2015-09-28 19:27:31 +03:00
|
|
|
|
|
|
|
Header *types.Header
|
|
|
|
Uncles []*types.Header
|
|
|
|
Transactions types.Transactions
|
|
|
|
Receipts types.Receipts
|
|
|
|
}
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
|
|
|
|
item := &fetchResult{
|
|
|
|
Header: header,
|
|
|
|
}
|
|
|
|
if !header.EmptyBody() {
|
|
|
|
item.pending |= (1 << bodyType)
|
|
|
|
}
|
|
|
|
if fastSync && !header.EmptyReceipts() {
|
|
|
|
item.pending |= (1 << receiptType)
|
|
|
|
}
|
|
|
|
return item
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetBodyDone flags the body as finished.
|
|
|
|
func (f *fetchResult) SetBodyDone() {
|
|
|
|
if v := atomic.LoadInt32(&f.pending); (v & (1 << bodyType)) != 0 {
|
|
|
|
atomic.AddInt32(&f.pending, -1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// AllDone checks if item is done.
|
|
|
|
func (f *fetchResult) AllDone() bool {
|
|
|
|
return atomic.LoadInt32(&f.pending) == 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetReceiptsDone flags the receipts as finished.
|
|
|
|
func (f *fetchResult) SetReceiptsDone() {
|
|
|
|
if v := atomic.LoadInt32(&f.pending); (v & (1 << receiptType)) != 0 {
|
|
|
|
atomic.AddInt32(&f.pending, -2)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Done checks if the given type is done already
|
|
|
|
func (f *fetchResult) Done(kind uint) bool {
|
|
|
|
v := atomic.LoadInt32(&f.pending)
|
|
|
|
return v&(1<<kind) == 0
|
|
|
|
}
|
|
|
|
|
2015-04-12 13:38:25 +03:00
|
|
|
// queue represents hashes that are either need fetching or are being fetched
|
|
|
|
type queue struct {
|
2018-02-05 19:40:32 +03:00
|
|
|
mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// Headers are "special", they download in batches, supported by a skeleton chain
|
2018-02-05 19:40:32 +03:00
|
|
|
headerHead common.Hash // [eth/62] Hash of the last queued header to verify order
|
2016-02-25 18:36:42 +02:00
|
|
|
headerTaskPool map[uint64]*types.Header // [eth/62] Pending header retrieval tasks, mapping starting indexes to skeleton headers
|
|
|
|
headerTaskQueue *prque.Prque // [eth/62] Priority queue of the skeleton indexes to fetch the filling headers for
|
|
|
|
headerPeerMiss map[string]map[uint64]struct{} // [eth/62] Set of per-peer header batches known to be unavailable
|
|
|
|
headerPendPool map[string]*fetchRequest // [eth/62] Currently pending header retrieval operations
|
|
|
|
headerResults []*types.Header // [eth/62] Result cache accumulating the completed headers
|
2016-04-19 12:27:37 +03:00
|
|
|
headerProced int // [eth/62] Number of headers already processed from the results
|
2016-02-25 18:36:42 +02:00
|
|
|
headerOffset uint64 // [eth/62] Number of the first header in the result cache
|
|
|
|
headerContCh chan bool // [eth/62] Channel to notify when header download finishes
|
|
|
|
|
|
|
|
// All data retrievals below are based on an already assembles header chain
|
2015-09-28 19:27:31 +03:00
|
|
|
blockTaskPool map[common.Hash]*types.Header // [eth/62] Pending block (body) retrieval tasks, mapping hashes to headers
|
|
|
|
blockTaskQueue *prque.Prque // [eth/62] Priority queue of the headers to fetch the blocks (bodies) for
|
|
|
|
blockPendPool map[string]*fetchRequest // [eth/62] Currently pending block (body) retrieval operations
|
2015-04-12 13:38:25 +03:00
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
receiptTaskPool map[common.Hash]*types.Header // [eth/63] Pending receipt retrieval tasks, mapping hashes to headers
|
|
|
|
receiptTaskQueue *prque.Prque // [eth/63] Priority queue of the headers to fetch the receipts for
|
|
|
|
receiptPendPool map[string]*fetchRequest // [eth/63] Currently pending receipt retrieval operations
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
resultCache *resultStore // Downloaded but not yet delivered fetch results
|
|
|
|
resultSize common.StorageSize // Approximate size of a block (exponential moving average)
|
2015-05-01 01:23:51 +03:00
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
lock *sync.RWMutex
|
2015-11-13 18:08:15 +02:00
|
|
|
active *sync.Cond
|
|
|
|
closed bool
|
2020-07-24 10:46:26 +03:00
|
|
|
|
|
|
|
lastStatLog time.Time
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|
|
|
|
|
2015-05-06 15:32:53 +03:00
|
|
|
// newQueue creates a new download queue for scheduling block retrieval.
|
2020-09-02 12:01:46 +03:00
|
|
|
func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
|
2020-07-24 10:46:26 +03:00
|
|
|
lock := new(sync.RWMutex)
|
|
|
|
q := &queue{
|
2016-02-25 18:36:42 +02:00
|
|
|
headerContCh: make(chan bool),
|
2018-09-03 18:33:21 +03:00
|
|
|
blockTaskQueue: prque.New(nil),
|
|
|
|
receiptTaskQueue: prque.New(nil),
|
2015-11-13 18:08:15 +02:00
|
|
|
active: sync.NewCond(lock),
|
|
|
|
lock: lock,
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|
2020-09-02 12:01:46 +03:00
|
|
|
q.Reset(blockCacheLimit, thresholdInitialSize)
|
2020-07-24 10:46:26 +03:00
|
|
|
return q
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|
|
|
|
|
2015-05-06 15:32:53 +03:00
|
|
|
// Reset clears out the queue contents.
|
2020-09-02 12:01:46 +03:00
|
|
|
func (q *queue) Reset(blockCacheLimit int, thresholdInitialSize int) {
|
2015-05-06 15:32:53 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-18 16:14:12 +03:00
|
|
|
|
2015-11-13 18:08:15 +02:00
|
|
|
q.closed = false
|
2015-10-05 19:37:56 +03:00
|
|
|
q.mode = FullSync
|
|
|
|
|
2015-09-15 13:33:45 +03:00
|
|
|
q.headerHead = common.Hash{}
|
2016-02-25 18:36:42 +02:00
|
|
|
q.headerPendPool = make(map[string]*fetchRequest)
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
q.blockTaskPool = make(map[common.Hash]*types.Header)
|
|
|
|
q.blockTaskQueue.Reset()
|
|
|
|
q.blockPendPool = make(map[string]*fetchRequest)
|
|
|
|
|
|
|
|
q.receiptTaskPool = make(map[common.Hash]*types.Header)
|
|
|
|
q.receiptTaskQueue.Reset()
|
|
|
|
q.receiptPendPool = make(map[string]*fetchRequest)
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
q.resultCache = newResultStore(blockCacheLimit)
|
2020-09-02 12:01:46 +03:00
|
|
|
q.resultCache.SetThrottleThreshold(uint64(thresholdInitialSize))
|
2015-05-01 01:23:51 +03:00
|
|
|
}
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2018-10-23 14:21:16 +03:00
|
|
|
// Close marks the end of the sync, unblocking Results.
|
2015-11-13 18:08:15 +02:00
|
|
|
// It may be called even if the queue is already closed.
|
|
|
|
func (q *queue) Close() {
|
|
|
|
q.lock.Lock()
|
|
|
|
q.closed = true
|
2020-07-24 10:46:26 +03:00
|
|
|
q.active.Signal()
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Unlock()
|
|
|
|
}
|
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// PendingHeaders retrieves the number of header requests pending for retrieval.
|
|
|
|
func (q *queue) PendingHeaders() int {
|
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
return q.headerTaskQueue.Size()
|
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// PendingBlocks retrieves the number of block (body) requests pending for retrieval.
|
|
|
|
func (q *queue) PendingBlocks() int {
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2016-07-21 12:36:38 +03:00
|
|
|
return q.blockTaskQueue.Size()
|
2015-05-01 01:23:51 +03:00
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// PendingReceipts retrieves the number of block receipts pending for retrieval.
|
|
|
|
func (q *queue) PendingReceipts() int {
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-12 13:38:25 +03:00
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
return q.receiptTaskQueue.Size()
|
2015-05-06 15:32:53 +03:00
|
|
|
}
|
2015-04-12 13:38:25 +03:00
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// InFlightHeaders retrieves whether there are header fetch requests currently
|
|
|
|
// in flight.
|
|
|
|
func (q *queue) InFlightHeaders() bool {
|
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
return len(q.headerPendPool) > 0
|
|
|
|
}
|
|
|
|
|
2015-10-07 12:14:30 +03:00
|
|
|
// InFlightBlocks retrieves whether there are block fetch requests currently in
|
|
|
|
// flight.
|
|
|
|
func (q *queue) InFlightBlocks() bool {
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-10-05 19:37:56 +03:00
|
|
|
|
2015-10-07 12:14:30 +03:00
|
|
|
return len(q.blockPendPool) > 0
|
2015-10-05 19:37:56 +03:00
|
|
|
}
|
|
|
|
|
2015-10-07 12:14:30 +03:00
|
|
|
// InFlightReceipts retrieves whether there are receipt fetch requests currently
|
|
|
|
// in flight.
|
|
|
|
func (q *queue) InFlightReceipts() bool {
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-12 13:38:25 +03:00
|
|
|
|
2015-10-07 12:14:30 +03:00
|
|
|
return len(q.receiptPendPool) > 0
|
|
|
|
}
|
|
|
|
|
eth/downloader: separate state sync from queue (#14460)
* eth/downloader: separate state sync from queue
Scheduling of state node downloads hogged the downloader queue lock when
new requests were scheduled. This caused timeouts for other requests.
With this change, state sync is fully independent of all other downloads
and doesn't involve the queue at all.
State sync is started and checked on in processContent. This is slightly
awkward because processContent doesn't have a select loop. Instead, the
queue is closed by an auxiliary goroutine when state sync fails. We
tried several alternatives to this but settled on the current approach
because it's the least amount of change overall.
Handling of the pivot block has changed slightly: the queue previously
prevented import of pivot block receipts before the state of the pivot
block was available. In this commit, the receipt will be imported before
the state. This causes an annoyance where the pivot block is committed
as fast block head even when state downloads fail. Stay tuned for more
updates in this area ;)
* eth/downloader: remove cancelTimeout channel
* eth/downloader: retry state requests on timeout
* eth/downloader: improve comment
* eth/downloader: mark peers idle when state sync is done
* eth/downloader: move pivot block splitting to processContent
This change also ensures that pivot block receipts aren't imported
before the pivot block itself.
* eth/downloader: limit state node retries
* eth/downloader: improve state node error handling and retry check
* eth/downloader: remove maxStateNodeRetries
It fails the sync too much.
* eth/downloader: remove last use of cancelCh in statesync.go
Fixes TestDeliverHeadersHang*Fast and (hopefully)
the weird cancellation behaviour at the end of fast sync.
* eth/downloader: fix leak in runStateSync
* eth/downloader: don't run processFullSyncContent in LightSync mode
* eth/downloader: improve comments
* eth/downloader: fix vet, megacheck
* eth/downloader: remove unrequested tasks anyway
* eth/downloader, trie: various polishes around duplicate items
This commit explicitly tracks duplicate and unexpected state
delieveries done against a trie Sync structure, also adding
there to import info logs.
The commit moves the db batch used to commit trie changes one
level deeper so its flushed after every node insertion. This
is needed to avoid a lot of duplicate retrievals caused by
inconsistencies between Sync internals and database. A better
approach is to track not-yet-written states in trie.Sync and
flush on commit, but I'm focuing on correctness first now.
The commit fixes a regression around pivot block fail count.
The counter previously was reset to 1 if and only if a sync
cycle progressed (inserted at least 1 entry to the database).
The current code reset it already if a node was delivered,
which is not stong enough, because unless it ends up written
to disk, an attacker can just loop and attack ad infinitum.
The commit also fixes a regression around state deliveries
and timeouts. The old downloader tracked if a delivery is
stale (none of the deliveries were requestedt), in which
case it didn't mark the node idle and did not send further
requests, since it signals a past timeout. The current code
did mark it idle even on stale deliveries, which eventually
caused two requests to be in flight at the same time, making
the deliveries always stale and mass duplicating retrievals
between multiple peers.
* eth/downloader: fix state request leak
This commit fixes the hang seen sometimes while doing the state
sync. The cause of the hang was a rare combination of events:
request state data from peer, peer drops and reconnects almost
immediately. This caused a new download task to be assigned to
the peer, overwriting the old one still waiting for a timeout,
which in turned leaked the requests out, never to be retried.
The fix is to ensure that a task assignment moves any pending
one back into the retry queue.
The commit also fixes a regression with peer dropping due to
stalls. The current code considered a peer stalling if they
timed out delivering 1 item. However, the downloader never
requests only one, the minimum is 2 (attempt to fine tune
estimated latency/bandwidth). The fix is simply to drop if
a timeout is detected at 2 items.
Apart from the above bugfixes, the commit contains some code
polishes I made while debugging the hang.
* core, eth, trie: support batched trie sync db writes
* trie: rename SyncMemCache to syncMemBatch
2017-06-22 15:26:03 +03:00
|
|
|
// Idle returns if the queue is fully idle or has some data still inside.
|
2015-09-28 19:27:31 +03:00
|
|
|
func (q *queue) Idle() bool {
|
2015-11-13 18:08:15 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-09-28 19:27:31 +03:00
|
|
|
|
eth/downloader: separate state sync from queue (#14460)
* eth/downloader: separate state sync from queue
Scheduling of state node downloads hogged the downloader queue lock when
new requests were scheduled. This caused timeouts for other requests.
With this change, state sync is fully independent of all other downloads
and doesn't involve the queue at all.
State sync is started and checked on in processContent. This is slightly
awkward because processContent doesn't have a select loop. Instead, the
queue is closed by an auxiliary goroutine when state sync fails. We
tried several alternatives to this but settled on the current approach
because it's the least amount of change overall.
Handling of the pivot block has changed slightly: the queue previously
prevented import of pivot block receipts before the state of the pivot
block was available. In this commit, the receipt will be imported before
the state. This causes an annoyance where the pivot block is committed
as fast block head even when state downloads fail. Stay tuned for more
updates in this area ;)
* eth/downloader: remove cancelTimeout channel
* eth/downloader: retry state requests on timeout
* eth/downloader: improve comment
* eth/downloader: mark peers idle when state sync is done
* eth/downloader: move pivot block splitting to processContent
This change also ensures that pivot block receipts aren't imported
before the pivot block itself.
* eth/downloader: limit state node retries
* eth/downloader: improve state node error handling and retry check
* eth/downloader: remove maxStateNodeRetries
It fails the sync too much.
* eth/downloader: remove last use of cancelCh in statesync.go
Fixes TestDeliverHeadersHang*Fast and (hopefully)
the weird cancellation behaviour at the end of fast sync.
* eth/downloader: fix leak in runStateSync
* eth/downloader: don't run processFullSyncContent in LightSync mode
* eth/downloader: improve comments
* eth/downloader: fix vet, megacheck
* eth/downloader: remove unrequested tasks anyway
* eth/downloader, trie: various polishes around duplicate items
This commit explicitly tracks duplicate and unexpected state
delieveries done against a trie Sync structure, also adding
there to import info logs.
The commit moves the db batch used to commit trie changes one
level deeper so its flushed after every node insertion. This
is needed to avoid a lot of duplicate retrievals caused by
inconsistencies between Sync internals and database. A better
approach is to track not-yet-written states in trie.Sync and
flush on commit, but I'm focuing on correctness first now.
The commit fixes a regression around pivot block fail count.
The counter previously was reset to 1 if and only if a sync
cycle progressed (inserted at least 1 entry to the database).
The current code reset it already if a node was delivered,
which is not stong enough, because unless it ends up written
to disk, an attacker can just loop and attack ad infinitum.
The commit also fixes a regression around state deliveries
and timeouts. The old downloader tracked if a delivery is
stale (none of the deliveries were requestedt), in which
case it didn't mark the node idle and did not send further
requests, since it signals a past timeout. The current code
did mark it idle even on stale deliveries, which eventually
caused two requests to be in flight at the same time, making
the deliveries always stale and mass duplicating retrievals
between multiple peers.
* eth/downloader: fix state request leak
This commit fixes the hang seen sometimes while doing the state
sync. The cause of the hang was a rare combination of events:
request state data from peer, peer drops and reconnects almost
immediately. This caused a new download task to be assigned to
the peer, overwriting the old one still waiting for a timeout,
which in turned leaked the requests out, never to be retried.
The fix is to ensure that a task assignment moves any pending
one back into the retry queue.
The commit also fixes a regression with peer dropping due to
stalls. The current code considered a peer stalling if they
timed out delivering 1 item. However, the downloader never
requests only one, the minimum is 2 (attempt to fine tune
estimated latency/bandwidth). The fix is simply to drop if
a timeout is detected at 2 items.
Apart from the above bugfixes, the commit contains some code
polishes I made while debugging the hang.
* core, eth, trie: support batched trie sync db writes
* trie: rename SyncMemCache to syncMemBatch
2017-06-22 15:26:03 +03:00
|
|
|
queued := q.blockTaskQueue.Size() + q.receiptTaskQueue.Size()
|
|
|
|
pending := len(q.blockPendPool) + len(q.receiptPendPool)
|
2015-05-06 15:32:53 +03:00
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
return (queued + pending) == 0
|
2015-05-06 15:32:53 +03:00
|
|
|
}
|
2015-04-18 19:54:57 +03:00
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// ScheduleSkeleton adds a batch of header retrieval tasks to the queue to fill
|
|
|
|
// up an already retrieved header skeleton.
|
|
|
|
func (q *queue) ScheduleSkeleton(from uint64, skeleton []*types.Header) {
|
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
// No skeleton retrieval can be in progress, fail hard if so (huge implementation bug)
|
|
|
|
if q.headerResults != nil {
|
|
|
|
panic("skeleton assembly already in progress")
|
|
|
|
}
|
2018-04-04 13:25:02 +03:00
|
|
|
// Schedule all the header retrieval tasks for the skeleton assembly
|
2016-02-25 18:36:42 +02:00
|
|
|
q.headerTaskPool = make(map[uint64]*types.Header)
|
2018-09-03 18:33:21 +03:00
|
|
|
q.headerTaskQueue = prque.New(nil)
|
2016-02-25 18:36:42 +02:00
|
|
|
q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
|
|
|
|
q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
|
2016-04-19 12:27:37 +03:00
|
|
|
q.headerProced = 0
|
2016-02-25 18:36:42 +02:00
|
|
|
q.headerOffset = from
|
|
|
|
q.headerContCh = make(chan bool, 1)
|
|
|
|
|
|
|
|
for i, header := range skeleton {
|
|
|
|
index := from + uint64(i*MaxHeaderFetch)
|
|
|
|
|
|
|
|
q.headerTaskPool[index] = header
|
2018-09-03 18:33:21 +03:00
|
|
|
q.headerTaskQueue.Push(index, -int64(index))
|
2016-02-25 18:36:42 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RetrieveHeaders retrieves the header chain assemble based on the scheduled
|
|
|
|
// skeleton.
|
2016-04-19 12:27:37 +03:00
|
|
|
func (q *queue) RetrieveHeaders() ([]*types.Header, int) {
|
2016-02-25 18:36:42 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2016-04-19 12:27:37 +03:00
|
|
|
headers, proced := q.headerResults, q.headerProced
|
|
|
|
q.headerResults, q.headerProced = nil, 0
|
2016-02-25 18:36:42 +02:00
|
|
|
|
2016-04-19 12:27:37 +03:00
|
|
|
return headers, proced
|
2016-02-25 18:36:42 +02:00
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// Schedule adds a set of headers for the download queue for scheduling, returning
|
2015-08-14 21:25:41 +03:00
|
|
|
// the new headers encountered.
|
2015-10-05 19:37:56 +03:00
|
|
|
func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
|
2015-08-14 21:25:41 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2015-10-13 12:04:25 +03:00
|
|
|
// Insert all the headers prioritised by the contained block number
|
2015-08-14 21:25:41 +03:00
|
|
|
inserts := make([]*types.Header, 0, len(headers))
|
|
|
|
for _, header := range headers {
|
2015-10-13 12:04:25 +03:00
|
|
|
// Make sure chain order is honoured and preserved throughout
|
2015-09-28 19:27:31 +03:00
|
|
|
hash := header.Hash()
|
2015-09-15 13:33:45 +03:00
|
|
|
if header.Number == nil || header.Number.Uint64() != from {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
|
2015-09-15 13:33:45 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
|
2015-09-15 13:33:45 +03:00
|
|
|
break
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
// Make sure no duplicate requests are executed
|
2020-07-24 10:46:26 +03:00
|
|
|
// We cannot skip this, even if the block is empty, since this is
|
|
|
|
// what triggers the fetchResult creation.
|
2015-09-28 19:27:31 +03:00
|
|
|
if _, ok := q.blockTaskPool[hash]; ok {
|
2018-11-15 17:31:24 +03:00
|
|
|
log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash)
|
2020-07-24 10:46:26 +03:00
|
|
|
} else {
|
|
|
|
q.blockTaskPool[hash] = header
|
|
|
|
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
// Queue for receipt retrieval
|
|
|
|
if q.mode == FastSync && !header.EmptyReceipts() {
|
|
|
|
if _, ok := q.receiptTaskPool[hash]; ok {
|
|
|
|
log.Warn("Header already scheduled for receipt fetch", "number", header.Number, "hash", hash)
|
|
|
|
} else {
|
|
|
|
q.receiptTaskPool[hash] = header
|
|
|
|
q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2015-08-14 21:25:41 +03:00
|
|
|
inserts = append(inserts, header)
|
2015-09-15 13:33:45 +03:00
|
|
|
q.headerHead = hash
|
|
|
|
from++
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
return inserts
|
|
|
|
}
|
|
|
|
|
2018-02-05 19:40:32 +03:00
|
|
|
// Results retrieves and permanently removes a batch of fetch results from
|
2020-07-24 10:46:26 +03:00
|
|
|
// the cache. the result slice will be empty if the queue has been closed.
|
|
|
|
// Results can be called concurrently with Deliver and Schedule,
|
|
|
|
// but assumes that there are not two simultaneous callers to Results
|
2018-02-05 19:40:32 +03:00
|
|
|
func (q *queue) Results(block bool) []*fetchResult {
|
2020-07-24 10:46:26 +03:00
|
|
|
// Abort early if there are no items and non-blocking requested
|
|
|
|
if !block && !q.resultCache.HasCompletedItems() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
closed := false
|
|
|
|
for !closed && !q.resultCache.HasCompletedItems() {
|
|
|
|
// In order to wait on 'active', we need to obtain the lock.
|
|
|
|
// That may take a while, if someone is delivering at the same
|
|
|
|
// time, so after obtaining the lock, we check again if there
|
|
|
|
// are any results to fetch.
|
|
|
|
// Also, in-between we ask for the lock and the lock is obtained,
|
|
|
|
// someone can have closed the queue. In that case, we should
|
|
|
|
// return the available results and stop blocking
|
|
|
|
q.lock.Lock()
|
|
|
|
if q.resultCache.HasCompletedItems() || q.closed {
|
|
|
|
q.lock.Unlock()
|
|
|
|
break
|
2018-02-05 19:40:32 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
// No items available, and not closed
|
2015-11-13 18:08:15 +02:00
|
|
|
q.active.Wait()
|
2020-07-24 10:46:26 +03:00
|
|
|
closed = q.closed
|
|
|
|
q.lock.Unlock()
|
|
|
|
}
|
|
|
|
// Regardless if closed or not, we can still deliver whatever we have
|
|
|
|
results := q.resultCache.GetCompleted(maxResultsProcess)
|
|
|
|
for _, result := range results {
|
|
|
|
// Recalculate the result item weights to prevent memory exhaustion
|
|
|
|
size := result.Header.Size()
|
|
|
|
for _, uncle := range result.Uncles {
|
|
|
|
size += uncle.Size()
|
2015-10-07 12:14:30 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
for _, receipt := range result.Receipts {
|
|
|
|
size += receipt.Size()
|
2015-10-13 12:04:25 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
for _, tx := range result.Transactions {
|
|
|
|
size += tx.Size()
|
2018-02-05 19:40:32 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
q.resultSize = common.StorageSize(blockCacheSizeWeight)*size +
|
|
|
|
(1-common.StorageSize(blockCacheSizeWeight))*q.resultSize
|
|
|
|
}
|
|
|
|
// Using the newly calibrated resultsize, figure out the new throttle limit
|
|
|
|
// on the result cache
|
|
|
|
throttleThreshold := uint64((common.StorageSize(blockCacheMemory) + q.resultSize - 1) / q.resultSize)
|
|
|
|
throttleThreshold = q.resultCache.SetThrottleThreshold(throttleThreshold)
|
|
|
|
|
|
|
|
// Log some info at certain times
|
2020-09-01 12:02:12 +03:00
|
|
|
if time.Since(q.lastStatLog) > 60*time.Second {
|
2020-07-24 10:46:26 +03:00
|
|
|
q.lastStatLog = time.Now()
|
|
|
|
info := q.Stats()
|
|
|
|
info = append(info, "throttle", throttleThreshold)
|
|
|
|
log.Info("Downloader queue stats", info...)
|
2015-10-05 19:37:56 +03:00
|
|
|
}
|
2015-11-13 18:08:15 +02:00
|
|
|
return results
|
2015-05-01 01:23:51 +03:00
|
|
|
}
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
func (q *queue) Stats() []interface{} {
|
|
|
|
q.lock.RLock()
|
|
|
|
defer q.lock.RUnlock()
|
|
|
|
|
|
|
|
return q.stats()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q *queue) stats() []interface{} {
|
|
|
|
return []interface{}{
|
|
|
|
"receiptTasks", q.receiptTaskQueue.Size(),
|
|
|
|
"blockTasks", q.blockTaskQueue.Size(),
|
|
|
|
"itemSize", q.resultSize,
|
2015-05-06 15:32:53 +03:00
|
|
|
}
|
2015-05-01 01:23:51 +03:00
|
|
|
}
|
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// ReserveHeaders reserves a set of headers for the given peer, skipping any
|
|
|
|
// previously failed batches.
|
2017-06-28 15:25:08 +03:00
|
|
|
func (q *queue) ReserveHeaders(p *peerConnection, count int) *fetchRequest {
|
2016-02-25 18:36:42 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
// Short circuit if the peer's already downloading something (sanity check to
|
|
|
|
// not corrupt state)
|
|
|
|
if _, ok := q.headerPendPool[p.id]; ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// Retrieve a batch of hashes, skipping previously failed ones
|
|
|
|
send, skip := uint64(0), []uint64{}
|
|
|
|
for send == 0 && !q.headerTaskQueue.Empty() {
|
|
|
|
from, _ := q.headerTaskQueue.Pop()
|
|
|
|
if q.headerPeerMiss[p.id] != nil {
|
|
|
|
if _, ok := q.headerPeerMiss[p.id][from.(uint64)]; ok {
|
|
|
|
skip = append(skip, from.(uint64))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
send = from.(uint64)
|
|
|
|
}
|
|
|
|
// Merge all the skipped batches back
|
|
|
|
for _, from := range skip {
|
2018-09-03 18:33:21 +03:00
|
|
|
q.headerTaskQueue.Push(from, -int64(from))
|
2016-02-25 18:36:42 +02:00
|
|
|
}
|
|
|
|
// Assemble and return the block download request
|
|
|
|
if send == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
request := &fetchRequest{
|
|
|
|
Peer: p,
|
|
|
|
From: send,
|
|
|
|
Time: time.Now(),
|
|
|
|
}
|
|
|
|
q.headerPendPool[p.id] = request
|
|
|
|
return request
|
|
|
|
}
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// ReserveBodies reserves a set of body fetches for the given peer, skipping any
|
2015-09-28 19:27:31 +03:00
|
|
|
// previously failed downloads. Beside the next batch of needed fetches, it also
|
|
|
|
// returns a flag whether empty blocks were queued requiring processing.
|
2020-07-24 10:46:26 +03:00
|
|
|
func (q *queue) ReserveBodies(p *peerConnection, count int) (*fetchRequest, bool, bool) {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, bodyType)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReserveReceipts reserves a set of receipt fetches for the given peer, skipping
|
|
|
|
// any previously failed downloads. Beside the next batch of needed fetches, it
|
|
|
|
// also returns a flag whether empty receipts were queued requiring importing.
|
2020-07-24 10:46:26 +03:00
|
|
|
func (q *queue) ReserveReceipts(p *peerConnection, count int) (*fetchRequest, bool, bool) {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, receiptType)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// reserveHeaders reserves a set of data download operations for a given peer,
|
2015-09-28 19:27:31 +03:00
|
|
|
// skipping any previously failed ones. This method is a generic version used
|
|
|
|
// by the individual special reservation functions.
|
2015-10-13 12:04:25 +03:00
|
|
|
//
|
|
|
|
// Note, this method expects the queue lock to be already held for writing. The
|
|
|
|
// reason the lock is not obtained in here is because the parameters already need
|
|
|
|
// to access the queue, so they already need a lock anyway.
|
2020-07-24 10:46:26 +03:00
|
|
|
//
|
|
|
|
// Returns:
|
|
|
|
// item - the fetchRequest
|
|
|
|
// progress - whether any progress was made
|
|
|
|
// throttle - if the caller should throttle for a while
|
2017-06-28 15:25:08 +03:00
|
|
|
func (q *queue) reserveHeaders(p *peerConnection, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
|
2020-07-24 10:46:26 +03:00
|
|
|
pendPool map[string]*fetchRequest, kind uint) (*fetchRequest, bool, bool) {
|
2015-08-14 21:25:41 +03:00
|
|
|
// Short circuit if the pool has been depleted, or if the peer's already
|
|
|
|
// downloading something (sanity check not to corrupt state)
|
2015-09-28 19:27:31 +03:00
|
|
|
if taskQueue.Empty() {
|
2020-07-24 10:46:26 +03:00
|
|
|
return nil, false, true
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
if _, ok := pendPool[p.id]; ok {
|
2020-07-24 10:46:26 +03:00
|
|
|
return nil, false, false
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
// Retrieve a batch of tasks, skipping previously failed ones
|
2015-08-14 21:25:41 +03:00
|
|
|
send := make([]*types.Header, 0, count)
|
|
|
|
skip := make([]*types.Header, 0)
|
2015-09-28 19:27:31 +03:00
|
|
|
progress := false
|
2020-07-24 10:46:26 +03:00
|
|
|
throttled := false
|
|
|
|
for proc := 0; len(send) < count && !taskQueue.Empty(); proc++ {
|
|
|
|
// the task queue will pop items in order, so the highest prio block
|
|
|
|
// is also the lowest block number.
|
|
|
|
h, _ := taskQueue.Peek()
|
|
|
|
header := h.(*types.Header)
|
|
|
|
// we can ask the resultcache if this header is within the
|
|
|
|
// "prioritized" segment of blocks. If it is not, we need to throttle
|
|
|
|
|
|
|
|
stale, throttle, item, err := q.resultCache.AddFetch(header, q.mode == FastSync)
|
|
|
|
if stale {
|
|
|
|
// Don't put back in the task queue, this item has already been
|
|
|
|
// delivered upstream
|
|
|
|
taskQueue.PopItem()
|
|
|
|
progress = true
|
|
|
|
delete(taskPool, header.Hash())
|
|
|
|
proc = proc - 1
|
|
|
|
log.Error("Fetch reservation already delivered", "number", header.Number.Uint64())
|
|
|
|
continue
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
if throttle {
|
|
|
|
// There are no resultslots available. Leave it in the task queue
|
|
|
|
// However, if there are any left as 'skipped', we should not tell
|
|
|
|
// the caller to throttle, since we still want some other
|
|
|
|
// peer to fetch those for us
|
|
|
|
throttled = len(skip) == 0
|
|
|
|
break
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
if err != nil {
|
|
|
|
// this most definitely should _not_ happen
|
|
|
|
log.Warn("Failed to reserve headers", "err", err)
|
|
|
|
// There are no resultslots available. Leave it in the task queue
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if item.Done(kind) {
|
|
|
|
// If it's a noop, we can skip this task
|
|
|
|
delete(taskPool, header.Hash())
|
|
|
|
taskQueue.PopItem()
|
|
|
|
proc = proc - 1
|
2015-09-28 19:27:31 +03:00
|
|
|
progress = true
|
2015-08-14 21:25:41 +03:00
|
|
|
continue
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
// Remove it from the task queue
|
|
|
|
taskQueue.PopItem()
|
2015-10-13 12:04:25 +03:00
|
|
|
// Otherwise unless the peer is known not to have the data, add to the retrieve list
|
2020-07-24 10:46:26 +03:00
|
|
|
if p.Lacks(header.Hash()) {
|
2015-08-14 21:25:41 +03:00
|
|
|
skip = append(skip, header)
|
|
|
|
} else {
|
|
|
|
send = append(send, header)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Merge all the skipped headers back
|
|
|
|
for _, header := range skip {
|
2018-09-03 18:33:21 +03:00
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
if q.resultCache.HasCompletedItems() {
|
2018-10-23 14:21:16 +03:00
|
|
|
// Wake Results, resultCache was modified
|
2015-11-13 18:08:15 +02:00
|
|
|
q.active.Signal()
|
|
|
|
}
|
2015-08-14 21:25:41 +03:00
|
|
|
// Assemble and return the block download request
|
|
|
|
if len(send) == 0 {
|
2020-07-24 10:46:26 +03:00
|
|
|
return nil, progress, throttled
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
request := &fetchRequest{
|
|
|
|
Peer: p,
|
|
|
|
Headers: send,
|
|
|
|
Time: time.Now(),
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
pendPool[p.id] = request
|
2020-07-24 10:46:26 +03:00
|
|
|
return request, progress, throttled
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// CancelHeaders aborts a fetch request, returning all pending skeleton indexes to the queue.
|
|
|
|
func (q *queue) CancelHeaders(request *fetchRequest) {
|
2020-02-25 12:44:21 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2016-02-25 18:36:42 +02:00
|
|
|
q.cancel(request, q.headerTaskQueue, q.headerPendPool)
|
|
|
|
}
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// CancelBodies aborts a body fetch request, returning all pending headers to the
|
2015-09-28 19:27:31 +03:00
|
|
|
// task queue.
|
2015-10-05 19:37:56 +03:00
|
|
|
func (q *queue) CancelBodies(request *fetchRequest) {
|
2020-02-25 12:44:21 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-09-28 19:27:31 +03:00
|
|
|
q.cancel(request, q.blockTaskQueue, q.blockPendPool)
|
|
|
|
}
|
2015-08-14 21:25:41 +03:00
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// CancelReceipts aborts a body fetch request, returning all pending headers to
|
2015-09-28 19:27:31 +03:00
|
|
|
// the task queue.
|
|
|
|
func (q *queue) CancelReceipts(request *fetchRequest) {
|
2020-02-25 12:44:21 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-09-28 19:27:31 +03:00
|
|
|
q.cancel(request, q.receiptTaskQueue, q.receiptPendPool)
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// Cancel aborts a fetch request, returning all pending hashes to the task queue.
|
|
|
|
func (q *queue) cancel(request *fetchRequest, taskQueue *prque.Prque, pendPool map[string]*fetchRequest) {
|
2016-02-25 18:36:42 +02:00
|
|
|
if request.From > 0 {
|
2018-09-03 18:33:21 +03:00
|
|
|
taskQueue.Push(request.From, -int64(request.From))
|
2016-02-25 18:36:42 +02:00
|
|
|
}
|
2015-08-14 21:25:41 +03:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 18:33:21 +03:00
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
delete(pendPool, request.Peer.id)
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// Revoke cancels all pending requests belonging to a given peer. This method is
|
|
|
|
// meant to be called during a peer drop to quickly reassign owned data fetches
|
|
|
|
// to remaining nodes.
|
2018-06-14 13:14:52 +03:00
|
|
|
func (q *queue) Revoke(peerID string) {
|
2015-09-28 19:27:31 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2018-06-14 13:14:52 +03:00
|
|
|
if request, ok := q.blockPendPool[peerID]; ok {
|
2015-09-28 19:27:31 +03:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 18:33:21 +03:00
|
|
|
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2018-06-14 13:14:52 +03:00
|
|
|
delete(q.blockPendPool, peerID)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2018-06-14 13:14:52 +03:00
|
|
|
if request, ok := q.receiptPendPool[peerID]; ok {
|
2015-09-28 19:27:31 +03:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 18:33:21 +03:00
|
|
|
q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2018-06-14 13:14:52 +03:00
|
|
|
delete(q.receiptPendPool, peerID)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// ExpireHeaders checks for in flight requests that exceeded a timeout allowance,
|
|
|
|
// canceling them and returning the responsible peers for penalisation.
|
|
|
|
func (q *queue) ExpireHeaders(timeout time.Duration) map[string]int {
|
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
return q.expire(timeout, q.headerPendPool, q.headerTaskQueue, headerTimeoutMeter)
|
|
|
|
}
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// ExpireBodies checks for in flight block body requests that exceeded a timeout
|
2015-10-13 12:04:25 +03:00
|
|
|
// allowance, canceling them and returning the responsible peers for penalisation.
|
2015-10-29 19:37:26 +03:00
|
|
|
func (q *queue) ExpireBodies(timeout time.Duration) map[string]int {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
return q.expire(timeout, q.blockPendPool, q.blockTaskQueue, bodyTimeoutMeter)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ExpireReceipts checks for in flight receipt requests that exceeded a timeout
|
2015-10-13 12:04:25 +03:00
|
|
|
// allowance, canceling them and returning the responsible peers for penalisation.
|
2015-10-29 19:37:26 +03:00
|
|
|
func (q *queue) ExpireReceipts(timeout time.Duration) map[string]int {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
return q.expire(timeout, q.receiptPendPool, q.receiptTaskQueue, receiptTimeoutMeter)
|
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// expire is the generic check that move expired tasks from a pending pool back
|
|
|
|
// into a task pool, returning all entities caught with expired tasks.
|
2015-10-13 12:04:25 +03:00
|
|
|
//
|
2015-11-13 18:08:15 +02:00
|
|
|
// Note, this method expects the queue lock to be already held. The
|
2015-10-13 12:04:25 +03:00
|
|
|
// reason the lock is not obtained in here is because the parameters already need
|
|
|
|
// to access the queue, so they already need a lock anyway.
|
2015-10-29 19:37:26 +03:00
|
|
|
func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest, taskQueue *prque.Prque, timeoutMeter metrics.Meter) map[string]int {
|
2015-05-06 15:32:53 +03:00
|
|
|
// Iterate over the expired requests and return each to the queue
|
2015-10-29 19:37:26 +03:00
|
|
|
expiries := make(map[string]int)
|
2015-09-28 19:27:31 +03:00
|
|
|
for id, request := range pendPool {
|
2015-05-06 15:32:53 +03:00
|
|
|
if time.Since(request.Time) > timeout {
|
2015-08-25 13:57:49 +03:00
|
|
|
// Update the metrics with the timeout
|
2015-10-05 19:37:56 +03:00
|
|
|
timeoutMeter.Mark(1)
|
|
|
|
|
2015-08-25 13:57:49 +03:00
|
|
|
// Return any non satisfied requests to the pool
|
2016-02-25 18:36:42 +02:00
|
|
|
if request.From > 0 {
|
2018-09-03 18:33:21 +03:00
|
|
|
taskQueue.Push(request.From, -int64(request.From))
|
2016-02-25 18:36:42 +02:00
|
|
|
}
|
2015-08-25 13:57:49 +03:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 18:33:21 +03:00
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-25 13:57:49 +03:00
|
|
|
}
|
2018-08-27 11:49:29 +03:00
|
|
|
// Add the peer to the expiry report along the number of failed requests
|
2018-02-05 19:40:32 +03:00
|
|
|
expiries[id] = len(request.Headers)
|
2018-11-07 16:30:19 +03:00
|
|
|
|
|
|
|
// Remove the expired requests from the pending pool directly
|
|
|
|
delete(pendPool, id)
|
2015-05-06 15:32:53 +03:00
|
|
|
}
|
|
|
|
}
|
2015-10-29 19:37:26 +03:00
|
|
|
return expiries
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|
|
|
|
|
2016-02-25 18:36:42 +02:00
|
|
|
// DeliverHeaders injects a header retrieval response into the header results
|
|
|
|
// cache. This method either accepts all headers it received, or none of them
|
|
|
|
// if they do not map correctly to the skeleton.
|
2016-04-19 12:27:37 +03:00
|
|
|
//
|
|
|
|
// If the headers are accepted, the method makes an attempt to deliver the set
|
|
|
|
// of ready headers to the processor to keep the pipeline full. However it will
|
|
|
|
// not block to prevent stalling other pending deliveries.
|
|
|
|
func (q *queue) DeliverHeaders(id string, headers []*types.Header, headerProcCh chan []*types.Header) (int, error) {
|
2016-02-25 18:36:42 +02:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
|
|
|
// Short circuit if the data was never requested
|
|
|
|
request := q.headerPendPool[id]
|
|
|
|
if request == nil {
|
|
|
|
return 0, errNoFetchesPending
|
|
|
|
}
|
|
|
|
headerReqTimer.UpdateSince(request.Time)
|
|
|
|
delete(q.headerPendPool, id)
|
|
|
|
|
|
|
|
// Ensure headers can be mapped onto the skeleton chain
|
|
|
|
target := q.headerTaskPool[request.From].Hash()
|
|
|
|
|
|
|
|
accepted := len(headers) == MaxHeaderFetch
|
|
|
|
if accepted {
|
|
|
|
if headers[0].Number.Uint64() != request.From {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Trace("First header broke chain ordering", "peer", id, "number", headers[0].Number, "hash", headers[0].Hash(), request.From)
|
2016-02-25 18:36:42 +02:00
|
|
|
accepted = false
|
|
|
|
} else if headers[len(headers)-1].Hash() != target {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Trace("Last header broke skeleton structure ", "peer", id, "number", headers[len(headers)-1].Number, "hash", headers[len(headers)-1].Hash(), "expected", target)
|
2016-02-25 18:36:42 +02:00
|
|
|
accepted = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if accepted {
|
|
|
|
for i, header := range headers[1:] {
|
|
|
|
hash := header.Hash()
|
|
|
|
if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Warn("Header broke chain ordering", "peer", id, "number", header.Number, "hash", hash, "expected", want)
|
2016-02-25 18:36:42 +02:00
|
|
|
accepted = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if headers[i].Hash() != header.ParentHash {
|
2017-02-27 18:06:40 +03:00
|
|
|
log.Warn("Header broke chain ancestry", "peer", id, "number", header.Number, "hash", hash)
|
2016-02-25 18:36:42 +02:00
|
|
|
accepted = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// If the batch of headers wasn't accepted, mark as unavailable
|
|
|
|
if !accepted {
|
2017-02-24 19:23:03 +03:00
|
|
|
log.Trace("Skeleton filling not accepted", "peer", id, "from", request.From)
|
2016-02-25 18:36:42 +02:00
|
|
|
|
|
|
|
miss := q.headerPeerMiss[id]
|
|
|
|
if miss == nil {
|
|
|
|
q.headerPeerMiss[id] = make(map[uint64]struct{})
|
|
|
|
miss = q.headerPeerMiss[id]
|
|
|
|
}
|
|
|
|
miss[request.From] = struct{}{}
|
|
|
|
|
2018-09-03 18:33:21 +03:00
|
|
|
q.headerTaskQueue.Push(request.From, -int64(request.From))
|
2016-02-25 18:36:42 +02:00
|
|
|
return 0, errors.New("delivery not accepted")
|
|
|
|
}
|
2016-04-19 12:27:37 +03:00
|
|
|
// Clean up a successful fetch and try to deliver any sub-results
|
2016-02-25 18:36:42 +02:00
|
|
|
copy(q.headerResults[request.From-q.headerOffset:], headers)
|
|
|
|
delete(q.headerTaskPool, request.From)
|
|
|
|
|
2016-04-19 12:27:37 +03:00
|
|
|
ready := 0
|
|
|
|
for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
|
|
|
|
ready += MaxHeaderFetch
|
|
|
|
}
|
|
|
|
if ready > 0 {
|
|
|
|
// Headers are ready for delivery, gather them and push forward (non blocking)
|
|
|
|
process := make([]*types.Header, ready)
|
|
|
|
copy(process, q.headerResults[q.headerProced:q.headerProced+ready])
|
|
|
|
|
|
|
|
select {
|
|
|
|
case headerProcCh <- process:
|
2017-02-24 19:23:03 +03:00
|
|
|
log.Trace("Pre-scheduled new headers", "peer", id, "count", len(process), "from", process[0].Number)
|
2016-04-19 12:27:37 +03:00
|
|
|
q.headerProced += len(process)
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Check for termination and return
|
2016-02-25 18:36:42 +02:00
|
|
|
if len(q.headerTaskPool) == 0 {
|
|
|
|
q.headerContCh <- false
|
|
|
|
}
|
|
|
|
return len(headers), nil
|
|
|
|
}
|
|
|
|
|
2015-10-05 19:37:56 +03:00
|
|
|
// DeliverBodies injects a block body retrieval response into the results queue.
|
2015-10-29 19:37:26 +03:00
|
|
|
// The method returns the number of blocks bodies accepted from the delivery and
|
|
|
|
// also wakes any threads waiting for data delivery.
|
|
|
|
func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLists [][]*types.Header) (int, error) {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2020-07-24 10:46:26 +03:00
|
|
|
validate := func(index int, header *types.Header) error {
|
2020-08-21 15:10:40 +03:00
|
|
|
if types.DeriveSha(types.Transactions(txLists[index]), new(trie.Trie)) != header.TxHash {
|
2015-09-28 19:27:31 +03:00
|
|
|
return errInvalidBody
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
if types.CalcUncleHash(uncleLists[index]) != header.UncleHash {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
reconstruct := func(index int, result *fetchResult) {
|
2015-09-28 19:27:31 +03:00
|
|
|
result.Transactions = txLists[index]
|
|
|
|
result.Uncles = uncleLists[index]
|
2020-07-24 10:46:26 +03:00
|
|
|
result.SetBodyDone()
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool,
|
|
|
|
bodyReqTimer, len(txLists), validate, reconstruct)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeliverReceipts injects a receipt retrieval response into the results queue.
|
2015-10-29 19:37:26 +03:00
|
|
|
// The method returns the number of transaction receipts accepted from the delivery
|
|
|
|
// and also wakes any threads waiting for data delivery.
|
|
|
|
func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) (int, error) {
|
2015-10-13 12:04:25 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2020-07-24 10:46:26 +03:00
|
|
|
validate := func(index int, header *types.Header) error {
|
2020-08-21 15:10:40 +03:00
|
|
|
if types.DeriveSha(types.Receipts(receiptList[index]), new(trie.Trie)) != header.ReceiptHash {
|
2015-09-28 19:27:31 +03:00
|
|
|
return errInvalidReceipt
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
reconstruct := func(index int, result *fetchResult) {
|
|
|
|
result.Receipts = receiptList[index]
|
|
|
|
result.SetReceiptsDone()
|
|
|
|
}
|
|
|
|
return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool,
|
|
|
|
receiptReqTimer, len(receiptList), validate, reconstruct)
|
2015-09-28 19:27:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// deliver injects a data retrieval response into the results queue.
|
2015-10-13 12:04:25 +03:00
|
|
|
//
|
|
|
|
// Note, this method expects the queue lock to be already held for writing. The
|
2020-07-24 10:46:26 +03:00
|
|
|
// reason this lock is not obtained in here is because the parameters already need
|
2015-10-13 12:04:25 +03:00
|
|
|
// to access the queue, so they already need a lock anyway.
|
2020-07-24 10:46:26 +03:00
|
|
|
func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
|
|
|
|
taskQueue *prque.Prque, pendPool map[string]*fetchRequest, reqTimer metrics.Timer,
|
|
|
|
results int, validate func(index int, header *types.Header) error,
|
|
|
|
reconstruct func(index int, result *fetchResult)) (int, error) {
|
2015-10-29 19:37:26 +03:00
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// Short circuit if the data was never requested
|
|
|
|
request := pendPool[id]
|
2015-08-14 21:25:41 +03:00
|
|
|
if request == nil {
|
2015-10-29 19:37:26 +03:00
|
|
|
return 0, errNoFetchesPending
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
reqTimer.UpdateSince(request.Time)
|
|
|
|
delete(pendPool, id)
|
2015-08-14 21:25:41 +03:00
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// If no data items were retrieved, mark them as unavailable for the origin peer
|
|
|
|
if results == 0 {
|
2015-11-04 13:18:48 +03:00
|
|
|
for _, header := range request.Headers {
|
|
|
|
request.Peer.MarkLacking(header.Hash())
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
// Assemble each of the results with their headers and retrieved data parts
|
2015-10-13 12:04:25 +03:00
|
|
|
var (
|
2015-10-29 19:37:26 +03:00
|
|
|
accepted int
|
|
|
|
failure error
|
2020-07-24 10:46:26 +03:00
|
|
|
i int
|
|
|
|
hashes []common.Hash
|
2015-10-13 12:04:25 +03:00
|
|
|
)
|
2020-07-24 10:46:26 +03:00
|
|
|
for _, header := range request.Headers {
|
2015-09-28 19:27:31 +03:00
|
|
|
// Short circuit assembly if no more fetch results are found
|
|
|
|
if i >= results {
|
2015-08-14 21:25:41 +03:00
|
|
|
break
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
// Validate the fields
|
|
|
|
if err := validate(i, header); err != nil {
|
2015-10-13 12:04:25 +03:00
|
|
|
failure = err
|
2015-08-14 21:25:41 +03:00
|
|
|
break
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
hashes = append(hashes, header.Hash())
|
|
|
|
i++
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
|
2020-07-24 10:46:26 +03:00
|
|
|
for _, header := range request.Headers[:i] {
|
|
|
|
if res, stale, err := q.resultCache.GetDeliverySlot(header.Number.Uint64()); err == nil {
|
|
|
|
reconstruct(accepted, res)
|
|
|
|
} else {
|
|
|
|
// else: betweeen here and above, some other peer filled this result,
|
|
|
|
// or it was indeed a no-op. This should not happen, but if it does it's
|
|
|
|
// not something to panic about
|
|
|
|
log.Error("Delivery stale", "stale", stale, "number", header.Number.Uint64(), "err", err)
|
|
|
|
failure = errStaleDelivery
|
|
|
|
}
|
2015-09-28 19:27:31 +03:00
|
|
|
// Clean up a successful fetch
|
2020-07-24 10:46:26 +03:00
|
|
|
delete(taskPool, hashes[accepted])
|
|
|
|
accepted++
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
// Return all failed or missing fetches to the queue
|
2020-07-24 10:46:26 +03:00
|
|
|
for _, header := range request.Headers[accepted:] {
|
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2018-10-23 14:21:16 +03:00
|
|
|
// Wake up Results
|
2015-10-29 19:37:26 +03:00
|
|
|
if accepted > 0 {
|
|
|
|
q.active.Signal()
|
|
|
|
}
|
2020-05-29 12:12:43 +03:00
|
|
|
if failure == nil {
|
|
|
|
return accepted, nil
|
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
// If none of the data was good, it's a stale delivery
|
2020-05-29 12:12:43 +03:00
|
|
|
if errors.Is(failure, errInvalidChain) {
|
2015-10-29 19:37:26 +03:00
|
|
|
return accepted, failure
|
2020-05-29 12:12:43 +03:00
|
|
|
}
|
2020-07-24 10:46:26 +03:00
|
|
|
if accepted > 0 {
|
2015-10-29 19:37:26 +03:00
|
|
|
return accepted, fmt.Errorf("partial failure: %v", failure)
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
2020-05-29 12:12:43 +03:00
|
|
|
return accepted, fmt.Errorf("%w: %v", failure, errStaleDelivery)
|
2015-08-14 21:25:41 +03:00
|
|
|
}
|
|
|
|
|
2015-09-28 19:27:31 +03:00
|
|
|
// Prepare configures the result cache to allow accepting and caching inbound
|
|
|
|
// fetch results.
|
2018-02-05 19:40:32 +03:00
|
|
|
func (q *queue) Prepare(offset uint64, mode SyncMode) {
|
2015-05-06 15:32:53 +03:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2016-05-27 14:26:00 +03:00
|
|
|
// Prepare the queue for sync results
|
2020-07-24 10:46:26 +03:00
|
|
|
q.resultCache.Prepare(offset)
|
2015-10-05 19:37:56 +03:00
|
|
|
q.mode = mode
|
2015-04-12 13:38:25 +03:00
|
|
|
}
|