Skip to main content

zebra_consensus/
checkpoint.rs

1//! Checkpoint-based block verification.
2//!
3//! Checkpoint-based verification uses a list of checkpoint hashes to
4//! speed up the initial chain sync for Zebra. This list is distributed
5//! with Zebra.
6//!
7//! The checkpoint verifier queues pending blocks. Once there is a
8//! chain from the previous checkpoint to a target checkpoint, it
9//! verifies all the blocks in that chain, and sends accepted blocks to
10//! the state service as finalized chain state, skipping the majority of
11//! contextual verification checks.
12//!
13//! Verification starts at the first checkpoint, which is the genesis
14//! block for the configured network.
15//!
16//! Admission also counts accepted commit owners until completion, including cancelled requests
17//! and failure recovery. The count allows four candidates per configured checkpoint gap or
18//! 2,000 bodies (two default sync batches), whichever is greater. Only queued bodies have the
19//! additional byte limit; these bounds are not process-RSS caps.
20
21use std::{
22    collections::{BTreeMap, HashSet},
23    ops::{Bound, Bound::*},
24    pin::Pin,
25    sync::{
26        atomic::{AtomicUsize, Ordering},
27        mpsc, Arc,
28    },
29    task::{Context, Poll},
30};
31
32use futures::{Future, FutureExt, TryFutureExt};
33use thiserror::Error;
34use tokio::sync::oneshot;
35use tower::{Service, ServiceExt};
36use tracing::instrument;
37
38use zebra_chain::{
39    amount::{self},
40    block::{self, Block},
41    parameters::{
42        checkpoint::list::CheckpointList, subsidy::SubsidyError, Network,
43        GENESIS_PREVIOUS_BLOCK_HASH,
44    },
45    transparent,
46    work::equihash,
47};
48use zebra_state::{self as zs, CheckpointVerifiedBlock};
49
50use crate::{
51    block::VerifyBlockError,
52    checkpoint::types::{
53        Progress::{self, *},
54        TargetHeight::{self, *},
55    },
56    error::BlockError,
57    BoxError,
58};
59
60mod types;
61
62#[cfg(test)]
63pub(crate) mod tests;
64
65pub use zebra_node_services::constants::{MAX_CHECKPOINT_BYTE_COUNT, MAX_CHECKPOINT_HEIGHT_GAP};
66
67/// An unverified block, which is in the queue for checkpoint verification.
68#[derive(Debug)]
69struct QueuedBlock {
70    /// The block, with additional precalculated data.
71    block: CheckpointVerifiedBlock,
72    /// The block's estimated memory use, which counts towards [`MAX_QUEUED_BYTES`].
73    bytes: usize,
74    /// The transmitting end of the oneshot channel for this block's result.
75    tx: oneshot::Sender<Result<Verified, VerifyCheckpointError>>,
76    /// Counts this body through queueing, state commit, and failure recovery.
77    retained: RetainedBlockPermit,
78}
79
80/// A lifetime reservation shared by queued blocks and accepted commit tasks.
81#[derive(Debug)]
82struct RetainedBlockPermit(Arc<AtomicUsize>);
83
84impl Drop for RetainedBlockPermit {
85    fn drop(&mut self) {
86        self.0.fetch_sub(1, Ordering::Relaxed);
87    }
88}
89
90/// A checkpoint verified block, ready to be committed to the state.
91#[derive(Debug)]
92struct Verified {
93    /// The block, with additional precalculated data.
94    block: CheckpointVerifiedBlock,
95    /// Keeps accepted work counted until commit or recovery finishes.
96    retained: RetainedBlockPermit,
97
98    /// The verifier's reset epoch when the block was verified.
99    epoch: u64,
100
101    /// Resolves once the previously verified block has been sent to the state.
102    ///
103    /// After a reset, the state fails blocks that arrive before the block right
104    /// above its tip, so blocks must be sent in the order they were verified.
105    previous_sent: Option<oneshot::Receiver<()>>,
106
107    /// Signals the next verified block once this block has been sent to the state.
108    sent: oneshot::Sender<()>,
109}
110
111/// A failed checkpoint block commit, sent from its commit task to the verifier.
112#[derive(Debug)]
113struct CommitFailure {
114    /// The verifier's reset epoch when the block was verified.
115    ///
116    /// Only the first failure in an epoch resets the verifier, because every
117    /// block sent after the failed block fails too, and those failures can
118    /// arrive after the verifier has verified the range again.
119    epoch: u64,
120
121    /// The state tip after the failure, which the verifier resets to.
122    tip: Option<(block::Height, block::Hash)>,
123
124    /// The failed block, if the state failed it without checking it.
125    ///
126    /// The state drops the blocks above a block that failed to commit, even if
127    /// they are valid. The verifier queues them again, and their commit tasks
128    /// commit them once they are verified again.
129    child: Option<QueuedBlock>,
130}
131
132/// A list of unverified blocks at a particular height.
133///
134/// Typically contains a single block, but might contain more if a peer
135/// has an old chain fork. (Or sends us a bad block.)
136///
137/// The CheckpointVerifier avoids creating zero-block lists.
138type QueuedBlockList = Vec<QueuedBlock>;
139
140/// The maximum number of queued blocks at any one height.
141///
142/// This value is a tradeoff between:
143/// - rejecting bad blocks: if we queue more blocks, we need fewer network
144///   retries, but use a bit more CPU when verifying,
145/// - avoiding a memory DoS: if we queue fewer blocks, we use less memory.
146///
147/// The verifier also limits the memory used by the queued blocks at all heights.
148pub const MAX_QUEUED_BLOCKS_PER_HEIGHT: usize = 4;
149
150/// The maximum estimated memory used by the blocks queued for checkpoint verification, in bytes.
151///
152/// This fits 2,000 full-size blocks, twice the syncer's default checkpoint lookahead, so it only
153/// limits syncing when a large lookahead is configured or peers send blocks Zebra can't use yet.
154// The block size limit fits in usize on every supported platform.
155const MAX_QUEUED_BYTES: usize = 2_000 * block::MAX_BLOCK_BYTES as usize;
156
157/// Convert a tip into its hash and matching progress.
158fn progress_from_tip(
159    checkpoint_list: &CheckpointList,
160    tip: Option<(block::Height, block::Hash)>,
161) -> (Option<block::Hash>, Progress<block::Height>) {
162    match tip {
163        Some((height, hash)) => {
164            if height >= checkpoint_list.max_height() {
165                (None, Progress::FinalCheckpoint)
166            } else {
167                metrics::gauge!("checkpoint.verified.height").set(height.0 as f64);
168                metrics::gauge!("checkpoint.processing.next.height").set(height.0 as f64);
169                (Some(hash), Progress::InitialTip(height))
170            }
171        }
172        // We start by verifying the genesis block, by itself
173        None => (None, Progress::BeforeGenesis),
174    }
175}
176
177/// A checkpointing block verifier.
178///
179/// Verifies blocks using a supplied list of checkpoints. There must be at
180/// least one checkpoint for the genesis block.
181pub struct CheckpointVerifier<S>
182where
183    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
184    S::Future: Send + 'static,
185{
186    /// The checkpoint list for this verifier.
187    checkpoint_list: Arc<CheckpointList>,
188
189    /// The network rules used by this verifier.
190    network: Network,
191
192    /// The hash of the initial tip, if any.
193    initial_tip_hash: Option<block::Hash>,
194
195    /// The underlying state service, possibly wrapped in other services.
196    state_service: S,
197
198    /// A queue of unverified blocks.
199    ///
200    /// Contains a list of unverified blocks at each block height. In most cases,
201    /// the checkpoint verifier will store zero or one block at each height.
202    ///
203    /// Blocks are verified in order, once there is a chain from the previous
204    /// checkpoint to a target checkpoint.
205    ///
206    /// The first checkpoint does not have any ancestors, so it only verifies the
207    /// genesis block.
208    queued: BTreeMap<block::Height, QueuedBlockList>,
209
210    /// Bodies and commit owners retained across all checkpoint ranges.
211    retained_blocks: Arc<AtomicUsize>,
212    /// Four candidates per configured maximum gap, or two default sync batches.
213    retained_block_limit: usize,
214
215    /// The estimated memory used by the blocks in `queued`, which is at most `max_queued_bytes`
216    /// after each new block is queued.
217    queued_bytes: usize,
218
219    /// The limit for `queued_bytes`, which is [`MAX_QUEUED_BYTES`] outside tests.
220    max_queued_bytes: usize,
221
222    /// The current progress of this verifier.
223    verifier_progress: Progress<block::Height>,
224
225    /// A channel to receive requests to reset the verifier,
226    /// receiving the tip of the state.
227    reset_receiver: mpsc::Receiver<CommitFailure>,
228    /// A channel to send requests to reset the verifier,
229    /// passing the tip of the state.
230    reset_sender: mpsc::Sender<CommitFailure>,
231
232    /// The number of times the verifier was reset after a failed block commit.
233    epoch: u64,
234
235    /// Resolves once the last verified block has been sent to the state.
236    previous_block_sent: Option<oneshot::Receiver<()>>,
237
238    /// Queued block height progress transmitter.
239    #[cfg(feature = "progress-bar")]
240    queued_blocks_bar: howudoin::Tx,
241
242    /// Verified checkpoint progress transmitter.
243    #[cfg(feature = "progress-bar")]
244    verified_checkpoint_bar: howudoin::Tx,
245}
246
247impl<S> std::fmt::Debug for CheckpointVerifier<S>
248where
249    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
250    S::Future: Send + 'static,
251{
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("CheckpointVerifier")
254            .field("checkpoint_list", &self.checkpoint_list)
255            .field("network", &self.network)
256            .field("initial_tip_hash", &self.initial_tip_hash)
257            .field("queued", &self.queued)
258            .field("verifier_progress", &self.verifier_progress)
259            .finish()
260    }
261}
262
263impl<S> CheckpointVerifier<S>
264where
265    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
266    S::Future: Send + 'static,
267{
268    /// Return a checkpoint verification service for `network`, using the
269    /// hard-coded checkpoint list, and the provided `state_service`.
270    ///
271    /// If `initial_tip` is Some(_), the verifier starts at that initial tip.
272    /// The initial tip can be between the checkpoints in the hard-coded
273    /// checkpoint list.
274    ///
275    /// The checkpoint verifier holds a state service of type `S`, into which newly
276    /// verified blocks will be committed. This state is pluggable to allow for
277    /// testing or instrumentation.
278    ///
279    /// This function should be called only once for a particular network, rather
280    /// than constructing multiple verification services for the same network. To
281    /// clone a CheckpointVerifier, you might need to wrap it in a
282    /// `tower::Buffer` service.
283    #[allow(dead_code)]
284    pub fn new(
285        network: &Network,
286        initial_tip: Option<(block::Height, block::Hash)>,
287        state_service: S,
288    ) -> Self {
289        let checkpoint_list = network.checkpoint_list();
290        let max_height = checkpoint_list.max_height();
291        tracing::info!(
292            ?max_height,
293            ?network,
294            ?initial_tip,
295            "initialising CheckpointVerifier"
296        );
297        Self::from_checkpoint_list(checkpoint_list, network, initial_tip, state_service)
298    }
299
300    /// Return a checkpoint verification service using `list`, `network`,
301    /// `initial_tip`, and `state_service`.
302    ///
303    /// Assumes that the provided genesis checkpoint is correct.
304    ///
305    /// Callers should prefer `CheckpointVerifier::new`, which uses the
306    /// hard-coded checkpoint lists, or `CheckpointList::from_list` if you need
307    /// to specify a custom checkpoint list. See those functions for more
308    /// details.
309    ///
310    /// This function is designed for use in tests.
311    #[allow(dead_code)]
312    pub(crate) fn from_list(
313        list: impl IntoIterator<Item = (block::Height, block::Hash)>,
314        network: &Network,
315        initial_tip: Option<(block::Height, block::Hash)>,
316        state_service: S,
317    ) -> Result<Self, VerifyCheckpointError> {
318        Ok(Self::from_checkpoint_list(
319            CheckpointList::from_list(list)
320                .map(Arc::new)
321                .map_err(VerifyCheckpointError::CheckpointList)?,
322            network,
323            initial_tip,
324            state_service,
325        ))
326    }
327
328    /// Return a checkpoint verification service using `checkpoint_list`,
329    /// `network`, `initial_tip`, and `state_service`.
330    ///
331    /// Assumes that the provided genesis checkpoint is correct.
332    ///
333    /// Callers should prefer `CheckpointVerifier::new`, which uses the
334    /// hard-coded checkpoint lists. See that function for more details.
335    pub(crate) fn from_checkpoint_list(
336        checkpoint_list: Arc<CheckpointList>,
337        network: &Network,
338        initial_tip: Option<(block::Height, block::Hash)>,
339        state_service: S,
340    ) -> Self {
341        // All the initialisers should call this function, so we only have to
342        // change fields or default values in one place.
343        let (initial_tip_hash, verifier_progress) =
344            progress_from_tip(&checkpoint_list, initial_tip);
345
346        let (sender, receiver) = mpsc::channel();
347        let mut previous_height = 0;
348        let maximum_gap = checkpoint_list
349            .iter()
350            .map(|(height, _)| {
351                let gap = height.0 - previous_height;
352                previous_height = height.0;
353                usize::try_from(gap).expect("block heights fit in usize")
354            })
355            .max()
356            .unwrap_or(1)
357            .max(1);
358        let retained_block_limit = maximum_gap
359            .saturating_mul(MAX_QUEUED_BLOCKS_PER_HEIGHT)
360            .max(2_000);
361
362        #[cfg(feature = "progress-bar")]
363        let queued_blocks_bar = howudoin::new_root().label("Checkpoint Queue Height");
364
365        #[cfg(feature = "progress-bar")]
366        let verified_checkpoint_bar =
367            howudoin::new_with_parent(queued_blocks_bar.id()).label("Verified Checkpoints");
368
369        let verifier = CheckpointVerifier {
370            checkpoint_list,
371            network: network.clone(),
372            initial_tip_hash,
373            state_service,
374            queued: BTreeMap::new(),
375            retained_blocks: Arc::new(AtomicUsize::new(0)),
376            retained_block_limit,
377            queued_bytes: 0,
378            max_queued_bytes: MAX_QUEUED_BYTES,
379            verifier_progress,
380            reset_receiver: receiver,
381            reset_sender: sender,
382            epoch: 0,
383            previous_block_sent: None,
384            #[cfg(feature = "progress-bar")]
385            queued_blocks_bar,
386            #[cfg(feature = "progress-bar")]
387            verified_checkpoint_bar,
388        };
389
390        if verifier_progress.is_final_checkpoint() {
391            verifier.finish_diagnostics();
392        } else {
393            verifier.verified_checkpoint_diagnostics(verifier_progress.height());
394        }
395
396        verifier
397    }
398
399    /// Update diagnostics for queued blocks.
400    fn queued_block_diagnostics(&self, height: block::Height, hash: block::Hash) {
401        let max_queued_height = self
402            .queued
403            .keys()
404            .next_back()
405            .expect("queued has at least one entry");
406
407        metrics::gauge!("checkpoint.queued.max.height").set(max_queued_height.0 as f64);
408
409        let is_checkpoint = self.checkpoint_list.contains(height);
410        tracing::debug!(?height, ?hash, ?is_checkpoint, "queued block");
411
412        #[cfg(feature = "progress-bar")]
413        if matches!(howudoin::cancelled(), Some(true)) {
414            self.finish_diagnostics();
415        } else {
416            self.queued_blocks_bar
417                .set_pos(max_queued_height.0)
418                .set_len(u64::from(self.checkpoint_list.max_height().0));
419        }
420    }
421
422    /// Update diagnostics for verified checkpoints.
423    fn verified_checkpoint_diagnostics(&self, verified_height: impl Into<Option<block::Height>>) {
424        let Some(verified_height) = verified_height.into() else {
425            // We don't know if we have already finished, or haven't started yet,
426            // so don't register any progress
427            return;
428        };
429
430        metrics::gauge!("checkpoint.verified.height").set(verified_height.0 as f64);
431
432        let checkpoint_index = self.checkpoint_list.prev_checkpoint_index(verified_height);
433        let checkpoint_count = self.checkpoint_list.len();
434
435        metrics::gauge!("checkpoint.verified.count").set(checkpoint_index as f64);
436
437        tracing::debug!(
438            ?verified_height,
439            ?checkpoint_index,
440            ?checkpoint_count,
441            "verified checkpoint",
442        );
443
444        #[cfg(feature = "progress-bar")]
445        if matches!(howudoin::cancelled(), Some(true)) {
446            self.finish_diagnostics();
447        } else {
448            self.verified_checkpoint_bar
449                .set_pos(u64::try_from(checkpoint_index).expect("fits in u64"))
450                .set_len(u64::try_from(checkpoint_count).expect("fits in u64"));
451        }
452    }
453
454    /// Finish checkpoint verifier diagnostics.
455    fn finish_diagnostics(&self) {
456        #[cfg(feature = "progress-bar")]
457        {
458            self.queued_blocks_bar.close();
459            self.verified_checkpoint_bar.close();
460        }
461    }
462
463    /// Reset the verifier progress back to given tip.
464    fn reset_progress(&mut self, tip: Option<(block::Height, block::Hash)>) {
465        let (initial_tip_hash, verifier_progress) = progress_from_tip(&self.checkpoint_list, tip);
466        self.initial_tip_hash = initial_tip_hash;
467        self.verifier_progress = verifier_progress;
468
469        // Recovery can cover queued blocks that are already in state.
470        while let Some((&height, _)) = self.queued.first_key_value() {
471            if self.check_height(height).is_ok() {
472                break;
473            }
474            let (_, blocks) = self.queued.pop_first().expect("the first entry exists");
475            for block in blocks {
476                self.queued_bytes -= block.bytes;
477                let error = self
478                    .check_height(height)
479                    .expect_err("this height is already in state");
480                let _ = block.tx.send(Err(error));
481            }
482        }
483
484        self.verified_checkpoint_diagnostics(verifier_progress.height());
485    }
486
487    /// Return the current verifier's progress.
488    ///
489    /// If verification has not started yet, returns `BeforeGenesis`,
490    /// or `InitialTip(height)` if there were cached verified blocks.
491    ///
492    /// If verification is ongoing, returns `PreviousCheckpoint(height)`.
493    /// `height` increases as checkpoints are verified.
494    ///
495    /// If verification has finished, returns `FinalCheckpoint`.
496    fn previous_checkpoint_height(&self) -> Progress<block::Height> {
497        self.verifier_progress
498    }
499
500    /// Return the start of the current checkpoint range.
501    ///
502    /// Returns None if verification has finished.
503    fn current_start_bound(&self) -> Option<Bound<block::Height>> {
504        match self.previous_checkpoint_height() {
505            BeforeGenesis => Some(Unbounded),
506            InitialTip(height) | PreviousCheckpoint(height) => Some(Excluded(height)),
507            FinalCheckpoint => None,
508        }
509    }
510
511    /// Return the target checkpoint height that we want to verify.
512    ///
513    /// If we need more blocks, returns `WaitingForBlocks`.
514    ///
515    /// If the queued blocks are continuous from the previous checkpoint to a
516    /// target checkpoint, returns `Checkpoint(height)`. The target checkpoint
517    /// can be multiple checkpoints ahead of the previous checkpoint.
518    ///
519    /// `height` increases as checkpoints are verified.
520    ///
521    /// If verification has finished, returns `FinishedVerifying`.
522    fn target_checkpoint_height(&self) -> TargetHeight {
523        // Find the height we want to start searching at
524        let start_height = match self.previous_checkpoint_height() {
525            // Check if we have the genesis block as a special case, to simplify the loop
526            BeforeGenesis if !self.queued.contains_key(&block::Height(0)) => {
527                tracing::trace!("Waiting for genesis block");
528                metrics::counter!("checkpoint.waiting.count").increment(1);
529                return WaitingForBlocks;
530            }
531            BeforeGenesis => block::Height(0),
532            InitialTip(height) | PreviousCheckpoint(height) => height,
533            FinalCheckpoint => return FinishedVerifying,
534        };
535
536        // Find the end of the continuous sequence of blocks, starting at the
537        // last verified checkpoint. If there is no verified checkpoint, start
538        // *after* the genesis block (which we checked above).
539        //
540        // If `btree_map::Range` implements `ExactSizeIterator`, it would be
541        // much faster to walk the checkpoint list, and compare the length of
542        // the `btree_map::Range` to the block height difference between
543        // checkpoints. (In maps, keys are unique, so we don't need to check
544        // each height value.)
545        //
546        // But at the moment, this implementation is slightly faster, because
547        // it stops after the first gap.
548        let mut pending_height = start_height;
549        for (&height, _) in self.queued.range((Excluded(pending_height), Unbounded)) {
550            // If the queued blocks are continuous.
551            if height == block::Height(pending_height.0 + 1) {
552                pending_height = height;
553            } else {
554                let gap = height.0 - pending_height.0;
555                // Try to log a useful message when checkpointing has issues
556                tracing::trace!(contiguous_height = ?pending_height,
557                                next_height = ?height,
558                                ?gap,
559                                "Waiting for more checkpoint blocks");
560                break;
561            }
562        }
563        metrics::gauge!("checkpoint.queued.continuous.height").set(pending_height.0 as f64);
564
565        // Now find the start of the checkpoint range
566        let start = self.current_start_bound().expect(
567            "if verification has finished, we should have returned earlier in the function",
568        );
569        // Find the highest checkpoint below pending_height, excluding any
570        // previously verified checkpoints
571        let target_checkpoint = self
572            .checkpoint_list
573            .max_height_in_range((start, Included(pending_height)));
574
575        tracing::trace!(
576            checkpoint_start = ?start,
577            highest_contiguous_block = ?pending_height,
578            ?target_checkpoint
579        );
580
581        if let Some(block::Height(target_checkpoint)) = target_checkpoint {
582            metrics::gauge!("checkpoint.processing.next.height").set(target_checkpoint as f64);
583        } else {
584            // Use the start height if there is no potential next checkpoint
585            metrics::gauge!("checkpoint.processing.next.height").set(start_height.0 as f64);
586            metrics::counter!("checkpoint.waiting.count").increment(1);
587        }
588
589        target_checkpoint
590            .map(Checkpoint)
591            .unwrap_or(WaitingForBlocks)
592    }
593
594    /// Return the most recently verified checkpoint's hash.
595    ///
596    /// See `previous_checkpoint_height()` for details.
597    fn previous_checkpoint_hash(&self) -> Progress<block::Hash> {
598        match self.previous_checkpoint_height() {
599            BeforeGenesis => BeforeGenesis,
600            InitialTip(_) => self
601                .initial_tip_hash
602                .map(InitialTip)
603                .expect("initial tip height must have an initial tip hash"),
604            PreviousCheckpoint(height) => self
605                .checkpoint_list
606                .hash(height)
607                .map(PreviousCheckpoint)
608                .expect("every checkpoint height must have a hash"),
609            FinalCheckpoint => FinalCheckpoint,
610        }
611    }
612
613    /// Check that `height` is valid and able to be verified.
614    ///
615    /// Returns an error if:
616    ///  - the block's height is greater than the maximum checkpoint
617    ///  - there are no checkpoints
618    ///  - the block's height is less than or equal to the previously verified
619    ///    checkpoint
620    ///  - verification has finished
621    fn check_height(&self, height: block::Height) -> Result<(), VerifyCheckpointError> {
622        if height > self.checkpoint_list.max_height() {
623            Err(VerifyCheckpointError::TooHigh {
624                height,
625                max_height: self.checkpoint_list.max_height(),
626            })?;
627        }
628
629        match self.previous_checkpoint_height() {
630            // Any height is valid
631            BeforeGenesis => {}
632            // Greater heights are valid
633            InitialTip(previous_height) | PreviousCheckpoint(previous_height)
634                if (height <= previous_height) =>
635            {
636                let e = Err(VerifyCheckpointError::AlreadyVerified {
637                    height,
638                    verified_height: previous_height,
639                });
640                tracing::trace!(?e);
641                e?;
642            }
643            InitialTip(_) | PreviousCheckpoint(_) => {}
644            // We're finished, so no checkpoint height is valid
645            FinalCheckpoint => Err(VerifyCheckpointError::Finished)?,
646        };
647
648        Ok(())
649    }
650
651    /// Increase the current checkpoint height to `verified_height`,
652    fn update_progress(&mut self, verified_height: block::Height) {
653        if let Some(max_height) = self.queued.keys().next_back() {
654            metrics::gauge!("checkpoint.queued.max.height").set(max_height.0 as f64);
655        } else {
656            // use f64::NAN as a sentinel value for "None", because 0 is a valid height
657            metrics::gauge!("checkpoint.queued.max.height").set(f64::NAN);
658        }
659        metrics::gauge!("checkpoint.queued_slots").set(self.queued.len() as f64);
660
661        // Ignore blocks that are below the previous checkpoint, or otherwise
662        // have invalid heights.
663        //
664        // We ignore out-of-order verification, such as:
665        //  - the height is less than the previous checkpoint height, or
666        //  - the previous checkpoint height is the maximum height (checkpoint verifies are finished),
667        // because futures might not resolve in height order.
668        if self.check_height(verified_height).is_err() {
669            return;
670        }
671
672        // Ignore heights that aren't checkpoint heights
673        if verified_height == self.checkpoint_list.max_height() {
674            self.verifier_progress = FinalCheckpoint;
675
676            tracing::info!(
677                final_checkpoint_height = ?verified_height,
678                "verified final checkpoint: starting full validation",
679            );
680
681            self.verified_checkpoint_diagnostics(verified_height);
682            self.finish_diagnostics();
683        } else if self.checkpoint_list.contains(verified_height) {
684            self.verifier_progress = PreviousCheckpoint(verified_height);
685            // We're done with the initial tip hash now
686            self.initial_tip_hash = None;
687
688            self.verified_checkpoint_diagnostics(verified_height);
689        }
690    }
691
692    /// Check that the proof of work, Merkle root, coinbase height commitment, and block height are
693    /// valid.
694    ///
695    /// Returns a [`CheckpointVerifiedBlock`] with precalculated block data.
696    ///
697    /// ## Security
698    ///
699    /// Checking the proof of work makes resource exhaustion attacks harder to
700    /// carry out, because malicious blocks require a valid proof of work.
701    ///
702    /// Checking the Merkle root ensures that the block hash binds the block
703    /// contents. To prevent malleability (CVE-2012-2459), we also need to check
704    /// whether the transaction hashes are unique.
705    ///
706    /// The block hash only commits to the header, so a peer can answer a request for a block hash
707    /// with the requested header and any body. The height is checked last, after the checks that
708    /// bind it to the header. Otherwise a body that claims an already verified height would get the
709    /// requested block dropped as a duplicate, and its range would never verify
710    /// (GHSA-g9rc-89v4-hhvf). A body could also claim an unverified height, and take queue slots
711    /// at heights that aren't its own.
712    ///
713    /// The coinbase height commitment is checked before the Merkle root, because
714    /// `merkle_root_validity()` uses the height to pick the network upgrade for its consensus
715    /// branch ID check.
716    fn check_block(
717        &self,
718        block: Arc<Block>,
719    ) -> Result<CheckpointVerifiedBlock, VerifyCheckpointError> {
720        let hash = block.hash();
721        let height = block
722            .coinbase_height()
723            .ok_or(VerifyCheckpointError::CoinbaseHeight { hash })?;
724
725        if self.network.disable_pow() {
726            crate::block::check::difficulty_threshold_is_valid(
727                &block.header,
728                &self.network,
729                &height,
730                &hash,
731            )?;
732        } else {
733            crate::block::check::difficulty_is_valid(&block.header, &self.network, &height, &hash)?;
734            crate::block::check::equihash_solution_is_valid(&block.header)?;
735        }
736
737        crate::block::check::coinbase_height_is_committed(&block, height)?;
738
739        // don't do precalculation until the block passes basic difficulty checks
740        let block = CheckpointVerifiedBlock::new(block, Some(hash));
741
742        crate::block::check::merkle_root_validity(
743            &self.network,
744            &block.block,
745            &block.transaction_hashes,
746        )?;
747
748        self.check_height(height)?;
749
750        Ok(block)
751    }
752
753    /// Queue `block` for verification.
754    ///
755    /// On success, returns the receiver for the block's verification result.
756    ///
757    /// Verification will finish when the chain to the next checkpoint is
758    /// complete, and the caller will be notified via the channel.
759    ///
760    /// If the block does not pass basic validity checks, or there is no room for it in the queue,
761    /// returns an error immediately.
762    fn queue_block(
763        &mut self,
764        block: Arc<Block>,
765    ) -> Result<oneshot::Receiver<Result<Verified, VerifyCheckpointError>>, VerifyCheckpointError>
766    {
767        // Set up a oneshot channel to send results
768        let (tx, rx) = oneshot::channel();
769
770        // Check that the height and Merkle roots are valid.
771        let block = self.check_block(block)?;
772        let height = block.height;
773        let hash = block.hash;
774        let bytes = block.retained_bytes();
775
776        self.make_room(height, hash, bytes, 1)?;
777
778        // Admission is serialized through &mut self; commit owners can only decrease the count.
779        self.retained_blocks.fetch_add(1, Ordering::Relaxed);
780        let new_qblock = QueuedBlock {
781            block,
782            bytes,
783            tx,
784            retained: RetainedBlockPermit(self.retained_blocks.clone()),
785        };
786        self.queued_bytes += bytes;
787
788        // Since we're using Arc<Block>, each entry is a single pointer to the
789        // Arc. But there are a lot of QueuedBlockLists in the queue, so we keep
790        // allocations as small as possible.
791        let qblocks = self
792            .queued
793            .entry(height)
794            .or_insert_with(|| QueuedBlockList::with_capacity(1));
795
796        // Replace older requests with newer ones.
797        // The newer block is ok, the older block is an error.
798        if let Some(qb) = qblocks.iter_mut().find(|qb| qb.block.hash == hash) {
799            let e = VerifyCheckpointError::NewerRequest { height, hash };
800            tracing::trace!(?e, "failing older of duplicate requests");
801
802            // ## Security
803            //
804            // Replace the entire queued block.
805            //
806            // We don't check the authorizing data hash until checkpoint blocks reach the state.
807            // So signatures, proofs, or scripts could be different,
808            // even if the block hash is the same.
809
810            let old = std::mem::replace(qb, new_qblock);
811            self.queued_bytes -= old.bytes;
812            let _ = old.tx.send(Err(e));
813            return Ok(rx);
814        }
815
816        // Add the block to the list of queued blocks at this height
817        // This is a no-op for the first block in each QueuedBlockList.
818        qblocks.reserve_exact(1);
819        qblocks.push(new_qblock);
820
821        self.queued_block_diagnostics(height, hash);
822
823        Ok(rx)
824    }
825
826    /// Returns the heights and hashes of the queued blocks that are linked to the next checkpoint
827    /// by their previous block hashes, and the block that is missing from that chain, if any.
828    ///
829    /// The linked blocks are the only queued blocks that are known to be in the checkpointed
830    /// chain. A block hash doesn't cover a V5 coinbase height, so a copy of a linked block at
831    /// another height isn't linked.
832    fn checkpoint_chain(
833        &self,
834    ) -> (
835        HashSet<(block::Height, block::Hash)>,
836        Option<(block::Height, block::Hash)>,
837    ) {
838        let mut linked = HashSet::new();
839
840        let next_checkpoint = self
841            .current_start_bound()
842            .and_then(|start| self.checkpoint_list.min_height_in_range((start, Unbounded)));
843        let Some(mut height) = next_checkpoint else {
844            return (linked, None);
845        };
846        let mut hash = self
847            .checkpoint_list
848            .hash(height)
849            .expect("every checkpoint height must have a hash");
850
851        while self.check_height(height).is_ok() {
852            let Some(qblock) = self
853                .queued
854                .get(&height)
855                .and_then(|qblocks| qblocks.iter().find(|qb| qb.block.hash == hash))
856            else {
857                return (linked, Some((height, hash)));
858            };
859
860            linked.insert((height, hash));
861            hash = qblock.block.block.header.previous_block_hash;
862            let Ok(previous_height) = height.previous() else {
863                break;
864            };
865            height = previous_height;
866        }
867
868        (linked, None)
869    }
870
871    /// Makes room in the queue for a block at `height` with `hash`, which uses `bytes`, by failing
872    /// other queued blocks with [`VerifyCheckpointError::QueuedLimit`].
873    ///
874    /// Never fails the blocks linked to the next checkpoint, because they are known to be in the
875    /// checkpointed chain. The block that chain needs next can replace any other block, including
876    /// one at a full height. Other blocks can only replace blocks above them, because lower
877    /// blocks are verified first. Same-height/hash replacements credit the old body's charge.
878    ///
879    /// Recovered children already own a reservation, so `additional_blocks` is zero for them.
880    /// Returns an error without failing any blocks if it can't make enough room.
881    #[allow(clippy::unwrap_in_result)]
882    fn make_room(
883        &mut self,
884        height: block::Height,
885        hash: block::Hash,
886        bytes: usize,
887        additional_blocks: usize,
888    ) -> Result<(), VerifyCheckpointError> {
889        let qblocks = self.queued.get(&height);
890        let replaced = qblocks.and_then(|qblocks| qblocks.iter().find(|qb| qb.block.hash == hash));
891        let additional = bytes.saturating_sub(replaced.map_or(0, |qb| qb.bytes));
892        let height_full = replaced.is_none()
893            && qblocks.is_some_and(|qblocks| qblocks.len() >= MAX_QUEUED_BLOCKS_PER_HEIGHT);
894        let mut excess = self
895            .queued_bytes
896            .saturating_add(additional)
897            .saturating_sub(self.max_queued_bytes);
898        let mut excess_blocks = self
899            .retained_blocks
900            .load(Ordering::Relaxed)
901            .saturating_add(additional_blocks.saturating_sub(usize::from(replaced.is_some())))
902            .saturating_sub(self.retained_block_limit);
903        if !height_full && excess == 0 && excess_blocks == 0 {
904            return Ok(());
905        }
906        let (linked, needed) = self.checkpoint_chain();
907        let is_needed = needed == Some((height, hash));
908        if height_full && !is_needed {
909            return Err(VerifyCheckpointError::QueuedLimit);
910        }
911
912        let mut failed = Vec::new();
913
914        // The chain doesn't link any of the blocks at the height it needs next.
915        let full_slot = height_full.then(|| (height, self.queued[&height].len() - 1));
916        if let Some((_, index)) = full_slot {
917            excess = excess.saturating_sub(self.queued[&height][index].bytes);
918            excess_blocks = excess_blocks.saturating_sub(1);
919        }
920        failed.extend(full_slot);
921
922        // Fail the highest blocks first, because they are verified last.
923        'heights: for (&queued_height, qblocks) in self.queued.iter().rev() {
924            if queued_height <= height && !is_needed {
925                break;
926            }
927
928            for (index, qblock) in qblocks.iter().enumerate().rev() {
929                if excess == 0 && excess_blocks == 0 {
930                    break 'heights;
931                }
932
933                if Some((queued_height, index)) != full_slot
934                    && !linked.contains(&(queued_height, qblock.block.hash))
935                {
936                    excess = excess.saturating_sub(qblock.bytes);
937                    excess_blocks = excess_blocks.saturating_sub(1);
938                    failed.push((queued_height, index));
939                }
940            }
941        }
942
943        if excess > 0 || excess_blocks > 0 {
944            return Err(VerifyCheckpointError::QueuedLimit);
945        }
946
947        // The blocks at each height are failed in decreasing index order, so removing one doesn't
948        // move the others.
949        for (queued_height, index) in failed {
950            let qblocks = self
951                .queued
952                .get_mut(&queued_height)
953                .expect("failed blocks are queued");
954            let qblock = qblocks.swap_remove(index);
955            if qblocks.is_empty() {
956                self.queued.remove(&queued_height);
957            }
958
959            self.queued_bytes -= qblock.bytes;
960            let _ = qblock.tx.send(Err(VerifyCheckpointError::QueuedLimit));
961        }
962
963        Ok(())
964    }
965
966    /// Queue `child` again, after the state failed it without checking it.
967    ///
968    /// It has already passed [`Self::check_block`], so only its height and queue limits are checked.
969    fn requeue_child(&mut self, child: QueuedBlock) {
970        let (height, hash) = (child.block.height, child.block.hash);
971        if let Err(e) = self.check_height(height) {
972            let _ = child.tx.send(Err(e));
973            return;
974        }
975
976        // Prefer a copy that a caller has already submitted again.
977        if self
978            .queued
979            .get(&height)
980            .is_some_and(|qblocks| qblocks.iter().any(|qb| qb.block.hash == hash))
981        {
982            let _ = child
983                .tx
984                .send(Err(VerifyCheckpointError::NewerRequest { height, hash }));
985            return;
986        }
987        if let Err(error) = self.make_room(height, hash, child.bytes, 0) {
988            let _ = child.tx.send(Err(error));
989            return;
990        }
991        self.queued_bytes += child.bytes;
992        self.queued
993            .entry(height)
994            .or_insert_with(|| QueuedBlockList::with_capacity(1))
995            .push(child);
996        self.queued_block_diagnostics(height, hash);
997    }
998
999    /// During checkpoint range processing, process all the blocks at `height`.
1000    ///
1001    /// Returns the first valid block. If there is no valid block, returns None.
1002    #[allow(clippy::unwrap_in_result)]
1003    fn process_height(
1004        &mut self,
1005        height: block::Height,
1006        expected_hash: block::Hash,
1007    ) -> Option<QueuedBlock> {
1008        let mut qblocks = self
1009            .queued
1010            .remove(&height)
1011            .expect("the current checkpoint range has continuous Vec<QueuedBlock>s");
1012        assert!(
1013            !qblocks.is_empty(),
1014            "the current checkpoint range has continuous Blocks"
1015        );
1016
1017        // Check interim checkpoints
1018        if let Some(checkpoint_hash) = self.checkpoint_list.hash(height) {
1019            // We assume the checkpoints are valid. And we have verified back
1020            // from the target checkpoint, so the last block must also be valid.
1021            // This is probably a bad checkpoint list, a zebra bug, or a bad
1022            // chain (in a testing mode like regtest).
1023            assert_eq!(expected_hash, checkpoint_hash,
1024                           "checkpoints in the range should match: bad checkpoint list, zebra bug, or bad chain"
1025                );
1026        }
1027
1028        // Find a queued block at this height, which is part of the hash chain.
1029        //
1030        // There are two possible outcomes here:
1031        //   - one of the blocks matches the chain (the common case)
1032        //   - no blocks match the chain, verification has failed for this range
1033        // If there are any side-chain blocks, they fail validation.
1034        let mut valid_qblock = None;
1035        for qblock in qblocks.drain(..) {
1036            if qblock.block.hash == expected_hash {
1037                if valid_qblock.is_none() {
1038                    // The first valid block at the current height
1039                    valid_qblock = Some(qblock);
1040                } else {
1041                    unreachable!("unexpected duplicate block {:?} {:?}: duplicate blocks should be rejected before being queued",
1042                                 height, qblock.block.hash);
1043                }
1044            } else {
1045                tracing::info!(?height, ?qblock.block.hash, ?expected_hash,
1046                               "Side chain hash at height in CheckpointVerifier");
1047                self.queued_bytes -= qblock.bytes;
1048                let _ = qblock
1049                    .tx
1050                    .send(Err(VerifyCheckpointError::UnexpectedSideChain {
1051                        found: qblock.block.hash,
1052                        expected: expected_hash,
1053                    }));
1054            }
1055        }
1056
1057        valid_qblock
1058    }
1059
1060    /// Try to verify from the previous checkpoint to a target checkpoint.
1061    ///
1062    /// Send `Ok` for the blocks that are in the chain, and `Err` for side-chain
1063    /// blocks.
1064    ///
1065    /// Does nothing if we are waiting for more blocks, or if verification has
1066    /// finished.
1067    fn process_checkpoint_range(&mut self) {
1068        // If this code shows up in profiles, we can try the following
1069        // optimisations:
1070        //   - only check the chain when the length of the queue is greater
1071        //     than or equal to the length of a checkpoint interval
1072        //     (note: the genesis checkpoint interval is only one block long)
1073        //   - cache the height of the last continuous chain as a new field in
1074        //     self, and start at that height during the next check.
1075
1076        // Return early if verification has finished
1077        let previous_checkpoint_hash = match self.previous_checkpoint_hash() {
1078            // Since genesis blocks are hard-coded in zcashd, and not verified
1079            // like other blocks, the genesis parent hash is set by the
1080            // consensus parameters.
1081            BeforeGenesis => GENESIS_PREVIOUS_BLOCK_HASH,
1082            InitialTip(hash) | PreviousCheckpoint(hash) => hash,
1083            FinalCheckpoint => return,
1084        };
1085        // Return early if we're still waiting for more blocks
1086        let (target_checkpoint_height, mut expected_hash) = match self.target_checkpoint_height() {
1087            Checkpoint(height) => (
1088                height,
1089                self.checkpoint_list
1090                    .hash(height)
1091                    .expect("every checkpoint height must have a hash"),
1092            ),
1093            WaitingForBlocks => {
1094                return;
1095            }
1096            FinishedVerifying => {
1097                unreachable!("the FinalCheckpoint case should have returned earlier")
1098            }
1099        };
1100
1101        // Keep the old previous checkpoint height, to make sure we're making
1102        // progress
1103        let old_prev_check_height = self.previous_checkpoint_height();
1104
1105        // Work out which blocks and checkpoints we're checking
1106        let current_range = (
1107            self.current_start_bound()
1108                .expect("earlier code checks if verification has finished"),
1109            Included(target_checkpoint_height),
1110        );
1111        let range_heights: Vec<block::Height> = self
1112            .queued
1113            .range_mut(current_range)
1114            .rev()
1115            .map(|(key, _)| *key)
1116            .collect();
1117        // A list of pending valid blocks, in reverse chain order
1118        let mut rev_valid_blocks = Vec::new();
1119
1120        // Check all the blocks, and discard all the bad blocks
1121        for current_height in range_heights {
1122            let valid_qblock = self.process_height(current_height, expected_hash);
1123            if let Some(qblock) = valid_qblock {
1124                expected_hash = qblock.block.block.header.previous_block_hash;
1125                // Add the block to the end of the pending block list
1126                // (since we're walking the chain backwards, the list is
1127                // in reverse chain order)
1128                rev_valid_blocks.push(qblock);
1129            } else {
1130                // The last block height we processed did not have any blocks
1131                // with a matching hash, so chain verification has failed.
1132                tracing::info!(
1133                    ?current_height,
1134                    ?current_range,
1135                    "No valid blocks at height in CheckpointVerifier"
1136                );
1137
1138                // We kept all the matching blocks down to this height, in
1139                // anticipation of the chain verifying. But the chain is
1140                // incomplete, so we have to put them back in the queue.
1141                //
1142                // The order here shouldn't matter, but add the blocks in
1143                // height order, for consistency.
1144                for vblock in rev_valid_blocks.drain(..).rev() {
1145                    self.queued
1146                        .entry(vblock.block.height)
1147                        .or_default()
1148                        .push(vblock);
1149                }
1150
1151                // Make sure the current progress hasn't changed
1152                assert_eq!(
1153                    self.previous_checkpoint_height(),
1154                    old_prev_check_height,
1155                    "we must not change the previous checkpoint on failure"
1156                );
1157                // We've reduced the target
1158                //
1159                // This check should be cheap, because we just reduced the target
1160                let current_target = self.target_checkpoint_height();
1161                assert!(
1162                    current_target == WaitingForBlocks
1163                        || current_target < Checkpoint(target_checkpoint_height),
1164                    "we must decrease or eliminate our target on failure"
1165                );
1166
1167                // Stop verifying, and wait for the next valid block
1168                return;
1169            }
1170        }
1171
1172        // The checkpoint and the parent hash must match.
1173        // See the detailed checkpoint comparison comment above.
1174        assert_eq!(
1175            expected_hash, previous_checkpoint_hash,
1176            "the previous checkpoint should match: bad checkpoint list, zebra bug, or bad chain"
1177        );
1178
1179        let block_count = rev_valid_blocks.len();
1180        tracing::info!(?block_count, ?current_range, "verified checkpoint range");
1181        metrics::counter!("checkpoint.verified.block.count").increment(block_count as u64);
1182
1183        // All the blocks we've kept are valid, so let's verify them
1184        // in height order.
1185        for qblock in rev_valid_blocks.drain(..).rev() {
1186            self.queued_bytes -= qblock.bytes;
1187            let (sent, next_sent) = oneshot::channel();
1188            let verified = Verified {
1189                block: qblock.block,
1190                retained: qblock.retained,
1191                epoch: self.epoch,
1192                previous_sent: self.previous_block_sent.replace(next_sent),
1193                sent,
1194            };
1195
1196            // Sending can fail, but there's nothing we can do about it.
1197            let _ = qblock.tx.send(Ok(verified));
1198        }
1199
1200        // Finally, update the checkpoint bounds
1201        self.update_progress(target_checkpoint_height);
1202
1203        // Ensure that we're making progress
1204        let new_progress = self.previous_checkpoint_height();
1205        assert!(
1206            new_progress > old_prev_check_height,
1207            "we must make progress on success"
1208        );
1209        // We met the old target
1210        if new_progress == FinalCheckpoint {
1211            assert_eq!(
1212                target_checkpoint_height,
1213                self.checkpoint_list.max_height(),
1214                "we finish at the maximum checkpoint"
1215            );
1216        } else {
1217            assert_eq!(
1218                new_progress,
1219                PreviousCheckpoint(target_checkpoint_height),
1220                "the new previous checkpoint must match the old target"
1221            );
1222        }
1223        // We processed all available checkpoints
1224        //
1225        // We've cleared the target range, so this check should be cheap
1226        let new_target = self.target_checkpoint_height();
1227        assert!(
1228            new_target == WaitingForBlocks || new_target == FinishedVerifying,
1229            "processing must cover all available checkpoints"
1230        );
1231    }
1232}
1233
1234/// CheckpointVerifier rejects pending futures on drop.
1235impl<S> Drop for CheckpointVerifier<S>
1236where
1237    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
1238    S::Future: Send + 'static,
1239{
1240    /// Send an error on `tx` for any `QueuedBlock`s that haven't been verified.
1241    ///
1242    /// We can't implement `Drop` on QueuedBlock, because `send()` consumes
1243    /// `tx`. And `tx` doesn't implement `Copy` or `Default` (for `take()`).
1244    fn drop(&mut self) {
1245        self.finish_diagnostics();
1246
1247        let drop_keys: Vec<_> = self.queued.keys().cloned().collect();
1248        for key in drop_keys {
1249            let mut qblocks = self
1250                .queued
1251                .remove(&key)
1252                .expect("each entry is only removed once");
1253            for qblock in qblocks.drain(..) {
1254                self.queued_bytes -= qblock.bytes;
1255                // Sending can fail, but there's nothing we can do about it.
1256                let _ = qblock.tx.send(Err(VerifyCheckpointError::Dropped));
1257            }
1258        }
1259
1260        while let Ok(CommitFailure { child, .. }) = self.reset_receiver.try_recv() {
1261            if let Some(child) = child {
1262                let _ = child.tx.send(Err(VerifyCheckpointError::Dropped));
1263            }
1264        }
1265    }
1266}
1267
1268#[derive(Debug, Error)]
1269#[allow(missing_docs)]
1270pub enum VerifyCheckpointError {
1271    #[error("checkpoint request after the final checkpoint has been verified")]
1272    Finished,
1273    #[error("block at {height:?} is higher than the maximum checkpoint {max_height:?}")]
1274    TooHigh {
1275        height: block::Height,
1276        max_height: block::Height,
1277    },
1278    #[error("block {height:?} is less than or equal to the verified tip {verified_height:?}")]
1279    AlreadyVerified {
1280        height: block::Height,
1281        verified_height: block::Height,
1282    },
1283    #[error("rejected older of duplicate verification requests for block at {height:?} {hash:?}")]
1284    NewerRequest {
1285        height: block::Height,
1286        hash: block::Hash,
1287    },
1288    #[error("the block {hash:?} does not have a coinbase height")]
1289    CoinbaseHeight { hash: block::Hash },
1290    #[error("merkle root {actual:?} does not match expected {expected:?}")]
1291    BadMerkleRoot {
1292        actual: block::merkle::Root,
1293        expected: block::merkle::Root,
1294    },
1295    #[error("duplicate transactions in block")]
1296    DuplicateTransaction,
1297    #[error("checkpoint verifier was dropped")]
1298    Dropped,
1299    #[error(transparent)]
1300    CommitCheckpointVerified(BoxError),
1301    #[error(transparent)]
1302    Tip(BoxError),
1303    #[error(transparent)]
1304    CheckpointList(BoxError),
1305    #[error(transparent)]
1306    VerifyBlock(VerifyBlockError),
1307    #[error("invalid block subsidy: {0}")]
1308    SubsidyError(#[from] SubsidyError),
1309    #[error("invalid amount: {0}")]
1310    AmountError(#[from] amount::Error),
1311    #[error("checkpoint retained-owner, queue memory, or per-height capacity is full")]
1312    QueuedLimit,
1313    #[error("the block hash does not match the chained checkpoint hash, expected {expected:?} found {found:?}")]
1314    UnexpectedSideChain {
1315        expected: block::Hash,
1316        found: block::Hash,
1317    },
1318    #[error("zebra is shutting down")]
1319    ShuttingDown,
1320}
1321
1322impl From<VerifyBlockError> for VerifyCheckpointError {
1323    fn from(err: VerifyBlockError) -> VerifyCheckpointError {
1324        VerifyCheckpointError::VerifyBlock(err)
1325    }
1326}
1327
1328impl From<BlockError> for VerifyCheckpointError {
1329    fn from(err: BlockError) -> VerifyCheckpointError {
1330        VerifyCheckpointError::VerifyBlock(err.into())
1331    }
1332}
1333
1334impl From<equihash::Error> for VerifyCheckpointError {
1335    fn from(err: equihash::Error) -> VerifyCheckpointError {
1336        VerifyCheckpointError::VerifyBlock(err.into())
1337    }
1338}
1339
1340impl VerifyCheckpointError {
1341    /// Returns `true` if this is definitely a duplicate request.
1342    /// Some duplicate requests might not be detected, and therefore return `false`.
1343    pub fn is_duplicate_request(&self) -> bool {
1344        match self {
1345            VerifyCheckpointError::AlreadyVerified { .. } => true,
1346            // TODO: make this duplicate-incomplete
1347            VerifyCheckpointError::NewerRequest { .. } => true,
1348            VerifyCheckpointError::VerifyBlock(block_error) => block_error.is_duplicate_request(),
1349            // The state boxes commit errors as `zs::CommitCheckpointVerifiedError`,
1350            // a newtype around `zs::CommitBlockError`, so the wrapper must be
1351            // unwrapped to classify duplicate blocks as benign.
1352            VerifyCheckpointError::CommitCheckpointVerified(source) => source
1353                .downcast_ref::<zs::CommitCheckpointVerifiedError>()
1354                .is_some_and(|commit_err| commit_err.inner().is_duplicate_request()),
1355            _ => false,
1356        }
1357    }
1358
1359    /// Returns `true` if the state failed to commit the block without checking it.
1360    ///
1361    /// The state drops the blocks above a block that failed to commit, and the
1362    /// blocks it can't queue after a reset. (It also fails blocks this way when
1363    /// it is shutting down.)
1364    fn is_unchecked_commit_failure(&self) -> bool {
1365        match self {
1366            VerifyCheckpointError::CommitCheckpointVerified(source) => source
1367                .downcast_ref::<zs::CommitCheckpointVerifiedError>()
1368                .is_some_and(|commit_err| {
1369                    matches!(
1370                        commit_err.inner(),
1371                        zs::CommitBlockError::WriteTaskExited { .. }
1372                    )
1373                }),
1374            _ => false,
1375        }
1376    }
1377
1378    /// Returns `true` if the block's authorizing data doesn't match the commitment in
1379    /// its header.
1380    ///
1381    /// See [`zs::ValidateContextError::is_auth_commitment_mismatch()`].
1382    pub fn is_auth_commitment_mismatch(&self) -> bool {
1383        match self {
1384            VerifyCheckpointError::VerifyBlock(block_error) => {
1385                block_error.is_auth_commitment_mismatch()
1386            }
1387            // Like `is_duplicate_request()`, the boxed `zs::CommitCheckpointVerifiedError`
1388            // newtype must be unwrapped to reach the state's classification.
1389            VerifyCheckpointError::CommitCheckpointVerified(source) => source
1390                .downcast_ref::<zs::CommitCheckpointVerifiedError>()
1391                .is_some_and(|commit_err| commit_err.inner().is_auth_commitment_mismatch()),
1392            _ => false,
1393        }
1394    }
1395
1396    /// Returns `true` if the block's transactions don't match its header.
1397    ///
1398    /// The checkpoint verifier checks this before it uses the block's height.
1399    /// See [`VerifyBlockError::is_body_header_mismatch()`].
1400    pub fn is_body_header_mismatch(&self) -> bool {
1401        match self {
1402            VerifyCheckpointError::VerifyBlock(source) => source.is_body_header_mismatch(),
1403            _ => false,
1404        }
1405    }
1406
1407    /// Returns a suggested misbehaviour score increment for a certain error.
1408    pub fn misbehavior_score(&self) -> u32 {
1409        // TODO: Adjust these values based on zcashd (#9258).
1410        match self {
1411            VerifyCheckpointError::VerifyBlock(verify_block_error) => {
1412                verify_block_error.misbehavior_score()
1413            }
1414            VerifyCheckpointError::SubsidyError(_)
1415            | VerifyCheckpointError::CoinbaseHeight { .. }
1416            | VerifyCheckpointError::DuplicateTransaction
1417            | VerifyCheckpointError::AmountError(_) => 100,
1418            // Checkpoint verification only checks the block hash, which doesn't
1419            // commit to the authorizing data, so a forged body reaches contextual
1420            // validation in the finalized state. Like `is_duplicate_request()`, the
1421            // boxed `zs::CommitCheckpointVerifiedError` newtype must be unwrapped
1422            // for the state's suggested score to reach the peer that served it.
1423            VerifyCheckpointError::CommitCheckpointVerified(source) => source
1424                .downcast_ref::<zs::CommitCheckpointVerifiedError>()
1425                .map_or(0, |commit_err| commit_err.inner().misbehavior_score()),
1426            _other => 0,
1427        }
1428    }
1429}
1430
1431/// The CheckpointVerifier service implementation.
1432///
1433/// After verification, the block futures resolve to their hashes.
1434impl<S> Service<Arc<Block>> for CheckpointVerifier<S>
1435where
1436    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
1437    S::Future: Send + 'static,
1438{
1439    type Response = block::Hash;
1440    type Error = VerifyCheckpointError;
1441    type Future =
1442        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
1443
1444    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1445        Poll::Ready(Ok(()))
1446    }
1447
1448    #[instrument(name = "checkpoint", skip(self, block))]
1449    fn call(&mut self, block: Arc<Block>) -> Self::Future {
1450        // Reset the verifier back to the state tip if requested
1451        // (e.g. due to an error when committing a block to the state)
1452        let mut requeued = false;
1453        while let Ok(CommitFailure { epoch, tip, child }) = self.reset_receiver.try_recv() {
1454            if epoch == self.epoch {
1455                self.reset_progress(tip);
1456                self.epoch = self.epoch.wrapping_add(1);
1457            }
1458
1459            if let Some(child) = child {
1460                self.requeue_child(child);
1461                requeued = true;
1462            }
1463        }
1464        if requeued {
1465            self.process_checkpoint_range();
1466        }
1467
1468        // # Security
1469        //
1470        // Once the final checkpoint is verified, `queue_block()` rejects every block as
1471        // `Finished`. Don't reject them before it checks them: a peer can rewrite the coinbase
1472        // height of the block it was asked for to route it here, and `Finished` would drop that
1473        // block without showing that its body was forged (GHSA-g9rc-89v4-hhvf).
1474        let mut rx = match self.queue_block(block) {
1475            Ok(rx) => rx,
1476            Err(e) => return async { Err(e) }.boxed(),
1477        };
1478
1479        self.process_checkpoint_range();
1480
1481        metrics::gauge!("checkpoint.queued_slots").set(self.queued.len() as f64);
1482
1483        // Because the checkpoint verifier duplicates state from the state
1484        // service (it tracks which checkpoints have been verified), we must
1485        // commit blocks transactionally on a per-checkpoint basis. Otherwise,
1486        // the checkpoint verifier's state could desync from the underlying
1487        // state service. Among other problems, this could cause the checkpoint
1488        // verifier to reject blocks not already in the state as
1489        // already-verified.
1490        //
1491        // # Dropped Receivers
1492        //
1493        // To commit blocks transactionally on a per-checkpoint basis, we must
1494        // commit all verified blocks in a checkpoint range, regardless of
1495        // whether or not the response futures for each block were dropped.
1496        //
1497        // We accomplish this by spawning a new task containing the
1498        // commit-if-verified logic. This task will always execute, except if
1499        // the program is interrupted, in which case there is no longer a
1500        // checkpoint verifier to keep in sync with the state.
1501        //
1502        // # State Commit Failures
1503        //
1504        // If the state commit fails due to corrupt block data,
1505        // we don't reject the entire checkpoint.
1506        // Instead, we reset the verifier to the successfully committed state tip.
1507        // If the state failed the block without checking it, the task queues
1508        // it again, and commits it once it is verified again.
1509        //
1510        // The reset happens in the spawned task, because the verifier has
1511        // already advanced its progress past this block. If the reset happened
1512        // in the returned future, a caller that dropped it (like the syncer
1513        // cancelling its downloads) would leave the verifier ahead of the
1514        // state, and it would reject the blocks it is missing.
1515        let state_service = self.state_service.clone();
1516        let reset_sender = self.reset_sender.clone();
1517        let commit_checkpoint_verified = tokio::spawn(async move {
1518            loop {
1519                let Verified {
1520                    mut block,
1521                    retained,
1522                    epoch,
1523                    previous_sent,
1524                    sent,
1525                } = rx
1526                    .await
1527                    // The verifier can drop a block it got back from a failed commit
1528                    // while it is being dropped.
1529                    .unwrap_or(Err(VerifyCheckpointError::Dropped))?;
1530                let hash = block.hash;
1531
1532                // Send blocks to the state in the order they were verified.
1533                if let Some(previous_sent) = previous_sent {
1534                    let _ = previous_sent.await;
1535                }
1536
1537                // Keep a copy of the block in case the state fails it without checking it.
1538                // Its new outputs are only rebuilt if that happens.
1539                let new_outputs = std::mem::take(&mut block.new_outputs);
1540                let mut child = block.clone();
1541                block.new_outputs = new_outputs;
1542
1543                let mut commit_state_service = state_service.clone();
1544                let result = async move {
1545                    // Every state service `poll_ready` has a corresponding `call`. See #1593.
1546                    let commit = commit_state_service
1547                        .ready()
1548                        .await
1549                        .map_err(VerifyCheckpointError::CommitCheckpointVerified)?
1550                        .call(zs::Request::CommitCheckpointVerifiedBlock(block));
1551
1552                    // The state service got this block first, so the next block can be sent.
1553                    let _ = sent.send(());
1554
1555                    match commit
1556                        .map_err(VerifyCheckpointError::CommitCheckpointVerified)
1557                        .await?
1558                    {
1559                        zs::Response::Committed(committed_hash) => {
1560                            assert_eq!(committed_hash, hash, "state must commit correct hash");
1561                            Ok::<_, VerifyCheckpointError>(hash)
1562                        }
1563                        _ => unreachable!("wrong response for CommitCheckpointVerifiedBlock"),
1564                    }
1565                }
1566                .await;
1567
1568                // Only reset the verifier's progress when a block that the verifier
1569                // accepted failed to commit to the state. Then the verifier's
1570                // progress can be ahead of the state's committed blocks, so it must
1571                // be re-aligned to the state tip.
1572                //
1573                // Other errors are rejections of this specific block (side-chain
1574                // fork candidates, duplicates, or invalid block data). They don't
1575                // change the committed chain, so the verifier's progress stays in
1576                // sync with the state, and resetting would be harmful:
1577                //
1578                // # Correctness
1579                //
1580                // Verified checkpoint ranges commit to the state in height order,
1581                // so the state tip can temporarily lag the verifier's progress
1582                // while a range is still committing. Resetting to that lagging tip
1583                // on unrelated errors rewinds the verifier below the last verified
1584                // checkpoint. The blocks in between have already been consumed
1585                // from the verifier's queue, so verification would stall until
1586                // they are submitted again. The syncer re-downloads them, but
1587                // other submitters (like the zcashd state migration) don't.
1588                if let Err(error @ VerifyCheckpointError::CommitCheckpointVerified(_)) = &result {
1589                    let tip = match state_service
1590                        .clone()
1591                        .oneshot(zs::Request::Tip)
1592                        .await
1593                        .map_err(VerifyCheckpointError::Tip)?
1594                    {
1595                        zs::Response::Tip(tip) => tip,
1596                        _ => unreachable!("wrong response for Tip"),
1597                    };
1598
1599                    // Sending can fail only when the verifier is being dropped,
1600                    // and then it doesn't matter anymore.
1601                    if error.is_unchecked_commit_failure() {
1602                        child.new_outputs = transparent::new_ordered_outputs(
1603                            &child.block,
1604                            &child.transaction_hashes,
1605                        );
1606                        let (tx, child_rx) = oneshot::channel();
1607                        let failure = CommitFailure {
1608                            epoch,
1609                            tip,
1610                            child: Some(QueuedBlock {
1611                                bytes: child.retained_bytes(),
1612                                block: child,
1613                                tx,
1614                                retained,
1615                            }),
1616                        };
1617                        if reset_sender.send(failure).is_ok() {
1618                            rx = child_rx;
1619                            continue;
1620                        }
1621                    } else {
1622                        let _ = reset_sender.send(CommitFailure {
1623                            epoch,
1624                            tip,
1625                            child: None,
1626                        });
1627                    }
1628                }
1629
1630                return result;
1631            }
1632        });
1633
1634        async move {
1635            let result = commit_checkpoint_verified.await;
1636            // Avoid a panic on shutdown
1637            //
1638            // When `zebrad` is terminated using Ctrl-C, the `commit_checkpoint_verified` task
1639            // can return a `JoinError::Cancelled`. We expect task cancellation on shutdown,
1640            // so we don't need to panic here. The persistent state is correct even when the
1641            // task is cancelled, because block data is committed inside transactions, in
1642            // height order.
1643            if zebra_chain::shutdown::is_shutting_down() {
1644                Err(VerifyCheckpointError::ShuttingDown)
1645            } else {
1646                result.expect("commit_checkpoint_verified should not panic")
1647            }
1648        }
1649        .boxed()
1650    }
1651}