2015-07-07 00:54:22 +00:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 16:48:40 +00:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-07 00:54:22 +00:00
|
|
|
//
|
2015-07-23 16:35:11 +00:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-07 00:54:22 +00: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 16:48:40 +00:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-07 00:54:22 +00:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 16:48:40 +00:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-07 00:54:22 +00: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 16:48:40 +00:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-07 00:54:22 +00:00
|
|
|
|
2015-05-11 11:26:20 +00:00
|
|
|
// Contains the block download scheduler to collect download tasks and schedule
|
|
|
|
// them in an ordered, and throttled way.
|
|
|
|
|
2015-04-12 10:38:25 +00:00
|
|
|
package downloader
|
|
|
|
|
|
|
|
import (
|
2015-05-06 12:32:53 +00:00
|
|
|
"errors"
|
2015-05-03 12:11:00 +00:00
|
|
|
"fmt"
|
2015-04-12 10:38:25 +00:00
|
|
|
"sync"
|
2020-07-24 07:46:26 +00:00
|
|
|
"sync/atomic"
|
2015-04-12 10:38:25 +00:00
|
|
|
"time"
|
|
|
|
|
2015-04-13 14:38:32 +00:00
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2018-09-03 15:33:21 +00:00
|
|
|
"github.com/ethereum/go-ethereum/common/prque"
|
2015-04-12 10:38:25 +00:00
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
2024-01-19 10:41:17 +00:00
|
|
|
"github.com/ethereum/go-ethereum/crypto/kzg4844"
|
2017-02-22 12:10:07 +00:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2018-02-23 09:56:08 +00:00
|
|
|
"github.com/ethereum/go-ethereum/metrics"
|
2023-05-31 07:21:13 +00:00
|
|
|
"github.com/ethereum/go-ethereum/params"
|
2015-04-12 10:38:25 +00:00
|
|
|
)
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
const (
|
|
|
|
bodyType = uint(0)
|
|
|
|
receiptType = uint(1)
|
|
|
|
)
|
|
|
|
|
2018-02-05 16:40:32 +00:00
|
|
|
var (
|
2021-06-25 12:53:22 +00: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 = 256 * 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 16:40:32 +00:00
|
|
|
)
|
2015-05-06 12:32:53 +00:00
|
|
|
|
2015-06-05 09:37:48 +00:00
|
|
|
var (
|
|
|
|
errNoFetchesPending = errors.New("no fetches pending")
|
|
|
|
errStaleDelivery = errors.New("stale delivery")
|
|
|
|
)
|
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
// fetchRequest is a currently running data retrieval operation.
|
2015-05-06 12:32:53 +00:00
|
|
|
type fetchRequest struct {
|
2018-02-05 16:40:32 +00:00
|
|
|
Peer *peerConnection // Peer to which the request was sent
|
2021-11-26 11:26:03 +00:00
|
|
|
From uint64 // Requested chain element index (used for skeleton fills only)
|
|
|
|
Headers []*types.Header // Requested headers, sorted by request order
|
2018-02-05 16:40:32 +00:00
|
|
|
Time time.Time // Time when the request was made
|
2015-05-06 12:32:53 +00:00
|
|
|
}
|
|
|
|
|
2015-10-13 09:04:25 +00: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 16:27:31 +00:00
|
|
|
type fetchResult struct {
|
2023-04-03 19:48:10 +00:00
|
|
|
pending atomic.Int32 // Flag telling what deliveries are outstanding
|
2015-09-28 16:27:31 +00:00
|
|
|
|
|
|
|
Header *types.Header
|
|
|
|
Uncles []*types.Header
|
|
|
|
Transactions types.Transactions
|
|
|
|
Receipts types.Receipts
|
2023-01-25 14:32:25 +00:00
|
|
|
Withdrawals types.Withdrawals
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
|
|
|
|
item := &fetchResult{
|
|
|
|
Header: header,
|
|
|
|
}
|
|
|
|
if !header.EmptyBody() {
|
2023-04-03 19:48:10 +00:00
|
|
|
item.pending.Store(item.pending.Load() | (1 << bodyType))
|
2023-02-16 10:28:01 +00:00
|
|
|
} else if header.WithdrawalsHash != nil {
|
|
|
|
item.Withdrawals = make(types.Withdrawals, 0)
|
2020-07-24 07:46:26 +00:00
|
|
|
}
|
|
|
|
if fastSync && !header.EmptyReceipts() {
|
2023-04-03 19:48:10 +00:00
|
|
|
item.pending.Store(item.pending.Load() | (1 << receiptType))
|
2020-07-24 07:46:26 +00:00
|
|
|
}
|
|
|
|
return item
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetBodyDone flags the body as finished.
|
|
|
|
func (f *fetchResult) SetBodyDone() {
|
2023-04-03 19:48:10 +00:00
|
|
|
if v := f.pending.Load(); (v & (1 << bodyType)) != 0 {
|
|
|
|
f.pending.Add(-1)
|
2020-07-24 07:46:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// AllDone checks if item is done.
|
|
|
|
func (f *fetchResult) AllDone() bool {
|
2023-04-03 19:48:10 +00:00
|
|
|
return f.pending.Load() == 0
|
2020-07-24 07:46:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetReceiptsDone flags the receipts as finished.
|
|
|
|
func (f *fetchResult) SetReceiptsDone() {
|
2023-04-03 19:48:10 +00:00
|
|
|
if v := f.pending.Load(); (v & (1 << receiptType)) != 0 {
|
|
|
|
f.pending.Add(-2)
|
2020-07-24 07:46:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Done checks if the given type is done already
|
|
|
|
func (f *fetchResult) Done(kind uint) bool {
|
2023-04-03 19:48:10 +00:00
|
|
|
v := f.pending.Load()
|
2020-07-24 07:46:26 +00:00
|
|
|
return v&(1<<kind) == 0
|
|
|
|
}
|
|
|
|
|
2015-04-12 10:38:25 +00:00
|
|
|
// queue represents hashes that are either need fetching or are being fetched
|
|
|
|
type queue struct {
|
2018-02-05 16:40:32 +00:00
|
|
|
mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
|
2015-05-06 12:32:53 +00:00
|
|
|
|
2016-02-25 16:36:42 +00:00
|
|
|
// Headers are "special", they download in batches, supported by a skeleton chain
|
2020-12-14 09:27:15 +00:00
|
|
|
headerHead common.Hash // Hash of the last queued header to verify order
|
|
|
|
headerTaskPool map[uint64]*types.Header // Pending header retrieval tasks, mapping starting indexes to skeleton headers
|
2023-02-09 11:03:54 +00:00
|
|
|
headerTaskQueue *prque.Prque[int64, uint64] // Priority queue of the skeleton indexes to fetch the filling headers for
|
2020-12-14 09:27:15 +00:00
|
|
|
headerPeerMiss map[string]map[uint64]struct{} // Set of per-peer header batches known to be unavailable
|
|
|
|
headerPendPool map[string]*fetchRequest // Currently pending header retrieval operations
|
|
|
|
headerResults []*types.Header // Result cache accumulating the completed headers
|
2021-12-01 18:18:12 +00:00
|
|
|
headerHashes []common.Hash // Result cache accumulating the completed header hashes
|
2020-12-14 09:27:15 +00:00
|
|
|
headerProced int // Number of headers already processed from the results
|
|
|
|
headerOffset uint64 // Number of the first header in the result cache
|
|
|
|
headerContCh chan bool // Channel to notify when header download finishes
|
2016-02-25 16:36:42 +00:00
|
|
|
|
|
|
|
// All data retrievals below are based on an already assembles header chain
|
2023-02-09 11:03:54 +00:00
|
|
|
blockTaskPool map[common.Hash]*types.Header // Pending block (body) retrieval tasks, mapping hashes to headers
|
|
|
|
blockTaskQueue *prque.Prque[int64, *types.Header] // Priority queue of the headers to fetch the blocks (bodies) for
|
|
|
|
blockPendPool map[string]*fetchRequest // Currently pending block (body) retrieval operations
|
|
|
|
blockWakeCh chan bool // Channel to notify the block fetcher of new tasks
|
2015-04-12 10:38:25 +00:00
|
|
|
|
2023-02-09 11:03:54 +00:00
|
|
|
receiptTaskPool map[common.Hash]*types.Header // Pending receipt retrieval tasks, mapping hashes to headers
|
|
|
|
receiptTaskQueue *prque.Prque[int64, *types.Header] // Priority queue of the headers to fetch the receipts for
|
|
|
|
receiptPendPool map[string]*fetchRequest // Currently pending receipt retrieval operations
|
|
|
|
receiptWakeCh chan bool // Channel to notify when receipt fetcher of new tasks
|
2015-09-28 16:27:31 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
resultCache *resultStore // Downloaded but not yet delivered fetch results
|
|
|
|
resultSize common.StorageSize // Approximate size of a block (exponential moving average)
|
2015-04-30 22:23:51 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
lock *sync.RWMutex
|
2015-11-13 16:08:15 +00:00
|
|
|
active *sync.Cond
|
|
|
|
closed bool
|
2020-07-24 07:46:26 +00:00
|
|
|
|
2023-02-21 10:17:34 +00:00
|
|
|
logTime time.Time // Time instance when status was last reported
|
2015-04-12 10:38:25 +00:00
|
|
|
}
|
|
|
|
|
2015-05-06 12:32:53 +00:00
|
|
|
// newQueue creates a new download queue for scheduling block retrieval.
|
2020-09-02 09:01:46 +00:00
|
|
|
func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
|
2020-07-24 07:46:26 +00:00
|
|
|
lock := new(sync.RWMutex)
|
|
|
|
q := &queue{
|
2021-11-26 11:26:03 +00:00
|
|
|
headerContCh: make(chan bool, 1),
|
2023-02-09 11:03:54 +00:00
|
|
|
blockTaskQueue: prque.New[int64, *types.Header](nil),
|
2021-11-26 11:26:03 +00:00
|
|
|
blockWakeCh: make(chan bool, 1),
|
2023-02-09 11:03:54 +00:00
|
|
|
receiptTaskQueue: prque.New[int64, *types.Header](nil),
|
2021-11-26 11:26:03 +00:00
|
|
|
receiptWakeCh: make(chan bool, 1),
|
2015-11-13 16:08:15 +00:00
|
|
|
active: sync.NewCond(lock),
|
|
|
|
lock: lock,
|
2015-04-12 10:38:25 +00:00
|
|
|
}
|
2020-09-02 09:01:46 +00:00
|
|
|
q.Reset(blockCacheLimit, thresholdInitialSize)
|
2020-07-24 07:46:26 +00:00
|
|
|
return q
|
2015-04-12 10:38:25 +00:00
|
|
|
}
|
|
|
|
|
2015-05-06 12:32:53 +00:00
|
|
|
// Reset clears out the queue contents.
|
2020-09-02 09:01:46 +00:00
|
|
|
func (q *queue) Reset(blockCacheLimit int, thresholdInitialSize int) {
|
2015-05-06 12:32:53 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-18 13:14:12 +00:00
|
|
|
|
2015-11-13 16:08:15 +00:00
|
|
|
q.closed = false
|
2015-10-05 16:37:56 +00:00
|
|
|
q.mode = FullSync
|
|
|
|
|
2015-09-15 10:33:45 +00:00
|
|
|
q.headerHead = common.Hash{}
|
2016-02-25 16:36:42 +00:00
|
|
|
q.headerPendPool = make(map[string]*fetchRequest)
|
|
|
|
|
2015-09-28 16:27:31 +00: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 12:32:53 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
q.resultCache = newResultStore(blockCacheLimit)
|
2020-09-02 09:01:46 +00:00
|
|
|
q.resultCache.SetThrottleThreshold(uint64(thresholdInitialSize))
|
2015-04-30 22:23:51 +00:00
|
|
|
}
|
2015-05-06 12:32:53 +00:00
|
|
|
|
2018-10-23 11:21:16 +00:00
|
|
|
// Close marks the end of the sync, unblocking Results.
|
2015-11-13 16:08:15 +00: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 07:46:26 +00:00
|
|
|
q.active.Signal()
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Unlock()
|
|
|
|
}
|
|
|
|
|
2016-02-25 16:36:42 +00: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()
|
|
|
|
}
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
// PendingBodies retrieves the number of block body requests pending for retrieval.
|
|
|
|
func (q *queue) PendingBodies() int {
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-05-06 12:32:53 +00:00
|
|
|
|
2016-07-21 09:36:38 +00:00
|
|
|
return q.blockTaskQueue.Size()
|
2015-04-30 22:23:51 +00:00
|
|
|
}
|
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
// PendingReceipts retrieves the number of block receipts pending for retrieval.
|
|
|
|
func (q *queue) PendingReceipts() int {
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-12 10:38:25 +00:00
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
return q.receiptTaskQueue.Size()
|
2015-05-06 12:32:53 +00:00
|
|
|
}
|
2015-04-12 10:38:25 +00:00
|
|
|
|
2015-10-07 09:14:30 +00:00
|
|
|
// InFlightBlocks retrieves whether there are block fetch requests currently in
|
|
|
|
// flight.
|
|
|
|
func (q *queue) InFlightBlocks() bool {
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-10-05 16:37:56 +00:00
|
|
|
|
2015-10-07 09:14:30 +00:00
|
|
|
return len(q.blockPendPool) > 0
|
2015-10-05 16:37:56 +00:00
|
|
|
}
|
|
|
|
|
2015-10-07 09:14:30 +00:00
|
|
|
// InFlightReceipts retrieves whether there are receipt fetch requests currently
|
|
|
|
// in flight.
|
|
|
|
func (q *queue) InFlightReceipts() bool {
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-04-12 10:38:25 +00:00
|
|
|
|
2015-10-07 09:14:30 +00: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 12:26:03 +00:00
|
|
|
// Idle returns if the queue is fully idle or has some data still inside.
|
2015-09-28 16:27:31 +00:00
|
|
|
func (q *queue) Idle() bool {
|
2015-11-13 16:08:15 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2015-09-28 16:27:31 +00: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 12:26:03 +00:00
|
|
|
queued := q.blockTaskQueue.Size() + q.receiptTaskQueue.Size()
|
|
|
|
pending := len(q.blockPendPool) + len(q.receiptPendPool)
|
2015-05-06 12:32:53 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
return (queued + pending) == 0
|
2015-05-06 12:32:53 +00:00
|
|
|
}
|
2015-04-18 16:54:57 +00:00
|
|
|
|
2016-02-25 16:36:42 +00: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 10:25:02 +00:00
|
|
|
// Schedule all the header retrieval tasks for the skeleton assembly
|
2016-02-25 16:36:42 +00:00
|
|
|
q.headerTaskPool = make(map[uint64]*types.Header)
|
2023-02-09 11:03:54 +00:00
|
|
|
q.headerTaskQueue = prque.New[int64, uint64](nil)
|
2016-02-25 16:36:42 +00:00
|
|
|
q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
|
|
|
|
q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
|
2021-12-01 18:18:12 +00:00
|
|
|
q.headerHashes = make([]common.Hash, len(skeleton)*MaxHeaderFetch)
|
2016-04-19 09:27:37 +00:00
|
|
|
q.headerProced = 0
|
2016-02-25 16:36:42 +00: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 15:33:21 +00:00
|
|
|
q.headerTaskQueue.Push(index, -int64(index))
|
2016-02-25 16:36:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RetrieveHeaders retrieves the header chain assemble based on the scheduled
|
|
|
|
// skeleton.
|
2021-12-01 18:18:12 +00:00
|
|
|
func (q *queue) RetrieveHeaders() ([]*types.Header, []common.Hash, int) {
|
2016-02-25 16:36:42 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2021-12-01 18:18:12 +00:00
|
|
|
headers, hashes, proced := q.headerResults, q.headerHashes, q.headerProced
|
|
|
|
q.headerResults, q.headerHashes, q.headerProced = nil, nil, 0
|
2016-02-25 16:36:42 +00:00
|
|
|
|
2021-12-01 18:18:12 +00:00
|
|
|
return headers, hashes, proced
|
2016-02-25 16:36:42 +00:00
|
|
|
}
|
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
// Schedule adds a set of headers for the download queue for scheduling, returning
|
2015-08-14 18:25:41 +00:00
|
|
|
// the new headers encountered.
|
2021-12-01 18:18:12 +00:00
|
|
|
func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uint64) []*types.Header {
|
2015-08-14 18:25:41 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2015-10-13 09:04:25 +00:00
|
|
|
// Insert all the headers prioritised by the contained block number
|
2015-08-14 18:25:41 +00:00
|
|
|
inserts := make([]*types.Header, 0, len(headers))
|
2021-12-01 18:18:12 +00:00
|
|
|
for i, header := range headers {
|
2015-10-13 09:04:25 +00:00
|
|
|
// Make sure chain order is honoured and preserved throughout
|
2021-12-01 18:18:12 +00:00
|
|
|
hash := hashes[i]
|
2015-09-15 10:33:45 +00:00
|
|
|
if header.Number == nil || header.Number.Uint64() != from {
|
2017-02-27 15:06:40 +00:00
|
|
|
log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
|
2015-09-15 10:33:45 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
|
2017-02-27 15:06:40 +00:00
|
|
|
log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
|
2015-09-15 10:33:45 +00:00
|
|
|
break
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
// Make sure no duplicate requests are executed
|
2020-07-24 07:46:26 +00:00
|
|
|
// We cannot skip this, even if the block is empty, since this is
|
|
|
|
// what triggers the fetchResult creation.
|
2015-09-28 16:27:31 +00:00
|
|
|
if _, ok := q.blockTaskPool[hash]; ok {
|
2018-11-15 14:31:24 +00:00
|
|
|
log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash)
|
2020-07-24 07:46:26 +00:00
|
|
|
} else {
|
|
|
|
q.blockTaskPool[hash] = header
|
|
|
|
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// Queue for receipt retrieval
|
2021-11-26 11:26:03 +00:00
|
|
|
if q.mode == SnapSync && !header.EmptyReceipts() {
|
2020-07-24 07:46:26 +00:00
|
|
|
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 16:27:31 +00:00
|
|
|
}
|
2015-08-14 18:25:41 +00:00
|
|
|
inserts = append(inserts, header)
|
2015-09-15 10:33:45 +00:00
|
|
|
q.headerHead = hash
|
|
|
|
from++
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
|
|
|
return inserts
|
|
|
|
}
|
|
|
|
|
2018-02-05 16:40:32 +00:00
|
|
|
// Results retrieves and permanently removes a batch of fetch results from
|
2020-07-24 07:46:26 +00: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 16:40:32 +00:00
|
|
|
func (q *queue) Results(block bool) []*fetchResult {
|
2020-07-24 07:46:26 +00: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 16:40:32 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// No items available, and not closed
|
2015-11-13 16:08:15 +00:00
|
|
|
q.active.Wait()
|
2020-07-24 07:46:26 +00: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 09:14:30 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
for _, receipt := range result.Receipts {
|
|
|
|
size += receipt.Size()
|
2015-10-13 09:04:25 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
for _, tx := range result.Transactions {
|
2022-10-26 12:23:07 +00:00
|
|
|
size += common.StorageSize(tx.Size())
|
2018-02-05 16:40:32 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00: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)
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
// With results removed from the cache, wake throttled fetchers
|
|
|
|
for _, ch := range []chan bool{q.blockWakeCh, q.receiptWakeCh} {
|
|
|
|
select {
|
|
|
|
case ch <- true:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// Log some info at certain times
|
2023-02-21 10:17:34 +00:00
|
|
|
if time.Since(q.logTime) >= 60*time.Second {
|
|
|
|
q.logTime = time.Now()
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
info := q.Stats()
|
|
|
|
info = append(info, "throttle", throttleThreshold)
|
2023-02-21 10:17:34 +00:00
|
|
|
log.Debug("Downloader queue stats", info...)
|
2015-10-05 16:37:56 +00:00
|
|
|
}
|
2015-11-13 16:08:15 +00:00
|
|
|
return results
|
2015-04-30 22:23:51 +00:00
|
|
|
}
|
|
|
|
|
2020-07-24 07:46:26 +00: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 12:32:53 +00:00
|
|
|
}
|
2015-04-30 22:23:51 +00:00
|
|
|
}
|
|
|
|
|
2016-02-25 16:36:42 +00:00
|
|
|
// ReserveHeaders reserves a set of headers for the given peer, skipping any
|
|
|
|
// previously failed batches.
|
2017-06-28 12:25:08 +00:00
|
|
|
func (q *queue) ReserveHeaders(p *peerConnection, count int) *fetchRequest {
|
2016-02-25 16:36:42 +00: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 {
|
2023-02-09 11:03:54 +00:00
|
|
|
if _, ok := q.headerPeerMiss[p.id][from]; ok {
|
|
|
|
skip = append(skip, from)
|
2016-02-25 16:36:42 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
2023-02-09 11:03:54 +00:00
|
|
|
send = from
|
2016-02-25 16:36:42 +00:00
|
|
|
}
|
|
|
|
// Merge all the skipped batches back
|
|
|
|
for _, from := range skip {
|
2018-09-03 15:33:21 +00:00
|
|
|
q.headerTaskQueue.Push(from, -int64(from))
|
2016-02-25 16:36:42 +00: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 16:37:56 +00:00
|
|
|
// ReserveBodies reserves a set of body fetches for the given peer, skipping any
|
2015-09-28 16:27:31 +00: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 07:46:26 +00:00
|
|
|
func (q *queue) ReserveBodies(p *peerConnection, count int) (*fetchRequest, bool, bool) {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, bodyType)
|
2015-09-28 16:27:31 +00: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 07:46:26 +00:00
|
|
|
func (q *queue) ReserveReceipts(p *peerConnection, count int) (*fetchRequest, bool, bool) {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, receiptType)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
2015-10-05 16:37:56 +00:00
|
|
|
// reserveHeaders reserves a set of data download operations for a given peer,
|
2015-09-28 16:27:31 +00:00
|
|
|
// skipping any previously failed ones. This method is a generic version used
|
|
|
|
// by the individual special reservation functions.
|
2015-10-13 09:04:25 +00: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 07:46:26 +00:00
|
|
|
//
|
|
|
|
// Returns:
|
2022-09-10 11:25:40 +00:00
|
|
|
//
|
|
|
|
// item - the fetchRequest
|
|
|
|
// progress - whether any progress was made
|
|
|
|
// throttle - if the caller should throttle for a while
|
2023-02-09 11:03:54 +00:00
|
|
|
func (q *queue) reserveHeaders(p *peerConnection, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque[int64, *types.Header],
|
2020-07-24 07:46:26 +00:00
|
|
|
pendPool map[string]*fetchRequest, kind uint) (*fetchRequest, bool, bool) {
|
2015-08-14 18:25:41 +00: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 16:27:31 +00:00
|
|
|
if taskQueue.Empty() {
|
2020-07-24 07:46:26 +00:00
|
|
|
return nil, false, true
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
if _, ok := pendPool[p.id]; ok {
|
2020-07-24 07:46:26 +00:00
|
|
|
return nil, false, false
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
// Retrieve a batch of tasks, skipping previously failed ones
|
2015-08-14 18:25:41 +00:00
|
|
|
send := make([]*types.Header, 0, count)
|
|
|
|
skip := make([]*types.Header, 0)
|
2015-09-28 16:27:31 +00:00
|
|
|
progress := false
|
2020-07-24 07:46:26 +00: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.
|
2023-02-09 11:03:54 +00:00
|
|
|
header, _ := taskQueue.Peek()
|
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
// we can ask the resultcache if this header is within the
|
|
|
|
// "prioritized" segment of blocks. If it is not, we need to throttle
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
stale, throttle, item, err := q.resultCache.AddFetch(header, q.mode == SnapSync)
|
2020-07-24 07:46:26 +00:00
|
|
|
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 16:27:31 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00: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 16:27:31 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00: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 16:27:31 +00:00
|
|
|
progress = true
|
2015-08-14 18:25:41 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// Remove it from the task queue
|
|
|
|
taskQueue.PopItem()
|
2015-10-13 09:04:25 +00:00
|
|
|
// Otherwise unless the peer is known not to have the data, add to the retrieve list
|
2020-07-24 07:46:26 +00:00
|
|
|
if p.Lacks(header.Hash()) {
|
2015-08-14 18:25:41 +00:00
|
|
|
skip = append(skip, header)
|
|
|
|
} else {
|
|
|
|
send = append(send, header)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Merge all the skipped headers back
|
|
|
|
for _, header := range skip {
|
2018-09-03 15:33:21 +00:00
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
if q.resultCache.HasCompletedItems() {
|
2018-10-23 11:21:16 +00:00
|
|
|
// Wake Results, resultCache was modified
|
2015-11-13 16:08:15 +00:00
|
|
|
q.active.Signal()
|
|
|
|
}
|
2015-08-14 18:25:41 +00:00
|
|
|
// Assemble and return the block download request
|
|
|
|
if len(send) == 0 {
|
2020-07-24 07:46:26 +00:00
|
|
|
return nil, progress, throttled
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
|
|
|
request := &fetchRequest{
|
|
|
|
Peer: p,
|
|
|
|
Headers: send,
|
|
|
|
Time: time.Now(),
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
pendPool[p.id] = request
|
2020-07-24 07:46:26 +00:00
|
|
|
return request, progress, throttled
|
2015-09-28 16:27:31 +00: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 10:14:52 +00:00
|
|
|
func (q *queue) Revoke(peerID string) {
|
2015-09-28 16:27:31 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
if request, ok := q.headerPendPool[peerID]; ok {
|
|
|
|
q.headerTaskQueue.Push(request.From, -int64(request.From))
|
|
|
|
delete(q.headerPendPool, peerID)
|
|
|
|
}
|
2018-06-14 10:14:52 +00:00
|
|
|
if request, ok := q.blockPendPool[peerID]; ok {
|
2015-09-28 16:27:31 +00:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 15:33:21 +00:00
|
|
|
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
2018-06-14 10:14:52 +00:00
|
|
|
delete(q.blockPendPool, peerID)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
2018-06-14 10:14:52 +00:00
|
|
|
if request, ok := q.receiptPendPool[peerID]; ok {
|
2015-09-28 16:27:31 +00:00
|
|
|
for _, header := range request.Headers {
|
2018-09-03 15:33:21 +00:00
|
|
|
q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
2018-06-14 10:14:52 +00:00
|
|
|
delete(q.receiptPendPool, peerID)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
// ExpireHeaders cancels a request that timed out and moves the pending fetch
|
|
|
|
// task back into the queue for rescheduling.
|
|
|
|
func (q *queue) ExpireHeaders(peer string) int {
|
2016-02-25 16:36:42 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
headerTimeoutMeter.Mark(1)
|
|
|
|
return q.expire(peer, q.headerPendPool, q.headerTaskQueue)
|
2016-02-25 16:36:42 +00:00
|
|
|
}
|
|
|
|
|
2015-10-05 16:37:56 +00:00
|
|
|
// ExpireBodies checks for in flight block body requests that exceeded a timeout
|
2015-10-13 09:04:25 +00:00
|
|
|
// allowance, canceling them and returning the responsible peers for penalisation.
|
2021-11-26 11:26:03 +00:00
|
|
|
func (q *queue) ExpireBodies(peer string) int {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
bodyTimeoutMeter.Mark(1)
|
|
|
|
return q.expire(peer, q.blockPendPool, q.blockTaskQueue)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ExpireReceipts checks for in flight receipt requests that exceeded a timeout
|
2015-10-13 09:04:25 +00:00
|
|
|
// allowance, canceling them and returning the responsible peers for penalisation.
|
2021-11-26 11:26:03 +00:00
|
|
|
func (q *queue) ExpireReceipts(peer string) int {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
receiptTimeoutMeter.Mark(1)
|
|
|
|
return q.expire(peer, q.receiptPendPool, q.receiptTaskQueue)
|
2015-10-05 16:37:56 +00:00
|
|
|
}
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
// expire is the generic check that moves a specific expired task from a pending
|
2023-02-09 11:03:54 +00:00
|
|
|
// pool back into a task pool. The syntax on the passed taskQueue is a bit weird
|
|
|
|
// as we would need a generic expire method to handle both types, but that is not
|
|
|
|
// supported at the moment at least (Go 1.19).
|
2015-10-13 09:04:25 +00:00
|
|
|
//
|
2021-11-26 11:26:03 +00:00
|
|
|
// Note, this method expects the queue lock to be already held. The reason the
|
|
|
|
// lock is not obtained in here is that the parameters already need to access
|
|
|
|
// the queue, so they already need a lock anyway.
|
2023-02-09 11:03:54 +00:00
|
|
|
func (q *queue) expire(peer string, pendPool map[string]*fetchRequest, taskQueue interface{}) int {
|
2022-10-11 07:37:00 +00:00
|
|
|
// Retrieve the request being expired and log an error if it's non-existent,
|
2021-11-26 11:26:03 +00:00
|
|
|
// as there's no order of events that should lead to such expirations.
|
|
|
|
req := pendPool[peer]
|
|
|
|
if req == nil {
|
|
|
|
log.Error("Expired request does not exist", "peer", peer)
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
delete(pendPool, peer)
|
|
|
|
|
|
|
|
// Return any non-satisfied requests to the pool
|
|
|
|
if req.From > 0 {
|
2023-02-09 11:03:54 +00:00
|
|
|
taskQueue.(*prque.Prque[int64, uint64]).Push(req.From, -int64(req.From))
|
2021-11-26 11:26:03 +00:00
|
|
|
}
|
|
|
|
for _, header := range req.Headers {
|
2023-02-09 11:03:54 +00:00
|
|
|
taskQueue.(*prque.Prque[int64, *types.Header]).Push(header, -int64(header.Number.Uint64()))
|
2015-05-06 12:32:53 +00:00
|
|
|
}
|
2021-11-26 11:26:03 +00:00
|
|
|
return len(req.Headers)
|
2015-04-12 10:38:25 +00:00
|
|
|
}
|
|
|
|
|
2016-02-25 16:36:42 +00: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 09:27:37 +00:00
|
|
|
//
|
|
|
|
// If the headers are accepted, the method makes an attempt to deliver the set
|
2021-11-26 11:26:03 +00:00
|
|
|
// of ready headers to the processor to keep the pipeline full. However, it will
|
2016-04-19 09:27:37 +00:00
|
|
|
// not block to prevent stalling other pending deliveries.
|
2021-12-01 18:18:12 +00:00
|
|
|
func (q *queue) DeliverHeaders(id string, headers []*types.Header, hashes []common.Hash, headerProcCh chan *headerTask) (int, error) {
|
2016-02-25 16:36:42 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2020-12-14 09:27:15 +00:00
|
|
|
var logger log.Logger
|
|
|
|
if len(id) < 16 {
|
|
|
|
// Tests use short IDs, don't choke on them
|
|
|
|
logger = log.New("peer", id)
|
|
|
|
} else {
|
|
|
|
logger = log.New("peer", id[:16])
|
|
|
|
}
|
2016-02-25 16:36:42 +00:00
|
|
|
// Short circuit if the data was never requested
|
|
|
|
request := q.headerPendPool[id]
|
|
|
|
if request == nil {
|
2021-11-26 11:26:03 +00:00
|
|
|
headerDropMeter.Mark(int64(len(headers)))
|
2016-02-25 16:36:42 +00:00
|
|
|
return 0, errNoFetchesPending
|
|
|
|
}
|
|
|
|
delete(q.headerPendPool, id)
|
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
headerReqTimer.UpdateSince(request.Time)
|
|
|
|
headerInMeter.Mark(int64(len(headers)))
|
|
|
|
|
2016-02-25 16:36:42 +00:00
|
|
|
// 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 {
|
2021-12-01 18:18:12 +00:00
|
|
|
logger.Trace("First header broke chain ordering", "number", headers[0].Number, "hash", hashes[0], "expected", request.From)
|
2016-02-25 16:36:42 +00:00
|
|
|
accepted = false
|
2021-12-01 18:18:12 +00:00
|
|
|
} else if hashes[len(headers)-1] != target {
|
|
|
|
logger.Trace("Last header broke skeleton structure ", "number", headers[len(headers)-1].Number, "hash", hashes[len(headers)-1], "expected", target)
|
2016-02-25 16:36:42 +00:00
|
|
|
accepted = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if accepted {
|
2021-12-01 18:18:12 +00:00
|
|
|
parentHash := hashes[0]
|
2016-02-25 16:36:42 +00:00
|
|
|
for i, header := range headers[1:] {
|
2021-12-01 18:18:12 +00:00
|
|
|
hash := hashes[i+1]
|
2016-02-25 16:36:42 +00:00
|
|
|
if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
|
2020-12-14 09:27:15 +00:00
|
|
|
logger.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", want)
|
2016-02-25 16:36:42 +00:00
|
|
|
accepted = false
|
|
|
|
break
|
|
|
|
}
|
2020-10-09 07:09:10 +00:00
|
|
|
if parentHash != header.ParentHash {
|
2020-12-14 09:27:15 +00:00
|
|
|
logger.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
|
2016-02-25 16:36:42 +00:00
|
|
|
accepted = false
|
|
|
|
break
|
|
|
|
}
|
2020-10-09 07:09:10 +00:00
|
|
|
// Set-up parent hash for next round
|
|
|
|
parentHash = hash
|
2016-02-25 16:36:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// If the batch of headers wasn't accepted, mark as unavailable
|
|
|
|
if !accepted {
|
2020-12-14 09:27:15 +00:00
|
|
|
logger.Trace("Skeleton filling not accepted", "from", request.From)
|
2021-11-26 11:26:03 +00:00
|
|
|
headerDropMeter.Mark(int64(len(headers)))
|
2016-02-25 16:36:42 +00: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 15:33:21 +00:00
|
|
|
q.headerTaskQueue.Push(request.From, -int64(request.From))
|
2016-02-25 16:36:42 +00:00
|
|
|
return 0, errors.New("delivery not accepted")
|
|
|
|
}
|
2016-04-19 09:27:37 +00:00
|
|
|
// Clean up a successful fetch and try to deliver any sub-results
|
2016-02-25 16:36:42 +00:00
|
|
|
copy(q.headerResults[request.From-q.headerOffset:], headers)
|
2021-12-01 18:18:12 +00:00
|
|
|
copy(q.headerHashes[request.From-q.headerOffset:], hashes)
|
|
|
|
|
2016-02-25 16:36:42 +00:00
|
|
|
delete(q.headerTaskPool, request.From)
|
|
|
|
|
2016-04-19 09:27:37 +00: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)
|
2021-12-01 18:18:12 +00:00
|
|
|
processHeaders := make([]*types.Header, ready)
|
|
|
|
copy(processHeaders, q.headerResults[q.headerProced:q.headerProced+ready])
|
|
|
|
|
|
|
|
processHashes := make([]common.Hash, ready)
|
|
|
|
copy(processHashes, q.headerHashes[q.headerProced:q.headerProced+ready])
|
2016-04-19 09:27:37 +00:00
|
|
|
|
|
|
|
select {
|
2021-12-01 18:18:12 +00:00
|
|
|
case headerProcCh <- &headerTask{
|
|
|
|
headers: processHeaders,
|
|
|
|
hashes: processHashes,
|
|
|
|
}:
|
|
|
|
logger.Trace("Pre-scheduled new headers", "count", len(processHeaders), "from", processHeaders[0].Number)
|
|
|
|
q.headerProced += len(processHeaders)
|
2016-04-19 09:27:37 +00:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Check for termination and return
|
2016-02-25 16:36:42 +00:00
|
|
|
if len(q.headerTaskPool) == 0 {
|
|
|
|
q.headerContCh <- false
|
|
|
|
}
|
|
|
|
return len(headers), nil
|
|
|
|
}
|
|
|
|
|
2015-10-05 16:37:56 +00:00
|
|
|
// DeliverBodies injects a block body retrieval response into the results queue.
|
2015-10-29 16:37:26 +00:00
|
|
|
// The method returns the number of blocks bodies accepted from the delivery and
|
|
|
|
// also wakes any threads waiting for data delivery.
|
2023-01-25 14:32:25 +00:00
|
|
|
func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, txListHashes []common.Hash,
|
|
|
|
uncleLists [][]*types.Header, uncleListHashes []common.Hash,
|
|
|
|
withdrawalLists [][]*types.Withdrawal, withdrawalListHashes []common.Hash) (int, error) {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2021-11-26 11:26:03 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
validate := func(index int, header *types.Header) error {
|
2021-12-01 18:18:12 +00:00
|
|
|
if txListHashes[index] != header.TxHash {
|
2015-09-28 16:27:31 +00:00
|
|
|
return errInvalidBody
|
|
|
|
}
|
2021-12-01 18:18:12 +00:00
|
|
|
if uncleListHashes[index] != header.UncleHash {
|
2020-07-24 07:46:26 +00:00
|
|
|
return errInvalidBody
|
|
|
|
}
|
2023-01-25 14:32:25 +00:00
|
|
|
if header.WithdrawalsHash == nil {
|
2023-02-16 17:40:16 +00:00
|
|
|
// nil hash means that withdrawals should not be present in body
|
2023-02-16 10:10:16 +00:00
|
|
|
if withdrawalLists[index] != nil {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
} else { // non-nil hash: body must have withdrawals
|
|
|
|
if withdrawalLists[index] == nil {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
if withdrawalListHashes[index] != *header.WithdrawalsHash {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
2023-01-25 14:32:25 +00:00
|
|
|
}
|
2023-05-31 07:21:13 +00:00
|
|
|
// Blocks must have a number of blobs corresponding to the header gas usage,
|
core/types: support for optional blob sidecar in BlobTx (#27841)
This PR removes the newly added txpool.Transaction wrapper type, and instead adds a way
of keeping the blob sidecar within types.Transaction. It's better this way because most
code in go-ethereum does not care about blob transactions, and probably never will. This
will start mattering especially on the client side of RPC, where all APIs are based on
types.Transaction. Users need to be able to use the same signing flows they already
have.
However, since blobs are only allowed in some places but not others, we will now need to
add checks to avoid creating invalid blocks. I'm still trying to figure out the best place
to do some of these. The way I have it currently is as follows:
- In block validation (import), txs are verified not to have a blob sidecar.
- In miner, we strip off the sidecar when committing the transaction into the block.
- In TxPool validation, txs must have a sidecar to be added into the blobpool.
- Note there is a special case here: when transactions are re-added because of a chain
reorg, we cannot use the transactions gathered from the old chain blocks as-is,
because they will be missing their blobs. This was previously handled by storing the
blobs into the 'blobpool limbo'. The code has now changed to store the full
transaction in the limbo instead, but it might be confusing for code readers why we're
not simply adding the types.Transaction we already have.
Code changes summary:
- txpool.Transaction removed and all uses replaced by types.Transaction again
- blobpool now stores types.Transaction instead of defining its own blobTx format for storage
- the blobpool limbo now stores types.Transaction instead of storing only the blobs
- checks to validate the presence/absence of the blob sidecar added in certain critical places
2023-08-14 08:13:34 +00:00
|
|
|
// and zero before the Cancun hardfork.
|
2023-05-31 07:21:13 +00:00
|
|
|
var blobs int
|
|
|
|
for _, tx := range txLists[index] {
|
2023-07-27 13:53:28 +00:00
|
|
|
// Count the number of blobs to validate against the header's blobGasUsed
|
2023-05-31 07:21:13 +00:00
|
|
|
blobs += len(tx.BlobHashes())
|
2023-05-31 08:12:26 +00:00
|
|
|
|
|
|
|
// Validate the data blobs individually too
|
|
|
|
if tx.Type() == types.BlobTxType {
|
|
|
|
if len(tx.BlobHashes()) == 0 {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
for _, hash := range tx.BlobHashes() {
|
2024-01-19 10:41:17 +00:00
|
|
|
if !kzg4844.IsValidVersionedHash(hash[:]) {
|
2023-05-31 08:12:26 +00:00
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
}
|
core/types: support for optional blob sidecar in BlobTx (#27841)
This PR removes the newly added txpool.Transaction wrapper type, and instead adds a way
of keeping the blob sidecar within types.Transaction. It's better this way because most
code in go-ethereum does not care about blob transactions, and probably never will. This
will start mattering especially on the client side of RPC, where all APIs are based on
types.Transaction. Users need to be able to use the same signing flows they already
have.
However, since blobs are only allowed in some places but not others, we will now need to
add checks to avoid creating invalid blocks. I'm still trying to figure out the best place
to do some of these. The way I have it currently is as follows:
- In block validation (import), txs are verified not to have a blob sidecar.
- In miner, we strip off the sidecar when committing the transaction into the block.
- In TxPool validation, txs must have a sidecar to be added into the blobpool.
- Note there is a special case here: when transactions are re-added because of a chain
reorg, we cannot use the transactions gathered from the old chain blocks as-is,
because they will be missing their blobs. This was previously handled by storing the
blobs into the 'blobpool limbo'. The code has now changed to store the full
transaction in the limbo instead, but it might be confusing for code readers why we're
not simply adding the types.Transaction we already have.
Code changes summary:
- txpool.Transaction removed and all uses replaced by types.Transaction again
- blobpool now stores types.Transaction instead of defining its own blobTx format for storage
- the blobpool limbo now stores types.Transaction instead of storing only the blobs
- checks to validate the presence/absence of the blob sidecar added in certain critical places
2023-08-14 08:13:34 +00:00
|
|
|
if tx.BlobTxSidecar() != nil {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
2023-05-31 08:12:26 +00:00
|
|
|
}
|
2023-05-31 07:21:13 +00:00
|
|
|
}
|
2023-07-27 13:53:28 +00:00
|
|
|
if header.BlobGasUsed != nil {
|
|
|
|
if want := *header.BlobGasUsed / params.BlobTxBlobGasPerBlob; uint64(blobs) != want { // div because the header is surely good vs the body might be bloated
|
2023-05-31 07:21:13 +00:00
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if blobs != 0 {
|
|
|
|
return errInvalidBody
|
|
|
|
}
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
reconstruct := func(index int, result *fetchResult) {
|
2015-09-28 16:27:31 +00:00
|
|
|
result.Transactions = txLists[index]
|
|
|
|
result.Uncles = uncleLists[index]
|
2023-01-25 14:32:25 +00:00
|
|
|
result.Withdrawals = withdrawalLists[index]
|
2020-07-24 07:46:26 +00:00
|
|
|
result.SetBodyDone()
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool,
|
2021-11-26 11:26:03 +00:00
|
|
|
bodyReqTimer, bodyInMeter, bodyDropMeter, len(txLists), validate, reconstruct)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeliverReceipts injects a receipt retrieval response into the results queue.
|
2015-10-29 16:37:26 +00:00
|
|
|
// The method returns the number of transaction receipts accepted from the delivery
|
|
|
|
// and also wakes any threads waiting for data delivery.
|
2021-12-01 18:18:12 +00:00
|
|
|
func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt, receiptListHashes []common.Hash) (int, error) {
|
2015-10-13 09:04:25 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
2021-11-26 11:26:03 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
validate := func(index int, header *types.Header) error {
|
2021-12-01 18:18:12 +00:00
|
|
|
if receiptListHashes[index] != header.ReceiptHash {
|
2015-09-28 16:27:31 +00:00
|
|
|
return errInvalidReceipt
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
reconstruct := func(index int, result *fetchResult) {
|
|
|
|
result.Receipts = receiptList[index]
|
|
|
|
result.SetReceiptsDone()
|
|
|
|
}
|
|
|
|
return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool,
|
2021-11-26 11:26:03 +00:00
|
|
|
receiptReqTimer, receiptInMeter, receiptDropMeter, len(receiptList), validate, reconstruct)
|
2015-09-28 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// deliver injects a data retrieval response into the results queue.
|
2015-10-13 09:04:25 +00:00
|
|
|
//
|
|
|
|
// Note, this method expects the queue lock to be already held for writing. The
|
2020-07-24 07:46:26 +00:00
|
|
|
// reason this lock is not obtained in here is because the parameters already need
|
2015-10-13 09:04:25 +00:00
|
|
|
// to access the queue, so they already need a lock anyway.
|
2020-07-24 07:46:26 +00:00
|
|
|
func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
|
2023-02-09 11:03:54 +00:00
|
|
|
taskQueue *prque.Prque[int64, *types.Header], pendPool map[string]*fetchRequest,
|
2021-11-26 11:26:03 +00:00
|
|
|
reqTimer metrics.Timer, resInMeter metrics.Meter, resDropMeter metrics.Meter,
|
2020-07-24 07:46:26 +00:00
|
|
|
results int, validate func(index int, header *types.Header) error,
|
|
|
|
reconstruct func(index int, result *fetchResult)) (int, error) {
|
2015-09-28 16:27:31 +00:00
|
|
|
// Short circuit if the data was never requested
|
|
|
|
request := pendPool[id]
|
2015-08-14 18:25:41 +00:00
|
|
|
if request == nil {
|
2021-11-26 11:26:03 +00:00
|
|
|
resDropMeter.Mark(int64(results))
|
2015-10-29 16:37:26 +00:00
|
|
|
return 0, errNoFetchesPending
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
delete(pendPool, id)
|
2015-08-14 18:25:41 +00:00
|
|
|
|
2021-11-26 11:26:03 +00:00
|
|
|
reqTimer.UpdateSince(request.Time)
|
|
|
|
resInMeter.Mark(int64(results))
|
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
// If no data items were retrieved, mark them as unavailable for the origin peer
|
|
|
|
if results == 0 {
|
2015-11-04 10:18:48 +00:00
|
|
|
for _, header := range request.Headers {
|
|
|
|
request.Peer.MarkLacking(header.Hash())
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
// Assemble each of the results with their headers and retrieved data parts
|
2015-10-13 09:04:25 +00:00
|
|
|
var (
|
2015-10-29 16:37:26 +00:00
|
|
|
accepted int
|
|
|
|
failure error
|
2020-07-24 07:46:26 +00:00
|
|
|
i int
|
|
|
|
hashes []common.Hash
|
2015-10-13 09:04:25 +00:00
|
|
|
)
|
2020-07-24 07:46:26 +00:00
|
|
|
for _, header := range request.Headers {
|
2015-09-28 16:27:31 +00:00
|
|
|
// Short circuit assembly if no more fetch results are found
|
|
|
|
if i >= results {
|
2015-08-14 18:25:41 +00:00
|
|
|
break
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// Validate the fields
|
|
|
|
if err := validate(i, header); err != nil {
|
2015-10-13 09:04:25 +00:00
|
|
|
failure = err
|
2015-08-14 18:25:41 +00:00
|
|
|
break
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
hashes = append(hashes, header.Hash())
|
|
|
|
i++
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
|
2020-07-24 07:46:26 +00:00
|
|
|
for _, header := range request.Headers[:i] {
|
2022-09-26 10:33:21 +00:00
|
|
|
if res, stale, err := q.resultCache.GetDeliverySlot(header.Number.Uint64()); err == nil && !stale {
|
2020-07-24 07:46:26 +00:00
|
|
|
reconstruct(accepted, res)
|
|
|
|
} else {
|
2022-08-19 06:00:21 +00:00
|
|
|
// else: between here and above, some other peer filled this result,
|
2020-07-24 07:46:26 +00:00
|
|
|
// 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 16:27:31 +00:00
|
|
|
// Clean up a successful fetch
|
2020-07-24 07:46:26 +00:00
|
|
|
delete(taskPool, hashes[accepted])
|
|
|
|
accepted++
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2021-11-26 11:26:03 +00:00
|
|
|
resDropMeter.Mark(int64(results - accepted))
|
|
|
|
|
2015-08-14 18:25:41 +00:00
|
|
|
// Return all failed or missing fetches to the queue
|
2020-07-24 07:46:26 +00:00
|
|
|
for _, header := range request.Headers[accepted:] {
|
|
|
|
taskQueue.Push(header, -int64(header.Number.Uint64()))
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2018-10-23 11:21:16 +00:00
|
|
|
// Wake up Results
|
2015-10-29 16:37:26 +00:00
|
|
|
if accepted > 0 {
|
|
|
|
q.active.Signal()
|
|
|
|
}
|
2020-05-29 09:12:43 +00:00
|
|
|
if failure == nil {
|
|
|
|
return accepted, nil
|
|
|
|
}
|
2020-07-24 07:46:26 +00:00
|
|
|
// If none of the data was good, it's a stale delivery
|
|
|
|
if accepted > 0 {
|
2015-10-29 16:37:26 +00:00
|
|
|
return accepted, fmt.Errorf("partial failure: %v", failure)
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
2020-05-29 09:12:43 +00:00
|
|
|
return accepted, fmt.Errorf("%w: %v", failure, errStaleDelivery)
|
2015-08-14 18:25:41 +00:00
|
|
|
}
|
|
|
|
|
2015-09-28 16:27:31 +00:00
|
|
|
// Prepare configures the result cache to allow accepting and caching inbound
|
|
|
|
// fetch results.
|
2018-02-05 16:40:32 +00:00
|
|
|
func (q *queue) Prepare(offset uint64, mode SyncMode) {
|
2015-05-06 12:32:53 +00:00
|
|
|
q.lock.Lock()
|
|
|
|
defer q.lock.Unlock()
|
|
|
|
|
2016-05-27 11:26:00 +00:00
|
|
|
// Prepare the queue for sync results
|
2020-07-24 07:46:26 +00:00
|
|
|
q.resultCache.Prepare(offset)
|
2015-10-05 16:37:56 +00:00
|
|
|
q.mode = mode
|
2015-04-12 10:38:25 +00:00
|
|
|
}
|