zebrad/components/inbound/downloads.rs
1//! A download stream that handles gossiped blocks from peers.
2
3#[cfg(test)]
4mod tests;
5
6use std::{
7 collections::{HashMap, HashSet},
8 net::IpAddr,
9 pin::Pin,
10 sync::Arc,
11 task::{Context, Poll},
12 time::Duration,
13};
14
15use futures::{
16 future::TryFutureExt,
17 ready,
18 stream::{FuturesUnordered, Stream},
19};
20use indexmap::IndexSet;
21use pin_project::pin_project;
22use thiserror::Error;
23use tokio::{
24 sync::oneshot,
25 task::JoinHandle,
26 time::{sleep, timeout, Instant},
27};
28use tower::{Service, ServiceExt};
29use tracing::Instrument;
30
31use zebra_chain::{
32 block::{self, Block, HeightDiff},
33 chain_tip::ChainTip,
34 parameters::subsidy::SubsidyError,
35};
36use zebra_consensus::{error::TransactionError, router::RouterError, BlockError, VerifyBlockError};
37use zebra_network::{self as zn, PeerSocketAddr};
38use zebra_state as zs;
39
40use crate::components::sync::{BLOCK_DOWNLOAD_TIMEOUT, MIN_CONCURRENCY_LIMIT};
41
42type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
43
44/// How long to wait for the parent-height lookup that decides whether a behind-tip gossiped block
45/// was forged.
46///
47/// Bounds a drop path that also fires for honest old blocks. Timing out is treated as "no proof",
48/// so a slow state read costs the supplying peer nothing.
49const PARENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
50
51/// A gossiped block was dropped before verification because its coinbase height was outside the
52/// accepted range around the chain tip.
53///
54/// Peers legitimately serve blocks that are genuinely far ahead of the tip while Zebra is catching
55/// up, and blocks that are genuinely older than the finalized tip, so this error is returned for
56/// every such drop. But a peer can also answer a [`BlockDownload`](zn::Request::BlockDownload) request
57/// with a canonical header and a rewritten coinbase height, because the coinbase scriptSig is
58/// excluded from the V5 transaction ID and therefore from the block hash (ZIP-244). The initial hash
59/// check still passes, so the forged height reaches these drops before consensus validation, and the
60/// verifier never scores the peer (GHSA-4f6v-mj46-gxg3).
61///
62/// The downloader attaches the supplying peer's address to the drop only when the parent header
63/// Zebra already holds proves the claimed height wrong (see [`advertiser_if_parent_contradicts`]),
64/// so the inbound handler scores a proven rewrite, and never an authentic block.
65///
66/// This is the inbound-gossip sibling of the sync path's height limit errors (GHSA-g95h-hw6g-pvgv).
67#[derive(Copy, Clone, Debug, Error)]
68pub enum HeightLimitError {
69 /// The block's coinbase height is above the lookahead limit.
70 #[error("gossiped block height {height:?} too far ahead of the tip: {hash:?}")]
71 AboveLookahead {
72 height: block::Height,
73 hash: block::Hash,
74 },
75
76 /// The block's coinbase height is behind the finalized tip.
77 #[error("gossiped block height {height:?} behind the finalized tip: {hash:?}")]
78 BehindTip {
79 height: block::Height,
80 hash: block::Hash,
81 },
82}
83
84impl HeightLimitError {
85 /// The misbehavior score for a gossiped block whose parent proves its height was rewritten.
86 ///
87 /// A rewritten coinbase height is unambiguous misbehavior whichever limit it crossed, so score it
88 /// at the ban threshold, matching the sync path (GHSA-g95h-hw6g-pvgv).
89 pub fn misbehavior_score(&self) -> u32 {
90 zn::constants::MAX_PEER_MISBEHAVIOR_SCORE
91 }
92}
93
94/// Returns `advertiser_addr` if the parent header Zebra already holds proves that a gossiped block's
95/// claimed `block_height` was rewritten, and `None` if there is no such proof.
96///
97/// # Security
98///
99/// A peer can answer a `BlockDownload` request with a canonical header and a rewritten coinbase
100/// height, because the coinbase scriptSig is excluded from the V5 transaction ID and therefore from
101/// the block hash (ZIP-244). The hash check passes, so the forged height reaches the height limit
102/// drops before consensus validation. Peers also legitimately serve blocks that are genuinely far
103/// ahead of the tip or genuinely older than the finalized tip, so the drop is only attributed to the
104/// supplying peer when the parent header Zebra holds contradicts the claimed height: a block's height
105/// is one more than its parent's, so a held parent whose height disagrees proves the body was
106/// rewritten, whichever limit the claimed height crossed.
107///
108/// A parent Zebra does not hold, a height consistent with the parent, and a failed or timed-out
109/// lookup are all treated as no proof, so honest peers are never scored and a slow state read costs
110/// the peer nothing. (GHSA-4f6v-mj46-gxg3, the inbound-gossip sibling of GHSA-g95h-hw6g-pvgv.)
111async fn advertiser_if_parent_contradicts<ZS>(
112 state: ZS,
113 parent_hash: block::Hash,
114 block_height: block::Height,
115 advertiser_addr: Option<PeerSocketAddr>,
116) -> Option<PeerSocketAddr>
117where
118 ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
119 ZS::Future: Send,
120{
121 // There is no peer to score, so skip the state lookup.
122 let advertiser_addr = advertiser_addr?;
123
124 match timeout(
125 PARENT_LOOKUP_TIMEOUT,
126 state.oneshot(zs::Request::BlockHeader(parent_hash.into())),
127 )
128 .await
129 {
130 Ok(Ok(zs::Response::BlockHeader {
131 height: parent_height,
132 ..
133 })) if (parent_height + 1) != Some(block_height) => Some(advertiser_addr),
134 // Parent unknown, height consistent with it, or the lookup failed or timed out: there is no
135 // proof of misbehavior, so the peer is not scored.
136 _ => None,
137 }
138}
139
140/// How long to wait for the state to check a block from a peer that negotiated compact block
141/// relay against the best tip.
142///
143/// Timing out keeps the peer's score, so a slow state read can't exempt a block from scoring.
144const EARLY_RELAY_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
145
146/// How long to wait for the parent of a block from a peer that negotiated compact block relay to
147/// become the best tip, when the block fails later validation first.
148///
149/// The peer can relay the block once its parent is the peer's best tip, so the block can fail here
150/// before its parent is committed. Timing out keeps the peer's score.
151const EARLY_RELAY_PARENT_TIMEOUT: Duration = Duration::from_secs(30);
152
153/// How often to check whether that parent has become the best tip.
154const EARLY_RELAY_PARENT_POLL_INTERVAL: Duration = Duration::from_millis(100);
155
156/// The maximum number of blocks from peers that negotiated compact block relay that a block
157/// downloader remembers as invalid, after they passed the checks that authenticate them for early
158/// relay.
159///
160/// Each of these blocks has valid proof of work at the expected difficulty, as a child of the best
161/// tip, and the limit bounds their memory on networks where that proof of work is cheap. It is the
162/// same as [`MAX_EARLY_RELAY_ALLOWANCES`], so forgetting a block takes at least as many later
163/// failures as forgetting an allowance. Each hash takes about 50 bytes.
164pub(crate) const MAX_REJECTED_EARLY_BLOCKS: usize = MAX_EARLY_RELAY_ALLOWANCES;
165
166/// The maximum number of peer groups and parent blocks that a block downloader remembers in its
167/// [`EarlyRelayAllowances`].
168///
169/// While a block is the best tip, each entry for it comes from a different peer group. So a peer
170/// group's entry is only evicted, which gives the group another allowance for the same parent,
171/// after this many other peer groups or later parents have used theirs. That is five times the 200
172/// peers that Zebra connects to with its default configuration. Each entry takes less than 100
173/// bytes.
174const MAX_EARLY_RELAY_ALLOWANCES: usize = 1_000;
175
176/// The peer groups that a block downloader didn't score for a later validation failure of a block
177/// from a connection that negotiated compact block relay, after the block passed the checks that
178/// authenticate it for early relay, with the parent of that block.
179///
180/// # Security
181///
182/// The draft Compact Block Relay ZIP says that a node must not penalize the peer for such a block.
183/// On networks where the minimum difficulty rule makes the early relay checks cheap, like Testnet,
184/// an unbounded exemption would let a peer make the node verify invalid blocks without ever being
185/// scored. So a peer gets at most one unpenalized later failure per parent block, and any other
186/// later failure on that parent scores the peer as if there was no exemption.
187///
188/// Each downloader remembers the hashes of these blocks, and doesn't download them again, so it
189/// doesn't ask a peer for a block that has already failed. An honest peer relays a block early
190/// once its parent is the peer's best tip. Valid blocks never fail later validation, including a
191/// valid sibling relayed during a race, so they never use the allowance.
192///
193/// Peers are grouped by [`zn::connection_limit_key()`], like connection limits and bans, so a peer
194/// doesn't get another allowance by reconnecting from another port or from another address in its
195/// IPv6 `/64`. Each block downloader has its own allowances.
196#[derive(Debug, Default)]
197pub(crate) struct EarlyRelayAllowances {
198 /// The peer groups and parent blocks that have used their allowance, oldest first.
199 ///
200 /// Size-bounded by [`MAX_EARLY_RELAY_ALLOWANCES`].
201 used: IndexSet<(IpAddr, block::Hash)>,
202}
203
204impl EarlyRelayAllowances {
205 /// Returns `true` if the group of `peer` can send a child of `parent` that failed later
206 /// validation without being scored, and uses the group's allowance for `parent`.
207 ///
208 /// That is the case if the group hasn't used its allowance for `parent`. Returns `false` if it
209 /// has, so the failure must score the peer.
210 pub(crate) fn try_use(&mut self, peer: PeerSocketAddr, parent: block::Hash) -> bool {
211 if !self
212 .used
213 .insert((zn::connection_limit_key(peer.ip()), parent))
214 {
215 return false;
216 }
217
218 if self.used.len() > MAX_EARLY_RELAY_ALLOWANCES {
219 self.used.shift_remove_index(0);
220 }
221
222 true
223 }
224}
225
226/// Remembers `hash`, the hash of a block from a peer that negotiated compact block relay, which
227/// passed the checks that authenticate it for early relay and then failed later validation, in
228/// `rejected`, a block downloader's list of those hashes, oldest first.
229///
230/// The block's hash commits to its transactions and their authorizing data, so the downloader
231/// ignores the hash instead of verifying the same invalid block again. Forgets the oldest hash
232/// once there are more than [`MAX_REJECTED_EARLY_BLOCKS`].
233pub(crate) fn remember_rejected_early_block(
234 rejected: &mut IndexSet<block::Hash>,
235 hash: block::Hash,
236) {
237 if rejected.insert(hash) && rejected.len() > MAX_REJECTED_EARLY_BLOCKS {
238 rejected.shift_remove_index(0);
239 }
240}
241
242/// A block from a peer that negotiated compact block relay failed later validation, after it passed
243/// the checks that authenticate it for early relay.
244///
245/// The draft Compact Block Relay ZIP says that a node must not penalize the peer for this block, so
246/// the gossiped block downloader doesn't attribute this error to the peer, if the peer has an
247/// allowance for the block's parent in its [`EarlyRelayAllowances`]. Otherwise, it attributes the
248/// wrapped error to the peer. The block's hash commits to its transactions and their authorizing
249/// data, so the downloader also ignores the hash after this error.
250#[derive(Debug, Error)]
251#[error("block failed later validation after it was authenticated for early relay: {error}")]
252pub struct AuthenticatedBlockRejected {
253 /// The block verifier's error.
254 #[source]
255 error: BoxError,
256
257 /// The peer that sent the block.
258 peer: PeerSocketAddr,
259
260 /// The block's parent.
261 parent: block::Hash,
262}
263
264/// Returns `true` if `error` scores the peer that sent a block, and the block verifier only
265/// returns it after the block passed the verifier's part of the checks that authenticate a block
266/// for early relay.
267///
268/// # Security
269///
270/// The [draft Compact Block Relay ZIP] lets a peer that sets the compact block relay service bit
271/// relay a block before it has validated it, once the block passes the ZIP's early relay checks.
272/// The ZIP's peer misbehaviour rules say a node must not penalize that peer when such an
273/// authenticated block fails later validation.
274///
275/// Before it verifies a block's transactions, the block verifier checks the block's proof of work,
276/// its time against the local clock, its Merkle root, transaction IDs and consensus branch IDs, its
277/// coinbase, its shielded action limits, and its subsidy and funding streams when they don't
278/// depend on the chain value pools. It only returns these errors once those checks pass:
279/// - a transaction failure,
280/// - too many transparent signature operations,
281/// - a miner fee failure, or
282/// - a state commit failure, except authorizing data that doesn't match the block's commitment.
283///
284/// [`early_block_is_authenticated()`] asks the state for the rest of the early relay checks, and
285/// [`EarlyRelayAllowances`] bounds the failures that don't score a peer. Every other error keeps
286/// its score, including all the checkpoint verifier's errors.
287///
288/// [draft Compact Block Relay ZIP]: https://github.com/zcash/zips/pull/1429
289pub(crate) fn is_later_validation_failure(
290 error: &(dyn std::error::Error + Send + Sync + 'static),
291) -> bool {
292 let error = match error.downcast_ref::<RouterError>() {
293 Some(RouterError::Block { source }) => source.as_ref(),
294 // The checkpoint verifier doesn't run the early relay checks.
295 Some(RouterError::Checkpoint { .. }) => return false,
296 // The inbound block verifier is a router, but its scoring also handles a block verifier
297 // error.
298 None => match error.downcast_ref::<VerifyBlockError>() {
299 Some(error) => error,
300 None => return false,
301 },
302 };
303
304 error.misbehavior_score() != 0
305 && match error {
306 VerifyBlockError::Transaction(_) => true,
307 VerifyBlockError::Block { source } => matches!(
308 source,
309 BlockError::TooManyTransparentSignatureOperations { .. }
310 // Only the miner fee check returns these subsidy errors as block errors.
311 | BlockError::Transaction(TransactionError::Subsidy(
312 SubsidyError::InvalidMinerFees | SubsidyError::Overflow
313 ))
314 ),
315 VerifyBlockError::Commit(error) => !error.is_auth_commitment_mismatch(),
316 _ => false,
317 }
318}
319
320/// Returns `true` if the state confirms that `block` passes the rest of the checks that
321/// authenticate it for early relay, against the current best tip.
322///
323/// The state checks that `block` is an NU5 or later child of the best tip, that its difficulty
324/// threshold and time are valid in that context, and that its header commits to the best tip's
325/// chain history and to the block's authorizing data. A failed or timed-out check returns `false`.
326async fn best_tip_commitments_are_valid<ZS>(read_state: ZS, block: Arc<Block>) -> bool
327where
328 ZS: zs::ReadState,
329{
330 matches!(
331 timeout(
332 EARLY_RELAY_CHECK_TIMEOUT,
333 read_state.oneshot(zs::ReadRequest::CheckBestTipBlockCommitments(block)),
334 )
335 .await,
336 Ok(Ok(zs::ReadResponse::ValidBestTipBlockCommitments))
337 )
338}
339
340/// Starts checking `block` against the best tip, if its parent is the best tip, and returns the
341/// task that checks it.
342///
343/// Only call this for a block from a connection that negotiated compact block relay, just before
344/// the block is verified. The check runs while the block is verified, so if the block fails later
345/// validation, the check doesn't depend on whether another block became the best tip first.
346pub(crate) fn start_early_relay_check<ZS, ZSTip>(
347 read_state: &ZS,
348 latest_chain_tip: &ZSTip,
349 block: &Arc<Block>,
350) -> Option<JoinHandle<bool>>
351where
352 ZS: zs::ReadState,
353 ZSTip: ChainTip,
354{
355 (latest_chain_tip.best_tip_hash() == Some(block.header.previous_block_hash)).then(|| {
356 tokio::spawn(best_tip_commitments_are_valid(
357 read_state.clone(),
358 block.clone(),
359 ))
360 })
361}
362
363/// Returns `true` if `block` at `height` passes the rest of the checks that authenticate it for
364/// early relay, so a later validation failure doesn't score the peer that sent it, if the peer has
365/// an allowance for the block's parent in its downloader's [`EarlyRelayAllowances`].
366///
367/// `early_check` is the task from [`start_early_relay_check()`], if there is one. Otherwise the
368/// state checks the block now.
369///
370/// Only call this for a block from a connection that negotiated compact block relay, after
371/// [`is_later_validation_failure()`] returns `true` for its error.
372///
373/// # Security
374///
375/// The peer can relay the block once its parent is the peer's best tip, so the block can fail here
376/// before its parent is committed. If the check fails, this waits up to
377/// [`EARLY_RELAY_PARENT_TIMEOUT`] for the parent to become the best tip, and checks the block
378/// again. If the check fails while the parent is the best tip, it is retried once, in case the
379/// best tip changed during the check.
380///
381/// The peer keeps its score if that check fails too, if a block at the same height or above
382/// becomes the best tip instead, or if the parent doesn't become the best tip in time. So a forged
383/// body is still scored, and so is a block that can't be checked against the best tip. The
384/// expected difficulty of a block depends on its parent's chain, so without that check, the block
385/// could have much less proof of work than a valid block.
386pub(crate) async fn early_block_is_authenticated<ZS, ZSTip>(
387 read_state: ZS,
388 latest_chain_tip: ZSTip,
389 block: Arc<Block>,
390 height: block::Height,
391 early_check: Option<JoinHandle<bool>>,
392) -> bool
393where
394 ZS: zs::ReadState,
395 ZSTip: ChainTip + Send + 'static,
396{
397 let authenticated = match early_check {
398 // The check task doesn't panic, so it only fails if the runtime is shutting down.
399 Some(early_check) => early_check.await.unwrap_or(false),
400 None => best_tip_commitments_are_valid(read_state.clone(), block.clone()).await,
401 };
402 if authenticated {
403 return true;
404 }
405
406 let parent = block.header.previous_block_hash;
407 timeout(EARLY_RELAY_PARENT_TIMEOUT, async move {
408 let mut retried = false;
409 loop {
410 let tip = latest_chain_tip.best_tip_height_and_hash();
411 match tip {
412 Some((_, tip_hash)) if tip_hash == parent => {
413 // The parent became the best tip, or the last check failed while the parent
414 // was the best tip.
415 if retried {
416 return false;
417 }
418 retried = true;
419
420 if best_tip_commitments_are_valid(read_state.clone(), block.clone()).await {
421 return true;
422 }
423 }
424 // The block can only be checked against the best tip, and the best tip has
425 // reached its height without it.
426 Some((tip_height, _)) if tip_height >= height => return false,
427 _ => sleep(EARLY_RELAY_PARENT_POLL_INTERVAL).await,
428 }
429 }
430 })
431 .await
432 .unwrap_or(false)
433}
434
435/// The maximum number of concurrent inbound download and verify tasks.
436/// Also used as the maximum lookahead limit, before block verification.
437///
438/// We expect the syncer to download and verify checkpoints, so this bound
439/// can be small.
440///
441/// ## Security
442///
443/// The maximum block size is 2 million bytes. A deserialized malicious
444/// block with ~225_000 transparent outputs can take up 9MB of RAM.
445/// The total queue bound is `MAX_INBOUND_CONCURRENCY * 9 MB`. Each peer IP
446/// is limited to one in-flight download (9 MB) by the per-IP cap enforced
447/// in [`Downloads::download_and_verify`], so a sybil or IPv6-range attacker
448/// still needs many distinct source IPs to approach the total bound.
449/// (See #1880 for more details.)
450///
451/// Malicious blocks will eventually timeout or fail contextual validation.
452/// Once validation fails, the block is dropped, and its memory is deallocated.
453pub const MAX_INBOUND_CONCURRENCY: usize = 200;
454
455/// The action taken in response to a peer's gossiped block hash.
456pub enum DownloadAction {
457 /// The block hash was successfully queued for download and verification.
458 AddedToQueue,
459
460 /// The block hash is already queued, so this request was ignored.
461 ///
462 /// Another peer has already gossiped the same hash to us.
463 AlreadyQueued,
464
465 /// The queue is at capacity, so this request was ignored.
466 ///
467 /// The sync service should discover this block later, when we are closer
468 /// to the tip. The queue's capacity is [`Downloads::full_verify_concurrency_limit`].
469 FullQueue,
470
471 /// The advertising peer's IP already has an in-flight download, so
472 /// this request was ignored. Zcash's post-Blossom target block spacing
473 /// is 75 seconds, so honest peers rarely gossip more than one block
474 /// before the first is verified; during reorgs or recovery the same
475 /// hash also arrives from other peers or via the syncer.
476 TooManyFromPeer,
477
478 /// The block hash belongs to a block from a peer that negotiated compact block relay, which
479 /// passed the checks that authenticate it for early relay and then failed later validation,
480 /// so this request was ignored.
481 ///
482 /// The block's hash commits to its transactions and their authorizing data, so the block
483 /// can't be valid.
484 AlreadyRejected,
485}
486
487/// Manages download and verification of blocks gossiped to this peer.
488#[pin_project]
489#[derive(Debug)]
490pub struct Downloads<ZN, ZV, ZS, ZSTip>
491where
492 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
493 ZN::Future: Send,
494 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
495 + Send
496 + Clone
497 + 'static,
498 ZV::Future: Send,
499 ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
500 ZS::Future: Send,
501 ZSTip: ChainTip + Clone + Send + 'static,
502{
503 // Configuration
504 //
505 /// The configured full verification concurrency limit, after applying the minimum limit.
506 full_verify_concurrency_limit: usize,
507
508 // Services
509 //
510 /// A service that forwards requests to connected peers, and returns their
511 /// responses.
512 network: ZN,
513
514 /// A service that verifies downloaded blocks.
515 verifier: ZV,
516
517 /// A service that manages cached blockchain state.
518 state: ZS,
519
520 /// A read-only state service, which checks a block from a peer that negotiated compact block
521 /// relay when the block fails later validation, before the failure is exempt from scoring.
522 ///
523 /// Without it, no failure is exempt.
524 read_state: Option<zs::ReadStateService>,
525
526 /// Allows efficient access to the best tip of the blockchain.
527 latest_chain_tip: ZSTip,
528
529 // Internal downloads state
530 //
531 /// A list of pending block download and verify tasks.
532 #[pin]
533 pending: FuturesUnordered<
534 JoinHandle<Result<block::Hash, (BoxError, block::Hash, Option<PeerSocketAddr>)>>,
535 >,
536
537 /// Cancellation handles for tasks in [`Self::pending`], keyed by block
538 /// hash. The `Option<IpAddr>` is the advertiser IP recorded in
539 /// [`Self::in_flight_ips`], so completion can remove it by hash lookup.
540 cancel_handles: HashMap<block::Hash, (oneshot::Sender<()>, Option<IpAddr>)>,
541
542 /// Advertiser IPs with an in-flight download and verify task.
543 ///
544 /// Invariant: an IP is present iff some entry in [`Self::cancel_handles`]
545 /// has value `(_, Some(ip))`. Enforces the one-download-per-IP cap.
546 ///
547 /// Size-bounded by `full_verify_concurrency_limit` (≤ [`MAX_INBOUND_CONCURRENCY`]),
548 /// inherited from the [`DownloadAction::FullQueue`] check on
549 /// [`Self::pending`].
550 in_flight_ips: HashSet<IpAddr>,
551
552 /// The hashes of blocks from peers that negotiated compact block relay, which passed the
553 /// checks that authenticate them for early relay and then failed later validation, oldest
554 /// first.
555 ///
556 /// Each of these hashes commits to its block's transactions and their authorizing data, so the
557 /// downloader ignores them instead of verifying the same invalid blocks again. See
558 /// [`remember_rejected_early_block()`].
559 rejected_early_blocks: IndexSet<block::Hash>,
560
561 /// The peer groups that have used their allowance for a block on a parent, which passed the
562 /// checks that authenticate it for early relay and then failed later validation.
563 early_relay_allowances: EarlyRelayAllowances,
564}
565
566impl<ZN, ZV, ZS, ZSTip> Stream for Downloads<ZN, ZV, ZS, ZSTip>
567where
568 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
569 ZN::Future: Send,
570 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
571 + Send
572 + Clone
573 + 'static,
574 ZV::Future: Send,
575 ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
576 ZS::Future: Send,
577 ZSTip: ChainTip + Clone + Send + 'static,
578{
579 type Item = Result<block::Hash, (BoxError, Option<PeerSocketAddr>)>;
580
581 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
582 let this = self.project();
583 // CORRECTNESS
584 //
585 // The current task must be scheduled for wakeup every time we return
586 // `Poll::Pending`.
587 //
588 // If no download and verify tasks have exited since the last poll, this
589 // task is scheduled for wakeup when the next task becomes ready.
590 //
591 // TODO: this would be cleaner with poll_map (#2693)
592 if let Some(join_result) = ready!(this.pending.poll_next(cx)) {
593 let (result, hash) = match join_result
594 .expect("block download and verify tasks must not panic")
595 {
596 Ok(hash) => (Ok(hash), hash),
597 Err((e, hash, advertiser_addr)) => match e.downcast::<AuthenticatedBlockRejected>()
598 {
599 Ok(rejected) => {
600 remember_rejected_early_block(this.rejected_early_blocks, hash);
601
602 if this
603 .early_relay_allowances
604 .try_use(rejected.peer, rejected.parent)
605 {
606 debug!(
607 ?hash,
608 peer = ?rejected.peer,
609 error = ?rejected.error,
610 "authenticated early relay block failed later validation: \
611 rejected it without scoring the peer",
612 );
613
614 let error: BoxError = rejected;
615 (Err((error, None)), hash)
616 } else {
617 debug!(
618 ?hash,
619 peer = ?rejected.peer,
620 error = ?rejected.error,
621 "peer already sent a block on the same parent that failed \
622 later validation: scoring the peer",
623 );
624
625 let AuthenticatedBlockRejected { error, peer, .. } = *rejected;
626 (Err((error, Some(peer))), hash)
627 }
628 }
629 Err(e) => (Err((e, advertiser_addr)), hash),
630 },
631 };
632 if let Some((_, Some(ip))) = this.cancel_handles.remove(&hash) {
633 assert!(
634 this.in_flight_ips.remove(&ip),
635 "every tracked IP was inserted when its download was queued",
636 );
637 }
638 Poll::Ready(Some(result))
639 } else {
640 Poll::Ready(None)
641 }
642 }
643
644 fn size_hint(&self) -> (usize, Option<usize>) {
645 self.pending.size_hint()
646 }
647}
648
649impl<ZN, ZV, ZS, ZSTip> Downloads<ZN, ZV, ZS, ZSTip>
650where
651 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
652 ZN::Future: Send,
653 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
654 + Send
655 + Clone
656 + 'static,
657 ZV::Future: Send,
658 ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
659 ZS::Future: Send,
660 ZSTip: ChainTip + Clone + Send + 'static,
661{
662 /// Initialize a new download stream with the provided `network`, `verifier`, and `state` services.
663 /// The `latest_chain_tip` must be linked to the provided `state` service.
664 ///
665 /// The download deadline covers network readiness and the response. Any retry policy
666 /// should be applied to `network` without a separate timeout that includes queued requests.
667 pub fn new(
668 full_verify_concurrency_limit: usize,
669 network: ZN,
670 verifier: ZV,
671 state: ZS,
672 latest_chain_tip: ZSTip,
673 ) -> Self {
674 // The syncer already warns about the minimum.
675 let full_verify_concurrency_limit =
676 full_verify_concurrency_limit.clamp(MIN_CONCURRENCY_LIMIT, MAX_INBOUND_CONCURRENCY);
677
678 Self {
679 full_verify_concurrency_limit,
680 network,
681 verifier,
682 state,
683 read_state: None,
684 latest_chain_tip,
685 pending: FuturesUnordered::new(),
686 cancel_handles: HashMap::new(),
687 in_flight_ips: HashSet::new(),
688 rejected_early_blocks: IndexSet::new(),
689 early_relay_allowances: EarlyRelayAllowances::default(),
690 }
691 }
692
693 /// Uses `read_state` to check the blocks from peers that negotiated compact block relay, so
694 /// later validation failures of the blocks that it authenticates don't score those peers.
695 ///
696 /// See [`is_later_validation_failure()`] and [`early_block_is_authenticated()`].
697 pub fn with_read_state(mut self, read_state: zs::ReadStateService) -> Self {
698 self.read_state = Some(read_state);
699 self
700 }
701
702 /// Forgets the blocks that failed later validation after they passed the checks that
703 /// authenticate them for early relay, like the downloader does once it has remembered
704 /// [`MAX_REJECTED_EARLY_BLOCKS`] newer ones.
705 #[cfg(test)]
706 pub(super) fn forget_rejected_early_blocks(&mut self) {
707 self.rejected_early_blocks.clear();
708 }
709
710 /// Queue a block for download and verification.
711 ///
712 /// When `advertiser` is `Some`, it is passed to the network as a known block source,
713 /// and its IP is tracked in [`Self::in_flight_ips`] to enforce the one-download-per-IP cap.
714 /// `None` bypasses per-IP accounting (for example when Zebra triggers the download internally).
715 #[instrument(skip(self, hash), fields(hash = %hash))]
716 pub fn download_and_verify(
717 &mut self,
718 hash: block::Hash,
719 advertiser: Option<PeerSocketAddr>,
720 ) -> DownloadAction {
721 if self.rejected_early_blocks.contains(&hash) {
722 debug!(
723 ?hash,
724 "block hash failed later validation after early relay: ignored block",
725 );
726
727 metrics::counter!("gossip.already.rejected.dropped.block.hash.count").increment(1);
728
729 return DownloadAction::AlreadyRejected;
730 }
731
732 if self.cancel_handles.contains_key(&hash) {
733 debug!(
734 ?hash,
735 queue_len = self.pending.len(),
736 concurrency_limit = self.full_verify_concurrency_limit,
737 "block hash already queued for inbound download: ignored block",
738 );
739
740 metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
741 metrics::counter!("gossip.already.queued.dropped.block.hash.count").increment(1);
742
743 return DownloadAction::AlreadyQueued;
744 }
745
746 if self.pending.len() >= self.full_verify_concurrency_limit {
747 debug!(
748 ?hash,
749 queue_len = self.pending.len(),
750 concurrency_limit = self.full_verify_concurrency_limit,
751 "too many blocks queued for inbound download: ignored block",
752 );
753
754 metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
755 metrics::counter!("gossip.full.queue.dropped.block.hash.count").increment(1);
756
757 return DownloadAction::FullQueue;
758 }
759
760 let advertiser_ip = advertiser.map(|addr| addr.ip());
761 if let Some(ip) = advertiser_ip {
762 if self.in_flight_ips.contains(&ip) {
763 debug!(
764 ?hash,
765 ?advertiser,
766 "already have an in-flight inbound download from peer IP: ignored block",
767 );
768
769 metrics::counter!("gossip.peer.limit.dropped.block.hash.count").increment(1);
770
771 return DownloadAction::TooManyFromPeer;
772 }
773 }
774
775 // This oneshot is used to signal cancellation to the download task.
776 let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
777
778 let state = self.state.clone();
779 let read_state = self.read_state.clone();
780 let network = self.network.clone();
781 let verifier = self.verifier.clone();
782 let latest_chain_tip = self.latest_chain_tip.clone();
783 let full_verify_concurrency_limit = self.full_verify_concurrency_limit;
784
785 let fut = async move {
786 // Check if the block is already in the state.
787 match state.clone().oneshot(zs::Request::KnownBlock(hash)).await {
788 Ok(zs::Response::KnownBlock(None)) => Ok(()),
789 Ok(zs::Response::KnownBlock(Some(_))) => Err("already present".into()),
790 Ok(_) => unreachable!("wrong response"),
791 Err(e) => Err(e),
792 }
793 .map_err(|e| (e, None))?;
794
795 let download_start = Instant::now();
796 let response = timeout(
797 zn::constants::REQUEST_TIMEOUT + BLOCK_DOWNLOAD_TIMEOUT,
798 network.oneshot(zn::Request::BlockDownload { hash, advertiser }),
799 )
800 .await
801 .map_err(|e| (BoxError::from(e), None))?
802 .map_err(|e| (e, None))?;
803 metrics::histogram!("gossip.block.download.duration_seconds")
804 .record(download_start.elapsed().as_secs_f64());
805 // A peer that negotiated compact block relay can send a block before it has validated
806 // it.
807 let early_relay = matches!(response, zn::Response::EarlyBlocks(_));
808 let (block, advertiser_addr) = if let zn::Response::Blocks(blocks)
809 | zn::Response::EarlyBlocks(blocks) = response
810 {
811 assert_eq!(
812 blocks.len(),
813 1,
814 "wrong number of blocks in response to a single hash",
815 );
816
817 blocks
818 .first()
819 .expect("just checked length")
820 .available()
821 .expect(
822 "unexpected missing block status: single block failures should be errors",
823 )
824 } else {
825 unreachable!("wrong response to block request");
826 };
827 metrics::counter!("gossip.downloaded.block.count").increment(1);
828
829 // # Security & Performance
830 //
831 // Reject blocks that are too far ahead of our tip,
832 // and blocks that are behind the finalized tip.
833 //
834 // Avoids denial of service attacks. Also reduces wasted work on high blocks
835 // that will timeout before being verified, and low blocks that can never be finalized.
836 let tip_height = latest_chain_tip.best_tip_height();
837
838 let max_lookahead_height = if let Some(tip_height) = tip_height {
839 let lookahead = HeightDiff::try_from(full_verify_concurrency_limit)
840 .expect("fits in HeightDiff");
841 (tip_height + lookahead).expect("tip is much lower than Height::MAX")
842 } else {
843 let genesis_lookahead =
844 u32::try_from(full_verify_concurrency_limit - 1).expect("fits in u32");
845 block::Height(genesis_lookahead)
846 };
847
848 // Get the finalized tip height, assuming we're using the non-finalized state.
849 //
850 // It doesn't matter if we're a few blocks off here, because blocks this low
851 // are part of a fork with much less work. So they would be rejected anyway.
852 //
853 // And if we're still checkpointing, the checkpointer will reject blocks behind
854 // the finalized tip anyway.
855 //
856 // TODO: get the actual finalized tip height
857 let min_accepted_height = tip_height
858 .map(|tip_height| {
859 block::Height(tip_height.0.saturating_sub(zs::MAX_BLOCK_REORG_HEIGHT))
860 })
861 .unwrap_or(block::Height(0));
862
863 let block_height = block
864 .coinbase_height()
865 .ok_or_else(|| {
866 debug!(
867 ?hash,
868 "gossiped block with no height: dropped downloaded block"
869 );
870 metrics::counter!("gossip.no.height.dropped.block.count").increment(1);
871
872 BoxError::from("gossiped block with no height")
873 })
874 .map_err(|e| (e, None))?;
875
876 if block_height > max_lookahead_height {
877 debug!(
878 ?hash,
879 ?block_height,
880 ?tip_height,
881 ?max_lookahead_height,
882 lookahead_limit = full_verify_concurrency_limit,
883 "gossiped block height too far ahead of the tip: dropped downloaded block",
884 );
885 metrics::counter!("gossip.max.height.limit.dropped.block.count").increment(1);
886
887 // # Security
888 //
889 // Attribute the drop to the supplying peer only if the parent Zebra holds proves the
890 // claimed height was rewritten (GHSA-4f6v-mj46-gxg3). A genuinely far-ahead block
891 // has a parent Zebra does not hold yet, so it is dropped anonymously.
892 let advertiser_addr = advertiser_if_parent_contradicts(
893 state,
894 block.header.previous_block_hash,
895 block_height,
896 advertiser_addr,
897 )
898 .await;
899
900 return Err((
901 BoxError::from(HeightLimitError::AboveLookahead {
902 height: block_height,
903 hash,
904 }),
905 advertiser_addr,
906 ));
907 } else if block_height < min_accepted_height {
908 debug!(
909 ?hash,
910 ?block_height,
911 ?tip_height,
912 ?min_accepted_height,
913 behind_tip_limit = ?zs::MAX_BLOCK_REORG_HEIGHT,
914 "gossiped block height behind the finalized tip: dropped downloaded block",
915 );
916 metrics::counter!("gossip.min.height.limit.dropped.block.count").increment(1);
917
918 // # Security
919 //
920 // Attribute the drop to the supplying peer only if the parent Zebra holds proves the
921 // claimed height was rewritten (GHSA-4f6v-mj46-gxg3). A genuinely old block is
922 // consistent with its parent, or has a parent Zebra does not hold, so it is dropped
923 // anonymously.
924 let advertiser_addr = advertiser_if_parent_contradicts(
925 state,
926 block.header.previous_block_hash,
927 block_height,
928 advertiser_addr,
929 )
930 .await;
931
932 return Err((
933 BoxError::from(HeightLimitError::BehindTip {
934 height: block_height,
935 hash,
936 }),
937 advertiser_addr,
938 ));
939 }
940
941 // Keep the block for the state to check, if it fails later validation.
942 let early_block = early_relay.then(|| block.clone());
943 // Check the block while it is verified, if its parent is the best tip, in case another
944 // block becomes the best tip before the verifier rejects this one.
945 let early_check = match (&early_block, &read_state) {
946 (Some(block), Some(read_state)) => {
947 start_early_relay_check(read_state, &latest_chain_tip, block)
948 }
949 _ => None,
950 };
951 let verify_start = Instant::now();
952 let result = verifier
953 .oneshot(zebra_consensus::Request::Commit(block))
954 .await
955 .map(|hash| (hash, block_height, verify_start.elapsed()))
956 .map_err(|e| (e, advertiser_addr));
957
958 // # Security
959 //
960 // The draft Compact Block Relay ZIP says that a peer that negotiated compact block
961 // relay must not be scored when a block that passes the ZIP's early relay checks fails
962 // later validation. The verifier has run its part of those checks before it returns
963 // a later validation failure, and the state runs the rest of them. Other blocks and
964 // failures keep their score, and `poll_next()` scores the peer if it has already used
965 // its allowance for the block's parent.
966 match (result, early_block, read_state) {
967 (Err((error, Some(advertiser_addr))), Some(block), Some(read_state))
968 if is_later_validation_failure(&*error) =>
969 {
970 let parent = block.header.previous_block_hash;
971 if early_block_is_authenticated(
972 read_state,
973 latest_chain_tip,
974 block,
975 block_height,
976 early_check,
977 )
978 .await
979 {
980 Err((
981 BoxError::from(AuthenticatedBlockRejected {
982 error,
983 peer: advertiser_addr,
984 parent,
985 }),
986 None,
987 ))
988 } else {
989 Err((error, Some(advertiser_addr)))
990 }
991 }
992 (result, _, _) => result,
993 }
994 }
995 .map_ok(|(hash, height, verify_commit)| {
996 metrics::histogram!("gossip.block.verify_commit.duration_seconds")
997 .record(verify_commit.as_secs_f64());
998 info!(?height, "downloaded and verified gossiped block");
999 metrics::counter!("gossip.verified.block.count").increment(1);
1000 hash
1001 })
1002 // Tack the hash onto the error so poll_next can look up the cancel
1003 // handle and advertising IP on failure as well as success.
1004 .map_err(move |(e, advertiser_addr)| (e, hash, advertiser_addr))
1005 .in_current_span();
1006
1007 let task = tokio::spawn(async move {
1008 // Prefer the cancel handle if both are ready.
1009 tokio::select! {
1010 biased;
1011 _ = &mut cancel_rx => {
1012 trace!("task cancelled prior to completion");
1013 metrics::counter!("gossip.cancelled.count").increment(1);
1014 Err(("canceled".into(), hash, None))
1015 }
1016 verification = fut => verification,
1017 }
1018 });
1019
1020 self.pending.push(task);
1021 assert!(
1022 self.cancel_handles
1023 .insert(hash, (cancel_tx, advertiser_ip))
1024 .is_none(),
1025 "blocks are only queued once"
1026 );
1027 if let Some(ip) = advertiser_ip {
1028 assert!(
1029 self.in_flight_ips.insert(ip),
1030 "the per-IP cap check above rejects any IP already in flight",
1031 );
1032 }
1033
1034 debug!(
1035 ?hash,
1036 queue_len = self.pending.len(),
1037 concurrency_limit = self.full_verify_concurrency_limit,
1038 "queued hash for download",
1039 );
1040 metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
1041
1042 DownloadAction::AddedToQueue
1043 }
1044}