zebrad/components/sync/downloads.rs
1//! A download stream for Zebra's block syncer.
2
3use std::{
4 collections::HashMap,
5 convert,
6 pin::Pin,
7 sync::Arc,
8 task::{Context, Poll},
9 time::Duration,
10};
11
12use futures::{
13 future::{FutureExt, TryFutureExt},
14 ready,
15 stream::{FuturesUnordered, Stream},
16};
17use indexmap::IndexSet;
18use pin_project::pin_project;
19use thiserror::Error;
20use tokio::{
21 sync::{oneshot, watch},
22 task::JoinHandle,
23 time::{timeout, timeout_at, Instant},
24};
25use tower::{Service, ServiceExt};
26use tracing::Instrument;
27
28use zebra_chain::{
29 block::{self, Height, HeightDiff},
30 chain_tip::ChainTip,
31};
32use zebra_network::{self as zn, PeerSocketAddr};
33use zebra_state as zs;
34
35use crate::components::{
36 inbound::downloads::{
37 early_block_is_authenticated, is_later_validation_failure, remember_rejected_early_block,
38 start_early_relay_check, EarlyRelayAllowances,
39 },
40 sync::{
41 diagnostics::InFlightBlocks, BLOCK_DOWNLOAD_ROUND_TIMEOUT, BLOCK_VERIFY_TIMEOUT,
42 FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT, FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT_LIMIT,
43 },
44};
45
46#[cfg(test)]
47mod tests;
48
49type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
50
51/// A multiplier used to calculate the extra number of blocks we allow in the
52/// verifier, state, and block commit pipelines, on top of the lookahead limit.
53///
54/// The extra number of blocks is calculated using
55/// `lookahead_limit * VERIFICATION_PIPELINE_SCALING_MULTIPLIER`.
56///
57/// This allows the verifier and state queues, and the block commit channel,
58/// to hold a few extra tips responses worth of blocks,
59/// even if the syncer queue is full. Any unused capacity is shared between both queues.
60///
61/// If this capacity is exceeded, the downloader will tell the syncer to pause new downloads.
62///
63/// Since the syncer queue is limited to the `lookahead_limit`,
64/// the rest of the capacity is reserved for the other queues.
65/// There is no reserved capacity for the syncer queue:
66/// if the other queues stay full, the syncer will eventually time out and reset.
67pub const VERIFICATION_PIPELINE_SCALING_MULTIPLIER: usize = 2;
68
69/// The maximum height difference between Zebra's state tip and a downloaded block.
70/// Blocks higher than this will get dropped and return an error.
71pub const VERIFICATION_PIPELINE_DROP_LIMIT: HeightDiff = 50_000;
72
73/// How long to wait for the parent-height lookup that decides whether a behind-tip block was
74/// forged.
75///
76/// Bounds a drop path that also fires for honest old blocks. Timing out is treated as "no proof",
77/// so a slow state read costs the peer nothing.
78const PARENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
79
80/// Returns a [`BlockDownloadVerifyError::BodyHeaderMismatch`] if `block`'s transactions don't
81/// match its header, so its coinbase height can't be trusted.
82///
83/// Only call this before using a block's height without verifying the block, because the block
84/// verifiers compute the same Merkle root. See [`zebra_consensus::body_matches_header()`].
85fn check_body_matches_header(
86 block: &block::Block,
87 hash: block::Hash,
88 advertiser_addr: Option<PeerSocketAddr>,
89) -> Result<(), BlockDownloadVerifyError> {
90 zebra_consensus::body_matches_header(block).map_err(|error| {
91 BlockDownloadVerifyError::BodyHeaderMismatch {
92 error,
93 hash,
94 advertiser_addr,
95 }
96 })
97}
98
99/// Errors that can occur while downloading and verifying a block.
100#[derive(Error, Debug)]
101#[allow(dead_code)]
102pub enum BlockDownloadVerifyError {
103 #[error("permanent readiness error from the network service: {error:?}")]
104 NetworkServiceError {
105 #[source]
106 error: BoxError,
107 },
108
109 #[error("readiness error from the verifier service: {error:?}")]
110 VerifierServiceError {
111 #[source]
112 error: BoxError,
113 },
114
115 #[error("duplicate block hash queued for download: {hash:?}")]
116 DuplicateBlockQueuedForDownload { hash: block::Hash },
117
118 /// The block came from a peer that negotiated compact block relay, passed the checks that
119 /// authenticate it for early relay, and then failed later validation, so it isn't downloaded
120 /// again.
121 ///
122 /// The block's hash commits to its transactions and their authorizing data, so the block
123 /// can't be valid.
124 #[error(
125 "block already failed validation after it was authenticated for early relay: {hash:?}"
126 )]
127 AlreadyRejected { hash: block::Hash },
128
129 #[error("error downloading block: {error:?} {hash:?}")]
130 DownloadFailed {
131 #[source]
132 error: BoxError,
133 hash: block::Hash,
134 },
135
136 /// No peer delivered the block before the download round's deadline.
137 ///
138 /// The round covers waiting for a peer that might have the block, retries, and both hedged
139 /// requests. The syncer treats this like a missing block: a hedged request that already
140 /// failed with `NotFound` can still be waiting for its sibling when the deadline drops both.
141 #[error("block download round timed out: {hash:?}")]
142 DownloadTimedOut { hash: block::Hash },
143
144 /// A downloaded block was a long way ahead of the state chain tip.
145 /// This error should be very rare during normal operation.
146 ///
147 /// We need to reset the syncer on this error, to allow the verifier and state to catch up,
148 /// or prevent it following a bad chain.
149 ///
150 /// If we don't reset the syncer on this error, it will continue downloading blocks from a bad
151 /// chain, or blocks far ahead of the current state tip.
152 #[error("downloaded block was too far ahead of the chain tip: {height:?} {hash:?}")]
153 AboveLookaheadHeightLimit {
154 height: block::Height,
155 hash: block::Hash,
156 },
157
158 /// A downloaded block claimed a height a long way behind the state chain tip.
159 ///
160 /// A peer can answer with a canonical header and a rewritten coinbase height because the
161 /// initial hash check does not recompute the header's commitment to the body's authorizing data
162 /// (GHSA-g95h-hw6g-pvgv). Peers also legitimately serve blocks that are genuinely this old, so
163 /// the block is dropped, but `advertiser_addr` is only set when the parent Zebra already holds
164 /// proves the claimed height wrong — a block's height is one more than its parent's. An
165 /// authentic old block is dropped anonymously. When Zebra doesn't hold the parent, a body that
166 /// doesn't match its header returns [`Self::BodyHeaderMismatch`] instead.
167 #[error("downloaded block was too far behind the chain tip: {height:?} {hash:?}")]
168 BehindTipHeightLimit {
169 height: block::Height,
170 hash: block::Hash,
171 advertiser_addr: Option<PeerSocketAddr>,
172 },
173
174 #[error("downloaded block had an invalid height: {hash:?}")]
175 InvalidHeight {
176 hash: block::Hash,
177 advertiser_addr: Option<PeerSocketAddr>,
178 },
179
180 /// A downloaded block was going to be dropped for its height, or to pause or resume new
181 /// downloads, but its transactions don't match its header.
182 ///
183 /// The block hash only commits to the header, so a peer can answer a request for a block hash
184 /// with a body that claims any coinbase height (GHSA-g9rc-89v4-hhvf). That height can't be
185 /// trusted, so the requested block is still wanted.
186 #[error("downloaded block body did not match its header: {error} {hash:?}")]
187 BodyHeaderMismatch {
188 #[source]
189 error: zebra_consensus::BlockError,
190 hash: block::Hash,
191 advertiser_addr: Option<PeerSocketAddr>,
192 },
193
194 #[error("block failed consensus validation: {error:?} {height:?} {hash:?}")]
195 Invalid {
196 #[source]
197 error: zebra_consensus::router::RouterError,
198 height: block::Height,
199 hash: block::Hash,
200 advertiser_addr: Option<PeerSocketAddr>,
201 },
202
203 #[error("block validation request failed: {error:?} {height:?} {hash:?}")]
204 ValidationRequestError {
205 #[source]
206 error: BoxError,
207 height: block::Height,
208 hash: block::Hash,
209 },
210
211 #[error("block download & verification was cancelled during download: {hash:?}")]
212 CancelledDuringDownload { hash: block::Hash },
213
214 #[error(
215 "block download & verification was cancelled while waiting for the verifier service: \
216 to become ready: {height:?} {hash:?}"
217 )]
218 CancelledAwaitingVerifierReadiness {
219 height: block::Height,
220 hash: block::Hash,
221 },
222
223 #[error(
224 "block download & verification was cancelled during verification: {height:?} {hash:?}"
225 )]
226 CancelledDuringVerification {
227 height: block::Height,
228 hash: block::Hash,
229 },
230
231 #[error("timeout waiting for the network service to be ready")]
232 Timeout,
233
234 #[error("the genesis block wasn't downloaded and verified before the genesis timeout")]
235 GenesisTimeout,
236}
237
238impl From<tokio::time::error::Elapsed> for BlockDownloadVerifyError {
239 fn from(_value: tokio::time::error::Elapsed) -> Self {
240 BlockDownloadVerifyError::Timeout
241 }
242}
243
244/// Represents a [`Stream`] of download and verification tasks during chain sync.
245#[pin_project]
246#[derive(Debug)]
247pub struct Downloads<ZN, ZV, ZS, ZSTip>
248where
249 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Sync + 'static,
250 ZN::Future: Send,
251 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
252 + Send
253 + Sync
254 + Clone
255 + 'static,
256 ZV::Future: Send,
257 ZS: zs::ReadState + Sync,
258 ZSTip: ChainTip + Clone + Send + 'static,
259{
260 // Services
261 //
262 /// A service that forwards requests to connected peers, and returns their
263 /// responses.
264 network: ZN,
265
266 /// A service that verifies downloaded blocks.
267 verifier: ZV,
268
269 /// A read-only handle to the state, used to query the blocks Zebra already holds.
270 ///
271 /// Checks a downloaded block's claimed height against its parent's, so a rewritten coinbase
272 /// height can be told apart from a genuinely old block (GHSA-g95h-hw6g-pvgv).
273 read_state: ZS,
274
275 /// Allows efficient access to the best tip of the blockchain.
276 latest_chain_tip: ZSTip,
277
278 // Configuration
279 //
280 /// The configured lookahead limit, after applying the minimum limit.
281 lookahead_limit: usize,
282
283 /// The largest block height for the checkpoint verifier, based on the current config.
284 max_checkpoint_height: Height,
285
286 // Shared syncer state
287 //
288 /// Sender that is set to `true` when the downloader is past the lookahead limit.
289 /// This is based on the downloaded block height and the state tip height.
290 past_lookahead_limit_sender: Arc<std::sync::Mutex<watch::Sender<bool>>>,
291
292 /// Receiver for `past_lookahead_limit_sender`, which is used to avoid accessing the mutex.
293 past_lookahead_limit_receiver: zs::WatchReceiver<bool>,
294
295 // Internal downloads state
296 //
297 /// A list of pending block download and verify tasks.
298 ///
299 /// A failed task returns its error, the hash of its block, and the block's parent if the block
300 /// came from a peer that negotiated compact block relay, passed the checks that authenticate it
301 /// for early relay, and then failed later validation.
302 #[pin]
303 pending: FuturesUnordered<
304 JoinHandle<
305 Result<
306 (Height, block::Hash),
307 (BlockDownloadVerifyError, block::Hash, Option<block::Hash>),
308 >,
309 >,
310 >,
311
312 /// A list of channels that can be used to cancel pending block download and
313 /// verify tasks, with the time each task was queued.
314 cancel_handles: HashMap<block::Hash, (oneshot::Sender<()>, std::time::Instant)>,
315
316 /// The pending tasks in `cancel_handles` that might still be running.
317 in_flight_blocks: InFlightBlocks,
318
319 /// Whether [`Self::download_and_verify`] is waiting for network capacity.
320 ///
321 /// It stays set when an enclosing timeout cancels that wait, so the syncer can count the
322 /// timeout as the block's error.
323 awaiting_network_capacity: bool,
324
325 /// The hashes of blocks from peers that negotiated compact block relay, which passed the
326 /// checks that authenticate them for early relay and then failed later validation, oldest
327 /// first.
328 ///
329 /// Each of these hashes commits to its block's transactions and their authorizing data, so
330 /// [`Self::download_and_verify`] refuses them instead of verifying the same invalid blocks
331 /// again. [`Self::cancel_all()`] keeps them. See [`remember_rejected_early_block()`].
332 rejected_early_blocks: IndexSet<block::Hash>,
333
334 /// The peer groups that have used their allowance for a block on a parent, which passed the
335 /// checks that authenticate it for early relay and then failed later validation.
336 ///
337 /// [`Self::cancel_all()`] keeps them, so a sync restart doesn't give a peer another allowance.
338 early_relay_allowances: EarlyRelayAllowances,
339}
340
341impl<ZN, ZV, ZS, ZSTip> Stream for Downloads<ZN, ZV, ZS, ZSTip>
342where
343 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Sync + 'static,
344 ZN::Future: Send,
345 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
346 + Send
347 + Sync
348 + Clone
349 + 'static,
350 ZV::Future: Send,
351 ZS: zs::ReadState + Sync,
352 ZSTip: ChainTip + Clone + Send + 'static,
353{
354 type Item = Result<(Height, block::Hash), BlockDownloadVerifyError>;
355
356 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
357 let this = self.project();
358 // CORRECTNESS
359 //
360 // The current task must be scheduled for wakeup every time we return
361 // `Poll::Pending`.
362 //
363 // If no download and verify tasks have exited since the last poll, this
364 // task is scheduled for wakeup when the next task becomes ready.
365 //
366 // TODO: this would be cleaner with poll_map (#2693)
367 if let Some(join_result) = ready!(this.pending.poll_next(cx)) {
368 let result = join_result.expect("block download and verify tasks must not panic");
369 let hash = match &result {
370 Ok((_, hash)) | Err((_, hash, _)) => *hash,
371 };
372 if let Some((_cancel, queued_at)) = this.cancel_handles.remove(&hash) {
373 this.in_flight_blocks.remove(queued_at, hash);
374 }
375
376 let rejected_early_blocks = this.rejected_early_blocks;
377 let early_relay_allowances = this.early_relay_allowances;
378 Poll::Ready(Some(result.map_err(
379 |(e, _hash, authenticated_parent)| match (e, authenticated_parent) {
380 // # Security
381 //
382 // A peer gets at most one unpenalized later failure per parent block, so a
383 // peer that sends another block on the same parent that fails later
384 // validation is scored. See `EarlyRelayAllowances` for details.
385 (
386 BlockDownloadVerifyError::Invalid {
387 error,
388 height,
389 hash,
390 advertiser_addr: Some(peer),
391 },
392 Some(parent),
393 ) => {
394 // The block's hash commits to its transactions and their authorizing
395 // data, so a later download of the hash is the same invalid block.
396 remember_rejected_early_block(rejected_early_blocks, hash);
397
398 let advertiser_addr = if early_relay_allowances.try_use(peer, parent) {
399 debug!(
400 ?hash,
401 ?peer,
402 ?error,
403 "authenticated early relay block failed later validation: \
404 rejected it without scoring the peer",
405 );
406 None
407 } else {
408 debug!(
409 ?hash,
410 ?peer,
411 ?error,
412 "peer already sent a block on the same parent that failed later \
413 validation: scoring the peer",
414 );
415 Some(peer)
416 };
417
418 BlockDownloadVerifyError::Invalid {
419 error,
420 height,
421 hash,
422 advertiser_addr,
423 }
424 }
425 (e, _) => e,
426 },
427 )))
428 } else {
429 Poll::Ready(None)
430 }
431 }
432
433 fn size_hint(&self) -> (usize, Option<usize>) {
434 self.pending.size_hint()
435 }
436}
437
438impl<ZN, ZV, ZS, ZSTip> Downloads<ZN, ZV, ZS, ZSTip>
439where
440 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Sync + 'static,
441 ZN::Future: Send,
442 ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
443 + Send
444 + Sync
445 + Clone
446 + 'static,
447 ZV::Future: Send,
448 ZS: zs::ReadState + Sync,
449 ZSTip: ChainTip + Clone + Send + 'static,
450{
451 /// Initialize a new download stream with the provided `network` and
452 /// `verifier` services.
453 ///
454 /// Uses the `latest_chain_tip` and `lookahead_limit` to drop blocks
455 /// that are too far ahead of the current state tip.
456 /// Uses `max_checkpoint_height` to work around a known block timeout (#5125).
457 ///
458 /// Retry and hedge policies are supplied by `network`. A single deadline bounds network
459 /// readiness and the complete download round, including retries and hedges.
460 pub fn new(
461 network: ZN,
462 verifier: ZV,
463 read_state: ZS,
464 latest_chain_tip: ZSTip,
465 past_lookahead_limit_sender: watch::Sender<bool>,
466 lookahead_limit: usize,
467 max_checkpoint_height: Height,
468 ) -> Self {
469 let past_lookahead_limit_receiver =
470 zs::WatchReceiver::new(past_lookahead_limit_sender.subscribe());
471
472 Self {
473 network,
474 verifier,
475 read_state,
476 latest_chain_tip,
477 lookahead_limit,
478 max_checkpoint_height,
479 past_lookahead_limit_sender: Arc::new(std::sync::Mutex::new(
480 past_lookahead_limit_sender,
481 )),
482 past_lookahead_limit_receiver,
483 pending: FuturesUnordered::new(),
484 cancel_handles: HashMap::new(),
485 in_flight_blocks: InFlightBlocks::default(),
486 awaiting_network_capacity: false,
487 rejected_early_blocks: IndexSet::new(),
488 early_relay_allowances: EarlyRelayAllowances::default(),
489 }
490 }
491
492 /// Queue a block for download and verification.
493 ///
494 /// This method waits for the network to become ready, returning an error if readiness fails
495 /// or the download deadline expires. It returns immediately after queuing the request.
496 ///
497 /// Returns [`BlockDownloadVerifyError::AlreadyRejected`] without downloading the block, if it
498 /// is one of the downloader's rejected early relay blocks.
499 #[instrument(level = "debug", skip(self), fields(%hash))]
500 pub async fn download_and_verify(
501 &mut self,
502 hash: block::Hash,
503 ) -> Result<(), BlockDownloadVerifyError> {
504 if self.rejected_early_blocks.contains(&hash) {
505 debug!(
506 ?hash,
507 "block hash failed later validation after early relay: ignored block",
508 );
509 metrics::counter!("sync.already.rejected.dropped.block.hash.count").increment(1);
510 return Err(BlockDownloadVerifyError::AlreadyRejected { hash });
511 }
512
513 if self.is_queued(&hash) {
514 metrics::counter!("sync.already.queued.dropped.block.hash.count").increment(1);
515 return Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { hash });
516 }
517
518 // We construct the block requests sequentially, waiting for the peer
519 // set to be ready to process each request. This ensures that we start
520 // block downloads in the order we want them (though they may resolve
521 // out of order), and it means that we respect backpressure. Otherwise,
522 // if we waited for readiness and did the service call in the spawned
523 // tasks, all of the spawned tasks would race each other waiting for the
524 // network to become ready.
525 let deadline = Instant::now() + BLOCK_DOWNLOAD_ROUND_TIMEOUT;
526 self.awaiting_network_capacity = true;
527 let ready = timeout_at(deadline, self.network.ready()).await;
528 self.awaiting_network_capacity = false;
529 let block_req = ready?
530 .map_err(|error| BlockDownloadVerifyError::NetworkServiceError { error })?
531 .call(zn::Request::BlockDownload {
532 hash,
533 advertiser: None,
534 });
535
536 // This oneshot is used to signal cancellation to the download task.
537 let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
538
539 let mut verifier = self.verifier.clone();
540 let read_state = self.read_state.clone();
541 let latest_chain_tip = self.latest_chain_tip.clone();
542
543 let lookahead_limit = self.lookahead_limit;
544 let max_checkpoint_height = self.max_checkpoint_height;
545
546 let past_lookahead_limit_sender = self.past_lookahead_limit_sender.clone();
547 let past_lookahead_limit_receiver = self.past_lookahead_limit_receiver.clone();
548
549 let task = tokio::spawn(
550 async move {
551 // Download the block.
552 // Prefer the cancel handle if both are ready.
553 let download_start = std::time::Instant::now();
554 let rsp = tokio::select! {
555 biased;
556 _ = &mut cancel_rx => {
557 trace!("task cancelled prior to download completion");
558 metrics::counter!("sync.cancelled.download.count").increment(1);
559 metrics::histogram!("sync.block.download.duration_seconds", "result" => "cancelled")
560 .record(download_start.elapsed().as_secs_f64());
561 return Err(BlockDownloadVerifyError::CancelledDuringDownload { hash })
562 }
563 rsp = timeout_at(deadline, block_req) => rsp
564 .map_err(|_| BlockDownloadVerifyError::DownloadTimedOut { hash })?
565 .map_err(|error| BlockDownloadVerifyError::DownloadFailed { error, hash})?,
566 };
567
568 // A peer that negotiated compact block relay can send a block before it has
569 // validated it.
570 let early_relay = matches!(rsp, zn::Response::EarlyBlocks(_));
571 let (block, advertiser_addr) = if let zn::Response::Blocks(blocks)
572 | zn::Response::EarlyBlocks(blocks) = rsp
573 {
574 assert_eq!(
575 blocks.len(),
576 1,
577 "wrong number of blocks in response to a single hash"
578 );
579
580 blocks
581 .first()
582 .expect("just checked length")
583 .available()
584 .expect("unexpected missing block status: single block failures should be errors")
585 } else {
586 unreachable!("wrong response to block request");
587 };
588 metrics::counter!("sync.downloaded.block.count").increment(1);
589 metrics::histogram!("sync.block.download.duration_seconds", "result" => "success")
590 .record(download_start.elapsed().as_secs_f64());
591
592 // Security & Performance: reject blocks that are too far ahead of our tip.
593 // Avoids denial of service attacks, and reduces wasted work on high blocks
594 // that will timeout before being verified.
595 let tip_height = latest_chain_tip.best_tip_height();
596
597 let (lookahead_drop_height, lookahead_pause_height, lookahead_reset_height) = if let Some(tip_height) = tip_height {
598 // Scale the height limit with the lookahead limit,
599 // so users with low capacity or under DoS can reduce them both.
600 let lookahead_pause = HeightDiff::try_from(
601 lookahead_limit + lookahead_limit * VERIFICATION_PIPELINE_SCALING_MULTIPLIER,
602 )
603 .expect("fits in HeightDiff");
604
605
606 ((tip_height + VERIFICATION_PIPELINE_DROP_LIMIT).expect("tip is much lower than Height::MAX"),
607 (tip_height + lookahead_pause).expect("tip is much lower than Height::MAX"),
608 (tip_height + lookahead_pause/2).expect("tip is much lower than Height::MAX"))
609 } else {
610 let genesis_drop = VERIFICATION_PIPELINE_DROP_LIMIT.try_into().expect("fits in u32");
611 let genesis_lookahead =
612 u32::try_from(lookahead_limit - 1).expect("fits in u32");
613
614 (block::Height(genesis_drop),
615 block::Height(genesis_lookahead),
616 block::Height(genesis_lookahead/2))
617 };
618
619 // Get the finalized tip height, assuming we're using the non-finalized state.
620 //
621 // It doesn't matter if we're a few blocks off here, because blocks this low
622 // are part of a fork with much less work. So they would be rejected anyway.
623 //
624 // And if we're still checkpointing, the checkpointer will reject blocks behind
625 // the finalized tip anyway.
626 //
627 // TODO: get the actual finalized tip height
628 let min_accepted_height = tip_height
629 .map(|tip_height| {
630 block::Height(tip_height.0.saturating_sub(zs::MAX_BLOCK_REORG_HEIGHT))
631 })
632 .unwrap_or(block::Height(0));
633
634 let block_height = if let Some(block_height) = block.coinbase_height() {
635 block_height
636 } else {
637 // Security: every valid block has a height, so a block without one is only
638 // dropped if its body is the one its header commits to.
639 check_body_matches_header(&block, hash, advertiser_addr)?;
640
641 debug!(
642 ?hash,
643 "synced block with no height: dropped downloaded block"
644 );
645 metrics::counter!("sync.no.height.dropped.block.count").increment(1);
646
647 return Err(BlockDownloadVerifyError::InvalidHeight { hash, advertiser_addr });
648 };
649
650 if block_height > lookahead_drop_height {
651 // Security: a peer can serve a requested block hash with a body that claims a
652 // height far ahead, so only drop the block if its body is the one its header
653 // commits to. A genuine block this far ahead is still dropped without scoring
654 // the peer that served it (GHSA-qhr3-cvch-5fh2).
655 check_body_matches_header(&block, hash, advertiser_addr)?;
656
657 Err(BlockDownloadVerifyError::AboveLookaheadHeightLimit {
658 height: block_height,
659 hash,
660 })?;
661 } else if block_height > lookahead_pause_height {
662 // This log can be very verbose, usually hundreds of blocks are dropped.
663 // So we only log at info level for the first above-height block.
664 if !past_lookahead_limit_receiver.cloned_watch_data() {
665 // Security: a peer can serve a requested block hash with a body that
666 // claims a height in this range, so only pause new downloads if the body
667 // is the one its header commits to (GHSA-g9rc-89v4-hhvf). This only checks
668 // the block that sets the pause, so the blocks that follow it, which the
669 // verifier checks anyway, aren't checked twice.
670 check_body_matches_header(&block, hash, advertiser_addr)?;
671
672 info!(
673 ?hash,
674 ?block_height,
675 ?tip_height,
676 ?lookahead_pause_height,
677 ?lookahead_reset_height,
678 lookahead_limit = ?lookahead_limit,
679 "synced block height too far ahead of the tip: \
680 waiting for downloaded blocks to commit to the state",
681 );
682
683 // Set the watched value to true, since we're over the limit.
684 //
685 // It is ok to block here, because we're going to pause new downloads anyway.
686 // But if Zebra is shutting down, ignore the send error.
687 let _ = past_lookahead_limit_sender.lock().expect("thread panicked while holding the past_lookahead_limit_sender mutex guard").send(true);
688 } else {
689 debug!(
690 ?hash,
691 ?block_height,
692 ?tip_height,
693 ?lookahead_pause_height,
694 ?lookahead_reset_height,
695 lookahead_limit = ?lookahead_limit,
696 "synced block height too far ahead of the tip: \
697 waiting for downloaded blocks to commit to the state",
698 );
699 }
700
701 metrics::counter!("sync.max.height.limit.paused.count").increment(1);
702 } else if block_height <= lookahead_reset_height && past_lookahead_limit_receiver.cloned_watch_data() {
703 // Security: like the pause, only a body that its header commits to can end
704 // it. This only checks the block that ends the pause.
705 check_body_matches_header(&block, hash, advertiser_addr)?;
706
707 // Reset the watched value to false, since we're well under the limit.
708 // We need to block here, because if we don't the syncer can hang.
709
710 // But if Zebra is shutting down, ignore the send error.
711 let _ = past_lookahead_limit_sender.lock().expect("thread panicked while holding the past_lookahead_limit_sender mutex guard").send(false);
712 metrics::counter!("sync.max.height.limit.reset.count").increment(1);
713
714 metrics::counter!("sync.max.height.limit.reset.attempt.count").increment(1);
715 }
716
717 if block_height < min_accepted_height {
718 debug!(
719 ?hash,
720 ?block_height,
721 ?tip_height,
722 ?min_accepted_height,
723 behind_tip_limit = ?zs::MAX_BLOCK_REORG_HEIGHT,
724 "synced block height behind the finalized tip: dropped downloaded block"
725 );
726 metrics::counter!("gossip.min.height.limit.dropped.block.count").increment(1);
727
728 // Security: only attribute the drop to the supplying peer when the block's own
729 // parent proves the claimed height wrong.
730 //
731 // A peer can answer with a canonical header and a rewritten coinbase height
732 // because the initial hash check does not recompute the header's commitment to
733 // the body's authorizing data (GHSA-g95h-hw6g-pvgv). A block's height is one
734 // more than its parent's, so a mismatch proves the body was rewritten.
735 //
736 // Peers legitimately serve genuinely old blocks: the syncer tolerates an
737 // out-of-order first hash in `FindBlocks` responses, so a requested hash can
738 // resolve to an old side-chain block that an honest peer still has. Those
739 // responses are consistent with their parent, or have a parent we don't hold
740 // and a body that matches their header, so they are dropped without scoring.
741 let parent_contradicts_height = match advertiser_addr {
742 Some(_) => matches!(
743 timeout(
744 PARENT_LOOKUP_TIMEOUT,
745 read_state.oneshot(zs::ReadRequest::BlockHeader(
746 block.header.previous_block_hash.into(),
747 )),
748 )
749 .await,
750 Ok(Ok(zs::ReadResponse::BlockHeader {
751 height: parent_height,
752 ..
753 })) if (parent_height + 1) != Some(block_height)
754 ),
755 // There is no peer to score, so skip the state lookup.
756 None => false,
757 };
758
759 if parent_contradicts_height {
760 return Err(BlockDownloadVerifyError::BehindTipHeightLimit {
761 height: block_height,
762 hash,
763 advertiser_addr,
764 });
765 }
766
767 // Parent unknown, height consistent with it, or the lookup failed or timed
768 // out: the parent doesn't prove misbehaviour. During checkpoint sync, Zebra
769 // only holds the parent of the first block in each checkpoint range, so check
770 // the body against its header instead (GHSA-g9rc-89v4-hhvf).
771 check_body_matches_header(&block, hash, advertiser_addr)?;
772
773 return Err(BlockDownloadVerifyError::BehindTipHeightLimit {
774 height: block_height,
775 hash,
776 advertiser_addr: None,
777 });
778 }
779
780 // Bound readiness separately: the verifier's request timeout starts at `call`.
781 let readiness = timeout(BLOCK_VERIFY_TIMEOUT, verifier.ready());
782 // Prefer the cancel handle if both are ready.
783 let verifier = tokio::select! {
784 biased;
785 _ = &mut cancel_rx => {
786 trace!("task cancelled waiting for verifier service readiness");
787 metrics::counter!("sync.cancelled.verify.ready.count").increment(1);
788 return Err(BlockDownloadVerifyError::CancelledAwaitingVerifierReadiness { height: block_height, hash })
789 }
790 verifier = readiness => verifier
791 .map_err(|error| BlockDownloadVerifyError::VerifierServiceError { error: error.into() })?,
792 };
793
794 // Keep the block for the state to check, if it fails later validation.
795 let early_block = early_relay.then(|| block.clone());
796 // Check the block while it is verified, if its parent is the best tip, in case
797 // another block becomes the best tip before the verifier rejects this one. The
798 // checkpoint verifier's failures always keep their score, so its blocks aren't
799 // checked.
800 let early_check = match &early_block {
801 Some(block) if block_height > max_checkpoint_height => {
802 start_early_relay_check(&read_state, &latest_chain_tip, block)
803 }
804 _ => None,
805 };
806
807 // Verify the block.
808 let verify_start = std::time::Instant::now();
809 let mut rsp = verifier
810 .map_err(|error| BlockDownloadVerifyError::VerifierServiceError { error })?
811 .call(zebra_consensus::Request::Commit(block)).boxed();
812
813 // Add a shorter timeout to workaround a known bug (#5125)
814 let short_timeout_max = (max_checkpoint_height + FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT_LIMIT).expect("checkpoint block height is in valid range");
815 // Only fully verified blocks: the checkpoint verifier holds the final checkpoint
816 // block until its whole range arrives, which can legitimately take longer.
817 if block_height > max_checkpoint_height && block_height <= short_timeout_max {
818 // Keep the typed `Elapsed` so `should_restart_sync` can match it (#11168).
819 rsp = timeout(FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT, rsp)
820 .map_err(BoxError::from)
821 .map(|nested_result| nested_result.and_then(convert::identity)).boxed();
822 }
823
824 let verification = tokio::select! {
825 biased;
826 _ = &mut cancel_rx => {
827 trace!("task cancelled prior to verification");
828 metrics::counter!("sync.cancelled.verify.count").increment(1);
829 metrics::histogram!("sync.block.verify.duration_seconds", "result" => "cancelled")
830 .record(verify_start.elapsed().as_secs_f64());
831 return Err(BlockDownloadVerifyError::CancelledDuringVerification { height: block_height, hash })
832 }
833 verification = rsp => verification,
834 };
835
836 let verify_result = if verification.is_ok() { "success" } else { "failure" };
837 metrics::histogram!("sync.block.verify.duration_seconds", "result" => verify_result)
838 .record(verify_start.elapsed().as_secs_f64());
839
840 if verification.is_ok() {
841 metrics::counter!("sync.verified.block.count").increment(1);
842 }
843
844 let result = verification
845 .map(|hash| (block_height, hash))
846 .map_err(|err| {
847 match err.downcast::<zebra_consensus::router::RouterError>() {
848 Ok(error) => BlockDownloadVerifyError::Invalid { error: *error, height: block_height, hash, advertiser_addr },
849 Err(error) => BlockDownloadVerifyError::ValidationRequestError { error, height: block_height, hash },
850 }
851 });
852
853 // # Security
854 //
855 // A peer that negotiated compact block relay can answer a sync download with a
856 // block it relays before validating it. Like the gossiped block downloader, this
857 // doesn't score that peer when the block passes the draft Compact Block Relay ZIP's
858 // early relay checks, and then fails later validation, unless `poll_next()` finds
859 // that the peer has already used its allowance for the block's parent.
860 match (result, early_block) {
861 (
862 Err(BlockDownloadVerifyError::Invalid { error, height, hash, advertiser_addr: Some(advertiser_addr) }),
863 Some(block),
864 ) if is_later_validation_failure(&error) => {
865 let parent = block.header.previous_block_hash;
866 // Prefer the cancel handle if both are ready.
867 let authenticated = tokio::select! {
868 biased;
869 _ = &mut cancel_rx => {
870 trace!("task cancelled while checking a block that failed verification");
871 metrics::counter!("sync.cancelled.verify.count").increment(1);
872 return Err(BlockDownloadVerifyError::CancelledDuringVerification { height, hash })
873 }
874 authenticated = early_block_is_authenticated(read_state, latest_chain_tip, block, height, early_check) => authenticated,
875 };
876
877 let error = BlockDownloadVerifyError::Invalid { error, height, hash, advertiser_addr: Some(advertiser_addr) };
878 Ok(Err((error, authenticated.then_some(parent))))
879 }
880 (result, _) => Ok(result.map_err(|error| (error, None))),
881 }
882 }
883 .in_current_span()
884 // Tack the hash onto the error so we can remove the cancel handle
885 // on failure as well as on success. The task's `Ok` is the verification result, with
886 // the parent of an authenticated early relay block that failed later validation, and
887 // its `Err` is a failure before verification.
888 .map(move |result| match result {
889 Ok(Ok(verified)) => Ok(verified),
890 Ok(Err((e, authenticated_parent))) => Err((e, hash, authenticated_parent)),
891 Err(e) => Err((e, hash, None)),
892 }),
893 );
894
895 // Try to start the spawned task before queueing the next block request
896 tokio::task::yield_now().await;
897
898 let queued_at = std::time::Instant::now();
899 let task_handle = task.abort_handle();
900 self.pending.push(task);
901 assert!(
902 self.cancel_handles
903 .insert(hash, (cancel_tx, queued_at))
904 .is_none(),
905 "blocks are only queued once"
906 );
907 self.in_flight_blocks.insert(queued_at, hash, task_handle);
908
909 Ok(())
910 }
911
912 /// Cancel all running tasks and reset the downloader state.
913 ///
914 /// Keeps the rejected early relay blocks, and the allowances that peers have used for them.
915 pub fn cancel_all(&mut self) {
916 // Replace the pending task list with an empty one and drop it.
917 let _ = std::mem::take(&mut self.pending);
918
919 // Signal cancellation to all running tasks.
920 // Since we already dropped the JoinHandles above, they should
921 // fail silently.
922 for (_hash, (cancel, _queued_at)) in self.cancel_handles.drain() {
923 let _ = cancel.send(());
924 }
925
926 self.in_flight_blocks.clear();
927
928 assert!(self.pending.is_empty());
929 assert!(self.cancel_handles.is_empty());
930
931 // Set the lookahead limit to false, since we're empty (so we're under the limit).
932 //
933 // It is ok to block here, because we're doing a reset and sleep anyway.
934 // But if Zebra is shutting down, ignore the send error.
935 let _ = self
936 .past_lookahead_limit_sender
937 .lock()
938 .expect("thread panicked while holding the past_lookahead_limit_sender mutex guard")
939 .send(false);
940 }
941
942 /// Returns whether an enclosing timeout cancelled a wait for network capacity, and forgets
943 /// that wait.
944 pub fn take_cancelled_network_wait(&mut self) -> bool {
945 std::mem::take(&mut self.awaiting_network_capacity)
946 }
947
948 /// Returns true while a hash is queued, including completed tasks whose results are unread.
949 pub fn is_queued(&self, hash: &block::Hash) -> bool {
950 self.cancel_handles.contains_key(hash)
951 }
952
953 /// Get the number of currently in-flight download and verify tasks.
954 pub fn in_flight(&mut self) -> usize {
955 self.pending.len()
956 }
957
958 /// Returns the tasks that might still be running, which the sync diagnostics share.
959 pub fn in_flight_blocks(&self) -> InFlightBlocks {
960 self.in_flight_blocks.clone()
961 }
962
963 /// Returns true if there are no in-flight download and verify tasks.
964 pub fn is_empty(&mut self) -> bool {
965 self.pending.is_empty()
966 }
967}