Skip to main content

zebrad/components/
sync.rs

1//! The syncer downloads and verifies large numbers of blocks from peers to Zebra.
2//!
3//! It is used when Zebra is a long way behind the current chain tip.
4
5use std::{
6    cmp::max,
7    collections::{HashMap, HashSet, VecDeque},
8    pin::Pin,
9    task::Poll,
10    time::Duration,
11};
12
13use color_eyre::eyre::{eyre, Report};
14use futures::{
15    future::{self, FutureExt as _},
16    stream::{self, FuturesUnordered, StreamExt as _, TryStreamExt as _},
17};
18use indexmap::IndexSet;
19use serde::{Deserialize, Serialize};
20use tokio::{
21    sync::{mpsc, watch},
22    task::JoinError,
23    time::{sleep, sleep_until, timeout, Instant},
24};
25use tower::{
26    builder::ServiceBuilder, limit::ConcurrencyLimit, retry::Retry, timeout::Timeout, Service,
27    ServiceExt,
28};
29
30use zebra_chain::{
31    block::{self, Height, HeightDiff},
32    chain_tip::ChainTip,
33};
34use zebra_consensus::{
35    error::TransactionError, BlockError, RouterError, VerifyBlockError, VerifyCheckpointError,
36};
37use zebra_network as zn;
38use zebra_state as zs;
39
40use crate::{
41    components::sync::downloads::BlockDownloadVerifyError, config::ZebradConfig, BoxError,
42};
43
44mod diagnostics;
45mod downloads;
46pub mod end_of_support;
47mod gossip;
48mod hedge;
49pub(crate) mod progress;
50mod recent_sync_lengths;
51mod status;
52
53#[cfg(test)]
54mod tests;
55
56use downloads::Downloads;
57use hedge::SuccessHedge;
58
59pub(crate) use diagnostics::{RestartReason, SyncDiagnostics};
60pub use downloads::VERIFICATION_PIPELINE_SCALING_MULTIPLIER;
61pub use gossip::{gossip_best_tip_block_hashes, BlockGossipError};
62pub use progress::{record_tip_block_delay, show_block_chain_progress};
63pub use recent_sync_lengths::RecentSyncLengths;
64pub use status::SyncStatus;
65
66/// Match the missing-block errors used by both hedging and sync recovery.
67fn is_not_found(error: &dyn std::error::Error) -> bool {
68    // TODO: improve this by checking the type (#2908).
69    format!("{error:?}").contains("NotFound")
70}
71
72/// Orders tip response hashes round-robin across responses, so each peer's next hash is admitted
73/// before any peer's later hashes when the lookahead limit caps the batch.
74///
75/// Duplicates are removed after interleaving, so one response can't bury another peer's next hash
76/// deep in its own list.
77fn interleave_peer_hashes(
78    download_set: &mut IndexSet<block::Hash>,
79    mut responses: VecDeque<impl Iterator<Item = block::Hash>>,
80) {
81    download_set.clear();
82    while let Some(mut hashes) = responses.pop_front() {
83        if let Some(hash) = hashes.next() {
84            download_set.insert(hash);
85            responses.push_back(hashes);
86        }
87    }
88}
89
90/// Controls the number of peers used for each ObtainTips and ExtendTips request.
91const FANOUT: usize = 3;
92
93/// Limits concurrent discovery membership checks against the shared state service.
94const KNOWN_BLOCK_CHECK_CONCURRENCY: usize = 16;
95
96/// Controls how many times we will retry each block download.
97///
98/// Failing block downloads is important because it defends against peers who
99/// feed us bad hashes. But spurious failures of valid blocks cause the syncer to
100/// restart from the previous checkpoint, potentially re-downloading blocks.
101///
102/// We also hedge requests, so we may retry up to twice this many times. Hedged
103/// retries may be concurrent, inner retries are sequential.
104const BLOCK_DOWNLOAD_RETRY_LIMIT: usize = 3;
105
106/// Controls how many times the syncer will re-request a block whose download
107/// failed because no peer delivered it (a `NotFound`), before giving up and
108/// letting the normal tip re-walk handle it.
109///
110/// Without this re-request, a single missing block at the checkpoint frontier
111/// is dropped and never re-fetched, wedging the whole verify pipeline until the
112/// 8-minute `BLOCK_VERIFY_TIMEOUT` fires (#5709). Each attempt already goes
113/// through the tower-level `BLOCK_DOWNLOAD_RETRY_LIMIT` (and hedging), so this
114/// is a coarse, hash-scoped retry on top of an exhausted per-request retry.
115const MAX_BLOCK_REOBTAIN_RETRIES: u8 = 3;
116
117/// The fewest `TransparentInputNotFound` drops without a verified block before the sync
118/// restarts, so a low `full_verify_concurrency_limit` can't disable the #11168 exemption.
119const MIN_UTXO_RACE_DROPS_BEFORE_RESTART: usize = 4;
120
121/// A lower bound on the user-specified checkpoint verification concurrency limit.
122///
123/// Set to the maximum checkpoint interval, so the pipeline holds around a checkpoint's
124/// worth of blocks.
125///
126/// ## Security
127///
128/// If a malicious node is chosen for an ObtainTips or ExtendTips request, it can
129/// provide up to 500 malicious block hashes. These block hashes will be
130/// distributed across all available peers. Assuming there are around 50 connected
131/// peers, the malicious node will receive approximately 10 of those block requests.
132///
133/// Malicious deserialized blocks can take up a large amount of RAM, see
134/// [`super::inbound::downloads::MAX_INBOUND_CONCURRENCY`] and #1880 for details.
135/// So we want to keep the lookahead limit reasonably small.
136///
137/// Invalid blocks are dropped without cancelling unrelated downloads. The lookahead limit bounds
138/// retained tasks, and verification timeouts release blocks whose ancestors never arrive.
139pub const MIN_CHECKPOINT_CONCURRENCY_LIMIT: usize = zebra_consensus::MAX_CHECKPOINT_HEIGHT_GAP;
140
141/// The default for the user-specified lookahead limit.
142///
143/// See [`MIN_CHECKPOINT_CONCURRENCY_LIMIT`] for details.
144pub const DEFAULT_CHECKPOINT_CONCURRENCY_LIMIT: usize = MAX_TIPS_RESPONSE_HASH_COUNT * 2;
145
146/// A lower bound on the user-specified concurrency limit.
147///
148/// If the concurrency limit is 0, Zebra can't download or verify any blocks.
149pub const MIN_CONCURRENCY_LIMIT: usize = 1;
150
151/// The expected maximum number of hashes in an ObtainTips or ExtendTips response.
152///
153/// This is used to allow block heights that are slightly beyond the lookahead limit,
154/// but still limit the number of blocks in the pipeline between the downloader and
155/// the state.
156///
157/// See [`MIN_CHECKPOINT_CONCURRENCY_LIMIT`] for details.
158pub const MAX_TIPS_RESPONSE_HASH_COUNT: usize = 500;
159
160/// Controls how long we wait for a tips response to return.
161///
162/// ## Correctness
163///
164/// If this timeout is removed (or set too high), the syncer will sometimes hang.
165///
166/// If this timeout is set too low, the syncer will sometimes get stuck in a
167/// failure loop.
168pub const TIPS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(6);
169
170/// How many rounds of [`FANOUT`] requests `extend_tips` sends for a tip before dropping it,
171/// when no peer answers a round.
172const EXTEND_TIP_ROUNDS: usize = 3;
173
174/// Controls how long we wait between gossiping successive batches of transactions.
175///
176/// ## Correctness
177///
178/// If this timeout is set too high, transactions won't propagate through
179/// the network efficiently.
180///
181/// If this timeout is set too low, the peer set and remote peers can get overloaded.
182#[cfg(not(test))]
183pub const PEER_GOSSIP_DELAY: Duration = Duration::from_secs(7);
184
185/// Keep gossip throttled in unit tests without waiting for real peer-network delays.
186#[cfg(test)]
187pub const PEER_GOSSIP_DELAY: Duration = Duration::from_millis(10);
188
189/// The per-peer wire-response budget used to derive complete download deadlines.
190///
191/// Connections start this timeout at dispatch, not while waiting for capacity. The complete sync
192/// operation is separately bounded by [`BLOCK_DOWNLOAD_ROUND_TIMEOUT`].
193pub(super) const BLOCK_DOWNLOAD_TIMEOUT: Duration = zn::constants::REQUEST_TIMEOUT;
194
195/// Bounds one complete block download round, including readiness, capacity waits and both hedges.
196///
197/// Reuse the existing four-attempt response budget rather than charging capacity waits as attempts.
198/// The retry limit is the constant 3, so conversion to u32 is lossless.
199const BLOCK_DOWNLOAD_ROUND_TIMEOUT: Duration =
200    BLOCK_DOWNLOAD_TIMEOUT.saturating_mul(BLOCK_DOWNLOAD_RETRY_LIMIT as u32 + 1);
201
202/// Controls how long we wait for a block verify request to complete.
203///
204/// This timeout makes sure that the syncer doesn't hang when:
205///  - the lookahead queue is full, and
206///  - all pending verifications:
207///    - are waiting on a missing download request,
208///    - are waiting on a download or verify request that has failed, but we have
209///      deliberately ignored the error,
210///    - are for blocks a long way ahead of the current tip, or
211///    - are for invalid blocks which will never verify, because they depend on
212///      missing blocks or transactions.
213///
214/// These conditions can happen during normal operation - they are not bugs.
215///
216/// This timeout also mitigates or hides the following kinds of bugs:
217///  - all pending verifications:
218///    - are waiting on a download or verify request that has failed, but we have
219///      accidentally dropped the error,
220///    - are waiting on a download request that has hung inside Zebra,
221///    - are on tokio threads that are waiting for blocked operations.
222///
223/// ## Correctness
224///
225/// If this timeout is removed (or set too high), the syncer will sometimes hang.
226///
227/// If this timeout is set too low, the syncer will sometimes get stuck in a
228/// failure loop.
229///
230/// We've observed spurious 15 minute timeouts when a lot of blocks are being committed to
231/// the state. But there are also some blocks that seem to hang entirely, and never return.
232///
233/// So we allow about half the spurious timeout, which might cause some re-downloads.
234pub(super) const BLOCK_VERIFY_TIMEOUT: Duration = Duration::from_secs(8 * 60);
235
236/// A shorter timeout used for the first few blocks after the final checkpoint.
237///
238/// This is a workaround for bug #5125, where the first fully validated blocks
239/// after the final checkpoint fail with a timeout, due to a UTXO race condition.
240const FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT: Duration = Duration::from_secs(2 * 60);
241
242/// The number of blocks after the final checkpoint that get the shorter timeout.
243///
244/// We've only seen this error on the first few blocks after the final checkpoint.
245const FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT_LIMIT: HeightDiff = 100;
246
247/// Controls how long we wait to restart syncing after finishing a sync run.
248///
249/// This delay should be long enough to:
250///   - allow zcashd peers to process pending requests. If the node only has a
251///     few peers, we want to clear as much peer state as possible. In
252///     particular, zcashd sends "next block range" hints, based on zcashd's
253///     internal model of our sync progress. But we want to discard these hints,
254///     so they don't get confused with ObtainTips and ExtendTips responses, and
255///   - allow in-progress downloads to time out.
256///
257/// This delay is particularly important on instances with slow or unreliable
258/// networks, and on testnet, which has a small number of slow peers.
259///
260/// Using a prime number makes sure that syncer fanouts don't synchronise with other crawls.
261///
262/// ## Correctness
263///
264/// If this delay is removed (or set too low), the syncer will
265/// sometimes get stuck in a failure loop, due to leftover downloads from
266/// previous sync runs.
267///
268/// Networks can override this delay, see
269/// [`Network::sync_restart_delay`](zebra_chain::parameters::Network::sync_restart_delay).
270const SYNC_RESTART_DELAY: Duration = Duration::from_secs(67);
271
272/// Controls how long we wait to retry a failed attempt to download
273/// and verify the genesis block.
274///
275/// This timeout gives the crawler time to find better peers.
276///
277/// ## Security
278///
279/// If this timeout is removed (or set too low), Zebra will immediately retry
280/// to download and verify the genesis block from its peers. This can cause
281/// a denial of service on those peers.
282///
283/// If this timeout is too short, old or buggy nodes will keep making useless
284/// network requests. If there are a lot of them, it could overwhelm the network.
285const GENESIS_TIMEOUT_RETRY: Duration = Duration::from_secs(10);
286
287/// Sync configuration section.
288#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
289#[serde(deny_unknown_fields, default)]
290pub struct Config {
291    /// The number of parallel block download requests.
292    ///
293    /// This is set to a low value by default, to avoid task and
294    /// network contention. Increasing this value may improve
295    /// performance on machines with a fast network connection.
296    #[serde(alias = "max_concurrent_block_requests")]
297    pub download_concurrency_limit: usize,
298
299    /// The number of blocks submitted in parallel to the checkpoint verifier.
300    ///
301    /// Increasing this limit increases the buffer size, so it reduces
302    /// the impact of an individual block request failing. However, it
303    /// also increases memory and CPU usage if block validation stalls,
304    /// or there are some large blocks in the pipeline.
305    ///
306    /// The block size limit is 2MB, so in theory, this could represent multiple
307    /// gigabytes of data, if we downloaded arbitrary blocks. However,
308    /// because we randomly load balance outbound requests, and separate
309    /// block download from obtaining block hashes, an adversary would
310    /// have to control a significant fraction of our peers to lead us
311    /// astray.
312    ///
313    /// For reliable checkpoint syncing, Zebra enforces a
314    /// [`MIN_CHECKPOINT_CONCURRENCY_LIMIT`].
315    ///
316    /// This is set to a high value by default, to avoid verification pipeline stalls.
317    /// Decreasing this value reduces RAM usage.
318    #[serde(alias = "lookahead_limit")]
319    pub checkpoint_verify_concurrency_limit: usize,
320
321    /// The number of blocks submitted in parallel to the full verifier.
322    ///
323    /// This is set to a low value by default, to avoid verification timeouts on large blocks.
324    /// Increasing this value may improve performance on machines with many cores.
325    pub full_verify_concurrency_limit: usize,
326
327    /// The number of threads used to verify signatures, proofs, and other CPU-intensive code.
328    ///
329    /// If the number of threads is not configured or zero, Zebra uses the number of logical cores.
330    /// If the number of logical cores can't be detected, Zebra uses one thread.
331    /// For details, see [the `rayon` documentation](https://docs.rs/rayon/latest/rayon/struct.ThreadPoolBuilder.html#method.num_threads).
332    pub parallel_cpu_threads: usize,
333}
334
335impl Default for Config {
336    fn default() -> Self {
337        Self {
338            // 2/3 of the default outbound peer limit.
339            download_concurrency_limit: 50,
340
341            // A few max-length checkpoints.
342            checkpoint_verify_concurrency_limit: DEFAULT_CHECKPOINT_CONCURRENCY_LIMIT,
343
344            // This default is deliberately very low, so Zebra can verify a few large blocks in under 60 seconds,
345            // even on machines with only a few cores.
346            //
347            // This lets users see the committed block height changing in every progress log,
348            // and avoids hangs due to out-of-order verifications flooding the CPUs.
349            //
350            // TODO:
351            // - limit full verification concurrency based on block transaction counts?
352            // - move more disk work to blocking tokio threads,
353            //   and CPU work to the rayon thread pool inside blocking tokio threads
354            full_verify_concurrency_limit: 20,
355
356            // Use one thread per CPU.
357            //
358            // If this causes tokio executor starvation, move CPU-intensive tasks to rayon threads,
359            // or reserve a few cores for tokio threads, based on `num_cpus()`.
360            parallel_cpu_threads: 0,
361        }
362    }
363}
364
365/// Helps work around defects in the bitcoin protocol by checking whether
366/// the returned hashes actually extend a chain tip.
367#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
368struct CheckedTip {
369    tip: block::Hash,
370    expected_next: block::Hash,
371}
372
373pub struct ChainSync<ZN, ZS, ZSR, ZV, ZSTip>
374where
375    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError>
376        + Send
377        + Sync
378        + Clone
379        + 'static,
380    ZN::Future: Send + 'static,
381    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError>
382        + Send
383        + Sync
384        + Clone
385        + 'static,
386    ZS::Future: Send,
387    ZSR: Service<zs::ReadRequest, Response = zs::ReadResponse, Error = BoxError>
388        + Send
389        + Sync
390        + Clone
391        + 'static,
392    ZSR::Future: Send,
393    ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
394        + Send
395        + Sync
396        + Clone
397        + 'static,
398    ZV::Future: Send,
399    ZSTip: ChainTip + Clone + Send + 'static,
400{
401    // Configuration
402    //
403    /// The genesis hash for the configured network
404    genesis_hash: block::Hash,
405
406    /// The largest block height for the checkpoint verifier, based on the current config.
407    max_checkpoint_height: Height,
408
409    /// The configured checkpoint verification concurrency limit, after applying the minimum limit.
410    checkpoint_verify_concurrency_limit: usize,
411
412    /// The configured full verification concurrency limit, after applying the minimum limit.
413    full_verify_concurrency_limit: usize,
414
415    /// Optional network override for the delay between sync restarts.
416    restart_delay: Option<Duration>,
417
418    // Services
419    //
420    /// A network service which is used to perform ObtainTips and ExtendTips
421    /// requests.
422    ///
423    /// Has no retry logic, because failover is handled using fanout.
424    tip_network: Timeout<ZN>,
425
426    /// A service which downloads and verifies blocks, using the provided
427    /// network and verifier services.
428    downloads: Pin<
429        Box<
430            Downloads<
431                ConcurrencyLimit<SuccessHedge<ConcurrencyLimit<Retry<zn::RetryLimit, ZN>>>>,
432                Timeout<ZV>,
433                ZSR,
434                ZSTip,
435            >,
436        >,
437    >,
438
439    /// The cached block chain state.
440    state: ZS,
441
442    /// Allows efficient access to the best tip of the blockchain.
443    latest_chain_tip: ZSTip,
444
445    // Internal sync state
446    //
447    /// The tips that the syncer is currently following.
448    prospective_tips: HashSet<CheckedTip>,
449
450    /// The lengths of recent sync responses.
451    recent_syncs: RecentSyncLengths,
452
453    /// Receiver that is `true` when the downloader is past the lookahead limit.
454    /// This is based on the downloaded block height and the state tip height.
455    past_lookahead_limit_receiver: zs::WatchReceiver<bool>,
456
457    /// Sender for reporting peer addresses that advertised unexpectedly invalid transactions.
458    misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
459
460    /// Blocks whose download failed with `NotFound` and should be re-requested on
461    /// the next sync round, instead of being silently dropped (#5709).
462    reobtain_hashes: IndexSet<block::Hash>,
463
464    /// Per-hash count of how many times a `NotFound` block has been re-requested,
465    /// bounded by [`MAX_BLOCK_REOBTAIN_RETRIES`].
466    block_reobtain_retries: HashMap<block::Hash, u8>,
467
468    /// `TransparentInputNotFound` drops since the last verified block, bounded by the
469    /// full-verify concurrency limit so a poisoned hash batch can't suppress restarts.
470    utxo_race_drops: usize,
471
472    /// Publishes the syncer state that the progress task logs when sync stalls.
473    diagnostics: watch::Sender<SyncDiagnostics>,
474}
475
476/// A sync round that ended early, and why.
477#[derive(Debug)]
478struct RestartError {
479    reason: RestartReason,
480    /// The block error kind, for [`RestartReason::BlockError`].
481    kind: Option<&'static str>,
482    error: Report,
483}
484
485impl RestartError {
486    fn new(reason: RestartReason, error: impl Into<Report>) -> Self {
487        Self {
488            reason,
489            kind: None,
490            error: error.into(),
491        }
492    }
493}
494
495/// Polls the network to determine whether further blocks are available and
496/// downloads them.
497///
498/// This component is used for initial block sync, but the `Inbound` service is
499/// responsible for participating in the gossip protocols used for block
500/// diffusion.
501impl<ZN, ZS, ZSR, ZV, ZSTip> ChainSync<ZN, ZS, ZSR, ZV, ZSTip>
502where
503    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError>
504        + Send
505        + Sync
506        + Clone
507        + 'static,
508    ZN::Future: Send + 'static,
509    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError>
510        + Send
511        + Sync
512        + Clone
513        + 'static,
514    ZS::Future: Send,
515    ZSR: Service<zs::ReadRequest, Response = zs::ReadResponse, Error = BoxError>
516        + Send
517        + Sync
518        + Clone
519        + 'static,
520    ZSR::Future: Send,
521    ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
522        + Send
523        + Sync
524        + Clone
525        + 'static,
526    ZV::Future: Send,
527    ZSTip: ChainTip + Clone + Send + 'static,
528{
529    /// Returns a new syncer instance, using:
530    ///  - chain: the zebra-chain `Network` to download (Mainnet or Testnet)
531    ///  - peers: the zebra-network peers to contact for downloads
532    ///  - verifier: the zebra-consensus verifier that checks the chain
533    ///  - state: the zebra-state that stores the chain
534    ///  - read_state: a read-only handle to the zebra-state, used to check downloaded block heights
535    ///  - latest_chain_tip: the latest chain tip from `state`
536    ///
537    /// Also returns a [`SyncStatus`] to check if the syncer has likely reached the chain tip.
538    #[allow(clippy::too_many_arguments)]
539    pub fn new(
540        config: &ZebradConfig,
541        max_checkpoint_height: Height,
542        peers: ZN,
543        verifier: ZV,
544        state: ZS,
545        read_state: ZSR,
546        latest_chain_tip: ZSTip,
547        misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
548    ) -> (Self, SyncStatus) {
549        let mut download_concurrency_limit = config.sync.download_concurrency_limit;
550        let mut checkpoint_verify_concurrency_limit =
551            config.sync.checkpoint_verify_concurrency_limit;
552        let mut full_verify_concurrency_limit = config.sync.full_verify_concurrency_limit;
553
554        if download_concurrency_limit < MIN_CONCURRENCY_LIMIT {
555            warn!(
556                "configured download concurrency limit {} too low, increasing to {}",
557                config.sync.download_concurrency_limit, MIN_CONCURRENCY_LIMIT,
558            );
559
560            download_concurrency_limit = MIN_CONCURRENCY_LIMIT;
561        }
562
563        if checkpoint_verify_concurrency_limit < MIN_CHECKPOINT_CONCURRENCY_LIMIT {
564            warn!(
565                "configured checkpoint verify concurrency limit {} too low, increasing to {}",
566                config.sync.checkpoint_verify_concurrency_limit, MIN_CHECKPOINT_CONCURRENCY_LIMIT,
567            );
568
569            checkpoint_verify_concurrency_limit = MIN_CHECKPOINT_CONCURRENCY_LIMIT;
570        }
571
572        if full_verify_concurrency_limit < MIN_CONCURRENCY_LIMIT {
573            warn!(
574                "configured full verify concurrency limit {} too low, increasing to {}",
575                config.sync.full_verify_concurrency_limit, MIN_CONCURRENCY_LIMIT,
576            );
577
578            full_verify_concurrency_limit = MIN_CONCURRENCY_LIMIT;
579        }
580
581        let tip_network = Timeout::new(peers.clone(), TIPS_RESPONSE_TIMEOUT);
582
583        // Capacity waiting stays inside the network request and does not consume a retry.
584        // Connections start response deadlines at wire dispatch; Downloads bounds readiness
585        // and the complete hedged retry operation with one absolute deadline.
586        // Hedge entire retry sequences so individual peer failures are retried before hedging.
587        // The inner limit bounds active sequences across both arms; exhausted arms release it
588        // immediately so their delayed siblings can start even at a limit of one.
589        // The outer limit bounds logical downloads, holding admission while any arm can succeed.
590        // Success, final failure, or cancellation releases it before block verification starts.
591        let block_network = SuccessHedge::new(
592            ServiceBuilder::new()
593                .concurrency_limit(download_concurrency_limit)
594                .retry(zn::RetryLimit::new(BLOCK_DOWNLOAD_RETRY_LIMIT))
595                .service(peers),
596        );
597        let block_network = ConcurrencyLimit::new(block_network, download_concurrency_limit);
598
599        // We apply a timeout to the verifier to avoid hangs due to missing earlier blocks.
600        let verifier = Timeout::new(verifier, BLOCK_VERIFY_TIMEOUT);
601
602        let (sync_status, recent_syncs) = SyncStatus::new_for_network(&config.network.network);
603        let (past_lookahead_limit_sender, past_lookahead_limit_receiver) = watch::channel(false);
604        let past_lookahead_limit_receiver = zs::WatchReceiver::new(past_lookahead_limit_receiver);
605
606        let downloads = Box::pin(Downloads::new(
607            block_network,
608            verifier,
609            read_state,
610            latest_chain_tip.clone(),
611            past_lookahead_limit_sender,
612            max(
613                checkpoint_verify_concurrency_limit,
614                full_verify_concurrency_limit,
615            ),
616            max_checkpoint_height,
617        ));
618
619        let (diagnostics, diagnostics_receiver) = watch::channel(SyncDiagnostics {
620            in_flight_blocks: downloads.in_flight_blocks(),
621            ..SyncDiagnostics::default()
622        });
623        let sync_status = sync_status.with_diagnostics(diagnostics_receiver);
624
625        let new_syncer = Self {
626            genesis_hash: config.network.network.genesis_hash(),
627            max_checkpoint_height,
628            checkpoint_verify_concurrency_limit,
629            full_verify_concurrency_limit,
630            restart_delay: config.network.network.sync_restart_delay(),
631            tip_network,
632            downloads,
633            state,
634            latest_chain_tip,
635            prospective_tips: HashSet::new(),
636            recent_syncs,
637            past_lookahead_limit_receiver,
638            misbehavior_sender,
639            reobtain_hashes: IndexSet::new(),
640            block_reobtain_retries: HashMap::new(),
641            utxo_race_drops: 0,
642            diagnostics,
643        };
644
645        (new_syncer, sync_status)
646    }
647
648    /// Runs the syncer to synchronize the chain and keep it synchronized.
649    #[instrument(skip(self))]
650    pub async fn sync(mut self) -> Result<(), Report> {
651        // We can't download the genesis block using our normal algorithm,
652        // due to protocol limitations
653        self.request_genesis().await?;
654
655        loop {
656            let start_tip = self.latest_chain_tip.best_tip_height();
657            let result = self.try_to_sync().await;
658            if result.is_err() {
659                self.count_finished_block_errors();
660                self.downloads.cancel_all();
661                self.reobtain_hashes.clear();
662                self.block_reobtain_retries.clear();
663            }
664
665            self.update_metrics();
666
667            let restart_delay = self.restart_delay.unwrap_or(SYNC_RESTART_DELAY);
668            let state_tip = self.latest_chain_tip.best_tip_height();
669            let made_progress = state_tip > start_tip;
670            let (reason, kind, error) = match result {
671                Ok(reason) => (reason, None, None),
672                Err(restart) => (
673                    restart.reason,
674                    restart.kind,
675                    Some(format!("{:#}", restart.error)),
676                ),
677            };
678            self.record_restart(reason, made_progress);
679
680            if error.is_some() && !made_progress {
681                warn!(
682                    reason = reason.as_str(),
683                    kind,
684                    error,
685                    timeout = ?restart_delay,
686                    ?state_tip,
687                    "sync failed without advancing the state tip, waiting to restart sync"
688                );
689            } else {
690                info!(
691                    reason = reason.as_str(),
692                    kind,
693                    made_progress,
694                    error,
695                    timeout = ?restart_delay,
696                    ?state_tip,
697                    "waiting to restart sync"
698                );
699            }
700            sleep(restart_delay).await;
701        }
702    }
703
704    /// Counts a finished sync round.
705    fn record_restart(&self, reason: RestartReason, made_progress: bool) {
706        metrics::counter!(
707            "sync.restart.count",
708            "reason" => reason.as_str(),
709            "made_progress" => if made_progress { "true" } else { "false" },
710        )
711        .increment(1);
712
713        self.diagnostics.send_modify(|diagnostics| {
714            diagnostics.last_restart = Some(reason);
715            diagnostics.restarts_without_progress = if made_progress {
716                0
717            } else {
718                diagnostics.restarts_without_progress.saturating_add(1)
719            };
720        });
721    }
722
723    /// Tries to synchronize the chain as far as it can.
724    ///
725    /// Obtains some prospective tips and iteratively tries to extend them and download the missing
726    /// blocks.
727    ///
728    /// Returns `Ok` if it was able to synchronize as much of the chain as it could, and then ran
729    /// out of prospective tips or made no chain progress within [`BLOCK_VERIFY_TIMEOUT`].
730    /// Either way, Zebra should attempt to obtain some more tips after the restart delay,
731    /// without cancelling unrelated downloads.
732    ///
733    /// Returns `Err` if an unrecoverable service error or a timeout obtaining initial tips
734    /// requires resetting the synchronization.
735    #[instrument(skip(self))]
736    async fn try_to_sync(&mut self) -> Result<RestartReason, RestartError> {
737        self.prospective_tips = HashSet::new();
738        self.utxo_race_drops = 0;
739        self.downloads.take_cancelled_network_wait();
740
741        // Reap the previous round even if the new tips never enter `try_to_sync_once`.
742        // Unfinished downloads can still make progress while we obtain fresh tips.
743        while let Poll::Ready(Some(response)) = futures::poll!(self.downloads.next()) {
744            self.handle_block_response(response)
745                .map_err(Self::block_restart_error)?;
746        }
747        // Preserve retry budgets for retained downloads, but discard terminal failures.
748        self.block_reobtain_retries.retain(|hash, _| {
749            self.downloads.is_queued(hash) || self.reobtain_hashes.contains(hash)
750        });
751
752        info!(
753            state_tip = ?self.latest_chain_tip.best_tip_height(),
754            "starting sync, obtaining new tips"
755        );
756        // Queueing the blocks it finds can wait for network capacity for longer than this timeout.
757        let mut extra_hashes = match timeout(SYNC_RESTART_DELAY, self.obtain_tips()).await {
758            Ok(tips) => {
759                tips.map_err(|e| Self::tips_restart_error(RestartReason::ObtainTipsError, e))?
760            }
761            Err(elapsed) => {
762                return Err(self.stage_timeout_error(RestartReason::ObtainTipsTimeout, elapsed));
763            }
764        };
765        self.update_metrics();
766
767        let mut chain_tip = self.latest_chain_tip.clone();
768        let mut last_height = chain_tip.best_tip_height();
769        let mut progress_deadline = Instant::now() + BLOCK_VERIFY_TIMEOUT;
770        while !self.prospective_tips.is_empty()
771            || !extra_hashes.is_empty()
772            || !self.reobtain_hashes.is_empty()
773        {
774            let result = {
775                let step = self.try_to_sync_once(extra_hashes);
776                tokio::pin!(step);
777                loop {
778                    tokio::select! {
779                        biased;
780                        Ok(()) = chain_tip.best_tip_changed() => {
781                            let height = chain_tip.best_tip_height();
782                            if height > last_height {
783                                last_height = height;
784                                progress_deadline = Instant::now() + BLOCK_VERIFY_TIMEOUT;
785                            }
786                        }
787                        result = &mut step => break Some(result),
788                        _ = sleep_until(progress_deadline) => break None,
789                    }
790                }
791            };
792            match result {
793                Some(result) => extra_hashes = result?,
794                None => {
795                    self.count_cancelled_network_wait();
796                    info!("no chain progress before the sync deadline, backing off");
797                    return Ok(RestartReason::SyncStepTimeout);
798                }
799            }
800        }
801
802        info!("exhausted prospective tip set");
803
804        Ok(RestartReason::ExhaustedTips)
805    }
806
807    /// Tries to synchronize the chain once, using the existing `extra_hashes`.
808    ///
809    /// Tries to extend the existing tips and download the missing blocks.
810    ///
811    /// Returns `Ok(extra_hashes)` if it was able to extend once and synchronize sone of the chain.
812    /// Returns `Err` if there was an unrecoverable error and restarting the synchronization is
813    /// necessary.
814    #[instrument(skip(self, extra_hashes))]
815    async fn try_to_sync_once(
816        &mut self,
817        mut extra_hashes: IndexSet<block::Hash>,
818    ) -> Result<IndexSet<block::Hash>, RestartError> {
819        // Check whether any block tasks are currently ready.
820        while let Poll::Ready(Some(rsp)) = futures::poll!(self.downloads.next()) {
821            // Some temporary errors are ignored, and syncing continues with other blocks.
822            // If it turns out they were actually important, syncing will run out of blocks, and
823            // the syncer will reset itself.
824            self.handle_block_response(rsp)
825                .map_err(Self::block_restart_error)?;
826        }
827        // Re-request any blocks that just failed with `NotFound`, before pausing
828        // on the lookahead limit (#5709).
829        self.reobtain_missing_blocks().await;
830        self.update_metrics();
831
832        // Pause new downloads while the syncer or downloader are past their lookahead limits.
833        //
834        // To avoid a deadlock or long waits for blocks to expire, we ignore the download
835        // lookahead limit when there are only a small number of blocks waiting.
836        while !self.downloads.is_empty()
837            && (self.downloads.in_flight() >= self.lookahead_limit()
838                || (self.downloads.in_flight() >= self.lookahead_limit() / 2
839                    && self.past_lookahead_limit_receiver.cloned_watch_data()))
840        {
841            trace!(
842                tips.len = self.prospective_tips.len(),
843                in_flight = self.downloads.in_flight(),
844                extra_hashes = extra_hashes.len(),
845                lookahead_limit = self.lookahead_limit(),
846                state_tip = ?self.latest_chain_tip.best_tip_height(),
847                "waiting for pending blocks",
848            );
849
850            let response = self.downloads.next().await.expect("downloads is nonempty");
851
852            self.handle_block_response(response)
853                .map_err(Self::block_restart_error)?;
854            // A block that just failed with `NotFound` is what unblocks the
855            // verifier, so re-request it now rather than waiting for the pause
856            // loop to clear — which it cannot until this block arrives (#5709).
857            self.reobtain_missing_blocks().await;
858            self.update_metrics();
859        }
860
861        // Once we're below the lookahead limit, we can request more blocks or hashes.
862        if !extra_hashes.is_empty() {
863            debug!(
864                tips.len = self.prospective_tips.len(),
865                in_flight = self.downloads.in_flight(),
866                extra_hashes = extra_hashes.len(),
867                lookahead_limit = self.lookahead_limit(),
868                state_tip = ?self.latest_chain_tip.best_tip_height(),
869                "requesting more blocks",
870            );
871
872            let response = self.request_blocks(extra_hashes).await;
873            extra_hashes =
874                Self::handle_hash_response(response).map_err(Self::block_restart_error)?;
875        } else {
876            info!(
877                tips.len = self.prospective_tips.len(),
878                in_flight = self.downloads.in_flight(),
879                extra_hashes = extra_hashes.len(),
880                lookahead_limit = self.lookahead_limit(),
881                state_tip = ?self.latest_chain_tip.best_tip_height(),
882                "extending tips",
883            );
884
885            extra_hashes = self
886                .extend_tips()
887                .await
888                .map_err(|e| Self::tips_restart_error(RestartReason::ExtendTipsError, e))?;
889        }
890        self.update_metrics();
891
892        Ok(extra_hashes)
893    }
894
895    /// Re-issues downloads for blocks that failed with `NotFound` (#5709).
896    ///
897    /// These are re-requested even while the download pipeline is past its
898    /// lookahead limit, because a missing low block is exactly what stops the
899    /// checkpoint verifier from advancing. Waiting for the lookahead pause to
900    /// clear would deadlock — the pause cannot clear until this block arrives.
901    /// The per-hash retry count is bounded by [`MAX_BLOCK_REOBTAIN_RETRIES`].
902    /// Blocks that can't get network capacity before the download deadline stay queued for the
903    /// next sync round.
904    async fn reobtain_missing_blocks(&mut self) {
905        if self.reobtain_hashes.is_empty() {
906            return;
907        }
908
909        while let Some(hash) = self.reobtain_hashes.first().copied() {
910            // Keep the hash queued across the await: the progress deadline can cancel dispatch.
911            // A duplicate means the block is already being handled, and a rejected early relay
912            // block can't be valid.
913            if let Err(error) = self.queue_block(hash).await {
914                trace!(?hash, ?error, "re-download of missing block not queued");
915                // Any other error means the network failed or wasn't ready before the download
916                // deadline. Keep this block and the rest for the next sync round, rather than
917                // dropping blocks the verifier is waiting for, or waiting out each deadline.
918                if !matches!(
919                    error,
920                    BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. }
921                        | BlockDownloadVerifyError::AlreadyRejected { .. }
922                ) {
923                    break;
924                }
925            }
926            self.reobtain_hashes.shift_remove(&hash);
927        }
928    }
929
930    /// Given a block_locator list fan out request for subsequent hashes to
931    /// multiple peers
932    #[instrument(skip(self))]
933    async fn obtain_tips(&mut self) -> Result<IndexSet<block::Hash>, Report> {
934        let stage_start = std::time::Instant::now();
935
936        let block_locator = self
937            .state
938            .ready()
939            .await
940            .map_err(|e| eyre!(e))?
941            .call(zebra_state::Request::BlockLocator)
942            .await
943            .map(|response| match response {
944                zebra_state::Response::BlockLocator(block_locator) => block_locator,
945                _ => unreachable!(
946                    "GetBlockLocator request can only result in Response::BlockLocator"
947                ),
948            })
949            .map_err(|e| eyre!(e))?;
950
951        debug!(
952            tip = ?block_locator.first().expect("we have at least one block locator object"),
953            ?block_locator,
954            "got block locator and trying to obtain new chain tips"
955        );
956
957        let mut requests = FuturesUnordered::new();
958        for attempt in 0..FANOUT {
959            if attempt > 0 {
960                // Let other tasks run, so we're more likely to choose a different peer.
961                //
962                // TODO: move fanouts into the PeerSet, so we always choose different peers (#2214)
963                tokio::task::yield_now().await;
964            }
965
966            let ready_tip_network = self.tip_network.ready().await;
967            requests.push(tokio::spawn(ready_tip_network.map_err(|e| eyre!(e))?.call(
968                zn::Request::FindBlocks {
969                    known_blocks: block_locator.clone(),
970                    stop: None,
971                },
972            )));
973        }
974
975        let mut download_set = IndexSet::new();
976        let mut response_candidates = Vec::with_capacity(FANOUT);
977        let mut peer_hashes = VecDeque::new();
978        while let Some(res) = requests.next().await {
979            match res
980                .unwrap_or_else(|e @ JoinError { .. }| {
981                    if e.is_panic() {
982                        panic!("panic in obtain tips task: {e:?}");
983                    } else {
984                        info!(
985                            "task error during obtain tips task: {e:?},\
986                     is Zebra shutting down?"
987                        );
988                        Err(e.into())
989                    }
990                })
991                .map_err::<Report, _>(|e| eyre!(e))
992            {
993                Ok(zn::Response::BlockHashes(hashes)) => {
994                    trace!(?hashes);
995
996                    if hashes.is_empty() {
997                        continue;
998                    }
999
1000                    let mut first_unknown = None;
1001                    for (i, &hash) in hashes.iter().enumerate() {
1002                        if !self.state_contains(hash).await? {
1003                            first_unknown = Some(i);
1004                            break;
1005                        }
1006                    }
1007
1008                    debug!(hashes.len = ?hashes.len(), ?first_unknown);
1009
1010                    let unknown_hashes = if let Some(index) = first_unknown {
1011                        &hashes[index..]
1012                    } else {
1013                        continue;
1014                    };
1015
1016                    trace!(?unknown_hashes);
1017
1018                    if let Some(end) = unknown_hashes.rchunks_exact(2).next() {
1019                        let new_tip = CheckedTip {
1020                            tip: end[0],
1021                            expected_next: end[1],
1022                        };
1023
1024                        // Preserve original candidates until state filtering decides eligibility.
1025                        response_candidates.push((new_tip, unknown_hashes.to_vec()));
1026                    } else {
1027                        debug!("downloading response that extends only one block");
1028                    }
1029
1030                    let prev_download_len = download_set.len();
1031                    download_set.extend(unknown_hashes);
1032                    let new_download_len = download_set.len();
1033                    let new_hashes = new_download_len - prev_download_len;
1034                    debug!(new_hashes, "added hashes to download set");
1035                    metrics::histogram!("sync.obtain.response.hash.count")
1036                        .record(new_hashes as f64);
1037                    let known_hashes = hashes.len() - unknown_hashes.len();
1038                    peer_hashes.push_back(hashes.into_iter().skip(known_hashes));
1039                }
1040                Ok(_) => unreachable!("network returned wrong response"),
1041                // We ignore this error because we made multiple fanout requests.
1042                Err(e) => debug!(?e),
1043            }
1044        }
1045
1046        // Interleave before filtering so rebuilding the set cannot restore committed hashes.
1047        interleave_peer_hashes(&mut download_set, peer_hashes);
1048
1049        // Filter after deduplication without discarding other peers' useful work.
1050        let state = self.state.clone();
1051        let download_set = stream::iter(download_set)
1052            .map(move |hash| {
1053                let state = state.clone();
1054
1055                async move {
1056                    let response = state
1057                        .oneshot(zs::Request::KnownBlock(hash))
1058                        .await
1059                        .map_err(|error| eyre!(error))?;
1060                    let zs::Response::KnownBlock(location) = response else {
1061                        unreachable!("wrong response to known block request");
1062                    };
1063
1064                    // As in `state_contains`, queued blocks still need their parents downloaded.
1065                    let is_known =
1066                        location.is_some_and(|location| location != zs::KnownBlock::Queue);
1067
1068                    Ok::<_, Report>((!is_known).then_some(hash))
1069                }
1070            })
1071            // Keep discovery order when splitting immediate and deferred downloads.
1072            .buffered(KNOWN_BLOCK_CHECK_CONCURRENCY)
1073            .try_filter_map(future::ok)
1074            .try_collect::<IndexSet<_>>()
1075            .await?;
1076
1077        // Only eligible responses may supersede another response's candidate.
1078        // The download set also contains useful work from ineligible responses,
1079        // so it must not be used to suppress an eligible tip during merging.
1080        let mut eligible_response_hashes = HashSet::new();
1081        for (response_tip, response_hashes) in response_candidates {
1082            // Check the original pair before merging; filtering must not manufacture adjacency.
1083            if !download_set.contains(&response_tip.tip)
1084                || !download_set.contains(&response_tip.expected_next)
1085            {
1086                continue;
1087            }
1088
1089            if !eligible_response_hashes.contains(&response_tip.expected_next) {
1090                self.prospective_tips
1091                    .retain(|tip| !response_hashes.contains(&tip.expected_next));
1092                self.prospective_tips.insert(response_tip);
1093            }
1094            eligible_response_hashes.extend(response_hashes);
1095        }
1096
1097        debug!(?self.prospective_tips);
1098
1099        let new_downloads = download_set.len();
1100        debug!(new_downloads, "queueing new downloads");
1101        metrics::gauge!("sync.obtain.queued.hash.count").set(new_downloads as f64);
1102
1103        // security: use the actual number of new downloads from all peers,
1104        // so the last peer to respond can't toggle our mempool
1105        self.recent_syncs.push_obtain_tips_length(new_downloads);
1106
1107        let response = self.request_blocks(download_set).await;
1108
1109        metrics::histogram!("sync.stage.duration_seconds", "stage" => "obtain_tips")
1110            .record(stage_start.elapsed().as_secs_f64());
1111
1112        Self::handle_hash_response(response).map_err(Into::into)
1113    }
1114
1115    #[instrument(skip(self))]
1116    async fn extend_tips(&mut self) -> Result<IndexSet<block::Hash>, Report> {
1117        let stage_start = std::time::Instant::now();
1118
1119        let tips = std::mem::take(&mut self.prospective_tips);
1120
1121        let mut download_set = IndexSet::new();
1122        let mut peer_hashes = VecDeque::new();
1123        debug!(tips = ?tips.len(), "trying to extend chain tips");
1124        for tip in tips {
1125            debug!(?tip, "asking peers to extend chain tip");
1126            // A tip whose requests all fail is dropped for good, so ask new peers before giving up.
1127            for round in 0..EXTEND_TIP_ROUNDS {
1128                if round > 0 {
1129                    debug!(
1130                        ?tip,
1131                        round, "no peer answered, asking other peers to extend chain tip"
1132                    );
1133                }
1134                let mut answered = false;
1135                let mut responses = FuturesUnordered::new();
1136                for attempt in 0..FANOUT {
1137                    if attempt > 0 {
1138                        // Let other tasks run, so we're more likely to choose a different peer.
1139                        //
1140                        // TODO: move fanouts into the PeerSet, so we always choose different peers (#2214)
1141                        tokio::task::yield_now().await;
1142                    }
1143
1144                    let ready_tip_network = self.tip_network.ready().await;
1145                    responses.push(tokio::spawn(ready_tip_network.map_err(|e| eyre!(e))?.call(
1146                        zn::Request::FindBlocks {
1147                            known_blocks: vec![tip.tip],
1148                            stop: None,
1149                        },
1150                    )));
1151                }
1152                while let Some(res) = responses.next().await {
1153                    match res
1154                        .expect("panic in spawned extend tips request")
1155                        .map_err::<Report, _>(|e| eyre!(e))
1156                    {
1157                        Ok(zn::Response::BlockHashes(hashes)) => {
1158                            debug!(first = ?hashes.first(), len = ?hashes.len());
1159                            trace!(?hashes);
1160
1161                            // Legacy zcashd nodes could prepend an unrelated hash
1162                            // to their response. Check the first hash against the
1163                            // previous response, and discard mismatches.
1164                            let unknown_hashes = match hashes.as_slice() {
1165                                [expected_hash, rest @ ..]
1166                                    if expected_hash == &tip.expected_next =>
1167                                {
1168                                    rest
1169                                }
1170                                // If the first hash doesn't match, retry with the second.
1171                                [first_hash, expected_hash, rest @ ..]
1172                                    if expected_hash == &tip.expected_next =>
1173                                {
1174                                    debug!(?first_hash,
1175                                                ?tip.expected_next,
1176                                                ?tip.tip,
1177                                                "unexpected first hash, but the second matches: using the hashes after the match");
1178                                    rest
1179                                }
1180                                // An empty list can't be an unrelated advertisement, so it answers.
1181                                // We ignore these responses.
1182                                [] => {
1183                                    answered = true;
1184                                    continue;
1185                                }
1186                                [single_hash] => {
1187                                    debug!(?single_hash,
1188                                                ?tip.expected_next,
1189                                                ?tip.tip,
1190                                                "discarding response containing a single unexpected hash");
1191                                    continue;
1192                                }
1193                                [first_hash, second_hash, rest @ ..] => {
1194                                    debug!(?first_hash,
1195                                                ?second_hash,
1196                                                rest_len = ?rest.len(),
1197                                                ?tip.expected_next,
1198                                                ?tip.tip,
1199                                                "discarding response that starts with two unexpected hashes");
1200                                    continue;
1201                                }
1202                            };
1203
1204                            // Unrelated hashes, such as a new block advertisement, aren't an answer.
1205                            answered = true;
1206
1207                            if unknown_hashes.is_empty() {
1208                                debug!(?tip.tip, "response contained no new hashes after the expected overlap");
1209                                continue;
1210                            }
1211
1212                            trace!(?unknown_hashes);
1213
1214                            if let Some(end) = unknown_hashes.rchunks_exact(2).next() {
1215                                let new_tip = CheckedTip {
1216                                    tip: end[0],
1217                                    expected_next: end[1],
1218                                };
1219
1220                                // Make sure we get the same tips, regardless of the
1221                                // order of peer responses
1222                                if !download_set.contains(&new_tip.expected_next) {
1223                                    debug!(
1224                                    ?new_tip,
1225                                    "adding new prospective tip, and removing any existing tips \
1226                                    in the new block hash list",
1227                                );
1228                                    self.prospective_tips
1229                                        .retain(|t| !unknown_hashes.contains(&t.expected_next));
1230                                    self.prospective_tips.insert(new_tip);
1231                                } else {
1232                                    debug!(
1233                                        ?new_tip,
1234                                        "discarding prospective tip: already in download set"
1235                                    );
1236                                }
1237                            } else {
1238                                debug!("downloading response that extends only one block");
1239                            }
1240
1241                            let prev_download_len = download_set.len();
1242                            download_set.extend(unknown_hashes);
1243                            let new_download_len = download_set.len();
1244                            let new_hashes = new_download_len - prev_download_len;
1245                            debug!(new_hashes, "added hashes to download set");
1246                            metrics::histogram!("sync.extend.response.hash.count")
1247                                .record(new_hashes as f64);
1248                            let known_hashes = hashes.len() - unknown_hashes.len();
1249                            peer_hashes.push_back(hashes.into_iter().skip(known_hashes));
1250                        }
1251                        Ok(_) => unreachable!("network returned wrong response"),
1252                        // We ignore this error because we made multiple fanout requests.
1253                        Err(e) => debug!(?e),
1254                    }
1255                }
1256                if answered {
1257                    break;
1258                }
1259            }
1260        }
1261
1262        let new_downloads = download_set.len();
1263        debug!(new_downloads, "queueing new downloads");
1264        metrics::gauge!("sync.extend.queued.hash.count").set(new_downloads as f64);
1265
1266        // security: use the actual number of new downloads from all peers,
1267        // so the last peer to respond can't toggle our mempool
1268        self.recent_syncs.push_extend_tips_length(new_downloads);
1269
1270        interleave_peer_hashes(&mut download_set, peer_hashes);
1271        let response = self.request_blocks(download_set).await;
1272
1273        metrics::histogram!("sync.stage.duration_seconds", "stage" => "extend_tips")
1274            .record(stage_start.elapsed().as_secs_f64());
1275
1276        Self::handle_hash_response(response).map_err(Into::into)
1277    }
1278
1279    /// Download and verify the genesis block, if it isn't currently known to
1280    /// our node.
1281    async fn request_genesis(&mut self) -> Result<(), Report> {
1282        // Due to Bitcoin protocol limitations, we can't request the genesis
1283        // block using our standard tip-following algorithm:
1284        //  - getblocks requires at least one hash
1285        //  - responses start with the block *after* the requested block, and
1286        //  - the genesis hash is used as a placeholder for "no matches".
1287        //
1288        // So we just download and verify the genesis block here.
1289        while !self.state_contains(self.genesis_hash).await? {
1290            info!("starting genesis block download and verify");
1291
1292            let response = match timeout(SYNC_RESTART_DELAY, self.request_genesis_once()).await {
1293                Ok(response) => Ok(response),
1294                Err(_) => Err(self.genesis_timeout()),
1295            };
1296
1297            // 3 layers of results is not ideal, but we need the timeout on the outside.
1298            match response {
1299                Ok(Ok(Ok(response))) => self
1300                    .handle_block_response(Ok(response))
1301                    .expect("never returns Err for Ok"),
1302                // Handle fatal errors
1303                Ok(Err(fatal_error)) => Err(fatal_error)?,
1304                // Handle timeouts and block errors
1305                Err(error) | Ok(Ok(Err(error))) => {
1306                    // TODO: exit syncer on permanent service errors (NetworkError, VerifierError)
1307                    if Self::should_restart_sync(&error) {
1308                        warn!(
1309                            ?error,
1310                            "could not download or verify genesis block, retrying"
1311                        );
1312                    } else {
1313                        info!(
1314                            ?error,
1315                            "temporary error downloading or verifying genesis block, retrying"
1316                        );
1317                    }
1318
1319                    tokio::time::sleep(GENESIS_TIMEOUT_RETRY).await;
1320                }
1321            }
1322        }
1323
1324        Ok(())
1325    }
1326
1327    /// Try to download and verify the genesis block once.
1328    ///
1329    /// Fatal errors are returned in the outer result, temporary errors in the inner one.
1330    async fn request_genesis_once(
1331        &mut self,
1332    ) -> Result<Result<(Height, block::Hash), BlockDownloadVerifyError>, Report> {
1333        let response = self.queue_block(self.genesis_hash).await;
1334        Self::handle_response(response).map_err(|e| eyre!(e))?;
1335        self.update_metrics();
1336
1337        let response = self
1338            .downloads
1339            .next()
1340            .await
1341            .expect("downloads is nonempty")
1342            .inspect_err(|error| self.count_block_error(error));
1343        self.update_metrics();
1344
1345        Ok(response)
1346    }
1347
1348    /// Queue download and verify tasks for each block that isn't currently known to our node.
1349    ///
1350    /// TODO: turn obtain and extend tips into a separate task, which sends hashes via a channel?
1351    async fn request_blocks(
1352        &mut self,
1353        mut hashes: IndexSet<block::Hash>,
1354    ) -> Result<IndexSet<block::Hash>, BlockDownloadVerifyError> {
1355        let lookahead_limit = self.lookahead_limit();
1356
1357        debug!(
1358            hashes.len = hashes.len(),
1359            ?lookahead_limit,
1360            "requesting blocks",
1361        );
1362
1363        // Missing blocks keep their slots until their bounded retries can be queued.
1364        let capacity = lookahead_limit
1365            .saturating_sub(self.downloads.in_flight())
1366            .saturating_sub(self.reobtain_hashes.len());
1367        let extra_hashes = if hashes.len() > capacity {
1368            hashes.split_off(capacity)
1369        } else {
1370            IndexSet::new()
1371        };
1372
1373        // Dispatch blocks with duplicate-tolerant error handling.
1374        // DuplicateBlockQueuedForDownload is caught and skipped instead of
1375        // propagating — this prevents dropping unprocessed hashes from the
1376        // batch, which would create frontier gaps and stalls (#5709).
1377        // AlreadyRejected is skipped the same way.
1378        for hash in hashes.into_iter() {
1379            match self.queue_block(hash).await {
1380                Ok(()) => {}
1381                Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. }) => {
1382                    debug!("block request was already queued, continuing");
1383                }
1384                Err(BlockDownloadVerifyError::AlreadyRejected { .. }) => {
1385                    debug!("block already failed validation after early relay, continuing");
1386                }
1387                Err(error) => return Err(error),
1388            }
1389        }
1390
1391        Ok(extra_hashes)
1392    }
1393
1394    /// The configured lookahead limit, including room to finish the final checkpoint before
1395    /// switching to full verification.
1396    fn lookahead_limit(&self) -> usize {
1397        let max_checkpoint_height: usize = self
1398            .max_checkpoint_height
1399            .0
1400            .try_into()
1401            .expect("fits in usize");
1402
1403        // When the state is empty, we want to verify using checkpoints
1404        let verified_height: usize = self
1405            .latest_chain_tip
1406            .best_tip_height()
1407            .unwrap_or(Height(0))
1408            .0
1409            .try_into()
1410            .expect("fits in usize");
1411
1412        if verified_height >= max_checkpoint_height {
1413            self.full_verify_concurrency_limit
1414        } else if max_checkpoint_height - verified_height
1415            <= self.checkpoint_verify_concurrency_limit
1416        {
1417            // Pending checkpoint blocks cannot finish until the whole range arrives. Reserve
1418            // its remaining distance, not just the portion present in the latest hash batch.
1419            let checkpoint_hashes = max_checkpoint_height - verified_height;
1420
1421            self.full_verify_concurrency_limit + checkpoint_hashes
1422        } else {
1423            self.checkpoint_verify_concurrency_limit
1424        }
1425    }
1426
1427    /// Handles a response for a requested block.
1428    ///
1429    /// See [`Self::handle_response`] for more details.
1430    #[allow(unknown_lints)]
1431    fn handle_block_response(
1432        &mut self,
1433        response: Result<(Height, block::Hash), BlockDownloadVerifyError>,
1434    ) -> Result<(), BlockDownloadVerifyError> {
1435        if let Err(error) = &response {
1436            self.count_block_error(error);
1437        }
1438
1439        match response {
1440            Ok((height, hash)) => {
1441                trace!(?height, ?hash, "verified and committed block to state");
1442
1443                // The block arrived, so forget any re-request bookkeeping for it.
1444                self.reobtain_hashes.shift_remove(&hash);
1445                self.block_reobtain_retries.remove(&hash);
1446                self.utxo_race_drops = 0;
1447
1448                return Ok(());
1449            }
1450
1451            Err(
1452                ref verify_error @ BlockDownloadVerifyError::Invalid {
1453                    ref error,
1454                    advertiser_addr: Some(advertiser_addr),
1455                    ..
1456                },
1457            ) if error.misbehavior_score() != 0 => {
1458                let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
1459                    advertiser_addr,
1460                    error.misbehavior_score(),
1461                    verify_error.to_string(),
1462                ));
1463            }
1464
1465            Err(
1466                ref verify_error @ BlockDownloadVerifyError::InvalidHeight {
1467                    advertiser_addr: Some(advertiser_addr),
1468                    ..
1469                },
1470            ) => {
1471                let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
1472                    advertiser_addr,
1473                    100,
1474                    verify_error.to_string(),
1475                ));
1476            }
1477
1478            // The downloader checked the served body against the header of the requested block
1479            // hash, so it is a forgery whatever block the peer has (GHSA-g9rc-89v4-hhvf).
1480            Err(
1481                ref verify_error @ BlockDownloadVerifyError::BodyHeaderMismatch {
1482                    advertiser_addr: Some(advertiser_addr),
1483                    ..
1484                },
1485            ) => {
1486                let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
1487                    advertiser_addr,
1488                    100,
1489                    verify_error.to_string(),
1490                ));
1491            }
1492
1493            // The downloader only sets `advertiser_addr` here when Zebra already holds the parent
1494            // header and it proves the body's claimed height wrong. A peer can answer with a
1495            // canonical header and a rewritten coinbase height because the initial hash check does
1496            // not recompute the header's commitment to the body's authorizing data
1497            // (GHSA-g95h-hw6g-pvgv). Peers that serve genuinely old blocks arrive unattributed and
1498            // fall through unscored. Score only a parent-proven rewrite.
1499            Err(
1500                ref verify_error @ BlockDownloadVerifyError::BehindTipHeightLimit {
1501                    advertiser_addr: Some(advertiser_addr),
1502                    ..
1503                },
1504            ) => {
1505                let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
1506                    advertiser_addr,
1507                    100,
1508                    format!("parent header contradicts coinbase height: {verify_error}"),
1509                ));
1510            }
1511
1512            // `AboveLookaheadHeightLimit` deliberately falls through unscored, and must
1513            // stay that way (GHSA-qhr3-cvch-5fh2): `FindBlocks` responses carry no
1514            // address, so the follow-up request goes to an independently chosen, honest
1515            // peer that served the block but did not choose its height. Scoring it let a
1516            // malicious `FindBlocks` responder evict honest peers throughout IBD. Unlike
1517            // the behind-tip sibling advisory, the block here is genuine, so there is no
1518            // local proof of forgery to re-attribute with. Do not add scoring back.
1519            Err(_) => {}
1520        };
1521
1522        // A hash the syncer still needs, whose download did not produce a usable block, is
1523        // otherwise dropped here and only rediscovered by a later sync round. Re-queue it for the
1524        // next sync round, bounded by `MAX_BLOCK_REOBTAIN_RETRIES`:
1525        // - `DownloadFailed`: no peer delivered the block, which wedges the checkpoint
1526        //   frontier until the verify timeout (#5709). This includes `NotFound`, and other
1527        //   download failures, which no longer restart the sync.
1528        // - `DownloadTimedOut`: no peer delivered the block within the download round. One hedged
1529        //   request can already have failed with `NotFound` while its sibling was still waiting.
1530        // - `BehindTipHeightLimit`: the body was not a usable block for this hash, so the hash is
1531        //   still missing (GHSA-g95h-hw6g-pvgv). This re-request runs whether or not the peer could
1532        //   be attributed, and covers the window before a score reaches the address book, which
1533        //   only applies misbehavior reports in batches.
1534        // - UTXO races (#11168): the block was never rejected, and the state parks its
1535        //   children until it arrives, so re-request it instead of waiting for a tip walk.
1536        // - Other body validation failures, including bad Merkle roots and transaction proofs:
1537        //   a different body can still satisfy the same header, so retry the hash before giving up.
1538        // - `Invalid` with a mismatched authorizing data commitment: the block itself is fine, only
1539        //   the served body was forged, so the hash is still valid and still wanted. The ban for
1540        //   the serving peer is sent to the address book right away, but the first re-request can
1541        //   still reach the same peer before the ban does; `MAX_BLOCK_REOBTAIN_RETRIES` bounds
1542        //   that.
1543        // - `Invalid` because an ancestor had a mismatched authorizing data commitment: the state
1544        //   rejects queued descendants along with the forged ancestor, but their hashes are still
1545        //   wanted, and the peers that served them are not scored.
1546        // - `Invalid` because a block verifier found that the body doesn't match its header, such
1547        //   as a rewritten coinbase height (GHSA-g9rc-89v4-hhvf): like a mismatched authorizing
1548        //   data commitment, only the served body was forged, and the serving peer is scored.
1549        // - `BodyHeaderMismatch`: the downloader was going to drop the block for its height, or
1550        //   use it to pause or resume downloads, but found that the body doesn't match its header,
1551        //   so the same applies.
1552        // - `Invalid` because a verifier queue was full: the block might be valid. Re-request it
1553        //   a bounded number of times, then restart to rediscover it instead of silently stalling.
1554        // Header and unrelated contextual failures are excluded: changing the body cannot fix them.
1555        let reobtain_hash = match &response {
1556            Err(BlockDownloadVerifyError::DownloadFailed { hash, .. }) => Some(*hash),
1557            Err(BlockDownloadVerifyError::DownloadTimedOut { hash }) => Some(*hash),
1558            Err(BlockDownloadVerifyError::BehindTipHeightLimit { hash, .. }) => Some(*hash),
1559            Err(BlockDownloadVerifyError::BodyHeaderMismatch { hash, .. }) => Some(*hash),
1560            Err(e @ BlockDownloadVerifyError::Invalid { hash, .. })
1561                if Self::is_utxo_lookup_timeout(e) =>
1562            {
1563                Some(*hash)
1564            }
1565            Err(BlockDownloadVerifyError::Invalid { error, hash, .. })
1566                if error.is_auth_commitment_mismatch()
1567                    || error.is_descendant_of_auth_commitment_mismatch()
1568                    || error.is_body_header_mismatch()
1569                    || Self::is_block_body_error(error) =>
1570            {
1571                Some(*hash)
1572            }
1573            Err(e @ BlockDownloadVerifyError::ValidationRequestError { hash, .. })
1574                if Self::is_post_checkpoint_verify_timeout(e) =>
1575            {
1576                Some(*hash)
1577            }
1578            Err(e @ BlockDownloadVerifyError::Invalid { hash, .. }) if Self::is_queue_full(e) => {
1579                Some(*hash)
1580            }
1581            _ => None,
1582        };
1583
1584        if let Some(hash) = reobtain_hash {
1585            let attempts = self.block_reobtain_retries.entry(hash).or_insert(0);
1586            if *attempts < MAX_BLOCK_REOBTAIN_RETRIES {
1587                *attempts += 1;
1588                self.reobtain_hashes.insert(hash);
1589                debug!(
1590                    ?hash,
1591                    attempts = *attempts,
1592                    "re-queueing missing block for re-download"
1593                );
1594            } else {
1595                debug!(?hash, "missing block exceeded re-download retries");
1596                self.block_reobtain_retries.remove(&hash);
1597                if response.as_ref().is_err_and(Self::is_queue_full) {
1598                    return response.map(|_| ());
1599                }
1600            }
1601        }
1602
1603        // A UTXO race resolves as soon as the parent commits. A whole lookahead wave of
1604        // timeouts with no commit isn't the race, so restart instead of draining the batch.
1605        if let Err(error) = &response {
1606            if Self::is_utxo_lookup_timeout(error) {
1607                self.utxo_race_drops += 1;
1608                if self.utxo_race_drops
1609                    >= self
1610                        .full_verify_concurrency_limit
1611                        .max(MIN_UTXO_RACE_DROPS_BEFORE_RESTART)
1612                {
1613                    warn!(
1614                        drops = self.utxo_race_drops,
1615                        "no block verified across a full wave of UTXO lookup timeouts, restarting sync"
1616                    );
1617                    return response.map(|_| ());
1618                }
1619            }
1620        }
1621
1622        Self::handle_response(response)
1623    }
1624
1625    /// Returns `true` for the `AwaitUtxo` timeout that `should_restart_sync` exempts (#11168).
1626    fn is_utxo_lookup_timeout(e: &BlockDownloadVerifyError) -> bool {
1627        matches!(
1628            e,
1629            BlockDownloadVerifyError::Invalid {
1630                error: RouterError::Block { source },
1631                ..
1632            } if matches!(
1633                **source,
1634                VerifyBlockError::Transaction(TransactionError::TransparentInputNotFound)
1635            )
1636        )
1637    }
1638
1639    /// Returns `true` for the short post-final-checkpoint verify timeout (#5125) that
1640    /// `should_restart_sync` exempts; the 8-minute tower timeout is a different type.
1641    fn is_post_checkpoint_verify_timeout(e: &BlockDownloadVerifyError) -> bool {
1642        matches!(
1643            e,
1644            BlockDownloadVerifyError::ValidationRequestError { error, .. }
1645                if error.is::<tokio::time::error::Elapsed>()
1646        )
1647    }
1648
1649    /// Returns `true` if the verifier dropped a block because its queue was full.
1650    ///
1651    /// The block might be valid, and Zebra might need it, so `should_restart_sync` exempts it,
1652    /// and the syncer requests it again a few times.
1653    fn is_queue_full(e: &BlockDownloadVerifyError) -> bool {
1654        match e {
1655            BlockDownloadVerifyError::Invalid {
1656                error: RouterError::Checkpoint { source },
1657                ..
1658            } => matches!(**source, VerifyCheckpointError::QueuedLimit),
1659            BlockDownloadVerifyError::Invalid {
1660                error: RouterError::Block { source },
1661                ..
1662            } => matches!(
1663                **source,
1664                VerifyBlockError::Commit(zs::CommitBlockError::OrphanQueueFull)
1665            ),
1666            _ => false,
1667        }
1668    }
1669
1670    /// Returns a bounded label for a block download or verify error, for metrics and logs.
1671    fn block_error_kind(e: &BlockDownloadVerifyError) -> &'static str {
1672        use BlockDownloadVerifyError::*;
1673
1674        match e {
1675            Invalid { error, .. } if error.is_duplicate_request() => "already_verified",
1676            Invalid { error, .. }
1677                if error.is_auth_commitment_mismatch()
1678                    || error.is_descendant_of_auth_commitment_mismatch() =>
1679            {
1680                "auth_commitment_mismatch"
1681            }
1682            Invalid { error, .. } if error.is_body_header_mismatch() => "body_header_mismatch",
1683            e if Self::is_utxo_lookup_timeout(e) => "utxo_lookup_timeout",
1684            e if Self::is_post_checkpoint_verify_timeout(e) => "final_checkpoint_verify_timeout",
1685            e if Self::is_queue_full(e) => "queue_full",
1686            Invalid { .. } => "invalid",
1687            ValidationRequestError { error, .. }
1688                if error.is::<tower::timeout::error::Elapsed>() =>
1689            {
1690                "verify_timeout"
1691            }
1692            ValidationRequestError { .. } => "validation_request",
1693            DownloadFailed { error, .. } if is_not_found(error.as_ref()) => "not_found",
1694            DownloadFailed { .. } => "download_failed",
1695            DownloadTimedOut { .. } => "download_timed_out",
1696            AboveLookaheadHeightLimit { .. } => "above_lookahead_limit",
1697            BehindTipHeightLimit { .. } => "behind_tip",
1698            InvalidHeight { .. } => "invalid_height",
1699            BodyHeaderMismatch { .. } => "body_header_mismatch",
1700            DuplicateBlockQueuedForDownload { .. } => "duplicate_queued",
1701            AlreadyRejected { .. } => "already_rejected",
1702            CancelledDuringDownload { .. }
1703            | CancelledAwaitingVerifierReadiness { .. }
1704            | CancelledDuringVerification { .. } => "cancelled",
1705            NetworkServiceError { .. } => "network_service",
1706            VerifierServiceError { .. } => "verifier_service",
1707            Timeout => "network_ready_timeout",
1708            GenesisTimeout => "genesis_timeout",
1709        }
1710    }
1711
1712    /// Queues `hash` for download and verification, which can wait for network capacity.
1713    ///
1714    /// Publishes the downloads before that wait. A block that is already queued isn't counted as
1715    /// an error, because the syncer ignores that error: it happens when a timed-out genesis
1716    /// attempt or an earlier round left the block queued. Neither is a rejected early relay block,
1717    /// because its failure was already counted.
1718    async fn queue_block(&mut self, hash: block::Hash) -> Result<(), BlockDownloadVerifyError> {
1719        self.update_metrics();
1720
1721        let result = self.downloads.download_and_verify(hash).await;
1722
1723        match &result {
1724            Ok(())
1725            | Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. })
1726            | Err(BlockDownloadVerifyError::AlreadyRejected { .. }) => {}
1727            Err(error) => self.count_block_error(error),
1728        }
1729
1730        result
1731    }
1732
1733    /// Counts a block whose wait for network capacity an enclosing timeout cancelled, as the
1734    /// network readiness timeout it would have reached, and returns whether there was one.
1735    fn count_cancelled_network_wait(&mut self) -> bool {
1736        let cancelled = self.downloads.take_cancelled_network_wait();
1737        if cancelled {
1738            self.count_block_error(&BlockDownloadVerifyError::Timeout);
1739        }
1740
1741        cancelled
1742    }
1743
1744    /// Returns the error for a sync stage that its timeout cancelled, as `reason`, or as a block
1745    /// error if the stage was waiting for network capacity, which also counts that block.
1746    fn stage_timeout_error(
1747        &mut self,
1748        reason: RestartReason,
1749        elapsed: tokio::time::error::Elapsed,
1750    ) -> RestartError {
1751        if self.count_cancelled_network_wait() {
1752            Self::block_restart_error(BlockDownloadVerifyError::Timeout)
1753        } else {
1754            RestartError::new(reason, elapsed)
1755        }
1756    }
1757
1758    /// Returns the error for a genesis attempt that the genesis timeout cancelled, and counts it
1759    /// if the block was still waiting for network capacity.
1760    fn genesis_timeout(&mut self) -> BlockDownloadVerifyError {
1761        if self.count_cancelled_network_wait() {
1762            BlockDownloadVerifyError::Timeout
1763        } else {
1764            BlockDownloadVerifyError::GenesisTimeout
1765        }
1766    }
1767
1768    /// Counts the errors of downloads that finished without the syncer reading their results,
1769    /// before a restart drops them.
1770    fn count_finished_block_errors(&mut self) {
1771        while let Some(Some(response)) = self.downloads.next().now_or_never() {
1772            if let Err(error) = response {
1773                self.count_block_error(&error);
1774            }
1775        }
1776    }
1777
1778    /// Counts a block that failed to queue, download, or verify.
1779    fn count_block_error(&self, error: &BlockDownloadVerifyError) {
1780        metrics::counter!("sync.block.error.count", "kind" => Self::block_error_kind(error))
1781            .increment(1);
1782    }
1783
1784    /// Wraps an error from obtaining or extending tips, which also queue the blocks they find, so
1785    /// a block that failed to queue is reported as a block error.
1786    fn tips_restart_error(reason: RestartReason, error: Report) -> RestartError {
1787        match error.downcast::<BlockDownloadVerifyError>() {
1788            Ok(error) => Self::block_restart_error(error),
1789            Err(error) => RestartError::new(reason, error),
1790        }
1791    }
1792
1793    /// Wraps a block error that restarts the sync.
1794    fn block_restart_error(error: BlockDownloadVerifyError) -> RestartError {
1795        RestartError {
1796            reason: RestartReason::BlockError,
1797            kind: Some(Self::block_error_kind(&error)),
1798            error: error.into(),
1799        }
1800    }
1801
1802    /// Handles a response to block hash submission, passing through any extra hashes.
1803    ///
1804    /// See [`Self::handle_response`] for more details.
1805    #[allow(unknown_lints)]
1806    fn handle_hash_response(
1807        response: Result<IndexSet<block::Hash>, BlockDownloadVerifyError>,
1808    ) -> Result<IndexSet<block::Hash>, BlockDownloadVerifyError> {
1809        match response {
1810            Ok(extra_hashes) => Ok(extra_hashes),
1811            Err(_) => Self::handle_response(response).map(|()| IndexSet::new()),
1812        }
1813    }
1814
1815    /// Handles a response to a syncer request.
1816    ///
1817    /// Returns `Ok` if the request was successful, or if an expected error occurred,
1818    /// so that the synchronization can continue normally.
1819    ///
1820    /// Returns `Err` if an unexpected error occurred, to force the synchronizer to restart.
1821    #[allow(unknown_lints)]
1822    fn handle_response<T>(
1823        response: Result<T, BlockDownloadVerifyError>,
1824    ) -> Result<(), BlockDownloadVerifyError> {
1825        match response {
1826            Ok(_t) => Ok(()),
1827            Err(error) => {
1828                // TODO: exit syncer on permanent service errors (NetworkError, VerifierError)
1829                if Self::should_restart_sync(&error) {
1830                    Err(error)
1831                } else {
1832                    Ok(())
1833                }
1834            }
1835        }
1836    }
1837
1838    /// Returns `true` if the hash is present in the state, and `false`
1839    /// if the hash is not present in the state.
1840    ///
1841    /// Blocks that are only queued in the state, waiting for their parent, are treated as not
1842    /// present. A sync restart cancels in-flight downloads, so the parent of a queued block may
1843    /// never arrive unless the syncer downloads it again along with its queued children. If the
1844    /// syncer skipped queued blocks, discovery could lose the continuation needed to recover
1845    /// their missing parents. Re-submitting a queued block is harmless: the block verifier rejects
1846    /// it as a duplicate, which doesn't restart the sync.
1847    pub(crate) async fn state_contains(&mut self, hash: block::Hash) -> Result<bool, Report> {
1848        match self
1849            .state
1850            .ready()
1851            .await
1852            .map_err(|e| eyre!(e))?
1853            .call(zebra_state::Request::KnownBlock(hash))
1854            .await
1855            .map_err(|e| eyre!(e))?
1856        {
1857            zs::Response::KnownBlock(loc) => {
1858                Ok(loc.is_some_and(|loc| loc != zs::KnownBlock::Queue))
1859            }
1860            _ => unreachable!("wrong response to known block request"),
1861        }
1862    }
1863
1864    fn update_metrics(&mut self) {
1865        let in_flight = self.downloads.in_flight();
1866
1867        metrics::gauge!("sync.prospective_tips.len",).set(self.prospective_tips.len() as f64);
1868        metrics::gauge!("sync.downloads.in_flight",).set(in_flight as f64);
1869
1870        self.diagnostics.send_modify(|diagnostics| {
1871            diagnostics.in_flight = in_flight;
1872        });
1873    }
1874
1875    /// Returns true for failures specific to the block, rather than verifier, state, or shutdown
1876    /// failures.
1877    fn is_block_validation_error(error: &RouterError) -> bool {
1878        let invalid_commit = |error: &zs::CommitBlockError| {
1879            let zs::CommitBlockError::ValidateContextError(error) = error else {
1880                return false;
1881            };
1882            let mut error = error.as_ref();
1883            while let zs::ValidateContextError::AncestorRejected { source, .. } = error {
1884                error = source.as_ref();
1885            }
1886            !matches!(
1887                error,
1888                zs::ValidateContextError::NotReadyToBeCommitted { .. }
1889                    | zs::ValidateContextError::NoteCommitmentTreeError(_)
1890                    | zs::ValidateContextError::HistoryTreeError(_)
1891            )
1892        };
1893        let error = match error {
1894            RouterError::Block { source } => source.as_ref(),
1895            RouterError::Checkpoint { source } => match source.as_ref() {
1896                VerifyCheckpointError::VerifyBlock(error) => error,
1897                VerifyCheckpointError::CoinbaseHeight { .. }
1898                | VerifyCheckpointError::UnexpectedSideChain { .. }
1899                // Competing blocks at one height, or a block at or below the final checkpoint
1900                // after it has been verified.
1901                | VerifyCheckpointError::QueuedLimit
1902                | VerifyCheckpointError::Finished => return true,
1903                VerifyCheckpointError::CommitCheckpointVerified(error) => {
1904                    return error
1905                        .downcast_ref::<zs::CommitCheckpointVerifiedError>()
1906                        .is_some_and(|error| invalid_commit(error.inner()));
1907                }
1908                _ => return false,
1909            },
1910        };
1911        match error {
1912            VerifyBlockError::Block {
1913                source: BlockError::Other(_),
1914            } => false,
1915            // `Other` is the Orchard-disable rejection on the block path; its input-alignment
1916            // error is mempool-only.
1917            VerifyBlockError::Block {
1918                source: BlockError::Transaction(error),
1919            }
1920            | VerifyBlockError::Transaction(error) => !matches!(
1921                error,
1922                TransactionError::InternalDowncastError(_)
1923                    | TransactionError::CoinbaseConstruction(_)
1924                    | TransactionError::ValidateMempoolLockTimeError(_)
1925                    | TransactionError::ValidateContextError(_)
1926            ),
1927            VerifyBlockError::Block { .. }
1928            | VerifyBlockError::Equihash { .. }
1929            | VerifyBlockError::Time(_)
1930            | VerifyBlockError::Subsidy(_) => true,
1931            VerifyBlockError::Commit(error) => invalid_commit(error),
1932            _ => false,
1933        }
1934    }
1935
1936    /// Returns true for body validation failures that do not invalidate the requested header hash.
1937    fn is_block_body_error(error: &RouterError) -> bool {
1938        if !Self::is_block_validation_error(error) {
1939            return false;
1940        }
1941        let error = match error {
1942            RouterError::Block { source } => source.as_ref(),
1943            RouterError::Checkpoint { source } => match source.as_ref() {
1944                VerifyCheckpointError::VerifyBlock(error) => error,
1945                VerifyCheckpointError::CoinbaseHeight { .. } => return true,
1946                _ => return false,
1947            },
1948        };
1949        match error {
1950            VerifyBlockError::Block { source } => !matches!(
1951                source,
1952                BlockError::AlreadyInChain(..)
1953                    | BlockError::InvalidDifficulty(..)
1954                    | BlockError::TargetDifficultyLimit(..)
1955                    | BlockError::DifficultyFilter(..)
1956            ),
1957            VerifyBlockError::Transaction(_) | VerifyBlockError::Subsidy(_) => true,
1958            _ => false,
1959        }
1960    }
1961
1962    /// Return if the sync should be restarted based on the given error
1963    /// from the block downloader and verifier stream.
1964    fn should_restart_sync(e: &BlockDownloadVerifyError) -> bool {
1965        match e {
1966            // Structural matches: downcasts
1967            BlockDownloadVerifyError::Invalid { error, .. } if error.is_duplicate_request() => {
1968                debug!(error = ?e, "block was already verified or committed, possibly from a previous sync run, continuing");
1969                false
1970            }
1971            BlockDownloadVerifyError::Invalid { error, .. }
1972                if error.is_auth_commitment_mismatch() =>
1973            {
1974                debug!(
1975                    error = ?e,
1976                    "served block body did not match the authorizing data commitment in its \
1977                     header: the block hash is still valid and is re-requested, and the serving \
1978                     peer is scored, continuing"
1979                );
1980                false
1981            }
1982            BlockDownloadVerifyError::Invalid { error, .. }
1983                if error.is_descendant_of_auth_commitment_mismatch() =>
1984            {
1985                debug!(
1986                    error = ?e,
1987                    "an ancestor's served body did not match the authorizing data commitment in \
1988                     its header: this block hash is still valid and is re-requested, continuing"
1989                );
1990                false
1991            }
1992            BlockDownloadVerifyError::Invalid { error, .. } if error.is_body_header_mismatch() => {
1993                debug!(
1994                    error = ?e,
1995                    "served block body did not match its header: the block hash is still valid \
1996                     and is re-requested, and the serving peer is scored, continuing"
1997                );
1998                false
1999            }
2000            // An `AwaitUtxo` timeout: the spent output is usually in a recent block whose
2001            // commit a restart would cancel, looping near the tip (#11168, #11132).
2002            e if Self::is_utxo_lookup_timeout(e) => {
2003                debug!(error = ?e, "block spends an output that is not in our state yet, re-requesting, continuing");
2004                false
2005            }
2006            // A peer can fill a verifier queue with blocks Zebra can't use, so a restart could
2007            // cancel the downloads that would drain it.
2008            e if Self::is_queue_full(e) => {
2009                debug!(error = ?e, "block verifier queue was full, re-requesting, continuing");
2010                false
2011            }
2012
2013            // Structural matches: direct
2014            BlockDownloadVerifyError::CancelledDuringDownload { .. }
2015            | BlockDownloadVerifyError::CancelledDuringVerification { .. } => {
2016                debug!(error = ?e, "block verification was cancelled, continuing");
2017                false
2018            }
2019            BlockDownloadVerifyError::BehindTipHeightLimit { .. } => {
2020                debug!(
2021                    error = ?e,
2022                    "block height is behind the current state tip: re-requesting the hash, \
2023                     and scoring the peer if the body contradicts the parent we hold, continuing"
2024                );
2025                false
2026            }
2027            BlockDownloadVerifyError::AboveLookaheadHeightLimit { .. } => {
2028                debug!(
2029                    error = ?e,
2030                    "block height is above the lookahead limit, \
2031                     dropping the block and continuing sync"
2032                );
2033                false
2034            }
2035            BlockDownloadVerifyError::InvalidHeight { .. } => {
2036                debug!(
2037                    error = ?e,
2038                    "block has no valid height, \
2039                     dropping the block and continuing sync"
2040                );
2041                false
2042            }
2043            BlockDownloadVerifyError::BodyHeaderMismatch { .. } => {
2044                debug!(
2045                    error = ?e,
2046                    "served block body did not match its header: the block hash is still valid \
2047                     and is re-requested, and the serving peer is scored, continuing"
2048                );
2049                false
2050            }
2051            BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. } => {
2052                debug!(
2053                    error = ?e,
2054                    "queued duplicate block hash for download, \
2055                     assuming the syncer will eventually resolve duplicates, continuing"
2056                );
2057                false
2058            }
2059            BlockDownloadVerifyError::AlreadyRejected { .. } => {
2060                debug!(
2061                    error = ?e,
2062                    "block already failed validation after early relay, \
2063                     not downloading it again, continuing"
2064                );
2065                false
2066            }
2067
2068            BlockDownloadVerifyError::DownloadFailed { ref error, .. }
2069                if is_not_found(error.as_ref()) =>
2070            {
2071                // Covers these errors:
2072                // - NotFoundResponse
2073                // - NotFoundRegistry
2074                //
2075                // TODO: improve this by checking the type (#2908)
2076                //       restart after a certain number of NotFound errors?
2077                debug!(error = ?e, "block was not found, possibly from a peer that doesn't have the block yet, continuing");
2078                false
2079            }
2080            BlockDownloadVerifyError::DownloadTimedOut { .. } => {
2081                debug!(error = ?e, "no peer delivered the block within the download round, re-requesting, continuing");
2082                false
2083            }
2084
2085            // The short post-final-checkpoint verify timeout is a UTXO race (#5125), not an
2086            // invalid block; the 8-minute tower timeout stays in the catch-all (#5709).
2087            e if Self::is_post_checkpoint_verify_timeout(e) => {
2088                debug!(error = ?e, "initial fully verified block timed out waiting for its parent's outputs, re-requesting, continuing");
2089                false
2090            }
2091
2092            // A failed block does not imply that unrelated pending blocks are invalid, so keep
2093            // their progress. Header and unrelated contextual failures are dropped; body
2094            // failures and failed downloads are re-requested a bounded number of times.
2095            BlockDownloadVerifyError::Invalid { error, .. }
2096                if Self::is_block_validation_error(error) =>
2097            {
2098                debug!(error = ?e, "block validation failed, continuing sync");
2099                false
2100            }
2101            BlockDownloadVerifyError::DownloadFailed { .. } => {
2102                debug!(error = ?e, "dropping failed block and continuing sync");
2103                false
2104            }
2105
2106            _ => {
2107                // download_and_verify downcasts errors from the block verifier
2108                // into VerifyChainError, and puts the result inside one of the
2109                // BlockDownloadVerifyError enumerations. This downcast could
2110                // become incorrect e.g. after some refactoring, and it is difficult
2111                // to write a test to check it. The test below is a best-effort
2112                // attempt to catch if that happens and log it.
2113                //
2114                // TODO: add a proper test and remove this
2115                // https://github.com/ZcashFoundation/zebra/issues/2909
2116                let err_str = format!("{e:?}");
2117                if err_str.contains("NotFound") {
2118                    error!(?e,
2119                        "a BlockDownloadVerifyError that should have been filtered out was detected, \
2120                        which possibly indicates a programming error in the downcast inside \
2121                        zebrad::components::sync::downloads::Downloads::download_and_verify"
2122                    )
2123                }
2124
2125                warn!(
2126                    ?e,
2127                    kind = Self::block_error_kind(e),
2128                    "error downloading and verifying block"
2129                );
2130                true
2131            }
2132        }
2133    }
2134}