Skip to main content

zebra_consensus/
block.rs

1//! Consensus-based block verification.
2//!
3//! In contrast to checkpoint verification, which only checks hardcoded
4//! hashes, block verification checks all Zcash consensus rules.
5//!
6//! The block verifier performs all of the semantic validation checks.
7//! If accepted, the block is sent to the state service for contextual
8//! verification, where it may be accepted or rejected.
9
10use std::{
11    future::Future,
12    pin::Pin,
13    sync::Arc,
14    task::{Context, Poll},
15    time::Instant,
16};
17
18use chrono::Utc;
19use futures::stream::FuturesUnordered;
20use futures_util::FutureExt;
21use thiserror::Error;
22use tower::{Service, ServiceExt};
23use tracing::Instrument;
24
25use zebra_chain::{
26    amount::Amount,
27    block,
28    parameters::{subsidy::SubsidyError, Network},
29    transparent,
30    work::equihash,
31};
32use zebra_state as zs;
33
34use crate::{error::*, transaction as tx, BoxError};
35
36pub mod check;
37pub mod request;
38
39pub use request::Request;
40
41#[cfg(test)]
42mod tests;
43
44/// Asynchronous semantic block verification.
45#[derive(Debug)]
46pub struct SemanticBlockVerifier<S, V> {
47    /// The network to be verified.
48    network: Network,
49    state_service: S,
50    transaction_verifier: V,
51}
52
53/// Block verification errors.
54// TODO: dedupe with crate::error::BlockError
55#[non_exhaustive]
56#[allow(missing_docs)]
57#[derive(Debug, Error)]
58pub enum VerifyBlockError {
59    #[error("unable to verify depth for block {hash} from chain state during block verification")]
60    Depth { source: BoxError, hash: block::Hash },
61
62    #[error(transparent)]
63    Block {
64        #[from]
65        source: BlockError,
66    },
67
68    #[error(transparent)]
69    Equihash {
70        #[from]
71        source: equihash::Error,
72    },
73
74    #[error(transparent)]
75    Time(zebra_chain::block::BlockTimeError),
76
77    /// Error when attempting to commit a block after semantic verification.
78    #[error("unable to commit block after semantic verification: {0}")]
79    Commit(#[from] zs::CommitBlockError),
80
81    #[error("unable to validate block proposal: failed semantic verification (proof of work is not checked for proposals): {0}")]
82    // TODO: make this into a concrete type (see #5732)
83    ValidateProposal(#[source] BoxError),
84
85    #[error("invalid transaction: {0}")]
86    Transaction(#[from] TransactionError),
87
88    #[error("invalid block subsidy: {0}")]
89    Subsidy(#[from] SubsidyError),
90
91    /// Errors originating from the state service, which may arise from general failures in interacting with the state.
92    /// This is for errors that are not specifically related to block depth or commit failures.
93    #[error("state service error for block {hash}: {source}")]
94    StateService { source: BoxError, hash: block::Hash },
95}
96
97impl VerifyBlockError {
98    /// Returns `true` if this is definitely a duplicate request.
99    /// Some duplicate requests might not be detected, and therefore return `false`.
100    pub fn is_duplicate_request(&self) -> bool {
101        match self {
102            VerifyBlockError::Block { source, .. } => source.is_duplicate_request(),
103            VerifyBlockError::Commit(commit_err) => commit_err.is_duplicate_request(),
104            _ => false,
105        }
106    }
107
108    /// Returns `true` if the block's authorizing data doesn't match the commitment in
109    /// its header.
110    ///
111    /// See [`zs::ValidateContextError::is_auth_commitment_mismatch()`].
112    pub fn is_auth_commitment_mismatch(&self) -> bool {
113        match self {
114            VerifyBlockError::Commit(commit_err) => commit_err.is_auth_commitment_mismatch(),
115            _ => false,
116        }
117    }
118
119    /// Returns `true` if the block was rejected because its transactions don't match its header,
120    /// in one of the checks that run before its height is used:
121    /// - the transaction IDs don't match the header's Merkle root,
122    /// - the transactions contain duplicates that keep the Merkle root (CVE-2012-2459), or
123    /// - a V5 or later coinbase claims a height other than its expiry height.
124    ///
125    /// The block hash only commits to the header, so a peer that serves a body for a requested
126    /// block hash can still send the wrong transactions. The block itself can still be valid.
127    pub fn is_body_header_mismatch(&self) -> bool {
128        matches!(
129            self,
130            VerifyBlockError::Block {
131                source: BlockError::BadMerkleRoot { .. }
132                    | BlockError::DuplicateTransaction
133                    | BlockError::Transaction(TransactionError::CoinbaseExpiryBlockHeight { .. }),
134            }
135        )
136    }
137
138    /// Returns `true` if the block was rejected only because an ancestor's authorizing
139    /// data didn't match the commitment in its header.
140    ///
141    /// See [`zs::ValidateContextError::is_descendant_of_auth_commitment_mismatch()`].
142    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
143        match self {
144            VerifyBlockError::Commit(commit_err) => {
145                commit_err.is_descendant_of_auth_commitment_mismatch()
146            }
147            _ => false,
148        }
149    }
150
151    /// Returns a suggested misbehaviour score increment for a certain error.
152    pub fn misbehavior_score(&self) -> u32 {
153        use VerifyBlockError::*;
154        match self {
155            Block { source } => source.misbehavior_score(),
156            Equihash { .. } | Subsidy(_) => 100,
157            Transaction(err) => err.mempool_misbehavior_score(),
158            Commit(err) => err.misbehavior_score(),
159            _other => 0,
160        }
161    }
162}
163
164/// Records the time since `phase_start` as the block verifier phase `phase`, then restarts the
165/// timer for the next phase.
166fn record_phase(phase: &'static str, phase_start: &mut Instant) {
167    let now = Instant::now();
168    metrics::histogram!("zebra.consensus.block.phase.duration_seconds", "phase" => phase)
169        .record(now.duration_since(*phase_start).as_secs_f64());
170    *phase_start = now;
171}
172
173/// Converts an error from a `CommitSemanticallyVerifiedBlock` state request
174/// into a [`VerifyBlockError`].
175///
176/// The state boxes commit errors as [`zs::CommitSemanticallyVerifiedError`], a
177/// newtype around [`zs::CommitBlockError`], so the wrapper must be unwrapped
178/// here for `is_duplicate_request()` and `misbehavior_score()` to classify
179/// duplicate blocks as benign.
180fn map_commit_error(source: BoxError, hash: block::Hash) -> VerifyBlockError {
181    if let Some(commit_err) = source
182        .downcast_ref::<zs::CommitSemanticallyVerifiedError>()
183        .map(zs::CommitSemanticallyVerifiedError::inner)
184        .or_else(|| source.downcast_ref::<zs::CommitBlockError>())
185    {
186        return VerifyBlockError::Commit(commit_err.clone());
187    }
188
189    VerifyBlockError::StateService { source, hash }
190}
191
192/// The maximum number of transparent signature operations allowed in a block.
193///
194/// # Consensus
195///
196/// For every block, the sum of legacy and P2SH transparent signature operations across all
197/// transactions must not exceed [20_000].
198///
199/// ## Notes
200///
201/// This rule is inherited from pre-SegWit Bitcoin, and is not explicitly stated in the Zcash
202/// protocol spec. It is covered implicitly in [§7.6], which closes with "Other rules inherited from
203/// Bitcoin". The inclusion of this rule is tracked in [`zcash/zips#568`].
204///
205/// Zebra mirrors `zcashd`'s `ConnectBlock`, which sums `GetLegacySigOpCount()` and
206/// `GetP2SHSigOpCount()` per transaction before comparing against this constant.
207///
208/// [20_000]: <https://github.com/zcash/zcash/blob/bad7f7eadbbb3466bebe3354266c7f69f607fcfd/src/consensus/consensus.h#L30>
209/// [`zcash/zips#568`]: <https://github.com/zcash/zips/issues/568>
210/// [§7.6]: <https://zips.z.cash/protocol/protocol.pdf#blockheader>
211pub const MAX_BLOCK_SIGOPS: u32 = 20_000;
212
213/// The [ZIP 218] per-pool and global shielded action limits, which apply from NU7 activation.
214///
215/// `GlobalShieldedBudget`, `OrchardProtocolBlockActionLimit`, `SaplingBlockIOLimit` and
216/// `SproutBlockJoinSplitLimit` in the ZIP. Orchard and Ironwood share the global budget and
217/// have the same per-pool action limit. Sprout JoinSplits are prohibited.
218///
219/// [ZIP 218]: https://zips.z.cash/zip-0218
220pub const GLOBAL_SHIELDED_BUDGET: usize = 330;
221/// The per-pool action limit for both Orchard and Ironwood. See [`GLOBAL_SHIELDED_BUDGET`].
222pub const ORCHARD_BLOCK_ACTION_LIMIT: usize = 330;
223/// See [`GLOBAL_SHIELDED_BUDGET`].
224pub const SAPLING_BLOCK_IO_LIMIT: usize = 300;
225/// See [`GLOBAL_SHIELDED_BUDGET`].
226pub const SPROUT_BLOCK_JOIN_SPLIT_LIMIT: usize = 0;
227
228/// The shielded components that the [ZIP 218] action limits count.
229///
230/// Shared by the block verifier's limit check and by `getblocktemplate` transaction selection, so
231/// that a template can not be built from transactions the verifier would then reject.
232///
233/// [ZIP 218]: https://zips.z.cash/zip-0218
234#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
235pub struct ShieldedActionCounts {
236    /// The number of Orchard actions.
237    pub orchard_actions: usize,
238    /// The number of Ironwood actions.
239    pub ironwood_actions: usize,
240    /// The number of Sapling inputs plus outputs.
241    pub sapling_io: usize,
242    /// The number of Sprout JoinSplits.
243    pub joinsplits: usize,
244}
245
246impl ShieldedActionCounts {
247    /// Returns the counts for `transaction`.
248    pub fn from_transaction(transaction: &zebra_chain::transaction::Transaction) -> Self {
249        Self {
250            orchard_actions: transaction.orchard_actions().count(),
251            ironwood_actions: transaction.ironwood_actions().count(),
252            sapling_io: transaction
253                .sapling_spends_count()
254                .saturating_add(transaction.sapling_outputs().count()),
255            joinsplits: transaction.joinsplit_count(),
256        }
257    }
258
259    /// Returns these counts plus `other`.
260    ///
261    /// Saturating, so that a malformed count can not wrap back below a limit.
262    pub fn saturating_add(self, other: Self) -> Self {
263        Self {
264            orchard_actions: self.orchard_actions.saturating_add(other.orchard_actions),
265            ironwood_actions: self.ironwood_actions.saturating_add(other.ironwood_actions),
266            sapling_io: self.sapling_io.saturating_add(other.sapling_io),
267            joinsplits: self.joinsplits.saturating_add(other.joinsplits),
268        }
269    }
270
271    /// Returns the total shielded cost, which each JoinSplit contributes twice to, because it
272    /// produces two shielded outputs.
273    pub fn shielded_cost(&self) -> usize {
274        self.orchard_actions
275            .saturating_add(self.ironwood_actions)
276            .saturating_add(self.sapling_io)
277            .saturating_add(self.joinsplits.saturating_mul(2))
278    }
279
280    /// Returns the first limit these counts exceed, as `(pool, count, limit)`.
281    pub fn exceeded_limit(&self) -> Option<(&'static str, usize, usize)> {
282        [
283            (
284                "Orchard actions",
285                self.orchard_actions,
286                ORCHARD_BLOCK_ACTION_LIMIT,
287            ),
288            (
289                "Ironwood actions",
290                self.ironwood_actions,
291                ORCHARD_BLOCK_ACTION_LIMIT,
292            ),
293            (
294                "Sapling inputs and outputs",
295                self.sapling_io,
296                SAPLING_BLOCK_IO_LIMIT,
297            ),
298            (
299                "Sprout JoinSplits",
300                self.joinsplits,
301                SPROUT_BLOCK_JOIN_SPLIT_LIMIT,
302            ),
303            (
304                "shielded actions across all pools",
305                self.shielded_cost(),
306                GLOBAL_SHIELDED_BUDGET,
307            ),
308        ]
309        .into_iter()
310        .find(|&(_, count, limit)| count > limit)
311    }
312}
313
314impl<S, V> SemanticBlockVerifier<S, V>
315where
316    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
317    S::Future: Send + 'static,
318    V: Service<tx::BlockRequest, Response = tx::BlockResponse, Error = BoxError>
319        + Send
320        + Clone
321        + 'static,
322    V::Future: Send + 'static,
323{
324    /// Creates a new SemanticBlockVerifier
325    pub fn new(network: &Network, state_service: S, transaction_verifier: V) -> Self {
326        Self {
327            network: network.clone(),
328            state_service,
329            transaction_verifier,
330        }
331    }
332}
333
334impl<S, V> Service<Request> for SemanticBlockVerifier<S, V>
335where
336    S: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
337    S::Future: Send + 'static,
338    V: Service<tx::BlockRequest, Response = tx::BlockResponse, Error = BoxError>
339        + Send
340        + Clone
341        + 'static,
342    V::Future: Send + 'static,
343{
344    type Response = block::Hash;
345    type Error = VerifyBlockError;
346    type Future =
347        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
348
349    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
350        // We use the state for contextual verification, and we expect those
351        // queries to be fast. So we don't need to call
352        // `state_service.poll_ready()` here.
353        Poll::Ready(Ok(()))
354    }
355
356    fn call(&mut self, request: Request) -> Self::Future {
357        // Stamp the time the verifier received this block: the non-finalized state's
358        // `Chain::cmp` uses it to prefer the first-received chain on equal-work ties.
359        let received_time = Instant::now();
360
361        let mut state_service = self.state_service.clone();
362        let mut transaction_verifier = self.transaction_verifier.clone();
363        let network = self.network.clone();
364
365        let block = request.block();
366
367        // We don't include the block hash, because it's likely already in a parent span
368        let span = tracing::debug_span!("block", height = ?block.coinbase_height());
369
370        async move {
371            let hash = block.hash();
372            // Check that this block is actually a new block.
373            tracing::trace!("checking that block is not already in state");
374            match state_service
375                .ready()
376                .await
377                .map_err(|source| VerifyBlockError::Depth { source, hash })?
378                .call(zs::Request::KnownBlock(hash))
379                .await
380                .map_err(|source| VerifyBlockError::Depth { source, hash })?
381            {
382                zs::Response::KnownBlock(Some(location)) => {
383                    return Err(BlockError::AlreadyInChain(hash, location).into())
384                }
385                zs::Response::KnownBlock(None) => {}
386                _ => unreachable!("wrong response to Request::KnownBlock"),
387            }
388
389            tracing::trace!("performing block checks");
390            // The template precompute verifies every template as a proposal, so timing proposals
391            // would mix template checks into the timings of blocks that are committed.
392            let record_phases = !request.is_proposal();
393            let mut phase_start = Instant::now();
394            let height = block
395                .coinbase_height()
396                .ok_or(BlockError::MissingHeight(hash))?;
397
398            // Zebra does not support heights greater than
399            // [`block::Height::MAX`].
400            if height > block::Height::MAX {
401                Err(BlockError::MaxHeight(height, hash, block::Height::MAX))?;
402            }
403
404            // > The block data MUST be validated and checked against the server's usual
405            // > acceptance rules (excluding the check for a valid proof-of-work).
406            // <https://en.bitcoin.it/wiki/BIP_0023#Block_Proposal>
407            if request.is_proposal() || network.disable_pow() {
408                check::difficulty_threshold_is_valid(&block.header, &network, &height, &hash)?;
409            } else {
410                // Do the difficulty checks first, to raise the threshold for
411                // attacks that use any other fields.
412                check::difficulty_is_valid(&block.header, &network, &height, &hash)?;
413                check::equihash_solution_is_valid(&block.header)?;
414            }
415
416            // # Security
417            //
418            // Check that the header commits to the coinbase height before anything uses it, as the
419            // checkpoint verifier does. A peer can rewrite the height of a V5 coinbase without
420            // changing the Merkle root. `merkle_root_validity()` uses the height to pick the
421            // network upgrade for its consensus branch ID check, and the checks after it use the
422            // height before the transaction verifier checks the coinbase expiry height against it.
423            // So a rewritten height would get the block checked at that height, or rejected for an
424            // error that doesn't show the body was forged (GHSA-g9rc-89v4-hhvf).
425            //
426            // The height is only authenticated once the Merkle root check also passes, but either
427            // failure shows that the body was forged.
428            check::coinbase_height_is_committed(&block, height)?;
429
430            // Next, check the Merkle root validity, to ensure that
431            // the header binds to the transactions in the blocks.
432
433            // Precomputing this avoids duplicating transaction hash computations.
434            let transaction_hashes: Arc<[_]> =
435                block.transactions.iter().map(|t| t.hash()).collect();
436
437            check::merkle_root_validity(&network, &block, &transaction_hashes)?;
438
439            // Since errors cause an early exit, try to do the
440            // quick checks first.
441
442            // Quick field validity and structure checks
443            let now = Utc::now();
444            check::time_is_valid_at(&block.header, now, &height, &hash)
445                .map_err(VerifyBlockError::Time)?;
446            let coinbase_tx = check::coinbase_is_first(&block)?;
447
448            // From the NSM reissuance height, the block subsidy depends on the
449            // NSM value balance after the parent block, which is not committed yet while
450            // blocks are verified concurrently. The state checks the subsidy, funding streams,
451            // and miner fees during contextual validation instead, where the parent's chain value
452            // pools are known.
453            let nsm_reissuance_is_active =
454                zebra_chain::parameters::subsidy::nsm_reissuance_is_active(height, &network);
455
456            let expected_subsidy_and_deferred_pool_balance_change = if nsm_reissuance_is_active {
457                None
458            } else {
459                let expected_block_subsidy =
460                    zebra_chain::parameters::subsidy::block_subsidy(height, &network)?;
461
462                // See [ZIP-1015](https://zips.z.cash/zip-1015).
463                let deferred_pool_balance_change =
464                    check::subsidy_is_valid(&block, &network, expected_block_subsidy)?;
465
466                Some((expected_block_subsidy, deferred_pool_balance_change))
467            };
468
469            // Bound shielded work before output recovery or proof verification.
470            check::shielded_action_limits_are_valid(&block, &network, height, hash)?;
471
472            // Now do the slower checks
473
474            // Check compatibility with ZIP-212 shielded Sapling and Orchard coinbase output decryption
475            tx::check::coinbase_outputs_are_decryptable(&coinbase_tx, &network, height)?;
476
477            if record_phases {
478                record_phase("block_checks", &mut phase_start);
479            }
480
481            // Send transactions to the transaction verifier to be checked
482            let mut async_checks = FuturesUnordered::new();
483
484            let known_utxos = Arc::new(transparent::new_ordered_outputs(
485                &block,
486                &transaction_hashes,
487            ));
488
489            for (&transaction_hash, transaction) in
490                transaction_hashes.iter().zip(block.transactions.iter())
491            {
492                let rsp = transaction_verifier
493                    .ready()
494                    .await
495                    .expect("transaction verifier is always ready")
496                    .call(tx::BlockRequest {
497                        transaction_hash,
498                        transaction: transaction.clone(),
499                        known_utxos: known_utxos.clone(),
500                        height,
501                        time: block.header.time,
502                    });
503                async_checks.push(rsp);
504            }
505            tracing::trace!(len = async_checks.len(), "built async tx checks");
506
507            // Get the transaction results back from the transaction verifier.
508
509            // Sum up some block totals from the transaction responses.
510            let mut sigops = 0;
511            let mut block_miner_fees = Ok(Amount::zero());
512
513            use futures::StreamExt;
514            while let Some(result) = async_checks.next().await {
515                tracing::trace!(?result, remaining = async_checks.len());
516                let response = result
517                    .map_err(Into::into)
518                    .map_err(VerifyBlockError::Transaction)?;
519
520                sigops += response.sigops;
521
522                // Coinbase transactions consume the miner fee,
523                // so they don't add any value to the block's total miner fee.
524                if let Some(miner_fee) = response.miner_fee {
525                    block_miner_fees += miner_fee;
526                }
527            }
528
529            // Check the summed block totals
530
531            if sigops > MAX_BLOCK_SIGOPS {
532                Err(BlockError::TooManyTransparentSignatureOperations {
533                    height,
534                    hash,
535                    sigops,
536                })?;
537            }
538
539            let block_miner_fees =
540                block_miner_fees.map_err(|amount_error| BlockError::SummingMinerFees {
541                    height,
542                    hash,
543                    source: amount_error,
544                })?;
545
546            if let Some((expected_block_subsidy, deferred_pool_balance_change)) =
547                expected_subsidy_and_deferred_pool_balance_change
548            {
549                check::miner_fees_are_valid(
550                    &coinbase_tx,
551                    height,
552                    block_miner_fees,
553                    expected_block_subsidy,
554                    deferred_pool_balance_change,
555                    &network,
556                )?;
557            }
558
559            if record_phases {
560                record_phase("transaction_verification", &mut phase_start);
561            }
562
563            // Finally, submit the block for contextual verification.
564            let new_outputs = Arc::into_inner(known_utxos)
565                .expect("all verification tasks using known_utxos are complete");
566
567            let prepared_block = zs::SemanticallyVerifiedBlock {
568                block,
569                hash,
570                height,
571                new_outputs,
572                transaction_hashes,
573                received_time: Some(received_time),
574            };
575
576            // Return early for proposal requests.
577            if request.is_proposal() {
578                return match state_service
579                    .ready()
580                    .await
581                    .map_err(VerifyBlockError::ValidateProposal)?
582                    .call(zs::Request::CheckBlockProposalValidity(prepared_block))
583                    .await
584                    .map_err(VerifyBlockError::ValidateProposal)?
585                {
586                    zs::Response::ValidBlockProposal => Ok(hash),
587                    _ => unreachable!("wrong response for CheckBlockProposalValidity"),
588                };
589            }
590
591            match state_service
592                .ready()
593                .await
594                .map_err(|source| VerifyBlockError::StateService { source, hash })?
595                .call(zs::Request::CommitSemanticallyVerifiedBlock(prepared_block))
596                .await
597            {
598                Ok(zs::Response::Committed(committed_hash)) => {
599                    assert_eq!(committed_hash, hash, "state must commit correct hash");
600                    record_phase("state_commit", &mut phase_start);
601                    Ok(hash)
602                }
603
604                Err(source) => Err(map_commit_error(source, hash)),
605
606                _ => unreachable!("wrong response for CommitSemanticallyVerifiedBlock"),
607            }
608        }
609        .instrument(span)
610        .boxed()
611    }
612}