Skip to main content

zebra_state/
error.rs

1//! Error types for Zebra's state.
2
3use std::{path::PathBuf, sync::Arc};
4
5use chrono::{DateTime, Utc};
6use derive_new::new;
7use thiserror::Error;
8
9use tokio::sync::broadcast::error::RecvError;
10use zebra_chain::{
11    amount::{self, NegativeAllowed, NonNegative},
12    block,
13    history_tree::HistoryTreeError,
14    ironwood, orchard, sapling, sprout, transaction, transparent,
15    value_balance::{ValueBalance, ValueBalanceError},
16    work::difficulty::CompactDifficulty,
17};
18
19use crate::{constants::MIN_TRANSPARENT_COINBASE_MATURITY, HashOrHeight, KnownBlock};
20
21/// A wrapper for type erased errors that is itself clonable and implements the
22/// Error trait
23#[derive(Debug, Error, Clone)]
24#[error(transparent)]
25pub struct CloneError {
26    source: Arc<dyn std::error::Error + Send + Sync + 'static>,
27}
28
29impl From<CommitSemanticallyVerifiedError> for CloneError {
30    fn from(source: CommitSemanticallyVerifiedError) -> Self {
31        let source = Arc::new(source);
32        Self { source }
33    }
34}
35
36impl From<BoxError> for CloneError {
37    fn from(source: BoxError) -> Self {
38        let source = Arc::from(source);
39        Self { source }
40    }
41}
42
43/// A boxed [`std::error::Error`].
44pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
45
46/// A known finalized block cannot be read as a complete block.
47///
48/// Unknown blocks and incomplete secondary views return `Ok(None)` instead. Missing primary bodies
49/// indicate corruption until historical body pruning is supported.
50#[derive(Debug, Error, Clone, PartialEq, Eq)]
51pub enum BlockReadError {
52    /// Some or all transaction rows are missing from a known block.
53    #[error("block body unavailable at height {height:?}: stored transactions are incomplete")]
54    BlockBodyUnavailable {
55        /// The height of the known block.
56        height: block::Height,
57    },
58
59    /// The retained header or transaction-location index is inconsistent.
60    #[error("corrupt block metadata at height {height:?}")]
61    CorruptBlock {
62        /// The height of the known block.
63        height: block::Height,
64    },
65}
66
67/// An error describing why opening the finalized state database failed.
68///
69/// These errors are recoverable open-time failures that the caller can report,
70/// as opposed to invariant violations that indicate a bug.
71#[derive(Debug, Error)]
72#[non_exhaustive]
73pub enum StateInitError {
74    /// A read-only state was requested, but the configured cache directory is
75    /// missing or unreadable.
76    ///
77    /// A read-only secondary instance must never create the primary's cache
78    /// directory, so a missing or unreadable directory is a fatal configuration
79    /// error rather than something to be created.
80    #[error(
81        "cannot open read-only state: cache directory {path:?} is missing or unreadable. \
82         Hint: a read-only state requires an existing Zebra cache directory; check that the \
83         state cache_dir in the Zebra config points at a running Zebra node's cache directory"
84    )]
85    ReadOnlyCacheDirUnreadable {
86        /// The configured cache directory that could not be read.
87        path: PathBuf,
88        /// The underlying I/O error returned while reading the directory.
89        source: std::io::Error,
90    },
91
92    /// A read-only state was requested, but no database exists at the expected
93    /// path.
94    ///
95    /// A read-only secondary instance cannot create a database, so the absence
96    /// of an existing database is a fatal configuration error.
97    #[error(
98        "cannot open read-only state: no database found at {path:?}. \
99         Hint: a read-only state requires an existing finalized database created by a running \
100         Zebra node; check that the state cache_dir in the Zebra config points at that node's \
101         cache directory"
102    )]
103    ReadOnlyDatabaseNotFound {
104        /// The database path at which no database was found.
105        path: PathBuf,
106    },
107
108    /// A read-only state was requested together with an ephemeral database.
109    ///
110    /// A read-only secondary follows another process's primary database and must
111    /// never delete it, whereas an ephemeral database deletes its files on drop. The
112    /// two are mutually exclusive, so requesting both is a fatal configuration error.
113    #[error(
114        "cannot open read-only state: an ephemeral database was also requested. \
115         Hint: a read-only state follows an existing Zebra node's database and must not \
116         delete it; set `ephemeral = false`, or do not request a read-only state"
117    )]
118    ReadOnlyEphemeralConflict,
119}
120
121/// An error describing why a block could not be queued to be committed to the state.
122#[derive(Debug, Error, Clone, PartialEq, Eq, new)]
123pub enum CommitBlockError {
124    #[error("block hash is a duplicate: already in {location}")]
125    /// The block is a duplicate: it is already queued or committed in the state.
126    Duplicate {
127        /// Hash or height of the duplicated block.
128        hash_or_height: Option<HashOrHeight>,
129        /// Location in the state where the block can be found.
130        location: KnownBlock,
131    },
132
133    /// Contextual validation failed.
134    #[error("could not contextually validate semantically verified block")]
135    ValidateContextError(#[from] Box<ValidateContextError>),
136
137    /// The write task exited (likely during shutdown).
138    #[error("block commit task exited. Is Zebra shutting down?")]
139    #[non_exhaustive]
140    WriteTaskExited,
141
142    /// The queue of blocks waiting for their parent blocks was full, so the state dropped this
143    /// block. It might be valid.
144    #[error("block was dropped from the full queue of blocks waiting for their parent blocks")]
145    OrphanQueueFull,
146}
147
148impl CommitBlockError {
149    /// Returns `true` if this is definitely a duplicate commit request.
150    /// Some duplicate requests might not be detected, and therefore return `false`.
151    pub fn is_duplicate_request(&self) -> bool {
152        matches!(self, CommitBlockError::Duplicate { .. })
153    }
154
155    /// Returns `true` if the block's authorizing data doesn't match the commitment in
156    /// its header.
157    ///
158    /// See [`ValidateContextError::is_auth_commitment_mismatch()`] for why this is
159    /// tracked separately from the misbehaviour score: the served body is invalid, but
160    /// the block hash is still valid and still wanted, so the syncer re-requests it
161    /// instead of restarting the sync round.
162    pub fn is_auth_commitment_mismatch(&self) -> bool {
163        match self {
164            CommitBlockError::ValidateContextError(err) => err.is_auth_commitment_mismatch(),
165            CommitBlockError::Duplicate { .. }
166            | CommitBlockError::WriteTaskExited
167            | CommitBlockError::OrphanQueueFull => false,
168        }
169    }
170
171    /// Returns `true` if the block was rejected only because an ancestor's authorizing
172    /// data didn't match the commitment in its header.
173    ///
174    /// See [`ValidateContextError::is_descendant_of_auth_commitment_mismatch()`].
175    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
176        match self {
177            CommitBlockError::ValidateContextError(err) => {
178                err.is_descendant_of_auth_commitment_mismatch()
179            }
180            CommitBlockError::Duplicate { .. }
181            | CommitBlockError::WriteTaskExited
182            | CommitBlockError::OrphanQueueFull => false,
183        }
184    }
185
186    /// Returns a suggested misbehaviour score increment for a certain error.
187    ///
188    /// Consensus-invalid subsidies and authorizing-data commitments score 100.
189    /// Duplicate requests, shutdowns, full queues, and rejected-ancestor descendants score 0.
190    pub fn misbehavior_score(&self) -> u32 {
191        match self {
192            CommitBlockError::ValidateContextError(err) => err.misbehavior_score(),
193            CommitBlockError::Duplicate { .. }
194            | CommitBlockError::WriteTaskExited
195            | CommitBlockError::OrphanQueueFull => 0,
196        }
197    }
198}
199
200/// An error describing why a `CommitSemanticallyVerified` request failed.
201#[derive(Debug, Error, Clone, PartialEq, Eq)]
202#[error("could not commit semantically-verified block")]
203pub struct CommitSemanticallyVerifiedError(#[from] CommitBlockError);
204
205impl CommitSemanticallyVerifiedError {
206    /// Returns the [`CommitBlockError`] describing why the commit failed.
207    pub fn inner(&self) -> &CommitBlockError {
208        &self.0
209    }
210}
211
212impl From<ValidateContextError> for CommitSemanticallyVerifiedError {
213    fn from(value: ValidateContextError) -> Self {
214        Self(CommitBlockError::ValidateContextError(Box::new(value)))
215    }
216}
217
218#[derive(Debug, Error)]
219pub enum LayeredStateError<E: std::error::Error + std::fmt::Display> {
220    #[error("{0}")]
221    State(E),
222    #[error("{0}")]
223    Layer(BoxError),
224}
225
226impl<E: std::error::Error + 'static> From<BoxError> for LayeredStateError<E> {
227    fn from(err: BoxError) -> Self {
228        match err.downcast::<E>() {
229            Ok(state_err) => Self::State(*state_err),
230            Err(layer_error) => Self::Layer(layer_error),
231        }
232    }
233}
234
235/// An error describing why a `CommitCheckpointVerifiedBlock` request failed.
236#[derive(Debug, Error, Clone)]
237#[error("could not commit checkpoint-verified block")]
238pub struct CommitCheckpointVerifiedError(#[from] CommitBlockError);
239
240impl CommitCheckpointVerifiedError {
241    /// Returns the [`CommitBlockError`] describing why the commit failed.
242    pub fn inner(&self) -> &CommitBlockError {
243        &self.0
244    }
245}
246
247impl From<ValidateContextError> for CommitCheckpointVerifiedError {
248    fn from(value: ValidateContextError) -> Self {
249        Self(CommitBlockError::ValidateContextError(Box::new(value)))
250    }
251}
252
253/// An error describing why a `InvalidateBlock` request failed.
254#[derive(Debug, Error)]
255#[non_exhaustive]
256pub enum InvalidateError {
257    /// The state is currently checkpointing blocks and cannot accept invalidation requests.
258    #[error("cannot invalidate blocks while still committing checkpointed blocks")]
259    ProcessingCheckpointedBlocks,
260
261    /// Sending the invalidate request to the block write task failed.
262    #[error("failed to send invalidate block request to block write task")]
263    SendInvalidateRequestFailed,
264
265    /// The invalidate request was dropped before processing.
266    #[error("invalidate block request was unexpectedly dropped")]
267    InvalidateRequestDropped,
268
269    /// The block hash was not found in any non-finalized chain.
270    #[error("block hash {0} not found in any non-finalized chain")]
271    BlockNotFound(block::Hash),
272
273    /// Invalidating this root would remove the only non-finalized chain.
274    #[error("cannot invalidate block {0}: it is the root of the only non-finalized chain")]
275    OnlyChainRoot(block::Hash),
276}
277
278/// An error describing why a `ReconsiderBlock` request failed.
279#[derive(Debug, Error)]
280#[non_exhaustive]
281pub enum ReconsiderError {
282    /// The block is not found in the list of invalidated blocks.
283    #[error("Block with hash {0} was not previously invalidated")]
284    MissingInvalidatedBlock(block::Hash),
285
286    /// The block's parent is missing from the non-finalized state.
287    #[error("Parent chain not found for block {0}")]
288    ParentChainNotFound(block::Hash),
289
290    /// There were no invalidated blocks when at least one was expected.
291    #[error("Invalidated blocks list is empty when it should contain at least one block")]
292    InvalidatedBlocksEmpty,
293
294    /// The state is currently checkpointing blocks and cannot accept reconsider requests.
295    #[error("cannot reconsider blocks while still committing checkpointed blocks")]
296    CheckpointCommitInProgress,
297
298    /// Sending the reconsider request to the block write task failed.
299    #[error("failed to send reconsider block request to block write task")]
300    ReconsiderSendFailed,
301
302    /// The reconsider request was dropped before processing.
303    #[error("reconsider block request was unexpectedly dropped")]
304    ReconsiderResponseDropped,
305
306    /// Replaying an invalidated block into the restored chain failed contextual
307    /// validation.
308    #[error("replaying a previously invalidated block failed contextual validation: {0}")]
309    ReplayFailed(#[source] ValidateContextError),
310}
311
312/// An error describing why an `AwaitUtxo` request failed.
313#[derive(Debug, Error)]
314#[non_exhaustive]
315pub enum AwaitUtxoError {
316    /// The state stopped responding, for example because it was dropped
317    /// during shutdown, before the UTXO could be found.
318    #[error("the state stopped responding before the UTXO arrived")]
319    Cancelled,
320
321    /// An internal channel error occurred while waiting for the UTXO.
322    #[error("internal channel error while waiting for the UTXO: receiver lagged by {0}")]
323    Lagged(u64),
324
325    /// The `ReadStateService` returned an error while looking up the UTXO.
326    #[error("the read state service returned an error: {0}")]
327    ReadStateFailed(#[source] BoxError),
328}
329
330impl From<RecvError> for AwaitUtxoError {
331    fn from(err: RecvError) -> Self {
332        match err {
333            RecvError::Closed => AwaitUtxoError::Cancelled,
334            RecvError::Lagged(skipped) => AwaitUtxoError::Lagged(skipped),
335        }
336    }
337}
338
339/// An error describing why a block failed contextual validation.
340#[derive(Debug, Error, Clone, PartialEq, Eq)]
341#[non_exhaustive]
342#[allow(missing_docs)]
343pub enum ValidateContextError {
344    #[error("block hash {block_hash} was previously invalidated")]
345    #[non_exhaustive]
346    BlockPreviouslyInvalidated { block_hash: block::Hash },
347
348    #[error("block parent not found in any chain, or not enough blocks in chain")]
349    #[non_exhaustive]
350    NotReadyToBeCommitted,
351
352    #[error("block height {candidate_height:?} is lower than the current finalized height {finalized_tip_height:?}")]
353    #[non_exhaustive]
354    OrphanedBlock {
355        candidate_height: block::Height,
356        finalized_tip_height: block::Height,
357    },
358
359    #[error("block height {candidate_height:?} is not one greater than its parent block's height {parent_height:?}")]
360    #[non_exhaustive]
361    NonSequentialBlock {
362        candidate_height: block::Height,
363        parent_height: block::Height,
364    },
365
366    #[error("block height {candidate_height:?} is not one greater than its finalized parent block's height {parent_height:?}")]
367    #[non_exhaustive]
368    NonSequentialFinalizedChild {
369        candidate_height: block::Height,
370        parent_height: block::Height,
371    },
372
373    #[error("block time {candidate_time:?} is less than or equal to the median-time-past for the block {median_time_past:?}")]
374    #[non_exhaustive]
375    TimeTooEarly {
376        candidate_time: DateTime<Utc>,
377        median_time_past: DateTime<Utc>,
378    },
379
380    #[error("block time {candidate_time:?} is greater than the median-time-past for the block plus 90 minutes {block_time_max:?}")]
381    #[non_exhaustive]
382    TimeTooLate {
383        candidate_time: DateTime<Utc>,
384        block_time_max: DateTime<Utc>,
385    },
386
387    #[error("block difficulty threshold {difficulty_threshold:?} is not equal to the expected difficulty for the block {expected_difficulty:?}")]
388    #[non_exhaustive]
389    InvalidDifficultyThreshold {
390        difficulty_threshold: CompactDifficulty,
391        expected_difficulty: CompactDifficulty,
392    },
393
394    #[error("transparent double-spend: {outpoint:?} is spent twice in {location:?}")]
395    #[non_exhaustive]
396    DuplicateTransparentSpend {
397        outpoint: transparent::OutPoint,
398        location: &'static str,
399    },
400
401    #[error("missing transparent output: possible double-spend of {outpoint:?} in {location:?}")]
402    #[non_exhaustive]
403    MissingTransparentOutput {
404        outpoint: transparent::OutPoint,
405        location: &'static str,
406    },
407
408    #[error("out-of-order transparent spend: {outpoint:?} is created by a later transaction in the same block")]
409    #[non_exhaustive]
410    EarlyTransparentSpend { outpoint: transparent::OutPoint },
411
412    #[error(
413        "unshielded transparent coinbase spend: {outpoint:?} \
414         must be spent in a transaction which only has shielded outputs"
415    )]
416    #[non_exhaustive]
417    UnshieldedTransparentCoinbaseSpend { outpoint: transparent::OutPoint },
418
419    #[error(
420        "immature transparent coinbase spend: \
421        attempt to spend {outpoint:?} at {spend_height:?}, \
422        but spends are invalid before {min_spend_height:?}, \
423        which is {MIN_TRANSPARENT_COINBASE_MATURITY:?} blocks \
424        after it was created at {created_height:?}"
425    )]
426    #[non_exhaustive]
427    ImmatureTransparentCoinbaseSpend {
428        outpoint: transparent::OutPoint,
429        spend_height: block::Height,
430        min_spend_height: block::Height,
431        created_height: block::Height,
432    },
433
434    #[error("sprout double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
435    #[non_exhaustive]
436    DuplicateSproutNullifier {
437        nullifier: sprout::Nullifier,
438        in_finalized_state: bool,
439    },
440
441    #[error("sapling double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
442    #[non_exhaustive]
443    DuplicateSaplingNullifier {
444        nullifier: sapling::Nullifier,
445        in_finalized_state: bool,
446    },
447
448    #[error("orchard double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
449    #[non_exhaustive]
450    DuplicateOrchardNullifier {
451        nullifier: orchard::Nullifier,
452        in_finalized_state: bool,
453    },
454
455    #[error("ironwood double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
456    #[non_exhaustive]
457    DuplicateIronwoodNullifier {
458        nullifier: ironwood::Nullifier,
459        in_finalized_state: bool,
460    },
461
462    #[error(
463        "the remaining value in the transparent transaction value pool MUST be nonnegative:\n\
464         {amount_error:?},\n\
465         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
466    )]
467    #[non_exhaustive]
468    NegativeRemainingTransactionValue {
469        amount_error: amount::Error,
470        height: block::Height,
471        tx_index_in_block: usize,
472        transaction_hash: transaction::Hash,
473    },
474
475    #[error(
476        "error calculating the remaining value in the transaction value pool:\n\
477         {amount_error:?},\n\
478         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
479    )]
480    #[non_exhaustive]
481    CalculateRemainingTransactionValue {
482        amount_error: amount::Error,
483        height: block::Height,
484        tx_index_in_block: usize,
485        transaction_hash: transaction::Hash,
486    },
487
488    #[error(
489        "error calculating value balances for the remaining value in the transaction value pool:\n\
490         {value_balance_error:?},\n\
491         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
492    )]
493    #[non_exhaustive]
494    CalculateTransactionValueBalances {
495        value_balance_error: ValueBalanceError,
496        height: block::Height,
497        tx_index_in_block: usize,
498        transaction_hash: transaction::Hash,
499    },
500
501    #[error(
502        "error calculating the block chain value pool change:\n\
503         {value_balance_error:?},\n\
504         {height:?}, {block_hash:?},\n\
505         transactions: {transaction_count:?}, spent UTXOs: {spent_utxo_count:?}"
506    )]
507    #[non_exhaustive]
508    CalculateBlockChainValueChange {
509        value_balance_error: ValueBalanceError,
510        height: block::Height,
511        block_hash: block::Hash,
512        transaction_count: usize,
513        spent_utxo_count: usize,
514    },
515
516    #[error(
517        "error adding value balances to the chain value pool:\n\
518         {value_balance_error:?},\n\
519         {chain_value_pools:?},\n\
520         {block_value_pool_change:?},\n\
521         {height:?}"
522    )]
523    #[non_exhaustive]
524    AddValuePool {
525        value_balance_error: ValueBalanceError,
526        chain_value_pools: Box<ValueBalance<NonNegative>>,
527        block_value_pool_change: Box<ValueBalance<NegativeAllowed>>,
528        height: Option<block::Height>,
529    },
530
531    #[error(
532        "invalid block subsidy, funding stream, or miner fee payment in block {block_hash:?} at \
533         {height:?}: {subsidy_error}"
534    )]
535    #[non_exhaustive]
536    InvalidSubsidy {
537        subsidy_error: zebra_chain::parameters::subsidy::CoinbaseTransactionError,
538        height: block::Height,
539        block_hash: block::Hash,
540    },
541
542    #[error("error updating a note commitment tree: {0}")]
543    NoteCommitmentTreeError(#[from] zebra_chain::parallel::tree::NoteCommitmentTreeError),
544
545    #[error("error building the history tree: {0}")]
546    HistoryTreeError(#[from] Arc<HistoryTreeError>),
547
548    #[error("block contains an invalid commitment: {0}")]
549    InvalidBlockCommitment(#[from] block::CommitmentError),
550
551    #[error(
552        "unknown Sprout anchor: {anchor:?},\n\
553         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
554    )]
555    #[non_exhaustive]
556    UnknownSproutAnchor {
557        anchor: sprout::tree::Root,
558        height: Option<block::Height>,
559        tx_index_in_block: Option<usize>,
560        transaction_hash: transaction::Hash,
561    },
562
563    #[error(
564        "unknown Sapling anchor: {anchor:?},\n\
565         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
566    )]
567    #[non_exhaustive]
568    UnknownSaplingAnchor {
569        anchor: sapling::tree::Root,
570        height: Option<block::Height>,
571        tx_index_in_block: Option<usize>,
572        transaction_hash: transaction::Hash,
573    },
574
575    #[error(
576        "unknown Orchard anchor: {anchor:?},\n\
577         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
578    )]
579    #[non_exhaustive]
580    UnknownOrchardAnchor {
581        anchor: orchard::tree::Root,
582        height: Option<block::Height>,
583        tx_index_in_block: Option<usize>,
584        transaction_hash: transaction::Hash,
585    },
586
587    #[error(
588        "unknown Ironwood anchor: {anchor:?},\n\
589         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
590    )]
591    #[non_exhaustive]
592    UnknownIronwoodAnchor {
593        // Ironwood reuses the Orchard tree root type.
594        anchor: orchard::tree::Root,
595        height: Option<block::Height>,
596        tx_index_in_block: Option<usize>,
597        transaction_hash: transaction::Hash,
598    },
599
600    /// The block was not validated because an ancestor in the same queued chain
601    /// failed contextual validation.
602    ///
603    /// This is a distinct variant, rather than a copy of the ancestor's error, so the
604    /// peer that served this block isn't scored or classified for the ancestor's
605    /// failure.
606    #[error("ancestor block {ancestor_hash} failed contextual validation")]
607    #[non_exhaustive]
608    AncestorRejected {
609        ancestor_hash: block::Hash,
610        source: Box<ValidateContextError>,
611    },
612}
613
614impl ValidateContextError {
615    /// Returns `true` if the block's authorizing data doesn't match the commitment in
616    /// its header.
617    ///
618    /// From NU5 onward, the block header hash and merkle root don't commit to the
619    /// authorizing data, so a peer can serve a forged body for a canonical header
620    /// without changing the block hash. A mismatched authorizing data commitment proves
621    /// the served body doesn't belong to its header, and an honest peer never serves
622    /// such a body, so the serving peer is misbehaving and the hash is still wanted.
623    pub fn is_auth_commitment_mismatch(&self) -> bool {
624        matches!(
625            self,
626            ValidateContextError::InvalidBlockCommitment(
627                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment { .. },
628            )
629        )
630    }
631
632    /// Returns `true` if the block was rejected only because an ancestor's authorizing
633    /// data didn't match the commitment in its header.
634    ///
635    /// The ancestor's served body was forged, but its hash is still wanted, so this
636    /// block's hash is still wanted too. The peer that served this block isn't the one
637    /// that forged the ancestor, so it must not be scored.
638    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
639        matches!(
640            self,
641            ValidateContextError::AncestorRejected { source, .. }
642                if source.is_auth_commitment_mismatch()
643        )
644    }
645
646    /// Wraps `self`, the error of a rejected ancestor block, into the error for one of
647    /// its descendants, so the descendant carries neither the ancestor's misbehaviour
648    /// score nor its classification.
649    pub fn for_descendant(&self, ancestor_hash: block::Hash) -> Self {
650        match self {
651            // Keep the original failing ancestor, so deep descendants don't nest errors.
652            ValidateContextError::AncestorRejected { .. } => self.clone(),
653            _ => ValidateContextError::AncestorRejected {
654                ancestor_hash,
655                source: Box::new(self.clone()),
656            },
657        }
658    }
659
660    /// Returns a suggested misbehaviour score increment for a certain error.
661    pub fn misbehavior_score(&self) -> u32 {
662        match self {
663            // A forged body proves the serving peer misbehaved, see
664            // `is_auth_commitment_mismatch()`.
665            ValidateContextError::InvalidBlockCommitment(
666                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment { .. },
667            ) => 100,
668            // A wrong block subsidy, funding stream, or miner fee payment is invalid given only
669            // the block and its parent, so the peer that sent it is misbehaving.
670            ValidateContextError::InvalidSubsidy { .. } => 100,
671            // The parent's height is known, so the block is invalid on its own.
672            ValidateContextError::NonSequentialFinalizedChild { .. } => 100,
673            _other => 0,
674        }
675    }
676}
677
678impl From<sprout::tree::NoteCommitmentTreeError> for ValidateContextError {
679    fn from(value: sprout::tree::NoteCommitmentTreeError) -> Self {
680        ValidateContextError::NoteCommitmentTreeError(value.into())
681    }
682}
683
684/// Trait for creating the corresponding duplicate nullifier error from a nullifier.
685pub trait DuplicateNullifierError {
686    /// Returns the corresponding duplicate nullifier error for `self`.
687    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError;
688}
689
690impl DuplicateNullifierError for sprout::Nullifier {
691    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
692        ValidateContextError::DuplicateSproutNullifier {
693            nullifier: *self,
694            in_finalized_state,
695        }
696    }
697}
698
699impl DuplicateNullifierError for sapling::Nullifier {
700    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
701        ValidateContextError::DuplicateSaplingNullifier {
702            nullifier: *self,
703            in_finalized_state,
704        }
705    }
706}
707
708impl DuplicateNullifierError for orchard::Nullifier {
709    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
710        ValidateContextError::DuplicateOrchardNullifier {
711            nullifier: *self,
712            in_finalized_state,
713        }
714    }
715}
716
717impl DuplicateNullifierError for ironwood::Nullifier {
718    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
719        ValidateContextError::DuplicateIronwoodNullifier {
720            nullifier: *self,
721            in_finalized_state,
722        }
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729    use zebra_chain::block::Height;
730
731    #[test]
732    fn commit_block_error_misbehavior_scores() {
733        let context_err = CommitBlockError::ValidateContextError(Box::new(
734            ValidateContextError::NonSequentialBlock {
735                candidate_height: Height(5),
736                parent_height: Height(3),
737            },
738        ));
739        assert_eq!(context_err.misbehavior_score(), 0);
740
741        let dup_err = CommitBlockError::Duplicate {
742            hash_or_height: None,
743            location: KnownBlock::BestChain,
744        };
745        assert_eq!(dup_err.misbehavior_score(), 0);
746
747        // A mismatched authorizing data commitment means the served body doesn't
748        // belong to its header, so the serving peer must be scored.
749        let auth_commitment_err = CommitBlockError::ValidateContextError(Box::new(
750            ValidateContextError::InvalidBlockCommitment(
751                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
752                    expected: [1; 32],
753                    actual: [2; 32],
754                },
755            ),
756        ));
757        assert_eq!(auth_commitment_err.misbehavior_score(), 100);
758    }
759
760    /// The state rejects queued descendants along with a failed block, but the peers that
761    /// served them didn't serve the failed block, so they must not inherit its score or
762    /// classification.
763    #[test]
764    fn descendant_errors_are_not_scored() {
765        let auth_commitment_err = ValidateContextError::InvalidBlockCommitment(
766            block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
767                expected: [1; 32],
768                actual: [2; 32],
769            },
770        );
771        let forged_hash = block::Hash([1; 32]);
772
773        let child_err = auth_commitment_err.for_descendant(forged_hash);
774        assert_eq!(child_err.misbehavior_score(), 0);
775        assert!(!child_err.is_auth_commitment_mismatch());
776        assert!(child_err.is_descendant_of_auth_commitment_mismatch());
777
778        // Deeper descendants keep pointing at the block that actually failed.
779        let grandchild_err = child_err.for_descendant(block::Hash([2; 32]));
780        assert_eq!(grandchild_err, child_err);
781
782        let commit_err = CommitBlockError::ValidateContextError(Box::new(child_err));
783        assert_eq!(commit_err.misbehavior_score(), 0);
784        assert!(!commit_err.is_auth_commitment_mismatch());
785        assert!(commit_err.is_descendant_of_auth_commitment_mismatch());
786
787        // Descendants of other contextual failures aren't re-requested.
788        let other_child_err = ValidateContextError::NonSequentialBlock {
789            candidate_height: Height(5),
790            parent_height: Height(3),
791        }
792        .for_descendant(forged_hash);
793        assert_eq!(other_child_err.misbehavior_score(), 0);
794        assert!(!other_child_err.is_descendant_of_auth_commitment_mismatch());
795    }
796
797    #[test]
798    fn invalid_subsidy_commit_error_misbehavior_score() {
799        use zebra_chain::parameters::subsidy::{CoinbaseTransactionError, SubsidyError};
800
801        let invalid_subsidy = ValidateContextError::InvalidSubsidy {
802            subsidy_error: CoinbaseTransactionError::Subsidy(SubsidyError::InvalidMinerFees),
803            height: Height(5),
804            block_hash: zebra_chain::block::Hash([0; 32]),
805        };
806        let descendant = invalid_subsidy.for_descendant(block::Hash([1; 32]));
807        assert_eq!(descendant.misbehavior_score(), 0);
808        assert!(!descendant.is_descendant_of_auth_commitment_mismatch());
809        let subsidy_err = CommitBlockError::ValidateContextError(Box::new(invalid_subsidy));
810        assert_eq!(subsidy_err.misbehavior_score(), 100);
811    }
812}