Skip to main content

zebra_consensus/
router.rs

1//! Top-level semantic block verification for Zebra.
2//!
3//! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`],
4//! depending on the config and block height.
5//!
6//! # Correctness
7//!
8//! Block and transaction verification requests should be wrapped in a timeout, because:
9//! - checkpoint verification waits for previous blocks, and
10//! - full block and transaction verification wait for UTXOs from previous blocks.
11//!
12//! Otherwise, verification of out-of-order and invalid blocks and transactions can hang
13//! indefinitely.
14
15use core::fmt;
16use std::{
17    future::Future,
18    pin::Pin,
19    sync::Arc,
20    task::{Context, Poll},
21};
22
23use futures::{FutureExt, TryFutureExt};
24use thiserror::Error;
25use tokio::{sync::oneshot, task::JoinHandle};
26use tower::{buffer::Buffer, util::BoxService, Service, ServiceExt};
27use tracing::{instrument, Instrument, Span};
28
29use zebra_chain::{
30    block::{self, Height},
31    parameters::{checkpoint::list::CheckpointList, Network},
32};
33
34use zebra_node_services::mempool;
35use zebra_state as zs;
36
37use crate::{
38    block::{Request, SemanticBlockVerifier, VerifyBlockError},
39    checkpoint::{CheckpointVerifier, VerifyCheckpointError},
40    error::TransactionError,
41    transaction, BoxError, Config,
42};
43
44pub mod service_trait;
45
46#[cfg(test)]
47mod tests;
48
49/// The bound for the chain verifier and transaction verifier buffers.
50///
51/// We choose the verifier buffer bound based on the maximum number of
52/// concurrent verifier users, to avoid contention:
53///   - the `ChainSync` block download and verify stream
54///   - the `Inbound` block download and verify stream
55///   - the `Mempool` transaction download and verify stream
56///   - a block miner component, which we might add in future, and
57///   - 1 extra slot to avoid contention.
58///
59/// We deliberately add extra slots, because they only cost a small amount of
60/// memory, but missing slots can significantly slow down Zebra.
61const VERIFIER_BUFFER_BOUND: usize = 5;
62
63/// The block verifier router routes requests to either the checkpoint verifier or the
64/// semantic block verifier, depending on the maximum checkpoint height.
65///
66/// # Correctness
67///
68/// Block verification requests should be wrapped in a timeout, so that
69/// out-of-order and invalid requests do not hang indefinitely. See the [`router`](`crate::router`)
70/// module documentation for details.
71struct BlockVerifierRouter<S, V>
72where
73    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
74    S::Future: Send + 'static,
75    V: Service<transaction::BlockRequest, Response = transaction::BlockResponse, Error = BoxError>
76        + Send
77        + Clone
78        + 'static,
79    V::Future: Send + 'static,
80{
81    /// The checkpointing block verifier.
82    ///
83    /// Always used for blocks before `Canopy`, optionally used for the entire checkpoint list.
84    checkpoint: CheckpointVerifier<S>,
85
86    /// The highest permitted checkpoint block.
87    ///
88    /// This height must be in the `checkpoint` verifier's checkpoint list.
89    max_checkpoint_height: block::Height,
90
91    /// The full semantic block verifier, used for blocks after `max_checkpoint_height`.
92    block: SemanticBlockVerifier<S, V>,
93}
94
95/// An error while semantically verifying a block.
96//
97// One or both of these error variants are at least 140 bytes
98#[derive(Debug, Error)]
99#[allow(missing_docs)]
100pub enum RouterError {
101    /// Block could not be checkpointed
102    Checkpoint { source: Box<VerifyCheckpointError> },
103    /// Block could not be full-verified
104    Block { source: Box<VerifyBlockError> },
105}
106
107impl fmt::Display for RouterError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str(&match self {
110            RouterError::Checkpoint { source } => {
111                format!("block could not be checkpointed due to: {source}")
112            }
113            RouterError::Block { source } => {
114                format!("block could not be full-verified due to: {source}")
115            }
116        })
117    }
118}
119
120impl From<VerifyCheckpointError> for RouterError {
121    fn from(err: VerifyCheckpointError) -> Self {
122        RouterError::Checkpoint {
123            source: Box::new(err),
124        }
125    }
126}
127
128impl From<VerifyBlockError> for RouterError {
129    fn from(err: VerifyBlockError) -> Self {
130        RouterError::Block {
131            source: Box::new(err),
132        }
133    }
134}
135
136impl RouterError {
137    /// Returns `true` if this is definitely a duplicate request.
138    /// Some duplicate requests might not be detected, and therefore return `false`.
139    pub fn is_duplicate_request(&self) -> bool {
140        match self {
141            RouterError::Checkpoint { source, .. } => source.is_duplicate_request(),
142            RouterError::Block { source, .. } => source.is_duplicate_request(),
143        }
144    }
145
146    /// Returns `true` if the block's authorizing data doesn't match the commitment in
147    /// its header.
148    ///
149    /// See [`zebra_state::ValidateContextError::is_auth_commitment_mismatch()`].
150    pub fn is_auth_commitment_mismatch(&self) -> bool {
151        match self {
152            RouterError::Checkpoint { source, .. } => source.is_auth_commitment_mismatch(),
153            RouterError::Block { source, .. } => source.is_auth_commitment_mismatch(),
154        }
155    }
156
157    /// Returns `true` if the block was rejected because its transactions don't match its header.
158    ///
159    /// See [`VerifyBlockError::is_body_header_mismatch()`].
160    pub fn is_body_header_mismatch(&self) -> bool {
161        match self {
162            RouterError::Checkpoint { source, .. } => source.is_body_header_mismatch(),
163            RouterError::Block { source, .. } => source.is_body_header_mismatch(),
164        }
165    }
166
167    /// Returns `true` if the block was rejected only because an ancestor's authorizing
168    /// data didn't match the commitment in its header.
169    ///
170    /// See [`zebra_state::ValidateContextError::is_descendant_of_auth_commitment_mismatch()`].
171    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
172        match self {
173            // The finalized state drops the descendants of a failed block instead of
174            // rejecting them with an error.
175            RouterError::Checkpoint { .. } => false,
176            RouterError::Block { source, .. } => source.is_descendant_of_auth_commitment_mismatch(),
177        }
178    }
179
180    /// Returns a suggested misbehaviour score increment for a certain error.
181    pub fn misbehavior_score(&self) -> u32 {
182        // TODO: Adjust these values based on zcashd (#9258).
183        match self {
184            RouterError::Checkpoint { source } => source.misbehavior_score(),
185            RouterError::Block { source } => source.misbehavior_score(),
186        }
187    }
188}
189
190impl<S, V> Service<Request> for BlockVerifierRouter<S, V>
191where
192    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
193    S::Future: Send + 'static,
194    V: Service<transaction::BlockRequest, Response = transaction::BlockResponse, Error = BoxError>
195        + Send
196        + Clone
197        + 'static,
198    V::Future: Send + 'static,
199{
200    type Response = block::Hash;
201    type Error = RouterError;
202    type Future =
203        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
204
205    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
206        // CORRECTNESS
207        //
208        // The current task must be scheduled for wakeup every time we return
209        // `Poll::Pending`.
210        //
211        // If either verifier is unready, this task is scheduled for wakeup when it becomes
212        // ready.
213        //
214        // We acquire checkpoint readiness before block readiness, to avoid an unlikely
215        // hang during the checkpoint to block verifier transition. If the checkpoint and
216        // block verifiers are contending for the same buffer/batch, we want the checkpoint
217        // verifier to win, so that checkpoint verification completes, and block verification
218        // can start. (Buffers and batches have multiple slots, so this contention is unlikely.)
219        use futures::ready;
220        // The chain verifier holds one slot in each verifier, for each concurrent task.
221        // Therefore, any shared buffers or batches polled by these verifiers should double
222        // their bounds. (For example, the state service buffer.)
223        ready!(self.checkpoint.poll_ready(cx))?;
224        ready!(self.block.poll_ready(cx))?;
225        Poll::Ready(Ok(()))
226    }
227
228    fn call(&mut self, request: Request) -> Self::Future {
229        let block = request.block();
230
231        match block.coinbase_height() {
232            // There's currently no known use case for block proposals below the checkpoint height,
233            // so it's okay to immediately return an error here.
234            Some(height) if height <= self.max_checkpoint_height && request.is_proposal() => {
235                async {
236                    // TODO: Add a `ValidateProposalError` enum with a `BelowCheckpoint` variant?
237                    Err(VerifyBlockError::ValidateProposal(
238                        "block proposals must be above checkpoint height".into(),
239                    ))?
240                }
241                .boxed()
242            }
243
244            Some(height) if height <= self.max_checkpoint_height => {
245                self.checkpoint.call(block).map_err(Into::into).boxed()
246            }
247            // This also covers blocks with no height, which the block verifier
248            // will reject immediately.
249            _ => self.block.call(request).map_err(Into::into).boxed(),
250        }
251    }
252}
253
254/// Initialize block and transaction verification services.
255///
256/// Returns a block verifier, mempool transaction verifier,
257/// a [`BackgroundTaskHandles`] with the state checkpoint verify task,
258/// and the maximum configured checkpoint verification height.
259///
260/// The consensus configuration is specified by `config`, and the Zcash network
261/// to verify blocks for is specified by `network`.
262///
263/// The block verification service asynchronously performs semantic verification
264/// checks. Blocks that pass semantic verification are submitted to the supplied
265/// `state_service` for contextual verification before being committed to the chain.
266///
267/// The transaction verification service asynchronously performs semantic verification
268/// checks. Transactions that pass semantic verification return an `Ok` result to the caller.
269///
270/// This function should only be called once for a particular state service.
271///
272/// Dropped requests are cancelled on a best-effort basis, but may continue to be processed.
273///
274/// # Correctness
275///
276/// Block and transaction verification requests should be wrapped in a timeout,
277/// so that out-of-order and invalid requests do not hang indefinitely.
278/// See the [`router`](`crate::router`) module documentation for details.
279#[instrument(skip(state_service, mempool))]
280pub async fn init<S, Mempool>(
281    config: Config,
282    network: &Network,
283    mut state_service: S,
284    mempool: oneshot::Receiver<Mempool>,
285) -> (
286    Buffer<BoxService<Request, block::Hash, RouterError>, Request>,
287    Buffer<
288        BoxService<transaction::MempoolRequest, transaction::MempoolResponse, TransactionError>,
289        transaction::MempoolRequest,
290    >,
291    BackgroundTaskHandles,
292    Height,
293)
294where
295    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
296    S::Future: Send + 'static,
297    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
298        + Send
299        + Clone
300        + 'static,
301    Mempool::Future: Send + 'static,
302{
303    // Give other tasks priority before spawning the checkpoint task.
304    tokio::task::yield_now().await;
305
306    // Make sure the state contains the known best chain checkpoints, in a separate thread.
307
308    let checkpoint_state_service = state_service.clone();
309    let checkpoint_sync = config.checkpoint_sync;
310    let checkpoint_network = network.clone();
311
312    let state_checkpoint_verify_handle = tokio::task::spawn(
313        // TODO: move this into an async function?
314        async move {
315            tracing::info!("starting state checkpoint validation");
316
317            // # Consensus
318            //
319            // We want to verify all available checkpoints, even if the node is not configured
320            // to use them for syncing. Zebra's checkpoints are updated with every release,
321            // which makes sure they include the latest settled network upgrade.
322            //
323            // > A network upgrade is settled on a given network when there is a social
324            // > consensus that it has activated with a given activation block hash.
325            // > A full validator that potentially risks Mainnet funds or displays Mainnet
326            // > transaction information to a user MUST do so only for a block chain that
327            // > includes the activation block of the most recent settled network upgrade,
328            // > with the corresponding activation block hash. Currently, there is social
329            // > consensus that NU5 has activated on the Zcash Mainnet and Testnet with the
330            // > activation block hashes given in § 3.12 ‘Mainnet and Testnet’ on p. 20.
331            //
332            // <https://zips.z.cash/protocol/protocol.pdf#blockchain>
333            let full_checkpoints = checkpoint_network.checkpoint_list();
334            let mut already_warned = false;
335
336            for (height, checkpoint_hash) in full_checkpoints.iter() {
337                let checkpoint_state_service = checkpoint_state_service.clone();
338                let request = zebra_state::Request::BestChainBlockHash(*height);
339
340                match checkpoint_state_service.oneshot(request).await {
341                    Ok(zebra_state::Response::BlockHash(Some(state_hash))) => assert_eq!(
342                        *checkpoint_hash, state_hash,
343                        "invalid block in state: a previous Zebra instance followed an \
344                         incorrect chain. Delete and re-sync your state to use the best chain"
345                    ),
346
347                    Ok(zebra_state::Response::BlockHash(None)) => {
348                        if checkpoint_sync {
349                            tracing::info!(
350                                "state is not fully synced yet, remaining checkpoints will be \
351                                 verified during syncing"
352                            );
353                        } else {
354                            tracing::warn!(
355                                "state is not fully synced yet, remaining checkpoints will be \
356                                 verified next time Zebra starts up. Zebra will be less secure \
357                                 until it is restarted. Use consensus.checkpoint_sync = true \
358                                 in zebrad.toml to make sure you are following a valid chain"
359                            );
360                        }
361
362                        break;
363                    }
364
365                    Ok(response) => {
366                        unreachable!("unexpected response type: {response:?} from state request")
367                    }
368                    Err(e) => {
369                        // This error happens a lot in some tests, and it could happen to users.
370                        if !already_warned {
371                            tracing::warn!(
372                                "unexpected error: {e:?} in state request while verifying previous \
373                                 state checkpoints. Is Zebra shutting down?"
374                            );
375                            already_warned = true;
376                        }
377                    }
378                }
379            }
380
381            tracing::info!("finished state checkpoint validation");
382        }
383        .instrument(Span::current()),
384    );
385
386    // transaction verification
387
388    let block_transaction = transaction::BlockTxVerifier::new(network, state_service.clone());
389    let block_transaction = Buffer::new(BoxService::new(block_transaction), VERIFIER_BUFFER_BOUND);
390
391    let mempool_transaction =
392        transaction::MempoolTxVerifier::new(network, state_service.clone(), mempool);
393    let mempool_transaction =
394        Buffer::new(BoxService::new(mempool_transaction), VERIFIER_BUFFER_BOUND);
395
396    // block verification
397    let (list, max_checkpoint_height) = init_checkpoint_list(config, network);
398
399    let tip = match state_service
400        .ready()
401        .await
402        .unwrap()
403        .call(zs::Request::Tip)
404        .await
405        .unwrap()
406    {
407        zs::Response::Tip(tip) => tip,
408        _ => unreachable!("wrong response to Request::Tip"),
409    };
410    tracing::info!(
411        ?tip,
412        ?max_checkpoint_height,
413        "initializing block verifier router"
414    );
415
416    let block =
417        SemanticBlockVerifier::new(network, state_service.clone(), block_transaction.clone());
418    let checkpoint = CheckpointVerifier::from_checkpoint_list(list, network, tip, state_service);
419    let router = BlockVerifierRouter {
420        checkpoint,
421        max_checkpoint_height,
422        block,
423    };
424
425    let router = Buffer::new(BoxService::new(router), VERIFIER_BUFFER_BOUND);
426
427    let task_handles = BackgroundTaskHandles {
428        state_checkpoint_verify_handle,
429    };
430
431    (
432        router,
433        mempool_transaction,
434        task_handles,
435        max_checkpoint_height,
436    )
437}
438
439/// Parses the checkpoint list for `network` and `config`.
440/// Returns the checkpoint list and maximum checkpoint height.
441pub fn init_checkpoint_list(config: Config, network: &Network) -> (Arc<CheckpointList>, Height) {
442    // TODO: Zebra parses the checkpoint list three times at startup.
443    //       Instead, cache the checkpoint list for each `network`.
444    let list = network.checkpoint_list();
445
446    let max_checkpoint_height = if config.checkpoint_sync {
447        list.max_height()
448    } else {
449        list.min_height_in_range(network.mandatory_checkpoint_height()..)
450            .expect("hardcoded checkpoint list extends past canopy activation")
451    };
452
453    (list, max_checkpoint_height)
454}
455
456/// The background task handles for `zebra-consensus` verifier initialization.
457#[derive(Debug)]
458pub struct BackgroundTaskHandles {
459    /// A handle to the state checkpoint verify task.
460    /// Finishes when all the checkpoints are verified, or when the state tip is reached.
461    pub state_checkpoint_verify_handle: JoinHandle<()>,
462}
463
464/// Calls [`init`] with a closed mempool setup channel for conciseness in tests.
465///
466/// See [`init`] for more details.
467#[cfg(any(test, feature = "proptest-impl"))]
468pub async fn init_test<S>(
469    config: Config,
470    network: &Network,
471    state_service: S,
472) -> (
473    Buffer<BoxService<Request, block::Hash, RouterError>, Request>,
474    Buffer<
475        BoxService<transaction::MempoolRequest, transaction::MempoolResponse, TransactionError>,
476        transaction::MempoolRequest,
477    >,
478    BackgroundTaskHandles,
479    Height,
480)
481where
482    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
483    S::Future: Send + 'static,
484{
485    init(
486        config.clone(),
487        network,
488        state_service.clone(),
489        oneshot::channel::<
490            Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>,
491        >()
492        .1,
493    )
494    .await
495}