zakura-state 7.1.0

State contextual verification and storage code for the Zakura node. Internal crate, published to support cargo install zakura
Documentation
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! Error types for Zebra's state.

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

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

use zakura_chain::{
    amount::{self, NegativeAllowed, NonNegative},
    block,
    history_tree::HistoryTreeError,
    ironwood, orchard, sapling, sprout,
    subtree::NoteCommitmentSubtreeIndex,
    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>;

/// The finalized database has blocks but no persisted Sprout tip frontier.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("missing Sprout note commitment tree at finalized tip {tip:?}")]
pub struct MissingSproutTipTree {
    /// The finalized tip whose Sprout frontier is missing.
    pub tip: block::Height,
}

/// The per-height note commitment tree for a historical block was never written, because this
/// database was built by the verified-commitment-trees fast-sync path.
///
/// Fast sync skips per-height trees across the half-open band `[U, H)`, where `U` is the first
/// height this binary committed and `H` is the last checkpoint. Read handlers return this
/// instead of an absent tree so the RPC boundary reports a diagnosable archive-mode failure:
/// clients following the lightwalletd contract read an absent treestate as the *empty* tree, and
/// would silently derive a wallet birthday anchor asserting an empty commitment tree deep in the
/// chain.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error(
    "historical note commitment tree at {hash_or_height} is unavailable: this node was fast-synced \
     with verified commitment trees, so per-height trees below the last checkpoint \
     {last_checkpoint:?} \
     were never written"
)]
pub struct HistoricalTreeUnavailable {
    /// The block whose per-height tree was requested.
    pub hash_or_height: HashOrHeight,

    /// The last checkpoint height `H`: the exclusive upper bound of the absent band.
    pub last_checkpoint: block::Height,
}

/// A completed note commitment subtree root was never recorded, because this database was built
/// by the verified-commitment-trees fast-sync path.
///
/// Subtree roots are a by-product of the per-height tree maintenance the fast path skips, so
/// every subtree that completed at or below the last checkpoint is missing. Read handlers
/// return this instead of an empty subtree list, which a client would otherwise read as "this
/// chain has no subtrees here" and seed nothing, failing later without a clear cause.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error(
    "historical {pool} note commitment subtree {index:?} is unavailable at last checkpoint \
     {last_checkpoint:?}: {reason}"
)]
pub struct HistoricalSubtreeUnavailable {
    /// The shielded pool whose subtree was requested, in `z_getsubtreesbyindex` spelling.
    pub pool: &'static str,

    /// The requested starting subtree index.
    pub index: NoteCommitmentSubtreeIndex,

    /// The last checkpoint height `H`, below which no subtree roots were recorded.
    pub last_checkpoint: block::Height,

    /// What this node knows about the subtree's availability.
    pub reason: HistoricalSubtreeUnavailableReason,
}

/// Why a requested historical subtree is currently unavailable.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum HistoricalSubtreeUnavailableReason {
    /// The node has not reached the fast-sync last checkpoint, so it cannot yet tell a
    /// subtree the fast path skipped from one the chain has not reached.
    ///
    /// This is not a promise of recovery. Deciding between the two needs the pool's leaf count
    /// at the last checkpoint, which only exists once sync gets there; every subtree that completed
    /// below the last checkpoint is skipped, and turns into [`Self::NotStored`] rather than appearing.
    #[error(
        "this node has not reached the last checkpoint, so it cannot yet tell whether the \
         subtree was skipped; subtrees completed below the last checkpoint are never recorded"
    )]
    Indeterminate,

    /// The node has passed the last checkpoint without recording the requested subtree.
    #[error(
        "this node did not record the subtree and continuing synchronization will not restore it; \
         use another node"
    )]
    NotStored,
}

/// 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 {
    /// The configured historical frontier artifact could not be read or decoded.
    ///
    /// Only nodes that derive historical trees reach this. A node that does not derive ignores an
    /// unusable artifact, because nothing would have read it.
    #[error(
        "the historical frontier artifact configured at {path:?} could not be loaded: {source}. \
         Hint: remove state.historical_frontier_artifact to serve without it"
    )]
    HistoricalFrontierArtifact {
        /// Artifact path that failed to load.
        path: PathBuf,
        /// Underlying I/O or artifact decoding error.
        source: BoxError,
    },

    /// The configured historical frontier artifact has gaps larger than one request may replay.
    #[error(
        "historical frontier artifact at {path:?} has a {blocks}-block gap, more than \
         MAX_HISTORICAL_TREE_REPLAY_BLOCKS = {limit}; a cold request would replay that range"
    )]
    HistoricalFrontierArtifactTooSparse {
        /// Artifact path whose grid does not tile genesis through `last_checkpoint`.
        path: PathBuf,
        /// Largest cold-request replay the file would require.
        blocks: u64,
        /// Configured per-request replay limit.
        limit: u64,
    },

    /// State could not read or parse the on-disk semantic format version.
    #[error(
        "cannot read state database format version at {path:?}. Hint: check the cache directory permissions and version file contents"
    )]
    DatabaseFormatVersion {
        /// Version file whose read or parse failed.
        path: PathBuf,
        /// Underlying I/O or semantic-version error.
        source: BoxError,
    },

    /// RocksDB could not open the requested primary or secondary database.
    #[error(
        "cannot open state database at {path:?}. Hint: check whether another process holds the database lock and whether cache_dir is readable and writable"
    )]
    DatabaseOpen {
        /// Database directory that failed to open.
        path: PathBuf,
        /// Underlying RocksDB error.
        source: rocksdb::Error,
    },

    /// A migration failure prevents the state database from opening.
    #[error(
        "cannot upgrade state database format at {path:?}. The database version remains unchanged, so Zakura can retry the migration: {source}"
    )]
    DatabaseFormatUpgrade {
        /// The path identifies the database that failed migration.
        path: PathBuf,
        /// The source describes the migration failure.
        source: BoxError,
    },

    /// 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 Zakura cache directory; check that the \
         state cache_dir in the Zakura config points at a running Zakura 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 \
         Zakura node; check that the state cache_dir in the Zakura 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 Zakura node's database and must not \
         delete it; set `ephemeral = false`, or do not request a read-only state"
    )]
    ReadOnlyEphemeralConflict,

    /// A Mainnet database written by the original VCT fast path is missing historical Sprout
    /// anchors, and the in-place repair for it no longer exists.
    #[error(
        "cannot open state: this database was written by an early verified-commitment-trees fast \
         sync and is missing historical Sprout anchors, so it cannot verify JoinSplits that spend \
         a historical Sprout anchor. \
         Hint: discard the database and resync, or restore a snapshot taken with a current release"
    )]
    VctSproutHistoryUnrepairable,
}

/// 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 body mutation could not commit its matching fork-aware header transition.
    #[error("could not commit matching header-chain transition: {error}")]
    HeaderChainError {
        /// Stable local error diagnostic.
        /// State never attributes this diagnostic to a peer.
        error: String,
    },

    /// The write task exited (likely during shutdown).
    #[error("block commit task exited. Is Zakura 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 the state location for duplicate commit requests.
    pub fn duplicate_location(&self) -> Option<&KnownBlock> {
        match self {
            CommitBlockError::Duplicate { location, .. } => Some(location),
            _ => None,
        }
    }

    /// Returns the missing VCT supplied-root height for retryable root-fetch stalls.
    pub fn vct_supplied_root_unavailable_height(&self) -> Option<block::Height> {
        match self {
            CommitBlockError::ValidateContextError(error) => {
                error.vct_supplied_root_unavailable_height()
            }
            _ => None,
        }
    }

    /// Returns the height for any retryable VCT root stall (absent/evicted root, or one
    /// not yet verifiable for lack of a stored successor header). See
    /// [`ValidateContextError::vct_retryable_height`].
    pub fn vct_retryable_height(&self) -> Option<block::Height> {
        match self {
            CommitBlockError::ValidateContextError(error) => error.vct_retryable_height(),
            _ => None,
        }
    }

    /// Returns a suggested misbehaviour score increment for a certain error.
    ///
    /// Callers must only apply this score when the failure is attributable to
    /// the peer supplying a fully verified block. Checkpoint commit failures
    /// can depend on auxiliary roots from another peer and must remain
    /// unscored by checkpoint verification.
    pub fn misbehavior_score(&self) -> u32 {
        match self {
            CommitBlockError::ValidateContextError(error) => error.misbehavior_score(),
            _ => 0,
        }
    }

    /// Classify this commit result before the caller attaches supplier identity and stable evidence.
    pub fn body_verification_class(&self) -> zakura_header_chain::BodyVerificationClass {
        use zakura_header_chain::{BodyVerificationClass, TransientBodyFailureKind};

        match self {
            Self::Duplicate { .. } => BodyVerificationClass::Duplicate,
            Self::ValidateContextError(error) => error.body_verification_class(),
            Self::HeaderChainError { .. } => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::Storage)
            }
            Self::WriteTaskExited => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::VerifierUnavailable)
            }
        }
    }
}

/// 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
    }

    /// Returns the state location for duplicate commit requests.
    pub fn duplicate_location(&self) -> Option<&KnownBlock> {
        self.0.duplicate_location()
    }
}

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 {
    #[source]
    inner: CommitBlockError,
    vct_failure: Option<VctCommitFailure>,
}

/// Exact VCT verification input implicated by a failed checkpoint commit.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum VctCommitFailure {
    /// A direct current-root check or fold failed.
    CurrentRoots,
    /// The successor boundary rejected the candidate containing the current roots.
    SuccessorBoundary,
}

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

    /// Returns the state location for duplicate commit requests.
    pub fn duplicate_location(&self) -> Option<&KnownBlock> {
        self.inner.duplicate_location()
    }

    /// Returns the missing VCT supplied-root height for retryable root-fetch stalls.
    pub fn vct_supplied_root_unavailable_height(&self) -> Option<block::Height> {
        self.inner.vct_supplied_root_unavailable_height()
    }

    /// Returns the height for any retryable VCT root stall (absent/evicted root, or one
    /// not yet verifiable for lack of a stored successor header). See
    /// [`ValidateContextError::vct_retryable_height`].
    pub fn vct_retryable_height(&self) -> Option<block::Height> {
        self.inner.vct_retryable_height()
    }

    pub(crate) fn with_vct_failure(mut self, failure: VctCommitFailure) -> Self {
        self.vct_failure = Some(failure);
        self
    }

    pub(crate) fn vct_failure(&self) -> Option<VctCommitFailure> {
        self.vct_failure
    }
}

impl From<CommitBlockError> for CommitCheckpointVerifiedError {
    fn from(inner: CommitBlockError) -> Self {
        Self {
            inner,
            vct_failure: None,
        }
    }
}

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

/// 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),

    /// The staged state mutation disagreed with or could not commit its header transition.
    #[error("could not commit matching header-chain invalidation: {error}")]
    HeaderChain {
        /// Stable local error diagnostic.
        /// State never attributes this diagnostic to a peer.
        error: String,
    },
}

/// 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),

    /// The finalized parent chain is missing its Sprout tip frontier.
    #[error(transparent)]
    MissingSproutTipTree(#[from] MissingSproutTipTree),

    /// The staged state mutation disagreed with or could not commit its header transition.
    #[error("could not commit matching header-chain reconsideration: {error}")]
    HeaderChain {
        /// Stable local error diagnostic.
        /// State never attributes this diagnostic to a peer.
        error: String,
    },
}

/// An error describing why a block failed contextual validation.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ValidateContextError {
    #[error(transparent)]
    MissingSproutTipTree(#[from] MissingSproutTipTree),

    #[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 descends from invalid ancestor {0}")]
    InvalidAncestorBlock(block::Hash),

    #[error(
        "verified-commitment-trees fast path has no valid supplied root for height \
         {height:?}: the note-commitment frontier is frozen, so this block cannot be \
         committed until a verifiable root is fetched from a peer (retryable)"
    )]
    #[non_exhaustive]
    VctSuppliedRootUnavailable { height: block::Height },

    #[error(
        "verified-commitment-trees fast path cannot yet verify the supplied root for height \
         {height:?}: no successor header is stored to confirm it against the header chain, and \
         committing it unverified would persist a root that is only checked one block later \
         (irreversibly, once on disk). Commit is deferred until the successor header arrives (retryable)"
    )]
    #[non_exhaustive]
    VctSuppliedRootAwaitingSuccessor { height: block::Height },

    #[error(
        "checkpoint block at {height:?} has authorizing-data root {actual:?}, but its cached \
         header prevalidation requires {expected:?}"
    )]
    #[non_exhaustive]
    VctBlockAuthDataRootMismatch {
        height: block::Height,
        expected: block::merkle::AuthDataRoot,
        actual: block::merkle::AuthDataRoot,
    },

    #[error(
        "locally reconstructed Sprout root at the VCT handoff height {height:?} is \
         {actual:?}, but the embedded handoff frontier requires {expected:?}"
    )]
    #[non_exhaustive]
    VctSproutHandoffRootMismatch {
        height: block::Height,
        expected: sprout::tree::Root,
        actual: sprout::tree::Root,
    },

    #[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("cumulative chain work overflows at block {block_hash} ({height:?})")]
    #[non_exhaustive]
    CumulativeWorkOverflow {
        height: block::Height,
        block_hash: block::Hash,
    },

    #[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("error updating a note commitment tree: {0}")]
    NoteCommitmentTreeError(#[from] zakura_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 {
        anchor: ironwood::tree::Root,
        height: Option<block::Height>,
        tx_index_in_block: Option<usize>,
        transaction_hash: transaction::Hash,
    },
}

impl ValidateContextError {
    /// Classify contextual validation without conflating peer data and local availability.
    pub fn body_verification_class(&self) -> zakura_header_chain::BodyVerificationClass {
        use zakura_chain::block::CommitmentError;
        use zakura_header_chain::{
            BodyCommitmentKind, BodyRuleId, BodyVerificationClass, TransientBodyFailureKind,
        };

        let consensus = |rule| BodyVerificationClass::ConsensusInvalid(BodyRuleId::new(rule));
        match self {
            Self::MissingSproutTipTree(_) | Self::NotReadyToBeCommitted => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::MissingContext)
            }
            Self::BlockPreviouslyInvalidated { .. }
            | Self::InvalidAncestorBlock(_)
            | Self::OrphanedBlock { .. } => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::Canceled)
            }
            Self::VctSuppliedRootUnavailable { .. }
            | Self::VctSuppliedRootAwaitingSuccessor { .. } => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::MissingContext)
            }
            Self::VctBlockAuthDataRootMismatch { .. } => {
                BodyVerificationClass::PayloadMismatch(BodyCommitmentKind::AuthDataRoot)
            }
            Self::VctSproutHandoffRootMismatch { .. }
            | Self::CumulativeWorkOverflow { .. }
            | Self::NoteCommitmentTreeError(_)
            | Self::HistoryTreeError(_) => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::Storage)
            }
            Self::InvalidBlockCommitment(error) => {
                let kind = match error {
                    CommitmentError::InvalidAuthDataRoot { .. } => BodyCommitmentKind::AuthDataRoot,
                    CommitmentError::InvalidFinalSaplingRoot { .. } => {
                        BodyCommitmentKind::Other("final_sapling_root")
                    }
                    CommitmentError::InvalidChainHistoryActivationReserved { .. } => {
                        BodyCommitmentKind::Other("chain_history_activation_reserved")
                    }
                    CommitmentError::InvalidChainHistoryRoot { .. } => {
                        BodyCommitmentKind::Other("chain_history_root")
                    }
                    CommitmentError::InvalidChainHistoryBlockTxAuthCommitment { .. } => {
                        BodyCommitmentKind::Other("chain_history_block_tx_auth_commitment")
                    }
                    CommitmentError::InvalidPreNu5OrchardRoot { .. } => {
                        BodyCommitmentKind::Other("pre_nu5_orchard_root")
                    }
                    CommitmentError::InvalidPreNu5OrchardTxCount { .. } => {
                        BodyCommitmentKind::Other("pre_nu5_orchard_tx_count")
                    }
                    CommitmentError::InvalidPreSaplingSaplingTxCount { .. } => {
                        BodyCommitmentKind::Other("pre_sapling_sapling_tx_count")
                    }
                    CommitmentError::InvalidPreNu6_3IronwoodRoot { .. } => {
                        BodyCommitmentKind::Other("pre_nu6_3_ironwood_root")
                    }
                    CommitmentError::InvalidPreNu6_3IronwoodTxCount { .. } => {
                        BodyCommitmentKind::Other("pre_nu6_3_ironwood_tx_count")
                    }
                    CommitmentError::MissingBlockHeight { .. } => {
                        BodyCommitmentKind::Other("missing_block_height")
                    }
                    CommitmentError::InvalidSapingRootBytes => {
                        BodyCommitmentKind::Other("invalid_sapling_root_bytes")
                    }
                };
                BodyVerificationClass::PayloadMismatch(kind)
            }
            Self::NonSequentialBlock { .. } => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::MissingContext)
            }
            Self::TimeTooEarly { .. }
            | Self::TimeTooLate { .. }
            | Self::InvalidDifficultyThreshold { .. } => {
                BodyVerificationClass::Retryable(TransientBodyFailureKind::VerifierUnavailable)
            }
            Self::DuplicateTransparentSpend { .. } => {
                consensus("context.duplicate_transparent_spend")
            }
            Self::MissingTransparentOutput { .. } => {
                consensus("context.missing_transparent_output")
            }
            Self::EarlyTransparentSpend { .. } => consensus("context.early_transparent_spend"),
            Self::UnshieldedTransparentCoinbaseSpend { .. } => {
                consensus("context.unshielded_transparent_coinbase_spend")
            }
            Self::ImmatureTransparentCoinbaseSpend { .. } => {
                consensus("context.immature_transparent_coinbase_spend")
            }
            Self::DuplicateSproutNullifier { .. } => {
                consensus("context.duplicate_sprout_nullifier")
            }
            Self::DuplicateSaplingNullifier { .. } => {
                consensus("context.duplicate_sapling_nullifier")
            }
            Self::DuplicateOrchardNullifier { .. } => {
                consensus("context.duplicate_orchard_nullifier")
            }
            Self::DuplicateIronwoodNullifier { .. } => {
                consensus("context.duplicate_ironwood_nullifier")
            }
            Self::NegativeRemainingTransactionValue { .. } => {
                consensus("context.negative_remaining_transaction_value")
            }
            Self::CalculateRemainingTransactionValue { .. } => {
                consensus("context.calculate_remaining_transaction_value")
            }
            Self::CalculateTransactionValueBalances { .. } => {
                consensus("context.calculate_transaction_value_balances")
            }
            Self::CalculateBlockChainValueChange { .. } => {
                consensus("context.calculate_block_chain_value_change")
            }
            Self::AddValuePool { .. } => consensus("context.add_value_pool"),
            Self::UnknownSproutAnchor { .. } => consensus("context.unknown_sprout_anchor"),
            Self::UnknownSaplingAnchor { .. } => consensus("context.unknown_sapling_anchor"),
            Self::UnknownOrchardAnchor { .. } => consensus("context.unknown_orchard_anchor"),
            Self::UnknownIronwoodAnchor { .. } => consensus("context.unknown_ironwood_anchor"),
        }
    }

    // Keep this match exhaustive so new contextual errors must make an explicit
    // peer-attribution decision.
    fn misbehavior_score(&self) -> u32 {
        match self {
            // Consensus violations the block itself proves: the supplier sent a
            // block that no honest peer could have produced.
            ValidateContextError::NonSequentialBlock { .. }
            | ValidateContextError::TimeTooEarly { .. }
            | ValidateContextError::TimeTooLate { .. }
            | ValidateContextError::InvalidDifficultyThreshold { .. }
            | ValidateContextError::DuplicateTransparentSpend { .. }
            | ValidateContextError::MissingTransparentOutput { .. }
            | ValidateContextError::EarlyTransparentSpend { .. }
            | ValidateContextError::UnshieldedTransparentCoinbaseSpend { .. }
            | ValidateContextError::ImmatureTransparentCoinbaseSpend { .. }
            | ValidateContextError::DuplicateSproutNullifier { .. }
            | ValidateContextError::DuplicateSaplingNullifier { .. }
            | ValidateContextError::DuplicateOrchardNullifier { .. }
            | ValidateContextError::DuplicateIronwoodNullifier { .. }
            | ValidateContextError::NegativeRemainingTransactionValue { .. }
            | ValidateContextError::AddValuePool { .. }
            | ValidateContextError::InvalidBlockCommitment(_)
            | ValidateContextError::UnknownSproutAnchor { .. }
            | ValidateContextError::UnknownSaplingAnchor { .. }
            | ValidateContextError::UnknownOrchardAnchor { .. }
            | ValidateContextError::UnknownIronwoodAnchor { .. } => 100,

            // Residual arithmetic failures in our own value summation, not
            // consensus violations. `remaining_transaction_value()` and
            // `value_balance()` peel off the "this block creates money" case
            // into `NegativeRemainingTransactionValue`, and `AddValuePool`
            // carries the ZIP-209 non-negative pool rule. What reaches these
            // variants is an out-of-range or overflowing intermediate, which a
            // local bookkeeping bug can produce just as easily as a bad block.
            // Scoring them would let one such bug ban every honest peer in turn,
            // so they stay unscored alongside the other local-state failures.
            ValidateContextError::CalculateRemainingTransactionValue { .. }
            | ValidateContextError::CalculateTransactionValueBalances { .. }
            | ValidateContextError::CalculateBlockChainValueChange { .. }

            // Failures that are not attributable to the block's supplier:
            // local state and tree errors, operator invalidation, stale forks,
            // out-of-order arrival, retryable stalls, and auxiliary roots that
            // may have come from a different peer.
            | ValidateContextError::MissingSproutTipTree(_)
            | ValidateContextError::BlockPreviouslyInvalidated { .. }
            | ValidateContextError::NotReadyToBeCommitted
            | ValidateContextError::InvalidAncestorBlock(_)
            | ValidateContextError::VctSuppliedRootUnavailable { .. }
            | ValidateContextError::VctSuppliedRootAwaitingSuccessor { .. }
            | ValidateContextError::VctBlockAuthDataRootMismatch { .. }
            | ValidateContextError::VctSproutHandoffRootMismatch { .. }
            | ValidateContextError::CumulativeWorkOverflow { .. }
            | ValidateContextError::OrphanedBlock { .. }
            | ValidateContextError::NoteCommitmentTreeError(_)
            | ValidateContextError::HistoryTreeError(_) => 0,
        }
    }

    /// Returns the missing VCT supplied-root height for retryable root stalls.
    ///
    /// The query returns the subset of [`Self::vct_retryable_height`] where the supplied root is
    /// missing. The peer either omitted the root from its header range or supplied a root that
    /// verification later evicted. Only a later delivery of the same header range can fill the
    /// missing root. Header sync does not request individual roots. An await-successor stall
    /// ([`Self::vct_retryable_height`] but not this method) already has its root
    /// and only waits for the next header to be stored.
    pub fn vct_supplied_root_unavailable_height(&self) -> Option<block::Height> {
        match self {
            ValidateContextError::VctSuppliedRootUnavailable { height } => Some(*height),
            _ => None,
        }
    }

    /// Returns the height for any retryable VCT root stall: either an absent/evicted supplied
    /// root ([`Self::VctSuppliedRootUnavailable`]) or one not yet verifiable because no successor
    /// is buffered to confirm it ([`Self::VctSuppliedRootAwaitingSuccessor`]). The write loop
    /// parks and retries the same block for both; the former polls slower because nothing is
    /// actively fetching a replacement root.
    pub fn vct_retryable_height(&self) -> Option<block::Height> {
        match self {
            ValidateContextError::VctSuppliedRootUnavailable { height }
            | ValidateContextError::VctSuppliedRootAwaitingSuccessor { height } => Some(*height),
            _ => None,
        }
    }
}

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,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zakura_header_chain::{
        BodyCommitmentKind, BodyVerificationClass, TransientBodyFailureKind,
    };

    #[test]
    fn body_verification_classes_preserve_attribution_boundaries() {
        assert_eq!(
            ValidateContextError::VctSuppliedRootUnavailable { height: Height(7) }
                .body_verification_class(),
            BodyVerificationClass::Retryable(TransientBodyFailureKind::MissingContext)
        );
        assert_eq!(
            ValidateContextError::InvalidAncestorBlock(block::Hash([9; 32]))
                .body_verification_class(),
            BodyVerificationClass::Retryable(TransientBodyFailureKind::Canceled)
        );
        assert_eq!(
            ValidateContextError::VctBlockAuthDataRootMismatch {
                height: Height(7),
                expected: block::merkle::AuthDataRoot::from([1; 32]),
                actual: block::merkle::AuthDataRoot::from([2; 32]),
            }
            .body_verification_class(),
            BodyVerificationClass::PayloadMismatch(BodyCommitmentKind::AuthDataRoot)
        );
        assert_eq!(
            ValidateContextError::DuplicateTransparentSpend {
                outpoint: transparent::OutPoint {
                    hash: [3; 32].into(),
                    index: 0,
                },
                location: "test chain",
            }
            .body_verification_class(),
            BodyVerificationClass::ConsensusInvalid(zakura_header_chain::BodyRuleId::new(
                "context.duplicate_transparent_spend"
            ))
        );
        assert_eq!(
            CommitBlockError::HeaderChainError {
                error: "local transition failure".to_owned(),
            }
            .body_verification_class(),
            BodyVerificationClass::Retryable(TransientBodyFailureKind::Storage)
        );
        assert_eq!(
            CommitBlockError::Duplicate {
                hash_or_height: None,
                location: KnownBlock::BestChain,
            }
            .body_verification_class(),
            BodyVerificationClass::Duplicate
        );
    }

    #[test]
    // DF-02: representative contextual failures cover every shared body
    // classification, so the two validation paths retain only intended differences.
    fn contextual_body_failure_classes_match_header_engine_contract() {
        use zakura_chain::value_balance::ValueBalanceError;
        use zakura_header_chain::{BodyRuleId, BodyVerificationClass};

        let outpoint = transparent::OutPoint {
            hash: [3; 32].into(),
            index: 0,
        };
        let transaction_hash = transaction::Hash::from([4; 32]);
        let now = Utc::now();
        let cases = [
            (
                ValidateContextError::DuplicateTransparentSpend {
                    outpoint,
                    location: "test chain",
                }
                .body_verification_class(),
                BodyVerificationClass::ConsensusInvalid(BodyRuleId::new(
                    "context.duplicate_transparent_spend",
                )),
            ),
            (
                ValidateContextError::DuplicateSproutNullifier {
                    nullifier: sprout::Nullifier::from([6; 32]),
                    in_finalized_state: false,
                }
                .body_verification_class(),
                BodyVerificationClass::ConsensusInvalid(BodyRuleId::new(
                    "context.duplicate_sprout_nullifier",
                )),
            ),
            (
                ValidateContextError::UnknownSproutAnchor {
                    anchor: sprout::tree::Root::default(),
                    height: Some(Height(7)),
                    tx_index_in_block: Some(0),
                    transaction_hash,
                }
                .body_verification_class(),
                BodyVerificationClass::ConsensusInvalid(BodyRuleId::new(
                    "context.unknown_sprout_anchor",
                )),
            ),
            (
                ValidateContextError::CalculateBlockChainValueChange {
                    value_balance_error: ValueBalanceError::Unparsable,
                    height: Height(7),
                    block_hash: block::Hash([5; 32]),
                    transaction_count: 1,
                    spent_utxo_count: 1,
                }
                .body_verification_class(),
                BodyVerificationClass::ConsensusInvalid(BodyRuleId::new(
                    "context.calculate_block_chain_value_change",
                )),
            ),
            (
                ValidateContextError::TimeTooLate {
                    candidate_time: now,
                    block_time_max: now - chrono::Duration::seconds(1),
                }
                .body_verification_class(),
                BodyVerificationClass::Retryable(TransientBodyFailureKind::VerifierUnavailable),
            ),
            (
                CommitBlockError::HeaderChainError {
                    error: "local transition failure".to_owned(),
                }
                .body_verification_class(),
                BodyVerificationClass::Retryable(TransientBodyFailureKind::Storage),
            ),
        ];

        for (actual, expected) in cases {
            assert_eq!(actual, expected);
        }
    }
    use zakura_chain::{
        block::{CommitmentError, Height},
        parameters::Network,
        work::difficulty::{ParameterDifficulty, INVALID_COMPACT_DIFFICULTY},
    };

    #[test]
    fn commit_block_error_misbehavior_scores() {
        let block_time = DateTime::from_timestamp(1_000_000, 0)
            .expect("test timestamp is in the supported range");
        let height = Height(5);
        let transaction_hash = transaction::Hash([2; 32]);
        let outpoint = transparent::OutPoint {
            hash: transaction_hash,
            index: 0,
        };
        let amount_error = amount::Error::Constraint {
            value: -1,
            range: 0..=1,
        };
        let value_balance_error = ValueBalanceError::Transparent(amount_error.clone());
        let orchard_nullifier = orchard::Nullifier::try_from([0; 32])
            .expect("zero is a canonical Orchard nullifier encoding");
        // Residual arithmetic failures in our own value summation. A local
        // bookkeeping bug produces these just as easily as a bad block does, so
        // they must not ban the peer that supplied the block.
        let arithmetic_faults = [
            ValidateContextError::CalculateRemainingTransactionValue {
                amount_error: amount_error.clone(),
                height,
                tx_index_in_block: 1,
                transaction_hash,
            },
            ValidateContextError::CalculateTransactionValueBalances {
                value_balance_error: value_balance_error.clone(),
                height,
                tx_index_in_block: 1,
                transaction_hash,
            },
            ValidateContextError::CalculateBlockChainValueChange {
                value_balance_error: value_balance_error.clone(),
                height,
                block_hash: block::Hash([3; 32]),
                transaction_count: 2,
                spent_utxo_count: 1,
            },
        ];

        let peer_faults = [
            ValidateContextError::NonSequentialBlock {
                candidate_height: height,
                parent_height: Height(3),
            },
            ValidateContextError::TimeTooEarly {
                candidate_time: block_time,
                median_time_past: block_time,
            },
            ValidateContextError::TimeTooLate {
                candidate_time: block_time,
                block_time_max: block_time,
            },
            ValidateContextError::InvalidDifficultyThreshold {
                difficulty_threshold: INVALID_COMPACT_DIFFICULTY,
                expected_difficulty: Network::Mainnet.target_difficulty_limit().to_compact(),
            },
            ValidateContextError::DuplicateTransparentSpend {
                outpoint,
                location: "test chain",
            },
            ValidateContextError::MissingTransparentOutput {
                outpoint,
                location: "test chain",
            },
            ValidateContextError::EarlyTransparentSpend { outpoint },
            ValidateContextError::UnshieldedTransparentCoinbaseSpend { outpoint },
            ValidateContextError::ImmatureTransparentCoinbaseSpend {
                outpoint,
                spend_height: height,
                min_spend_height: Height(100),
                created_height: Height(1),
            },
            ValidateContextError::DuplicateSproutNullifier {
                nullifier: sprout::Nullifier::from([0; 32]),
                in_finalized_state: false,
            },
            ValidateContextError::DuplicateSaplingNullifier {
                nullifier: sapling::Nullifier::from([0; 32]),
                in_finalized_state: false,
            },
            ValidateContextError::DuplicateOrchardNullifier {
                nullifier: orchard_nullifier,
                in_finalized_state: false,
            },
            ValidateContextError::DuplicateIronwoodNullifier {
                nullifier: orchard_nullifier,
                in_finalized_state: false,
            },
            ValidateContextError::NegativeRemainingTransactionValue {
                amount_error: amount_error.clone(),
                height,
                tx_index_in_block: 1,
                transaction_hash,
            },
            ValidateContextError::AddValuePool {
                value_balance_error,
                chain_value_pools: Box::new(ValueBalance::<NonNegative>::zero()),
                block_value_pool_change: Box::new(ValueBalance::<NegativeAllowed>::zero()),
                height: Some(height),
            },
            ValidateContextError::InvalidBlockCommitment(
                CommitmentError::InvalidChainHistoryActivationReserved { actual: [1; 32] },
            ),
            ValidateContextError::UnknownSproutAnchor {
                anchor: sprout::tree::Root::default(),
                height: Some(height),
                tx_index_in_block: Some(1),
                transaction_hash,
            },
            ValidateContextError::UnknownSaplingAnchor {
                anchor: sapling::tree::Root::default(),
                height: Some(height),
                tx_index_in_block: Some(1),
                transaction_hash,
            },
            ValidateContextError::UnknownOrchardAnchor {
                anchor: orchard::tree::Root::default(),
                height: Some(height),
                tx_index_in_block: Some(1),
                transaction_hash,
            },
            ValidateContextError::UnknownIronwoodAnchor {
                anchor: ironwood::tree::Root::default(),
                height: Some(height),
                tx_index_in_block: Some(1),
                transaction_hash,
            },
        ];

        for error in peer_faults {
            let commit_error = CommitBlockError::ValidateContextError(Box::new(error));
            assert_eq!(
                commit_error.misbehavior_score(),
                100,
                "direct contextual consensus failure must be scored: {commit_error:?}"
            );
        }

        for error in arithmetic_faults {
            let commit_error = CommitBlockError::ValidateContextError(Box::new(error));
            assert_eq!(
                commit_error.misbehavior_score(),
                0,
                "value-summation arithmetic failure must not be attributed to a peer: \
                 {commit_error:?}"
            );
        }

        let transient_context_error = CommitBlockError::ValidateContextError(Box::new(
            ValidateContextError::NotReadyToBeCommitted,
        ));
        assert_eq!(transient_context_error.misbehavior_score(), 0);

        let invalid_ancestor_error = CommitBlockError::ValidateContextError(Box::new(
            ValidateContextError::InvalidAncestorBlock(block::Hash([1; 32])),
        ));
        assert_eq!(invalid_ancestor_error.misbehavior_score(), 0);

        let stale_fork_error =
            CommitBlockError::ValidateContextError(Box::new(ValidateContextError::OrphanedBlock {
                candidate_height: Height(3),
                finalized_tip_height: height,
            }));
        assert_eq!(stale_fork_error.misbehavior_score(), 0);

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

    #[test]
    fn checkpoint_error_exposes_retryable_vct_root_height() {
        let height = Height(42);
        let retryable =
            CommitCheckpointVerifiedError::from(ValidateContextError::VctSuppliedRootUnavailable {
                height,
            })
            .with_vct_failure(VctCommitFailure::SuccessorBoundary);
        assert_eq!(
            retryable.vct_supplied_root_unavailable_height(),
            Some(height),
            "checkpoint commit errors expose retryable VCT root misses"
        );
        assert_eq!(
            retryable.vct_failure(),
            Some(VctCommitFailure::SuccessorBoundary),
            "checkpoint errors preserve the exact VCT verifier stage"
        );

        let non_retryable: CommitCheckpointVerifiedError =
            ValidateContextError::NonSequentialBlock {
                candidate_height: Height(5),
                parent_height: Height(3),
            }
            .into();
        assert_eq!(
            non_retryable.vct_supplied_root_unavailable_height(),
            None,
            "unrelated validation errors are not treated as VCT root misses"
        );
        assert_eq!(
            non_retryable.vct_retryable_height(),
            None,
            "unrelated validation errors are not retryable VCT stalls"
        );
    }

    /// An await-successor stall is retryable (the write loop parks and re-commits) but is
    /// *not* a missing-root case: the root is present, only its successor is missing. So it
    /// must surface through `vct_retryable_height` while
    /// `vct_supplied_root_unavailable_height` (which selects the slower missing-root wait)
    /// stays `None` — otherwise the committer would poll slowly for a root it already holds.
    #[test]
    fn await_successor_is_retryable_but_not_root_unavailable() {
        let height = Height(7);
        let awaiting: CommitCheckpointVerifiedError =
            ValidateContextError::VctSuppliedRootAwaitingSuccessor { height }.into();

        assert_eq!(
            awaiting.vct_retryable_height(),
            Some(height),
            "an await-successor stall is retryable",
        );
        assert_eq!(
            awaiting.vct_supplied_root_unavailable_height(),
            None,
            "an await-successor stall is not a missing root (the root is present)",
        );

        // The unavailable case is both retryable and a missing root.
        let unavailable: CommitCheckpointVerifiedError =
            ValidateContextError::VctSuppliedRootUnavailable { height }.into();
        assert_eq!(unavailable.vct_retryable_height(), Some(height));
        assert_eq!(
            unavailable.vct_supplied_root_unavailable_height(),
            Some(height)
        );
    }
}