zebra-state 15.0.0

State contextual verification and storage code for Zebra
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Error types for Zebra's state.

use std::{path::PathBuf, sync::Arc};

use chrono::{DateTime, Utc};
use derive_new::new;
use thiserror::Error;

use tokio::sync::broadcast::error::RecvError;
use zebra_chain::{
    amount::{self, NegativeAllowed, NonNegative},
    block,
    history_tree::HistoryTreeError,
    ironwood, orchard, sapling, sprout, transaction, transparent,
    value_balance::{ValueBalance, ValueBalanceError},
    work::difficulty::CompactDifficulty,
};

use crate::{constants::MIN_TRANSPARENT_COINBASE_MATURITY, HashOrHeight, KnownBlock};

/// A wrapper for type erased errors that is itself clonable and implements the
/// Error trait
#[derive(Debug, Error, Clone)]
#[error(transparent)]
pub struct CloneError {
    source: Arc<dyn std::error::Error + Send + Sync + 'static>,
}

impl From<CommitSemanticallyVerifiedError> for CloneError {
    fn from(source: CommitSemanticallyVerifiedError) -> Self {
        let source = Arc::new(source);
        Self { source }
    }
}

impl From<BoxError> for CloneError {
    fn from(source: BoxError) -> Self {
        let source = Arc::from(source);
        Self { source }
    }
}

/// A boxed [`std::error::Error`].
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// An error describing why opening the finalized state database failed.
///
/// These errors are recoverable open-time failures that the caller can report,
/// as opposed to invariant violations that indicate a bug.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StateInitError {
    /// A read-only state was requested, but the configured cache directory is
    /// missing or unreadable.
    ///
    /// A read-only secondary instance must never create the primary's cache
    /// directory, so a missing or unreadable directory is a fatal configuration
    /// error rather than something to be created.
    #[error(
        "cannot open read-only state: cache directory {path:?} is missing or unreadable. \
         Hint: a read-only state requires an existing Zebra cache directory; check that the \
         state cache_dir in the Zebra config points at a running Zebra node's cache directory"
    )]
    ReadOnlyCacheDirUnreadable {
        /// The configured cache directory that could not be read.
        path: PathBuf,
        /// The underlying I/O error returned while reading the directory.
        source: std::io::Error,
    },

    /// A read-only state was requested, but no database exists at the expected
    /// path.
    ///
    /// A read-only secondary instance cannot create a database, so the absence
    /// of an existing database is a fatal configuration error.
    #[error(
        "cannot open read-only state: no database found at {path:?}. \
         Hint: a read-only state requires an existing finalized database created by a running \
         Zebra node; check that the state cache_dir in the Zebra config points at that node's \
         cache directory"
    )]
    ReadOnlyDatabaseNotFound {
        /// The database path at which no database was found.
        path: PathBuf,
    },

    /// A read-only state was requested together with an ephemeral database.
    ///
    /// A read-only secondary follows another process's primary database and must
    /// never delete it, whereas an ephemeral database deletes its files on drop. The
    /// two are mutually exclusive, so requesting both is a fatal configuration error.
    #[error(
        "cannot open read-only state: an ephemeral database was also requested. \
         Hint: a read-only state follows an existing Zebra node's database and must not \
         delete it; set `ephemeral = false`, or do not request a read-only state"
    )]
    ReadOnlyEphemeralConflict,
}

/// An error describing why a block could not be queued to be committed to the state.
#[derive(Debug, Error, Clone, PartialEq, Eq, new)]
pub enum CommitBlockError {
    #[error("block hash is a duplicate: already in {location}")]
    /// The block is a duplicate: it is already queued or committed in the state.
    Duplicate {
        /// Hash or height of the duplicated block.
        hash_or_height: Option<HashOrHeight>,
        /// Location in the state where the block can be found.
        location: KnownBlock,
    },

    /// Contextual validation failed.
    #[error("could not contextually validate semantically verified block")]
    ValidateContextError(#[from] Box<ValidateContextError>),

    /// The write task exited (likely during shutdown).
    #[error("block commit task exited. Is Zebra shutting down?")]
    #[non_exhaustive]
    WriteTaskExited,
}

impl CommitBlockError {
    /// Returns `true` if this is definitely a duplicate commit request.
    /// Some duplicate requests might not be detected, and therefore return `false`.
    pub fn is_duplicate_request(&self) -> bool {
        matches!(self, CommitBlockError::Duplicate { .. })
    }

    /// Returns `true` if the block's authorizing data doesn't match the commitment in
    /// its header.
    ///
    /// See [`ValidateContextError::is_auth_commitment_mismatch()`] for why this is
    /// tracked separately from the misbehaviour score: the served body is invalid, but
    /// the block hash is still valid and still wanted, so the syncer re-requests it
    /// instead of restarting the sync round.
    pub fn is_auth_commitment_mismatch(&self) -> bool {
        match self {
            CommitBlockError::ValidateContextError(err) => err.is_auth_commitment_mismatch(),
            CommitBlockError::Duplicate { .. } | CommitBlockError::WriteTaskExited => false,
        }
    }

    /// Returns `true` if the block was rejected only because an ancestor's authorizing
    /// data didn't match the commitment in its header.
    ///
    /// See [`ValidateContextError::is_descendant_of_auth_commitment_mismatch()`].
    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
        match self {
            CommitBlockError::ValidateContextError(err) => {
                err.is_descendant_of_auth_commitment_mismatch()
            }
            CommitBlockError::Duplicate { .. } | CommitBlockError::WriteTaskExited => false,
        }
    }

    /// Returns a suggested misbehaviour score increment for a certain error.
    ///
    /// Consensus-invalid subsidies and authorizing-data commitments score 100.
    /// Duplicate requests, shutdowns, and rejected-ancestor descendants score 0.
    pub fn misbehavior_score(&self) -> u32 {
        match self {
            CommitBlockError::ValidateContextError(err) => err.misbehavior_score(),
            CommitBlockError::Duplicate { .. } | CommitBlockError::WriteTaskExited => 0,
        }
    }
}

/// An error describing why a `CommitSemanticallyVerified` request failed.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[error("could not commit semantically-verified block")]
pub struct CommitSemanticallyVerifiedError(#[from] CommitBlockError);

impl CommitSemanticallyVerifiedError {
    /// Returns the [`CommitBlockError`] describing why the commit failed.
    pub fn inner(&self) -> &CommitBlockError {
        &self.0
    }
}

impl From<ValidateContextError> for CommitSemanticallyVerifiedError {
    fn from(value: ValidateContextError) -> Self {
        Self(CommitBlockError::ValidateContextError(Box::new(value)))
    }
}

#[derive(Debug, Error)]
pub enum LayeredStateError<E: std::error::Error + std::fmt::Display> {
    #[error("{0}")]
    State(E),
    #[error("{0}")]
    Layer(BoxError),
}

impl<E: std::error::Error + 'static> From<BoxError> for LayeredStateError<E> {
    fn from(err: BoxError) -> Self {
        match err.downcast::<E>() {
            Ok(state_err) => Self::State(*state_err),
            Err(layer_error) => Self::Layer(layer_error),
        }
    }
}

/// An error describing why a `CommitCheckpointVerifiedBlock` request failed.
#[derive(Debug, Error, Clone)]
#[error("could not commit checkpoint-verified block")]
pub struct CommitCheckpointVerifiedError(#[from] CommitBlockError);

impl CommitCheckpointVerifiedError {
    /// Returns the [`CommitBlockError`] describing why the commit failed.
    pub fn inner(&self) -> &CommitBlockError {
        &self.0
    }
}

impl From<ValidateContextError> for CommitCheckpointVerifiedError {
    fn from(value: ValidateContextError) -> Self {
        Self(CommitBlockError::ValidateContextError(Box::new(value)))
    }
}

/// An error describing why a `InvalidateBlock` request failed.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum InvalidateError {
    /// The state is currently checkpointing blocks and cannot accept invalidation requests.
    #[error("cannot invalidate blocks while still committing checkpointed blocks")]
    ProcessingCheckpointedBlocks,

    /// Sending the invalidate request to the block write task failed.
    #[error("failed to send invalidate block request to block write task")]
    SendInvalidateRequestFailed,

    /// The invalidate request was dropped before processing.
    #[error("invalidate block request was unexpectedly dropped")]
    InvalidateRequestDropped,

    /// The block hash was not found in any non-finalized chain.
    #[error("block hash {0} not found in any non-finalized chain")]
    BlockNotFound(block::Hash),
}

/// An error describing why a `ReconsiderBlock` request failed.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ReconsiderError {
    /// The block is not found in the list of invalidated blocks.
    #[error("Block with hash {0} was not previously invalidated")]
    MissingInvalidatedBlock(block::Hash),

    /// The block's parent is missing from the non-finalized state.
    #[error("Parent chain not found for block {0}")]
    ParentChainNotFound(block::Hash),

    /// There were no invalidated blocks when at least one was expected.
    #[error("Invalidated blocks list is empty when it should contain at least one block")]
    InvalidatedBlocksEmpty,

    /// The state is currently checkpointing blocks and cannot accept reconsider requests.
    #[error("cannot reconsider blocks while still committing checkpointed blocks")]
    CheckpointCommitInProgress,

    /// Sending the reconsider request to the block write task failed.
    #[error("failed to send reconsider block request to block write task")]
    ReconsiderSendFailed,

    /// The reconsider request was dropped before processing.
    #[error("reconsider block request was unexpectedly dropped")]
    ReconsiderResponseDropped,

    /// Replaying an invalidated block into the restored chain failed contextual
    /// validation.
    #[error("replaying a previously invalidated block failed contextual validation: {0}")]
    ReplayFailed(#[source] ValidateContextError),
}

/// An error describing why an `AwaitUtxo` request failed.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AwaitUtxoError {
    /// The state stopped responding, for example because it was dropped
    /// during shutdown, before the UTXO could be found.
    #[error("the state stopped responding before the UTXO arrived")]
    Cancelled,

    /// An internal channel error occurred while waiting for the UTXO.
    #[error("internal channel error while waiting for the UTXO: receiver lagged by {0}")]
    Lagged(u64),

    /// The `ReadStateService` returned an error while looking up the UTXO.
    #[error("the read state service returned an error: {0}")]
    ReadStateFailed(#[source] BoxError),
}

impl From<RecvError> for AwaitUtxoError {
    fn from(err: RecvError) -> Self {
        match err {
            RecvError::Closed => AwaitUtxoError::Cancelled,
            RecvError::Lagged(skipped) => AwaitUtxoError::Lagged(skipped),
        }
    }
}

/// An error describing why a block failed contextual validation.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ValidateContextError {
    #[error("block hash {block_hash} was previously invalidated")]
    #[non_exhaustive]
    BlockPreviouslyInvalidated { block_hash: block::Hash },

    #[error("block parent not found in any chain, or not enough blocks in chain")]
    #[non_exhaustive]
    NotReadyToBeCommitted,

    #[error("block height {candidate_height:?} is lower than the current finalized height {finalized_tip_height:?}")]
    #[non_exhaustive]
    OrphanedBlock {
        candidate_height: block::Height,
        finalized_tip_height: block::Height,
    },

    #[error("block height {candidate_height:?} is not one greater than its parent block's height {parent_height:?}")]
    #[non_exhaustive]
    NonSequentialBlock {
        candidate_height: block::Height,
        parent_height: block::Height,
    },

    #[error("block time {candidate_time:?} is less than or equal to the median-time-past for the block {median_time_past:?}")]
    #[non_exhaustive]
    TimeTooEarly {
        candidate_time: DateTime<Utc>,
        median_time_past: DateTime<Utc>,
    },

    #[error("block time {candidate_time:?} is greater than the median-time-past for the block plus 90 minutes {block_time_max:?}")]
    #[non_exhaustive]
    TimeTooLate {
        candidate_time: DateTime<Utc>,
        block_time_max: DateTime<Utc>,
    },

    #[error("block difficulty threshold {difficulty_threshold:?} is not equal to the expected difficulty for the block {expected_difficulty:?}")]
    #[non_exhaustive]
    InvalidDifficultyThreshold {
        difficulty_threshold: CompactDifficulty,
        expected_difficulty: CompactDifficulty,
    },

    #[error("transparent double-spend: {outpoint:?} is spent twice in {location:?}")]
    #[non_exhaustive]
    DuplicateTransparentSpend {
        outpoint: transparent::OutPoint,
        location: &'static str,
    },

    #[error("missing transparent output: possible double-spend of {outpoint:?} in {location:?}")]
    #[non_exhaustive]
    MissingTransparentOutput {
        outpoint: transparent::OutPoint,
        location: &'static str,
    },

    #[error("out-of-order transparent spend: {outpoint:?} is created by a later transaction in the same block")]
    #[non_exhaustive]
    EarlyTransparentSpend { outpoint: transparent::OutPoint },

    #[error(
        "unshielded transparent coinbase spend: {outpoint:?} \
         must be spent in a transaction which only has shielded outputs"
    )]
    #[non_exhaustive]
    UnshieldedTransparentCoinbaseSpend { outpoint: transparent::OutPoint },

    #[error(
        "immature transparent coinbase spend: \
        attempt to spend {outpoint:?} at {spend_height:?}, \
        but spends are invalid before {min_spend_height:?}, \
        which is {MIN_TRANSPARENT_COINBASE_MATURITY:?} blocks \
        after it was created at {created_height:?}"
    )]
    #[non_exhaustive]
    ImmatureTransparentCoinbaseSpend {
        outpoint: transparent::OutPoint,
        spend_height: block::Height,
        min_spend_height: block::Height,
        created_height: block::Height,
    },

    #[error("sprout double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
    #[non_exhaustive]
    DuplicateSproutNullifier {
        nullifier: sprout::Nullifier,
        in_finalized_state: bool,
    },

    #[error("sapling double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
    #[non_exhaustive]
    DuplicateSaplingNullifier {
        nullifier: sapling::Nullifier,
        in_finalized_state: bool,
    },

    #[error("orchard double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
    #[non_exhaustive]
    DuplicateOrchardNullifier {
        nullifier: orchard::Nullifier,
        in_finalized_state: bool,
    },

    #[error("ironwood double-spend: duplicate nullifier: {nullifier:?}, in finalized state: {in_finalized_state:?}")]
    #[non_exhaustive]
    DuplicateIronwoodNullifier {
        nullifier: ironwood::Nullifier,
        in_finalized_state: bool,
    },

    #[error(
        "the remaining value in the transparent transaction value pool MUST be nonnegative:\n\
         {amount_error:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    NegativeRemainingTransactionValue {
        amount_error: amount::Error,
        height: block::Height,
        tx_index_in_block: usize,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "error calculating the remaining value in the transaction value pool:\n\
         {amount_error:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    CalculateRemainingTransactionValue {
        amount_error: amount::Error,
        height: block::Height,
        tx_index_in_block: usize,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "error calculating value balances for the remaining value in the transaction value pool:\n\
         {value_balance_error:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    CalculateTransactionValueBalances {
        value_balance_error: ValueBalanceError,
        height: block::Height,
        tx_index_in_block: usize,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "error calculating the block chain value pool change:\n\
         {value_balance_error:?},\n\
         {height:?}, {block_hash:?},\n\
         transactions: {transaction_count:?}, spent UTXOs: {spent_utxo_count:?}"
    )]
    #[non_exhaustive]
    CalculateBlockChainValueChange {
        value_balance_error: ValueBalanceError,
        height: block::Height,
        block_hash: block::Hash,
        transaction_count: usize,
        spent_utxo_count: usize,
    },

    #[error(
        "error adding value balances to the chain value pool:\n\
         {value_balance_error:?},\n\
         {chain_value_pools:?},\n\
         {block_value_pool_change:?},\n\
         {height:?}"
    )]
    #[non_exhaustive]
    AddValuePool {
        value_balance_error: ValueBalanceError,
        chain_value_pools: Box<ValueBalance<NonNegative>>,
        block_value_pool_change: Box<ValueBalance<NegativeAllowed>>,
        height: Option<block::Height>,
    },

    #[error(
        "invalid block subsidy, funding stream, or miner fee payment in block {block_hash:?} at \
         {height:?}: {subsidy_error}"
    )]
    #[non_exhaustive]
    InvalidSubsidy {
        subsidy_error: zebra_chain::parameters::subsidy::CoinbaseTransactionError,
        height: block::Height,
        block_hash: block::Hash,
    },

    #[error("error updating a note commitment tree: {0}")]
    NoteCommitmentTreeError(#[from] zebra_chain::parallel::tree::NoteCommitmentTreeError),

    #[error("error building the history tree: {0}")]
    HistoryTreeError(#[from] Arc<HistoryTreeError>),

    #[error("block contains an invalid commitment: {0}")]
    InvalidBlockCommitment(#[from] block::CommitmentError),

    #[error(
        "unknown Sprout anchor: {anchor:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    UnknownSproutAnchor {
        anchor: sprout::tree::Root,
        height: Option<block::Height>,
        tx_index_in_block: Option<usize>,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "unknown Sapling anchor: {anchor:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    UnknownSaplingAnchor {
        anchor: sapling::tree::Root,
        height: Option<block::Height>,
        tx_index_in_block: Option<usize>,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "unknown Orchard anchor: {anchor:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    UnknownOrchardAnchor {
        anchor: orchard::tree::Root,
        height: Option<block::Height>,
        tx_index_in_block: Option<usize>,
        transaction_hash: transaction::Hash,
    },

    #[error(
        "unknown Ironwood anchor: {anchor:?},\n\
         {height:?}, index in block: {tx_index_in_block:?}, {transaction_hash:?}"
    )]
    #[non_exhaustive]
    UnknownIronwoodAnchor {
        // Ironwood reuses the Orchard tree root type.
        anchor: orchard::tree::Root,
        height: Option<block::Height>,
        tx_index_in_block: Option<usize>,
        transaction_hash: transaction::Hash,
    },

    /// The block was not validated because an ancestor in the same queued chain
    /// failed contextual validation.
    ///
    /// This is a distinct variant, rather than a copy of the ancestor's error, so the
    /// peer that served this block isn't scored or classified for the ancestor's
    /// failure.
    #[error("ancestor block {ancestor_hash} failed contextual validation")]
    #[non_exhaustive]
    AncestorRejected {
        ancestor_hash: block::Hash,
        source: Box<ValidateContextError>,
    },
}

impl ValidateContextError {
    /// Returns `true` if the block's authorizing data doesn't match the commitment in
    /// its header.
    ///
    /// From NU5 onward, the block header hash and merkle root don't commit to the
    /// authorizing data, so a peer can serve a forged body for a canonical header
    /// without changing the block hash. A mismatched authorizing data commitment proves
    /// the served body doesn't belong to its header, and an honest peer never serves
    /// such a body, so the serving peer is misbehaving and the hash is still wanted.
    pub fn is_auth_commitment_mismatch(&self) -> bool {
        matches!(
            self,
            ValidateContextError::InvalidBlockCommitment(
                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment { .. },
            )
        )
    }

    /// Returns `true` if the block was rejected only because an ancestor's authorizing
    /// data didn't match the commitment in its header.
    ///
    /// The ancestor's served body was forged, but its hash is still wanted, so this
    /// block's hash is still wanted too. The peer that served this block isn't the one
    /// that forged the ancestor, so it must not be scored.
    pub fn is_descendant_of_auth_commitment_mismatch(&self) -> bool {
        matches!(
            self,
            ValidateContextError::AncestorRejected { source, .. }
                if source.is_auth_commitment_mismatch()
        )
    }

    /// Wraps `self`, the error of a rejected ancestor block, into the error for one of
    /// its descendants, so the descendant carries neither the ancestor's misbehaviour
    /// score nor its classification.
    pub fn for_descendant(&self, ancestor_hash: block::Hash) -> Self {
        match self {
            // Keep the original failing ancestor, so deep descendants don't nest errors.
            ValidateContextError::AncestorRejected { .. } => self.clone(),
            _ => ValidateContextError::AncestorRejected {
                ancestor_hash,
                source: Box::new(self.clone()),
            },
        }
    }

    /// Returns a suggested misbehaviour score increment for a certain error.
    pub fn misbehavior_score(&self) -> u32 {
        match self {
            // A forged body proves the serving peer misbehaved, see
            // `is_auth_commitment_mismatch()`.
            ValidateContextError::InvalidBlockCommitment(
                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment { .. },
            ) => 100,
            // A wrong block subsidy, funding stream, or miner fee payment is invalid given only
            // the block and its parent, so the peer that sent it is misbehaving.
            ValidateContextError::InvalidSubsidy { .. } => 100,
            _other => 0,
        }
    }
}

impl From<sprout::tree::NoteCommitmentTreeError> for ValidateContextError {
    fn from(value: sprout::tree::NoteCommitmentTreeError) -> Self {
        ValidateContextError::NoteCommitmentTreeError(value.into())
    }
}

/// Trait for creating the corresponding duplicate nullifier error from a nullifier.
pub trait DuplicateNullifierError {
    /// Returns the corresponding duplicate nullifier error for `self`.
    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError;
}

impl DuplicateNullifierError for sprout::Nullifier {
    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
        ValidateContextError::DuplicateSproutNullifier {
            nullifier: *self,
            in_finalized_state,
        }
    }
}

impl DuplicateNullifierError for sapling::Nullifier {
    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
        ValidateContextError::DuplicateSaplingNullifier {
            nullifier: *self,
            in_finalized_state,
        }
    }
}

impl DuplicateNullifierError for orchard::Nullifier {
    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
        ValidateContextError::DuplicateOrchardNullifier {
            nullifier: *self,
            in_finalized_state,
        }
    }
}

impl DuplicateNullifierError for ironwood::Nullifier {
    fn duplicate_nullifier_error(&self, in_finalized_state: bool) -> ValidateContextError {
        ValidateContextError::DuplicateIronwoodNullifier {
            nullifier: *self,
            in_finalized_state,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zebra_chain::block::Height;

    #[test]
    fn commit_block_error_misbehavior_scores() {
        let context_err = CommitBlockError::ValidateContextError(Box::new(
            ValidateContextError::NonSequentialBlock {
                candidate_height: Height(5),
                parent_height: Height(3),
            },
        ));
        assert_eq!(context_err.misbehavior_score(), 0);

        let dup_err = CommitBlockError::Duplicate {
            hash_or_height: None,
            location: KnownBlock::BestChain,
        };
        assert_eq!(dup_err.misbehavior_score(), 0);

        // A mismatched authorizing data commitment means the served body doesn't
        // belong to its header, so the serving peer must be scored.
        let auth_commitment_err = CommitBlockError::ValidateContextError(Box::new(
            ValidateContextError::InvalidBlockCommitment(
                block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
                    expected: [1; 32],
                    actual: [2; 32],
                },
            ),
        ));
        assert_eq!(auth_commitment_err.misbehavior_score(), 100);
    }

    /// The state rejects queued descendants along with a failed block, but the peers that
    /// served them didn't serve the failed block, so they must not inherit its score or
    /// classification.
    #[test]
    fn descendant_errors_are_not_scored() {
        let auth_commitment_err = ValidateContextError::InvalidBlockCommitment(
            block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
                expected: [1; 32],
                actual: [2; 32],
            },
        );
        let forged_hash = block::Hash([1; 32]);

        let child_err = auth_commitment_err.for_descendant(forged_hash);
        assert_eq!(child_err.misbehavior_score(), 0);
        assert!(!child_err.is_auth_commitment_mismatch());
        assert!(child_err.is_descendant_of_auth_commitment_mismatch());

        // Deeper descendants keep pointing at the block that actually failed.
        let grandchild_err = child_err.for_descendant(block::Hash([2; 32]));
        assert_eq!(grandchild_err, child_err);

        let commit_err = CommitBlockError::ValidateContextError(Box::new(child_err));
        assert_eq!(commit_err.misbehavior_score(), 0);
        assert!(!commit_err.is_auth_commitment_mismatch());
        assert!(commit_err.is_descendant_of_auth_commitment_mismatch());

        // Descendants of other contextual failures aren't re-requested.
        let other_child_err = ValidateContextError::NonSequentialBlock {
            candidate_height: Height(5),
            parent_height: Height(3),
        }
        .for_descendant(forged_hash);
        assert_eq!(other_child_err.misbehavior_score(), 0);
        assert!(!other_child_err.is_descendant_of_auth_commitment_mismatch());
    }

    #[test]
    fn invalid_subsidy_commit_error_misbehavior_score() {
        use zebra_chain::parameters::subsidy::{CoinbaseTransactionError, SubsidyError};

        let invalid_subsidy = ValidateContextError::InvalidSubsidy {
            subsidy_error: CoinbaseTransactionError::Subsidy(SubsidyError::InvalidMinerFees),
            height: Height(5),
            block_hash: zebra_chain::block::Hash([0; 32]),
        };
        let descendant = invalid_subsidy.for_descendant(block::Hash([1; 32]));
        assert_eq!(descendant.misbehavior_score(), 0);
        assert!(!descendant.is_descendant_of_auth_commitment_mismatch());
        let subsidy_err = CommitBlockError::ValidateContextError(Box::new(invalid_subsidy));
        assert_eq!(subsidy_err.misbehavior_score(), 100);
    }
}