miden-protocol 0.17.0-rc.4

Core components of the Miden protocol
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
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::error::Error;

use miden_assembly::Report;
use miden_assembly::diagnostics::reporting::PrintDiagnostic;
use miden_core::deferred::IntegrityError;
use miden_core::mast::MastForestError;
use miden_crypto::merkle::mmr::MmrError;
use miden_crypto::merkle::smt::{SmtLeafError, SmtProofError};
use miden_crypto::utils::HexParseError;
use miden_processor::ExecutionError;
use miden_verifier::VerificationError;
use thiserror::Error;

use super::account::{AccountId, RoleSymbol};
use super::asset::{Asset, AssetComposition, AssetId, FungibleAsset, TokenSymbol};
use super::crypto::merkle::MerkleError;
use super::note::NoteId;
use super::{
    MAX_ACCOUNTS_PER_BLOCK,
    MAX_BATCHES_PER_BLOCK,
    MAX_INPUT_NOTES_PER_BLOCK,
    MAX_OUTPUT_NOTES_PER_BATCH,
    Word,
};
use crate::account::component::{SchemaTypeError, StorageValueName, StorageValueNameError};
use crate::account::delta::AssetDeltaOperation;
use crate::account::{
    AccountCode,
    AccountHeader,
    AccountIdPrefix,
    AccountProcedureRoot,
    AccountStorage,
    AccountVaultDelta,
    StorageMapKey,
    StorageSlotId,
    StorageSlotName,
};
use crate::address::AddressType;
use crate::asset::AssetClass;
use crate::batch::BatchId;
use crate::block::{BlockNumber, ValidatorConfig};
use crate::note::{
    NoteAssets,
    NoteAttachment,
    NoteAttachmentScheme,
    NoteAttachments,
    NoteTag,
    NoteType,
    Nullifier,
};
use crate::protocol_config::KernelConfig;
use crate::script::MastForestScriptError;
use crate::transaction::TransactionId;
use crate::utils::serde::DeserializationError;
use crate::vm::EventId;
use crate::{
    ACCOUNT_UPDATE_MAX_SIZE,
    Felt,
    MAX_ACCOUNTS_PER_BATCH,
    MAX_INPUT_NOTES_PER_BATCH,
    MAX_INPUT_NOTES_PER_TX,
    MAX_NOTE_STORAGE_ITEMS,
    MAX_OUTPUT_NOTES_PER_TX,
    NOTE_MAX_SIZE,
};

#[cfg(any(feature = "testing", test))]
mod masm_error;
#[cfg(any(feature = "testing", test))]
pub use masm_error::MasmError;

/// The errors from the MASM code of the transaction kernel.
#[cfg(any(feature = "testing", test))]
pub mod tx_kernel {
    include!(concat!(env!("OUT_DIR"), "/tx_kernel_errors.rs"));
}

/// The errors from the MASM code of the Miden protocol library.
#[cfg(any(feature = "testing", test))]
pub mod protocol {
    include!(concat!(env!("OUT_DIR"), "/protocol_errors.rs"));
}

// ACCOUNT COMPONENT TEMPLATE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum ComponentMetadataError {
    #[error("storage slot name `{0}` is duplicate")]
    DuplicateSlotName(StorageSlotName),
    #[error("storage init value name `{0}` is duplicate")]
    DuplicateInitValueName(StorageValueName),
    #[error("storage value name is incorrect: {0}")]
    IncorrectStorageValueName(#[source] StorageValueNameError),
    #[error("invalid storage schema: {0}")]
    InvalidSchema(String),
    #[error("type `{0}` is not valid for `{1}` slots")]
    InvalidType(String, String),
    #[error("error deserializing component metadata: {0}")]
    MetadataDeserializationError(String),
    #[error("init storage value `{0}` was not provided")]
    InitValueNotProvided(StorageValueName),
    #[error("invalid init storage value for `{0}`: {1}")]
    InvalidInitStorageValue(StorageValueName, String),
    #[error("error converting value into expected type: {0}")]
    StorageValueParsingError(#[source] SchemaTypeError),
    #[error("storage map contains duplicate keys")]
    StorageMapHasDuplicateKeys(#[source] Box<dyn Error + Send + Sync + 'static>),
    #[cfg(feature = "std")]
    #[error("error trying to deserialize from toml")]
    TomlDeserializationError(#[source] toml::de::Error),
    #[cfg(feature = "std")]
    #[error("error trying to deserialize from toml")]
    TomlSerializationError(#[source] toml::ser::Error),
}

// ACCOUNT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountError {
    #[error("account code does not contain an auth component")]
    AccountCodeNoAuthComponent,
    #[error("account code contains multiple auth components")]
    AccountCodeMultipleAuthComponents,
    #[error("account code must contain at least one non-auth procedure")]
    AccountCodeNoProcedures,
    #[error("account procedure {0} is not contained in the provided mast forest")]
    AccountCodeProcedureNotInMastForest(AccountProcedureRoot),
    #[error("account code contains {0} procedures but it may contain at most {max} procedures", max = AccountCode::MAX_NUM_PROCEDURES)]
    AccountCodeTooManyProcedures(usize),
    #[error("account code contains a duplicate procedure with root {0}")]
    AccountCodeDuplicateProcedureRoot(AccountProcedureRoot),
    #[error(
        "account code procedures following the authentication procedure are not sorted in ascending order"
    )]
    AccountCodeProceduresUnsorted,
    #[error("failed to assemble account component:\n{}", PrintDiagnostic::new(.0))]
    AccountComponentAssemblyError(Report),
    #[error("failed to merge components into one account code mast forest")]
    AccountComponentMastForestMergeError(#[source] MastForestError),
    #[error("account component contains multiple authentication procedures")]
    AccountComponentMultipleAuthProcedures,
    #[error(
        "storage of account {0} contains an asset callback slot but its asset callback flag is disabled, so the callback would never be invoked"
    )]
    AssetCallbackSlotWithDisabledFlag(AccountId),
    #[error("failed to update asset vault")]
    AssetVaultUpdateError(#[source] AssetVaultError),
    #[error("account build error: {0}")]
    BuildError(String, #[source] Option<Box<AccountError>>),
    #[error("failed to parse account ID from final account header")]
    FinalAccountHeaderIdParsingFailed(#[source] AccountIdError),
    #[error("account header data has length {actual} but it must be of length {expected}",
        expected = AccountHeader::NUM_ELEMENTS
    )]
    UnexpectedHeaderLength { actual: usize },
    #[error("account has an unsupported version {0}")]
    UnsupportedAccountVersion(u64),
    #[error("final nonce {new} is not strictly greater than current account nonce {current}")]
    NonceMustIncrease { current: Felt, new: Felt },
    #[error(
        "digest of the seed has {actual} trailing zeroes but must have at least {expected} trailing zeroes"
    )]
    SeedDigestTooFewTrailingZeros { expected: u32, actual: u32 },
    #[error("account ID {actual} computed from seed does not match ID {expected} on account")]
    AccountIdSeedMismatch { actual: AccountId, expected: AccountId },
    #[error("account ID seed was provided for an existing account")]
    ExistingAccountWithSeed,
    #[error("account ID seed was not provided for a new account")]
    NewAccountMissingSeed,
    #[error(
        "an account with a seed cannot be converted into a delta since it represents an unregistered account"
    )]
    DeltaFromAccountWithSeed,
    #[error(
        "an account with a seed cannot be converted into a patch since it represents an unregistered account"
    )]
    PatchFromAccountWithSeed,
    #[error("seed converts to an invalid account ID")]
    SeedConvertsToInvalidAccountId(#[source] AccountIdError),
    #[error("storage map root {0} not found in the account storage")]
    StorageMapRootNotFound(Word),
    #[error("storage slot {0} is not of type map")]
    StorageSlotNotMap(StorageSlotName),
    #[error("storage slot {0} is not of type value")]
    StorageSlotNotValue(StorageSlotName),
    #[error("storage slot name {0} is assigned to more than one slot")]
    DuplicateStorageSlotName(StorageSlotName),
    #[error("storage does not contain a slot with name {slot_name}")]
    StorageSlotNameNotFound { slot_name: StorageSlotName },
    #[error("storage does not contain a slot with ID {slot_id}")]
    StorageSlotIdNotFound { slot_id: StorageSlotId },
    #[error("storage slots must be sorted by slot ID")]
    UnsortedStorageSlots,
    #[error("reserved element of a storage slot must be zero but was {0}")]
    StorageSlotReservedElementNotZero(Felt),
    #[error("number of storage slots is {0} but max possible number is {max}", max = AccountStorage::MAX_NUM_STORAGE_SLOTS)]
    StorageTooManySlots(u64),
    #[error(
        "failed to apply full state patch to existing account; full state patches can be converted to accounts directly"
    )]
    ApplyFullStatePatchToAccount,
    #[error("patch is for account ID {patch_id} but is being applied to account {account_id}")]
    PatchAccountIdMismatch {
        account_id: AccountId,
        patch_id: AccountId,
    },
    #[error("only account deltas representing a full account can be converted to a full account")]
    PartialStateDeltaToAccount,
    #[error("assets cannot be removed from a new account with an empty asset vault")]
    AssetsRemovedFromNewAccount,
    #[error("only account patches representing a full account can be converted to a full account")]
    PartialStatePatchToAccount,
    #[error("maximum number of storage map leaves exceeded")]
    MaxNumStorageMapLeavesExceeded(#[source] MerkleError),
    #[error("unknown storage patch operation tag {0}")]
    UnknownStoragePatchOperation(u8),
    /// This variant can be used by methods that are not inherent to the account but want to return
    /// this error type.
    #[error("{error_msg}")]
    Other {
        error_msg: Box<str>,
        // thiserror will return this when calling Error::source on AccountError.
        source: Option<Box<dyn Error + Send + Sync + 'static>>,
    },
}

impl AccountError {
    /// Creates a custom error using the [`AccountError::Other`] variant from an error message.
    pub fn other(message: impl Into<String>) -> Self {
        let message: String = message.into();
        Self::Other { error_msg: message.into(), source: None }
    }

    /// Creates a custom error using the [`AccountError::Other`] variant from an error message and
    /// a source error.
    pub fn other_with_source(
        message: impl Into<String>,
        source: impl Error + Send + Sync + 'static,
    ) -> Self {
        let message: String = message.into();
        Self::Other {
            error_msg: message.into(),
            source: Some(Box::new(source)),
        }
    }
}

/// Error returned when account update details are incompatible with an account ID.
#[derive(Debug)]
pub(crate) enum AccountUpdateDetailsValidationError {
    PrivateAccountWithDetails(AccountId),
    PublicStateAccountMissingDetails(AccountId),
    AccountIdMismatch {
        account_id: AccountId,
        patch_account_id: AccountId,
    },
}

/// Error returned when serialized account update details exceed the size limit.
#[derive(Debug)]
pub(crate) struct AccountUpdateSizeValidationError {
    pub(crate) account_id: AccountId,
    pub(crate) update_size: usize,
}

/// Error returned when a new public account cannot be reconstructed from its update details.
#[derive(Debug)]
pub(crate) enum NewPublicAccountValidationError {
    RequiresFullStatePatch {
        id: AccountId,
        source: AccountError,
    },
    FinalCommitmentMismatch {
        final_state_commitment: Word,
        account_commitment: Word,
    },
}

// ACCOUNT ID ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountIdError {
    #[error("failed to convert bytes into account ID prefix field element")]
    AccountIdInvalidPrefixFieldElement(#[source] DeserializationError),
    #[error("failed to convert bytes into account ID suffix field element")]
    AccountIdInvalidSuffixFieldElement(#[source] DeserializationError),
    #[error("`{0}` is not a known account type")]
    UnknownAccountType(Box<str>),
    #[error("failed to parse hex string into account ID")]
    AccountIdHexParseError(#[source] HexParseError),
    #[error("`{0}` is not a known account ID version")]
    UnknownAccountIdVersion(u8),
    #[error("most significant bit of account ID suffix must be zero")]
    AccountIdSuffixMostSignificantBitMustBeZero,
    #[error("least significant byte of account ID suffix must be zero")]
    AccountIdSuffixLeastSignificantByteMustBeZero,
    #[error("failed to decode bech32 string into account ID")]
    Bech32DecodeError(#[source] Bech32Error),
}

// SLOT NAME ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum StorageSlotNameError {
    #[error("slot name must only contain characters a..z, A..Z, 0..9, double colon or underscore")]
    InvalidCharacter,
    #[error("slot names must be separated by double colons")]
    UnexpectedColon,
    #[error("slot name components must not start with an underscore")]
    UnexpectedUnderscore,
    #[error(
        "slot names must contain at least {} components separated by double colons",
        StorageSlotName::MIN_NUM_COMPONENTS
    )]
    TooShort,
    #[error("slot names must contain at most {} characters", StorageSlotName::MAX_LENGTH)]
    TooLong,
}

// ACCOUNT CODE INTERFACE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountCodeInterfaceError {
    #[error(
        "account code interface must contain at least {} procedures, but only {actual} were given",
        AccountCode::MIN_NUM_PROCEDURES
    )]
    TooFewProcedures { actual: usize },
    #[error(
        "account code interface contains {actual} procedures but it may contain at most {} procedures",
        AccountCode::MAX_NUM_PROCEDURES
    )]
    TooManyProcedures { actual: usize },
}

// ACCOUNT COMPONENT NAME ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountComponentNameError {
    #[error(
        "account component name must only contain characters a..z, A..Z, 0..9, double colon or underscore"
    )]
    InvalidCharacter,
    #[error("account component names must be separated by double colons")]
    UnexpectedColon,
    #[error("account component name components must not start with an underscore")]
    UnexpectedUnderscore,
    #[error(
        "account component names must contain at least {} components separated by double colons",
        StorageSlotName::MIN_NUM_COMPONENTS
    )]
    TooShort,
    #[error(
        "account component names must contain at most {} characters",
        StorageSlotName::MAX_LENGTH
    )]
    TooLong,
}

// ACCOUNT TREE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountTreeError {
    #[error(
        "account tree contains multiple account IDs that share the same prefix {duplicate_prefix}"
    )]
    DuplicateIdPrefix { duplicate_prefix: AccountIdPrefix },
    #[error(
        "entries passed to account tree contain multiple state commitments for the same account ID prefix {prefix}"
    )]
    DuplicateStateCommitments { prefix: AccountIdPrefix },
    #[error("untracked account ID {id} used in partial account tree")]
    UntrackedAccountId { id: AccountId, source: MerkleError },
    #[error("new tree root after account witness insertion does not match previous tree root")]
    TreeRootConflict(#[source] MerkleError),
    #[error("failed to apply mutations to account tree")]
    ApplyMutations(#[source] MerkleError),
    #[error("failed to compute account tree mutations")]
    ComputeMutations(#[source] MerkleError),
    #[error("provided smt contains an invalid account ID in key {key}")]
    InvalidAccountIdKey { key: Word, source: AccountIdError },
    #[error("smt leaf's index is not a valid account ID prefix")]
    InvalidAccountIdPrefix(#[source] AccountIdError),
    #[error("account witness merkle path depth {0} does not match AccountTree::DEPTH")]
    WitnessMerklePathDepthDoesNotMatchAccountTreeDepth(usize),
}

// ADDRESS ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AddressError {
    #[error("tag length {0} is too large, must be less than or equal to {max}",
        max = NoteTag::MAX_ACCOUNT_TARGET_TAG_LENGTH
    )]
    TagLengthTooLarge(u8),
    #[error("unknown address interface `{0}`")]
    UnknownAddressInterface(u16),
    #[error("failed to decode account ID")]
    AccountIdDecodeError(#[source] AccountIdError),
    #[error("address separator must not be included without routing parameters")]
    TrailingSeparator,
    #[error("failed to decode bech32 string into an address")]
    Bech32DecodeError(#[source] Bech32Error),
    #[error("{error_msg}")]
    DecodeError {
        error_msg: Box<str>,
        // thiserror will return this when calling Error::source on AddressError.
        source: Option<Box<dyn Error + Send + Sync + 'static>>,
    },
    #[error("found unknown routing parameter key {0}")]
    UnknownRoutingParameterKey(u8),
}

impl AddressError {
    /// Creates an [`AddressError::DecodeError`] variant from an error message.
    pub fn decode_error(message: impl Into<String>) -> Self {
        let message: String = message.into();
        Self::DecodeError { error_msg: message.into(), source: None }
    }

    /// Creates an [`AddressError::DecodeError`] variant from an error message and
    /// a source error.
    pub fn decode_error_with_source(
        message: impl Into<String>,
        source: impl Error + Send + Sync + 'static,
    ) -> Self {
        let message: String = message.into();
        Self::DecodeError {
            error_msg: message.into(),
            source: Some(Box::new(source)),
        }
    }
}

// BECH32 ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum Bech32Error {
    #[error(transparent)]
    DecodeError(Box<dyn Error + Send + Sync + 'static>),
    #[error("found unknown address type {0} which is not the expected {account_addr} account ID address type",
      account_addr = AddressType::AccountId as u8
    )]
    UnknownAddressType(u8),
    #[error("expected bech32 data to be of length {expected} but it was of length {actual}")]
    InvalidDataLength { expected: usize, actual: usize },
}

// NETWORK ID ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum NetworkIdError {
    #[error("failed to parse string into a network ID")]
    NetworkIdParseError(#[source] Box<dyn Error + Send + Sync + 'static>),
}

// ACCOUNT DELTA ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountDeltaError {
    #[error("storage slot {0} was used as different slot types")]
    StorageSlotUsedAsDifferentTypes(StorageSlotName),
    #[error("asset {0} is changed by more than one asset delta")]
    DuplicateAssetDelta(AssetId),
    #[error(
        "number of {delta_op} operations in account vault delta is {num_ops} but max is {max}",
        max = AccountVaultDelta::MAX_ASSETS_PER_DELTA_OP
    )]
    TooManyVaultAssetDeltas {
        delta_op: AssetDeltaOperation,
        num_ops: usize,
    },
    #[error(
        "account update of type `{left_update_type}` cannot be merged with account update of type `{right_update_type}`"
    )]
    IncompatibleAccountUpdates {
        left_update_type: &'static str,
        right_update_type: &'static str,
    },
    #[error("account delta could not be applied to account {account_id}")]
    AccountDeltaApplicationFailed {
        account_id: AccountId,
        source: AccountError,
    },
    #[error("non-empty account storage or vault delta with zero nonce delta is not allowed")]
    NonEmptyStorageOrVaultDeltaWithZeroNonceDelta,
    #[error("cannot merge two full state deltas")]
    MergingFullStateDeltas,
    #[error("a full state delta must only contain storage create operations")]
    FullStateDeltaContainsNonCreateOp,
}

#[derive(Debug, Error)]
pub enum AccountPatchError {
    #[error("final nonce can never be set to zero")]
    FinalNonceIsZero,

    #[error(
        "state change to an account (store, vault or code) require that the final nonce is incremented"
    )]
    StateChangeRequiresNonceUpdate,

    #[error("account code must be provided for new accounts (with nonce = 1)")]
    CodeMustBeProvidedForNewAccounts,

    #[error("a full state patch must only contain storage create operations")]
    FullStatePatchContainsNonCreateStorageOp,

    #[error("storage slot {0} was used as different slot types")]
    StorageSlotUsedAsDifferentTypes(StorageSlotName),

    #[error("storage slot name {0} is assigned to more than one slot patch")]
    DuplicateStorageSlotName(StorageSlotName),

    #[error("number of storage slot patches is {0} but max possible number is {max}", max = AccountStorage::MAX_NUM_STORAGE_SLOTS)]
    TooManyStorageSlotPatches(usize),

    #[error(
        "a full state patch cannot be merged on top of another patch; it must be the merge base"
    )]
    MergeIncomingFullStatePatch,

    #[error("failed to merge storage patch for slot {0}: cannot create a slot twice")]
    StoragePatchMergeDoubleCreate(StorageSlotName),

    #[error(
        "failed to merge storage patch for slot {0}: cannot create a slot after it was updated, which indicates it already exists"
    )]
    StoragePatchMergeCreateAfterUpdate(StorageSlotName),

    #[error("failed to merge storage patch for slot {0}: cannot update slot after it was removed")]
    StoragePatchMergeUpdateAfterRemove(StorageSlotName),

    #[error("failed to merge storage patch for slot {0}: cannot remove a slot twice")]
    StoragePatchMergeDoubleRemove(StorageSlotName),

    #[error(
        "nonce in the patch being merged is {new} which is not exactly one greater than current patch nonce {current}"
    )]
    NonceMustIncrementByOne { current: Felt, new: Felt },

    #[error(
        "patch is for account ID {actual} but is being merged into patch for account {expected}"
    )]
    AccountIdMismatch { expected: AccountId, actual: AccountId },

    #[error(
        "account update of type `{left_update_type}` cannot be merged with account update of type `{right_update_type}`"
    )]
    IncompatibleAccountUpdates {
        left_update_type: &'static str,
        right_update_type: &'static str,
    },
}

// STORAGE MAP ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum StorageMapError {
    #[error("map entries contain key {key} twice with values {value0} and {value1}")]
    DuplicateKey {
        key: StorageMapKey,
        value0: Word,
        value1: Word,
    },
    #[error("map key {key} is not present in provided SMT proof")]
    MissingKey { key: StorageMapKey },
}

// BATCH ACCOUNT UPDATE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum BatchAccountUpdateError {
    #[error(
        "account update of size {update_size} for account {account_id} exceeds maximum update size of {ACCOUNT_UPDATE_MAX_SIZE}"
    )]
    AccountUpdateSizeLimitExceeded {
        account_id: AccountId,
        update_size: usize,
    },
    #[error("private account {0} should not have account details")]
    PrivateAccountWithDetails(AccountId),
    #[error("account {0} with public state is missing its account details")]
    PublicStateAccountMissingDetails(AccountId),
    #[error(
        "batch account update's account ID {account_id} and account patch ID {patch_account_id} must match"
    )]
    AccountIdMismatch {
        account_id: AccountId,
        patch_account_id: AccountId,
    },
    #[error("new account {id} with public state must be accompanied by a full state patch")]
    NewPublicStateAccountRequiresFullStatePatch { id: AccountId, source: AccountError },
    #[error(
        "batch account update's final commitment {final_state_commitment} and reconstructed account commitment {account_commitment} must match"
    )]
    AccountFinalCommitmentMismatch {
        final_state_commitment: Word,
        account_commitment: Word,
    },
    #[error(
        "account update for account {expected_account_id} cannot be merged with update from transaction {transaction} which was executed against account {actual_account_id}"
    )]
    AccountUpdateIdMismatch {
        transaction: TransactionId,
        expected_account_id: AccountId,
        actual_account_id: AccountId,
    },
    #[error(
        "final state commitment in account update from transaction {0} does not match initial state of current update"
    )]
    AccountUpdateInitialStateMismatch(TransactionId),
    #[error("failed to merge account patch from transaction {0}")]
    TransactionUpdateMergeError(TransactionId, #[source] Box<AccountPatchError>),
}

// BLOCK ACCOUNT UPDATE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum BlockAccountUpdateError {
    #[error("private account {0} should not have account details")]
    PrivateAccountWithDetails(AccountId),
    #[error("account {0} with public state is missing its account details")]
    PublicStateAccountMissingDetails(AccountId),
    #[error(
        "block account update's account ID {account_id} and account patch ID {patch_account_id} must match"
    )]
    AccountIdMismatch {
        account_id: AccountId,
        patch_account_id: AccountId,
    },
    #[error("new account {id} with public state must be accompanied by a full state patch")]
    NewPublicStateAccountRequiresFullStatePatch { id: AccountId, source: AccountError },
    #[error(
        "block account update's final commitment {final_state_commitment} and reconstructed account commitment {account_commitment} must match"
    )]
    AccountFinalCommitmentMismatch {
        final_state_commitment: Word,
        account_commitment: Word,
    },
}

// BLOCK BODY ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum BlockBodyError {
    #[error("block has {0} account updates but at most {MAX_ACCOUNTS_PER_BLOCK} are allowed")]
    TooManyAccountUpdates(usize),
    #[error("block has {0} nullifiers but at most {MAX_INPUT_NOTES_PER_BLOCK} are allowed")]
    TooManyNullifiers(usize),
    #[error("block has {0} output note batches but at most {MAX_BATCHES_PER_BLOCK} are allowed")]
    TooManyOutputNoteBatches(usize),
    #[error(
        "output note batch {batch_index} has {note_count} notes but at most {MAX_OUTPUT_NOTES_PER_BATCH} are allowed"
    )]
    TooManyOutputNotes { batch_index: usize, note_count: usize },
    #[error("output note batch {batch_index} contains invalid note index {note_index}")]
    InvalidOutputNoteIndex { batch_index: usize, note_index: usize },
    #[error("output note batch {batch_index} contains note index {note_index} twice")]
    DuplicateOutputNoteIndex { batch_index: usize, note_index: usize },
    #[error("output note {0} appears twice in the block body")]
    DuplicateOutputNote(NoteId),
    #[error("account update for {0} appears twice in the block body")]
    DuplicateAccountUpdate(AccountId),
    #[error("nullifier {0} appears twice in the block body")]
    DuplicateNullifier(Nullifier),
    #[error("transaction {0} appears twice in the block body")]
    DuplicateTransaction(TransactionId),
}

// ASSET ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AssetError {
    #[error(
      "fungible asset amount {0} exceeds the max allowed amount of {max_amount}",
      max_amount = FungibleAsset::MAX_AMOUNT
    )]
    FungibleAssetAmountTooBig(u64),
    #[error("subtracting {subtrahend} from fungible asset amount {minuend} would underflow")]
    FungibleAssetAmountNotSufficient { minuend: u64, subtrahend: u64 },
    #[error(
        "cannot combine fungible assets with different asset IDs: {original_id} and {other_id}"
    )]
    FungibleAssetInconsistentIds { original_id: AssetId, other_id: AssetId },
    #[error("faucet account ID in asset is invalid")]
    InvalidFaucetAccountId(#[source] Box<dyn Error + Send + Sync + 'static>),
    #[error(
        "asset class prefix and suffix in a non-fungible asset ID must match indices 0 and 1 in the value, but asset class was {asset_class} and value was {value}"
    )]
    NonFungibleAssetClassMustMatchValue { asset_class: AssetClass, value: Word },
    #[error("asset class prefix and suffix in a fungible asset ID must be zero but was {0}")]
    FungibleAssetClassMustBeZero(AssetClass),
    #[error(
        "the three most significant elements in a fungible asset's value must be zero but provided value was {0}"
    )]
    FungibleAssetValueMostSignificantElementsMustBeZero(Word),
    #[error("smt proof in asset witness contains invalid ID or value")]
    AssetWitnessInvalid(#[source] Box<AssetError>),
    #[error("asset ID {id} is not present in the provided asset witness SMT proof")]
    AssetWitnessMissingId { id: AssetId },
    #[error("unknown asset composition encoding: {0}")]
    UnknownAssetComposition(u8),
    #[error("unknown asset delta operation encoding: {0}")]
    UnknownAssetDeltaOperation(u8),
    #[error("asset composition {0:?} is not supported at this operational site")]
    UnsupportedAssetComposition(AssetComposition),
    #[error(
        "asset composition mismatch for faucet {faucet_id}: expected {expected:?}, found {actual:?}"
    )]
    AssetCompositionMismatch {
        faucet_id: AccountId,
        expected: AssetComposition,
        actual: AssetComposition,
    },
    #[error("asset metadata byte 0x{0:02x} has reserved bits set to non-zero values")]
    ReservedAssetMetadata(u8),
    #[error("unknown asset ID version: {0}")]
    UnknownAssetIdVersion(u8),
}

// TOKEN SYMBOL ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TokenSymbolError {
    #[error("token symbol value {0} cannot exceed {max}", max = TokenSymbol::MAX_ENCODED_VALUE)]
    ValueTooLarge(u64),
    #[error(
        "token symbol value {0} cannot be less than {min}",
        min = TokenSymbol::MIN_ENCODED_VALUE
    )]
    ValueTooSmall(u64),
    #[error("token symbol should have length between 1 and 12 characters, but {0} was provided")]
    InvalidLength(usize),
    #[error("token symbol contains a character that is not uppercase ASCII")]
    InvalidCharacter,
    #[error("token symbol data left after decoding the specified number of characters")]
    DataNotFullyDecoded,
}

impl From<ShortCapitalStringError> for TokenSymbolError {
    fn from(value: ShortCapitalStringError) -> Self {
        match value {
            ShortCapitalStringError::ValueTooLarge(v) => Self::ValueTooLarge(v),
            ShortCapitalStringError::ValueTooSmall(v) => Self::ValueTooSmall(v),
            ShortCapitalStringError::InvalidLength(v) => Self::InvalidLength(v),
            ShortCapitalStringError::InvalidCharacter => Self::InvalidCharacter,
            ShortCapitalStringError::DataNotFullyDecoded => Self::DataNotFullyDecoded,
        }
    }
}

// ROLE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum RoleSymbolError {
    #[error("role symbol value {0} cannot exceed {max}", max = RoleSymbol::MAX_ENCODED_VALUE)]
    ValueTooLarge(u64),
    #[error("role symbol value {0} cannot be less than {min}", min = RoleSymbol::MIN_ENCODED_VALUE)]
    ValueTooSmall(u64),
    #[error("role symbol should have length between 1 and 12 characters, but {0} was provided")]
    InvalidLength(usize),
    #[error("role symbol contains a character that is not uppercase ASCII or underscore")]
    InvalidCharacter,
    #[error("role symbol data left after decoding the specified number of characters")]
    DataNotFullyDecoded,
}

impl From<ShortCapitalStringError> for RoleSymbolError {
    fn from(value: ShortCapitalStringError) -> Self {
        match value {
            ShortCapitalStringError::ValueTooLarge(v) => Self::ValueTooLarge(v),
            ShortCapitalStringError::ValueTooSmall(v) => Self::ValueTooSmall(v),
            ShortCapitalStringError::InvalidLength(v) => Self::InvalidLength(v),
            ShortCapitalStringError::InvalidCharacter => Self::InvalidCharacter,
            ShortCapitalStringError::DataNotFullyDecoded => Self::DataNotFullyDecoded,
        }
    }
}

// SHORT CAPITAL STRING ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub(crate) enum ShortCapitalStringError {
    #[error("short capital string value {0} is too large")]
    ValueTooLarge(u64),
    #[error("short capital string value {0} is too small")]
    ValueTooSmall(u64),
    #[error(
        "short capital string should have length between 1 and 12 characters, but {0} was provided"
    )]
    InvalidLength(usize),
    #[error("short capital string contains an invalid character")]
    InvalidCharacter,
    #[error("short capital string data left after decoding the specified number of characters")]
    DataNotFullyDecoded,
}

// ASSET VAULT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AssetVaultError {
    #[error("adding fungible asset amounts would exceed maximum allowed amount")]
    AddFungibleAssetBalanceError(#[source] AssetError),
    #[error("provided assets contain duplicates")]
    DuplicateAsset(#[source] MerkleError),
    #[error("non fungible asset {0} already exists in the vault")]
    DuplicateNonFungibleAsset(Asset),
    #[error("fungible asset {0} does not exist in the vault")]
    FungibleAssetNotFound(FungibleAsset),
    #[error("non fungible asset {0} does not exist in the vault")]
    NonFungibleAssetNotFound(Asset),
    #[error("subtracting fungible asset amounts would underflow")]
    SubtractFungibleAssetBalanceError(#[source] AssetError),
    #[error("maximum number of asset vault leaves exceeded")]
    MaxLeafEntriesExceeded(#[source] MerkleError),
}

// PARTIAL ASSET VAULT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum PartialAssetVaultError {
    #[error("duplicate asset ID {0} in partial vault")]
    DuplicateAssetId(AssetId),
    #[error("partial vault contains invalid asset value {value} at ID {id}")]
    InvalidAssetForId {
        id: AssetId,
        value: Word,
        #[source]
        source: AssetError,
    },
    #[error("failed to add asset proof")]
    FailedToAddProof(#[source] MerkleError),
    #[error("asset is not tracked in the partial vault")]
    UntrackedAsset(#[source] MerkleError),
}

// NOTE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum NoteError {
    #[error("error while creating note script: {0}")]
    MastForestScript(#[source] MastForestScriptError),
    #[error("note tag length {0} exceeds the maximum of {max}", max = NoteTag::MAX_ACCOUNT_TARGET_TAG_LENGTH)]
    NoteTagLengthTooLarge(u8),
    #[error("duplicate fungible asset from issuer {0} in note")]
    DuplicateFungibleAsset(AccountId),
    #[error("duplicate non fungible asset {0} in note")]
    DuplicateNonFungibleAsset(Asset),
    #[error("note type {0} is inconsistent with note tag {1}")]
    InconsistentNoteTag(NoteType, u64),
    #[error("adding fungible asset amounts would exceed maximum allowed amount")]
    AddFungibleAssetBalanceError(#[source] AssetError),
    #[error("note sender is not a valid account ID")]
    NoteSenderInvalidAccountId(#[source] AccountIdError),
    #[error("note execution hint after block variant cannot contain u32::MAX")]
    NoteExecutionHintAfterBlockCannotBeU32Max,
    #[error("invalid note execution hint payload {1} for tag {0}")]
    InvalidNoteExecutionHintPayload(u8, u32),
    #[error(
    "note type {0} does not match any of the valid note types {public} or {private}",
    public = NoteType::Public,
    private = NoteType::Private,
    )]
    UnknownNoteType(Box<str>),
    #[error("block note tree index {block_note_tree_index} is out of bounds 0..={highest_index}")]
    BlockNoteTreeIndexOutOfBounds {
        block_note_tree_index: u16,
        highest_index: usize,
    },
    #[error("note network execution requires a public note but note is of type {0}")]
    NetworkExecutionRequiresPublicNote(NoteType),
    #[error("failed to assemble note script:\n{}", PrintDiagnostic::new(.0))]
    NoteScriptAssemblyError(Report),
    #[error("failed to deserialize note script")]
    NoteScriptDeserializationError(#[source] DeserializationError),
    #[error("note contains {0} assets which exceeds the maximum of {max}", max = NoteAssets::MAX_NUM_ASSETS)]
    TooManyAssets(usize),
    #[error("note contains {0} storage items which exceeds the maximum of {max}", max = MAX_NOTE_STORAGE_ITEMS)]
    TooManyStorageItems(usize),
    #[error("invalid note storage length: expected {expected} items, got {actual}")]
    InvalidNoteStorageLength { expected: usize, actual: usize },
    #[error("note tag requires a public note but the note is of type {0}")]
    PublicNoteRequired(NoteType),
    #[error("note attachment content must have at least one word")]
    NoteAttachmentContentEmpty,
    #[error(
        "note attachment content contains {0} words, but the maximum is {max} words",
        max = NoteAttachment::MAX_NUM_WORDS
    )]
    NoteAttachmentContentTooManyWords(usize),
    #[error(
        "note attachments contain a total of {0} words, but the maximum allowed is {max} words",
        max = NoteAttachments::MAX_NUM_WORDS
    )]
    NoteAttachmentsTooManyWords(usize),
    #[error(
        "attachment size {0} exceeds maximum {max}",
        max = NoteAttachment::MAX_NUM_WORDS
    )]
    NoteAttachmentHeaderSizeExceeded(u8),
    #[error("{0} attachments were provided but maximum is {max}", max = NoteAttachments::MAX_COUNT)]
    TooManyAttachments(usize),
    #[error("attachment scheme {0} exceeds maximum value of {max}", max = NoteAttachmentScheme::MAX)]
    NoteAttachmentSchemeExceeded(u32),
    #[error("attachment scheme value 0 is reserved")]
    NoteAttachmentSchemeZeroReserved,
    #[error("{error_msg}")]
    Other {
        error_msg: Box<str>,
        // thiserror will return this when calling Error::source on NoteError.
        source: Option<Box<dyn Error + Send + Sync + 'static>>,
    },
}

impl NoteError {
    /// Creates a custom error using the [`NoteError::Other`] variant from an error message.
    pub fn other(message: impl Into<String>) -> Self {
        let message: String = message.into();
        Self::Other { error_msg: message.into(), source: None }
    }

    /// Creates a custom error using the [`NoteError::Other`] variant from an error message and
    /// a source error.
    pub fn other_with_source(
        message: impl Into<String>,
        source: impl Error + Send + Sync + 'static,
    ) -> Self {
        let message: String = message.into();
        Self::Other {
            error_msg: message.into(),
            source: Some(Box::new(source)),
        }
    }
}

// PARTIAL BLOCKCHAIN ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum PartialBlockchainError {
    #[error(
        "block num {block_num} exceeds chain length {chain_length} implied by the partial blockchain"
    )]
    BlockNumTooBig {
        chain_length: usize,
        block_num: BlockNumber,
    },

    #[error("duplicate block {block_num} in partial blockchain")]
    DuplicateBlock { block_num: BlockNumber },

    #[error("partial blockchain does not track authentication paths for block {block_num}")]
    UntrackedBlock { block_num: BlockNumber },

    #[error(
        "provided block header with number {block_num} and commitment {block_commitment} is not tracked by partial MMR"
    )]
    BlockHeaderCommitmentMismatch {
        block_num: BlockNumber,
        block_commitment: Word,
        source: MmrError,
    },
}

impl PartialBlockchainError {
    pub fn block_num_too_big(chain_length: usize, block_num: BlockNumber) -> Self {
        Self::BlockNumTooBig { chain_length, block_num }
    }

    pub fn duplicate_block(block_num: BlockNumber) -> Self {
        Self::DuplicateBlock { block_num }
    }

    pub fn untracked_block(block_num: BlockNumber) -> Self {
        Self::UntrackedBlock { block_num }
    }
}

// TRANSACTION INPUT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TransactionInputError {
    #[error("transaction input note with nullifier {0} is a duplicate")]
    DuplicateInputNote(Nullifier),
    #[error("partial blockchain has length {actual} which does not match block number {expected}")]
    InconsistentChainLength {
        expected: BlockNumber,
        actual: BlockNumber,
    },
    #[error(
        "partial blockchain has commitment {actual} which does not match the block header's chain commitment {expected}"
    )]
    InconsistentChainCommitment { expected: Word, actual: Word },
    #[error(
        "protocol config has commitment {actual} which does not match the block header's protocol config commitment {expected}"
    )]
    InconsistentProtocolConfig { expected: Word, actual: Word },
    #[error("block in which input note with id {0} was created is not in partial blockchain")]
    InputNoteBlockNotInPartialBlockchain(NoteId),
    #[error("input note with id {0} was not created in block {1}")]
    InputNoteNotInBlock(NoteId, BlockNumber),
    #[error(
        "total number of input notes is {0} which exceeds the maximum of {MAX_INPUT_NOTES_PER_TX}"
    )]
    TooManyInputNotes(usize),
}

// TRANSACTION INPUTS EXTRACTION ERROR
// ===============================================================================================

#[derive(Debug, Error)]
pub enum TransactionInputsExtractionError {
    #[error("specified foreign account id matches the transaction input's account id")]
    AccountNotForeign,
    #[error("foreign account data not found in advice map for account {0}")]
    ForeignAccountNotFound(AccountId),
    #[error("foreign account code not found for account {0}")]
    ForeignAccountCodeNotFound(AccountId),
    #[error("storage header data not found in advice map for account {0}")]
    StorageHeaderNotFound(AccountId),
    #[error("failed to handle account data")]
    AccountError(#[from] AccountError),
    #[error("failed to handle merkle data")]
    MerkleError(#[from] MerkleError),
    #[error("failed to handle account tree data")]
    AccountTreeError(#[from] AccountTreeError),
    #[error("missing vault root from Merkle store")]
    MissingVaultRoot,
    #[error("missing storage map root from Merkle store")]
    MissingMapRoot,
    #[error("failed to construct SMT proof")]
    SmtProofError(#[from] SmtProofError),
    #[error("failed to construct an asset")]
    AssetError(#[from] AssetError),
    #[error("failed to handle storage map data")]
    StorageMapError(#[from] StorageMapError),
    #[error("failed to convert elements to leaf index: {0}")]
    LeafConversionError(String),
    #[error("failed to construct SMT leaf")]
    SmtLeafError(#[from] SmtLeafError),
}

// TRANSACTION OUTPUT ERROR
// ===============================================================================================

#[derive(Debug, Error)]
pub enum TransactionOutputError {
    #[error("transaction output note with id {0} is a duplicate")]
    DuplicateOutputNote(NoteId),
    #[error("final account commitment is not in the advice map")]
    FinalAccountCommitmentMissingInAdviceMap,
    #[error("failed to parse final account header")]
    FinalAccountHeaderParseFailure(#[source] AccountError),
    #[error(
        "output notes commitment {expected} from kernel does not match computed commitment {actual}"
    )]
    OutputNotesCommitmentInconsistent { expected: Word, actual: Word },
    #[error("transaction kernel output stack is invalid: {0}")]
    OutputStackInvalid(String),
    #[error(
        "total number of output notes is {0} which exceeds the maximum of {MAX_OUTPUT_NOTES_PER_TX}"
    )]
    TooManyOutputNotes(usize),
    #[error("failed to process account update commitment: {0}")]
    AccountUpdateCommitment(Box<str>),
}

// OUTPUT NOTE ERROR
// ================================================================================================

/// Errors that can occur when creating a
/// [`PublicOutputNote`](crate::transaction::PublicOutputNote) or
/// [`PrivateOutputNote`](crate::transaction::PrivateOutputNote).
#[derive(Debug, Error)]
pub enum OutputNoteError {
    #[error("attachment headers do not match attachments for private note with id {0}")]
    AttachmentHeadersMismatch(NoteId),
    #[error("attachments commitment does not match attachments for private note with id {0}")]
    AttachmentsCommitmentMismatch(NoteId),
    #[error("note with id {0} is private but expected a public note")]
    NoteIsPrivate(NoteId),
    #[error("note with id {0} is public but expected a private note")]
    NoteIsPublic(NoteId),
    #[error(
        "public note with id {note_id} has size {note_size} bytes which exceeds maximum note size of {NOTE_MAX_SIZE}"
    )]
    NoteSizeLimitExceeded { note_id: NoteId, note_size: usize },
}

// TRANSACTION SUMMARY ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TransactionSummaryError {
    #[error(
        "transaction summary preimage contains {actual} elements but expected {expected} elements"
    )]
    InvalidPreimageLength { actual: usize, expected: usize },
    #[error("transaction summary metadata element {0} sets bits above the packed fields")]
    MetadataOutOfRange(Felt),
    #[error(
        "transaction summary layout version is {actual} but only version {expected} is supported"
    )]
    UnsupportedVersion { actual: Felt, expected: u8 },
}

// TRANSACTION EVENT PARSING ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TransactionEventError {
    #[error("event id {0} is not a valid transaction event")]
    InvalidTransactionEvent(EventId),
}

// TRANSACTION TRACE PARSING ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TransactionTraceParsingError {
    #[error("trace id {0} is an unknown transaction kernel trace")]
    UnknownTransactionTrace(u32),
}

// PROVEN TRANSACTION ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum ProvenTransactionError {
    #[error(
        "proven transaction's final account commitment {tx_final_commitment} and account details commitment {details_commitment} must match"
    )]
    AccountFinalCommitmentMismatch {
        tx_final_commitment: Word,
        details_commitment: Word,
    },
    #[error(
        "proven transaction's final account ID {tx_account_id} and account details id {details_account_id} must match"
    )]
    AccountIdMismatch {
        tx_account_id: AccountId,
        details_account_id: AccountId,
    },
    #[error("failed to construct input notes for proven transaction")]
    InputNotesError(TransactionInputError),
    #[error("private account {0} should not have account details")]
    PrivateAccountWithDetails(AccountId),
    #[error("account {0} with public state is missing its account details")]
    PublicStateAccountMissingDetails(AccountId),
    #[error("new account {id} with public state must be accompanied by a full state patch")]
    NewPublicStateAccountRequiresFullStatePatch { id: AccountId, source: AccountError },
    #[error(
        "existing account {0} with public state should only provide delta updates instead of full details"
    )]
    ExistingPublicStateAccountRequiresDeltaDetails(AccountId),
    #[error("failed to construct output notes for proven transaction")]
    OutputNotesError(#[source] TransactionOutputError),
    #[error(
        "account update of size {update_size} for account {account_id} exceeds maximum update size of {ACCOUNT_UPDATE_MAX_SIZE}"
    )]
    AccountUpdateSizeLimitExceeded {
        account_id: AccountId,
        update_size: usize,
    },
    #[error("proven transaction neither changed the account state, nor consumed any notes")]
    EmptyTransaction,
    #[error(
        "expected account patch commitment {expected_patch_commitment} but found {actual_patch_commitment}"
    )]
    AccountPatchCommitmentMismatch {
        expected_patch_commitment: Word,
        actual_patch_commitment: Word,
    },
    #[error("note with id {0} is both created and consumed by the transaction")]
    NoteCreatedAndConsumed(NoteId),
}

// TRANSACTION HEADER ERROR
// ================================================================================================

/// Error returned when constructing an invalid transaction header.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TransactionHeaderError {
    #[error("input note with nullifier {0} appears twice in the transaction header")]
    DuplicateInputNote(Nullifier),
    #[error("output note {0} appears twice in the transaction header")]
    DuplicateOutputNote(NoteId),
    #[error("note with id {0} is both created and consumed by the transaction header")]
    NoteCreatedAndConsumed(NoteId),
}

impl From<AccountUpdateDetailsValidationError> for ProvenTransactionError {
    fn from(error: AccountUpdateDetailsValidationError) -> Self {
        match error {
            AccountUpdateDetailsValidationError::PrivateAccountWithDetails(account_id) => {
                Self::PrivateAccountWithDetails(account_id)
            },
            AccountUpdateDetailsValidationError::PublicStateAccountMissingDetails(account_id) => {
                Self::PublicStateAccountMissingDetails(account_id)
            },
            AccountUpdateDetailsValidationError::AccountIdMismatch {
                account_id,
                patch_account_id,
            } => Self::AccountIdMismatch {
                tx_account_id: account_id,
                details_account_id: patch_account_id,
            },
        }
    }
}

impl From<AccountUpdateSizeValidationError> for ProvenTransactionError {
    fn from(error: AccountUpdateSizeValidationError) -> Self {
        Self::AccountUpdateSizeLimitExceeded {
            account_id: error.account_id,
            update_size: error.update_size,
        }
    }
}

impl From<AccountUpdateSizeValidationError> for BatchAccountUpdateError {
    fn from(error: AccountUpdateSizeValidationError) -> Self {
        Self::AccountUpdateSizeLimitExceeded {
            account_id: error.account_id,
            update_size: error.update_size,
        }
    }
}

impl From<AccountUpdateDetailsValidationError> for BatchAccountUpdateError {
    fn from(error: AccountUpdateDetailsValidationError) -> Self {
        match error {
            AccountUpdateDetailsValidationError::PrivateAccountWithDetails(account_id) => {
                Self::PrivateAccountWithDetails(account_id)
            },
            AccountUpdateDetailsValidationError::PublicStateAccountMissingDetails(account_id) => {
                Self::PublicStateAccountMissingDetails(account_id)
            },
            AccountUpdateDetailsValidationError::AccountIdMismatch {
                account_id,
                patch_account_id,
            } => Self::AccountIdMismatch { account_id, patch_account_id },
        }
    }
}

impl From<AccountUpdateDetailsValidationError> for BlockAccountUpdateError {
    fn from(error: AccountUpdateDetailsValidationError) -> Self {
        match error {
            AccountUpdateDetailsValidationError::PrivateAccountWithDetails(account_id) => {
                Self::PrivateAccountWithDetails(account_id)
            },
            AccountUpdateDetailsValidationError::PublicStateAccountMissingDetails(account_id) => {
                Self::PublicStateAccountMissingDetails(account_id)
            },
            AccountUpdateDetailsValidationError::AccountIdMismatch {
                account_id,
                patch_account_id,
            } => Self::AccountIdMismatch { account_id, patch_account_id },
        }
    }
}

impl From<NewPublicAccountValidationError> for ProvenTransactionError {
    fn from(error: NewPublicAccountValidationError) -> Self {
        match error {
            NewPublicAccountValidationError::RequiresFullStatePatch { id, source } => {
                Self::NewPublicStateAccountRequiresFullStatePatch { id, source }
            },
            NewPublicAccountValidationError::FinalCommitmentMismatch {
                final_state_commitment,
                account_commitment,
            } => Self::AccountFinalCommitmentMismatch {
                tx_final_commitment: final_state_commitment,
                details_commitment: account_commitment,
            },
        }
    }
}

impl From<NewPublicAccountValidationError> for BatchAccountUpdateError {
    fn from(error: NewPublicAccountValidationError) -> Self {
        match error {
            NewPublicAccountValidationError::RequiresFullStatePatch { id, source } => {
                Self::NewPublicStateAccountRequiresFullStatePatch { id, source }
            },
            NewPublicAccountValidationError::FinalCommitmentMismatch {
                final_state_commitment,
                account_commitment,
            } => Self::AccountFinalCommitmentMismatch {
                final_state_commitment,
                account_commitment,
            },
        }
    }
}

impl From<NewPublicAccountValidationError> for BlockAccountUpdateError {
    fn from(error: NewPublicAccountValidationError) -> Self {
        match error {
            NewPublicAccountValidationError::RequiresFullStatePatch { id, source } => {
                Self::NewPublicStateAccountRequiresFullStatePatch { id, source }
            },
            NewPublicAccountValidationError::FinalCommitmentMismatch {
                final_state_commitment,
                account_commitment,
            } => Self::AccountFinalCommitmentMismatch {
                final_state_commitment,
                account_commitment,
            },
        }
    }
}

// PROPOSED BATCH ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum ProposedBatchError {
    #[error("failed to verify transaction {transaction_id} in transaction batch")]
    TransactionVerificationFailed {
        transaction_id: TransactionId,
        source: TransactionVerifierError,
    },

    #[error("transaction {transaction_id} has an outstanding precompile obligation")]
    IncompleteTransactionProof { transaction_id: TransactionId },

    #[error(
        "transaction batch has {0} input notes but at most {MAX_INPUT_NOTES_PER_BATCH} are allowed"
    )]
    TooManyInputNotes(usize),

    #[error(
        "transaction batch has {0} output notes but at most {MAX_OUTPUT_NOTES_PER_BATCH} are allowed"
    )]
    TooManyOutputNotes(usize),

    #[error(
        "transaction batch has {0} account updates but at most {MAX_ACCOUNTS_PER_BATCH} are allowed"
    )]
    TooManyAccountUpdates(usize),

    #[error(
        "transaction {transaction_id} expires at block number {transaction_expiration_num} which is not greater than the number of the batch's reference block {reference_block_num}"
    )]
    ExpiredTransaction {
        transaction_id: TransactionId,
        transaction_expiration_num: BlockNumber,
        reference_block_num: BlockNumber,
    },

    #[error("transaction batch must contain at least one transaction")]
    EmptyTransactionBatch,

    #[error("transaction {transaction_id} appears twice in the proposed batch input")]
    DuplicateTransaction { transaction_id: TransactionId },

    #[error(
        "transaction {second_transaction_id} consumes the note with nullifier {note_nullifier} that is also consumed by another transaction {first_transaction_id} in the batch"
    )]
    DuplicateInputNote {
        note_nullifier: Nullifier,
        first_transaction_id: TransactionId,
        second_transaction_id: TransactionId,
    },

    #[error(
        "transaction {second_transaction_id} creates the note with id {note_id} that is also created by another transaction {first_transaction_id} in the batch"
    )]
    DuplicateOutputNote {
        note_id: NoteId,
        first_transaction_id: TransactionId,
        second_transaction_id: TransactionId,
    },

    #[error(
        "transaction {consumed_by} that consumes the note with ID {note_id} must be ordered before transaction {created_by} that creates the note"
    )]
    NoteConsumedBeforeCreated {
        note_id: NoteId,
        consumed_by: TransactionId,
        created_by: TransactionId,
    },

    #[error("failed to merge transaction patch into account {account_id}")]
    AccountUpdateError {
        account_id: AccountId,
        source: BatchAccountUpdateError,
    },

    #[error(
        "unable to prove unauthenticated note inclusion because block {block_number} in which note with id {note_id} was created is not in partial blockchain"
    )]
    UnauthenticatedInputNoteBlockNotInPartialBlockchain {
        block_number: BlockNumber,
        note_id: NoteId,
    },

    #[error(
        "unable to prove unauthenticated note inclusion of note {note_id} in block {block_num}"
    )]
    UnauthenticatedNoteAuthenticationFailed {
        note_id: NoteId,
        block_num: BlockNumber,
        source: MerkleError,
    },

    #[error("partial blockchain has length {actual} which does not match block number {expected}")]
    InconsistentChainLength {
        expected: BlockNumber,
        actual: BlockNumber,
    },

    #[error(
        "partial blockchain has root {actual} which does not match block header's root {expected}"
    )]
    InconsistentChainRoot { expected: Word, actual: Word },

    #[error(
        "block {block_num} referenced by transaction {transaction_id} is not in the partial blockchain"
    )]
    MissingTransactionReferenceBlock {
        transaction_id: TransactionId,
        block_num: BlockNumber,
    },

    #[error(
        "transaction {transaction_id} references block {block_num} with commitment {actual_block_commitment}, but the block in the chain with the same number has commitment {expected_block_commitment}"
    )]
    TransactionReferenceBlockCommitmentMismatch {
        transaction_id: TransactionId,
        block_num: BlockNumber,
        expected_block_commitment: Word,
        actual_block_commitment: Word,
    },
}

// PROVEN BATCH ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum ProvenBatchError {
    #[error("transaction batch must contain at least one transaction")]
    EmptyTransactionBatch,
    #[error("transaction {0} appears twice in the proven batch")]
    DuplicateTransaction(TransactionId),
    #[error(
        "transaction batch has {0} input notes but at most {MAX_INPUT_NOTES_PER_BATCH} are allowed"
    )]
    TooManyInputNotes(usize),
    #[error("input note with nullifier {0} appears twice in the proven batch")]
    DuplicateInputNote(Nullifier),
    #[error(
        "transaction batch has {0} output notes but at most {MAX_OUTPUT_NOTES_PER_BATCH} are allowed"
    )]
    TooManyOutputNotes(usize),
    #[error(
        "transaction batch has at least {0} account updates but at most {MAX_ACCOUNTS_PER_BATCH} are allowed"
    )]
    TooManyAccountUpdates(usize),
    #[error("output note {0} appears twice in the proven batch")]
    DuplicateOutputNote(NoteId),
    #[error("note with id {0} is both created and consumed by the proven batch")]
    NoteCreatedAndConsumed(NoteId),
    #[error("account {0} is updated more than once in the proven batch")]
    DuplicateAccountUpdate(AccountId),
    #[error("account update for {0} is missing from the proven batch")]
    MissingAccountUpdate(AccountId),
    #[error("account update for {0} has no corresponding transaction in the proven batch")]
    UnexpectedAccountUpdate(AccountId),
    #[error(
        "transaction {transaction_id} for account {account_id} starts from state {actual_initial_state_commitment}, but the previous transaction ends at state {expected_initial_state_commitment}"
    )]
    TransactionAccountStateMismatch {
        account_id: AccountId,
        transaction_id: TransactionId,
        expected_initial_state_commitment: Word,
        actual_initial_state_commitment: Word,
    },
    #[error(
        "account update for {account_id} starts from state {actual}, but its first transaction starts from state {expected}"
    )]
    AccountUpdateInitialStateMismatch {
        account_id: AccountId,
        expected: Word,
        actual: Word,
    },
    #[error(
        "account update for {account_id} ends at state {actual}, but its last transaction ends at state {expected}"
    )]
    AccountUpdateFinalStateMismatch {
        account_id: AccountId,
        expected: Word,
        actual: Word,
    },
    #[error(
        "batch expiration block number {batch_expiration_block_num} is not greater than the reference block number {reference_block_num}"
    )]
    InvalidBatchExpirationBlockNum {
        batch_expiration_block_num: BlockNumber,
        reference_block_num: BlockNumber,
    },
    #[error("batch kernel execution failed")]
    BatchKernelExecutionFailed(#[source] ExecutionError),
    #[error("batch kernel proving failed")]
    BatchKernelProvingFailed(#[source] ExecutionError),
    #[error("batch proof contains precompiles")]
    BatchProofContainsPrecompiles,
    #[error("batch kernel produced an invalid output stack")]
    BatchKernelOutputInvalid(#[source] BatchOutputError),
}

// BATCH OUTPUT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum BatchOutputError {
    #[error("batch kernel output stack is invalid: {0}")]
    OutputStackInvalid(String),
    #[error("batch expiration block number {0} does not fit into a u32")]
    ExpirationBlockNumberTooLarge(Felt),
}

// BLOCK OUTPUT ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum BlockOutputError {
    #[error(
        "block kernel output stack has a non-zero element at index {index}, but everything past the nullifier commitment must be zero padding"
    )]
    PaddingNotZero { index: usize },
}

// PROPOSED BLOCK ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum ProposedBlockError {
    #[error("block must contain at least one transaction batch")]
    EmptyBlock,

    #[error("block must contain at most {MAX_BATCHES_PER_BLOCK} transaction batches")]
    TooManyBatches,

    #[error(
        "batch {batch_id} expired at block {batch_expiration_block_num} but the current block number is {current_block_num}"
    )]
    ExpiredBatch {
        batch_id: BatchId,
        batch_expiration_block_num: BlockNumber,
        current_block_num: BlockNumber,
    },

    #[error("batch {batch_id} appears twice in the block inputs")]
    DuplicateBatch { batch_id: BatchId },

    #[error(
        "batch {second_batch_id} consumes the note with nullifier {note_nullifier} that is also consumed by another batch {first_batch_id} in the block"
    )]
    DuplicateInputNote {
        note_nullifier: Nullifier,
        first_batch_id: BatchId,
        second_batch_id: BatchId,
    },

    #[error(
        "batch {second_batch_id} creates the note with ID {note_id} that is also created by another batch {first_batch_id} in the block"
    )]
    DuplicateOutputNote {
        note_id: NoteId,
        first_batch_id: BatchId,
        second_batch_id: BatchId,
    },

    #[error(
        "batch {consumed_by} that consumes the note with ID {note_id} must be ordered before batch {created_by} that creates the note"
    )]
    NoteConsumedBeforeCreated {
        note_id: NoteId,
        consumed_by: BatchId,
        created_by: BatchId,
    },

    #[error(
        "timestamp {provided_timestamp} does not increase monotonically compared to timestamp {previous_timestamp} from the previous block header"
    )]
    TimestampDoesNotIncreaseMonotonically {
        provided_timestamp: u32,
        previous_timestamp: u32,
    },

    #[error(
        "account {account_id} is updated from the same initial state commitment {initial_state_commitment} by multiple conflicting batches with IDs {first_batch_id} and {second_batch_id}"
    )]
    ConflictingBatchesUpdateSameAccount {
        account_id: AccountId,
        initial_state_commitment: Word,
        first_batch_id: BatchId,
        second_batch_id: BatchId,
    },

    #[error(
        "partial blockchain has length {chain_length} which does not match the block number {prev_block_num} of the previous block referenced by the to-be-built block"
    )]
    ChainLengthNotEqualToPreviousBlockNumber {
        chain_length: BlockNumber,
        prev_block_num: BlockNumber,
    },

    #[error(
        "partial blockchain has commitment {chain_commitment} which does not match the chain commitment {prev_block_chain_commitment} of the previous block {prev_block_num}"
    )]
    ChainRootNotEqualToPreviousBlockChainCommitment {
        chain_commitment: Word,
        prev_block_chain_commitment: Word,
        prev_block_num: BlockNumber,
    },

    #[error(
        "partial blockchain is missing block {reference_block_num} referenced by batch {batch_id} in the block"
    )]
    BatchReferenceBlockMissingFromChain {
        reference_block_num: BlockNumber,
        batch_id: BatchId,
    },

    #[error(
        "failed to prove unauthenticated note inclusion because block {block_number} in which note with id {note_id} was created is not in partial blockchain"
    )]
    UnauthenticatedInputNoteBlockNotInPartialBlockchain {
        block_number: BlockNumber,
        note_id: NoteId,
    },

    #[error(
        "failed to prove unauthenticated note inclusion of note {note_id} in block {block_num}"
    )]
    UnauthenticatedNoteAuthenticationFailed {
        note_id: NoteId,
        block_num: BlockNumber,
        source: MerkleError,
    },

    #[error(
        "unauthenticated note with nullifier {nullifier} was not created in the same block and no inclusion proof to authenticate it was provided"
    )]
    UnauthenticatedNoteConsumed { nullifier: Nullifier },

    #[error("block inputs do not contain a proof of inclusion for account {0}")]
    MissingAccountWitness(AccountId),

    #[error(
        "account {account_id} with state {state_commitment} cannot transition to any of the remaining states {}",
        remaining_state_commitments.iter().map(Word::to_hex).collect::<Vec<_>>().join(", ")
    )]
    InconsistentAccountStateTransition {
        account_id: AccountId,
        state_commitment: Word,
        remaining_state_commitments: Vec<Word>,
    },

    #[error("no proof for nullifier {0} was provided")]
    NullifierProofMissing(Nullifier),

    #[error("note with nullifier {0} is already spent")]
    NullifierSpent(Nullifier),

    #[error("failed to merge transaction patch into account {account_id}")]
    AccountUpdateError {
        account_id: AccountId,
        source: Box<AccountPatchError>,
    },

    #[error("failed to track account witness")]
    AccountWitnessTracking { source: AccountTreeError },

    #[error(
        "account tree root of the previous block header is {prev_block_account_root} but the root of the partial tree computed from account witnesses is {stale_account_root}, indicating that the witnesses are stale"
    )]
    StaleAccountTreeRoot {
        prev_block_account_root: Word,
        stale_account_root: Word,
    },

    #[error("account ID prefix already exists in the tree")]
    AccountIdPrefixDuplicate { source: AccountTreeError },

    #[error(
        "nullifier tree root of the previous block header is {prev_block_nullifier_root} but the root of the partial tree computed from nullifier witnesses is {stale_nullifier_root}, indicating that the witnesses are stale"
    )]
    StaleNullifierTreeRoot {
        prev_block_nullifier_root: Word,
        stale_nullifier_root: Word,
    },

    #[error("nullifier witness has a different root than the current nullifier tree root")]
    NullifierWitnessRootMismatch(NullifierTreeError),
}

// PROTOCOL CONFIG ERROR
// ================================================================================================

/// Error returned when constructing an invalid protocol configuration.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolConfigError {
    #[error("fee asset composition {0:?} is not supported, it must be fungible")]
    FeeAssetMustBeFungible(AssetComposition),
    #[error("minimum proof security must be at least one bit")]
    MinimumSecurityBitsMustBeNonZero,
    #[error("next protocol config cannot become effective at the genesis block")]
    NextConfigEffectiveAtGenesis,
    #[error(
        "kernel config contains {count} procedures but must contain at most {max}",
        max = KernelConfig::MAX_NUM_KERNEL_PROCEDURES,
    )]
    TooManyKernelProcedures { count: usize },
}

// VALIDATOR CONFIG ERROR
// ================================================================================================

/// Error returned when constructing an invalid [`ValidatorConfig`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ValidatorConfigError {
    #[error("validator set must contain at least one key")]
    EmptySet,
    #[error(
        "validator set contains {count} keys but must contain at most {max}",
        max = ValidatorConfig::MAX_VALIDATORS,
    )]
    TooManyKeys { count: usize },
    #[error("validator set contains duplicate public keys")]
    DuplicateKey,
    #[error("quorum is {quorum} but must equal the validator count of {count}")]
    QuorumMustEqualValidatorCount { quorum: u16, count: usize },
}

// NULLIFIER TREE ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum NullifierTreeError {
    #[error(
        "entries passed to nullifier tree contain multiple block numbers for the same nullifier"
    )]
    DuplicateNullifierBlockNumbers(#[source] MerkleError),

    #[error("attempt to mark nullifier {0} as spent but it is already spent")]
    NullifierAlreadySpent(Nullifier),

    #[error("maximum number of nullifier tree leaves exceeded")]
    MaxLeafEntriesExceeded(#[source] MerkleError),

    #[error("nullifier {nullifier} is not tracked by the partial nullifier tree")]
    UntrackedNullifier {
        nullifier: Nullifier,
        source: MerkleError,
    },

    #[error("new tree root after nullifier witness insertion does not match previous tree root")]
    TreeRootConflict(#[source] MerkleError),

    #[error("failed to compute nullifier tree mutations")]
    ComputeMutations(#[source] MerkleError),

    #[error("invalid nullifier block number")]
    InvalidNullifierBlockNumber(Word),
}

// AUTH SCHEME ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum AuthSchemeError {
    #[error("auth scheme identifier `{0}` is not valid")]
    InvalidAuthSchemeIdentifier(String),
}

// TRANSACTION VERIFIER ERROR
// ================================================================================================

#[derive(Debug, Error)]
pub enum TransactionVerifierError {
    #[error("failed to verify transaction")]
    TransactionVerificationFailed(#[source] VerificationError),
    #[error("transaction proof contains settled precompile work")]
    TransactionProofContainsPrecompiles,
    #[error("transaction precompile witness is invalid")]
    InvalidTransactionPrecompileWitness(#[source] IntegrityError),
    #[error(
        "transaction precompile witness root ({actual}) does not match the VM proof root ({expected})"
    )]
    TransactionPrecompileRootMismatch { expected: Word, actual: Word },
    #[error("transaction proof security level is {actual} but must be at least {expected_minimum}")]
    InsufficientProofSecurityLevel { actual: u32, expected_minimum: u32 },
}