Skip to main content

miden_protocol/errors/
mod.rs

1use alloc::boxed::Box;
2use alloc::string::String;
3use alloc::vec::Vec;
4use core::error::Error;
5
6use miden_assembly::Report;
7use miden_assembly::diagnostics::reporting::PrintDiagnostic;
8use miden_core::Felt;
9use miden_core::mast::MastForestError;
10use miden_crypto::merkle::mmr::MmrError;
11use miden_crypto::merkle::smt::{SmtLeafError, SmtProofError};
12use miden_crypto::utils::HexParseError;
13use thiserror::Error;
14
15use super::account::AccountId;
16use super::asset::{FungibleAsset, NonFungibleAsset, TokenSymbol};
17use super::crypto::merkle::MerkleError;
18use super::note::NoteId;
19use super::{MAX_BATCHES_PER_BLOCK, MAX_OUTPUT_NOTES_PER_BATCH, Word};
20use crate::account::component::{SchemaTypeError, StorageValueName, StorageValueNameError};
21use crate::account::{
22    AccountCode,
23    AccountIdPrefix,
24    AccountStorage,
25    AccountType,
26    StorageMapKey,
27    StorageSlotId,
28    StorageSlotName,
29};
30use crate::address::AddressType;
31use crate::asset::AssetId;
32use crate::batch::BatchId;
33use crate::block::BlockNumber;
34use crate::note::{
35    NoteAssets,
36    NoteAttachmentArray,
37    NoteAttachmentKind,
38    NoteAttachmentScheme,
39    NoteTag,
40    NoteType,
41    Nullifier,
42};
43use crate::transaction::{TransactionEventId, TransactionId};
44use crate::utils::serde::DeserializationError;
45use crate::vm::EventId;
46use crate::{
47    ACCOUNT_UPDATE_MAX_SIZE,
48    MAX_ACCOUNTS_PER_BATCH,
49    MAX_INPUT_NOTES_PER_BATCH,
50    MAX_INPUT_NOTES_PER_TX,
51    MAX_NOTE_STORAGE_ITEMS,
52    MAX_OUTPUT_NOTES_PER_TX,
53    NOTE_MAX_SIZE,
54};
55
56#[cfg(any(feature = "testing", test))]
57mod masm_error;
58#[cfg(any(feature = "testing", test))]
59pub use masm_error::MasmError;
60
61/// The errors from the MASM code of the transaction kernel.
62#[cfg(any(feature = "testing", test))]
63pub mod tx_kernel {
64    include!(concat!(env!("OUT_DIR"), "/tx_kernel_errors.rs"));
65}
66
67/// The errors from the MASM code of the Miden protocol library.
68#[cfg(any(feature = "testing", test))]
69pub mod protocol {
70    include!(concat!(env!("OUT_DIR"), "/protocol_errors.rs"));
71}
72
73// ACCOUNT COMPONENT TEMPLATE ERROR
74// ================================================================================================
75
76#[derive(Debug, Error)]
77pub enum ComponentMetadataError {
78    #[error("storage slot name `{0}` is duplicate")]
79    DuplicateSlotName(StorageSlotName),
80    #[error("storage init value name `{0}` is duplicate")]
81    DuplicateInitValueName(StorageValueName),
82    #[error("storage value name is incorrect: {0}")]
83    IncorrectStorageValueName(#[source] StorageValueNameError),
84    #[error("invalid storage schema: {0}")]
85    InvalidSchema(String),
86    #[error("type `{0}` is not valid for `{1}` slots")]
87    InvalidType(String, String),
88    #[error("error deserializing component metadata: {0}")]
89    MetadataDeserializationError(String),
90    #[error("init storage value `{0}` was not provided")]
91    InitValueNotProvided(StorageValueName),
92    #[error("invalid init storage value for `{0}`: {1}")]
93    InvalidInitStorageValue(StorageValueName, String),
94    #[error("error converting value into expected type: {0}")]
95    StorageValueParsingError(#[source] SchemaTypeError),
96    #[error("storage map contains duplicate keys")]
97    StorageMapHasDuplicateKeys(#[source] Box<dyn Error + Send + Sync + 'static>),
98    #[cfg(feature = "std")]
99    #[error("error trying to deserialize from toml")]
100    TomlDeserializationError(#[source] toml::de::Error),
101    #[cfg(feature = "std")]
102    #[error("error trying to deserialize from toml")]
103    TomlSerializationError(#[source] toml::ser::Error),
104}
105
106// ACCOUNT ERROR
107// ================================================================================================
108
109#[derive(Debug, Error)]
110pub enum AccountError {
111    #[error("failed to deserialize account code")]
112    AccountCodeDeserializationError(#[source] DeserializationError),
113    #[error("account code does not contain an auth component")]
114    AccountCodeNoAuthComponent,
115    #[error("account code contains multiple auth components")]
116    AccountCodeMultipleAuthComponents,
117    #[error("account code must contain at least one non-auth procedure")]
118    AccountCodeNoProcedures,
119    #[error("account code contains {0} procedures but it may contain at most {max} procedures", max = AccountCode::MAX_NUM_PROCEDURES)]
120    AccountCodeTooManyProcedures(usize),
121    #[error("failed to assemble account component:\n{}", PrintDiagnostic::new(.0))]
122    AccountComponentAssemblyError(Report),
123    #[error("failed to merge components into one account code mast forest")]
124    AccountComponentMastForestMergeError(#[source] MastForestError),
125    #[error("account component contains multiple authentication procedures")]
126    AccountComponentMultipleAuthProcedures,
127    #[error("failed to update asset vault")]
128    AssetVaultUpdateError(#[source] AssetVaultError),
129    #[error("account build error: {0}")]
130    BuildError(String, #[source] Option<Box<AccountError>>),
131    #[error("failed to parse account ID from final account header")]
132    FinalAccountHeaderIdParsingFailed(#[source] AccountIdError),
133    #[error("account header data has length {actual} but it must be of length {expected}")]
134    HeaderDataIncorrectLength { actual: usize, expected: usize },
135    #[error("active account nonce {current} plus increment {increment} overflows a felt to {new}")]
136    NonceOverflow {
137        current: Felt,
138        increment: Felt,
139        new: Felt,
140    },
141    #[error(
142        "digest of the seed has {actual} trailing zeroes but must have at least {expected} trailing zeroes"
143    )]
144    SeedDigestTooFewTrailingZeros { expected: u32, actual: u32 },
145    #[error("account ID {actual} computed from seed does not match ID {expected} on account")]
146    AccountIdSeedMismatch { actual: AccountId, expected: AccountId },
147    #[error("account ID seed was provided for an existing account")]
148    ExistingAccountWithSeed,
149    #[error("account ID seed was not provided for a new account")]
150    NewAccountMissingSeed,
151    #[error(
152        "an account with a seed cannot be converted into a delta since it represents an unregistered account"
153    )]
154    DeltaFromAccountWithSeed,
155    #[error("seed converts to an invalid account ID")]
156    SeedConvertsToInvalidAccountId(#[source] AccountIdError),
157    #[error("storage map root {0} not found in the account storage")]
158    StorageMapRootNotFound(Word),
159    #[error("storage slot {0} is not of type map")]
160    StorageSlotNotMap(StorageSlotName),
161    #[error("storage slot {0} is not of type value")]
162    StorageSlotNotValue(StorageSlotName),
163    #[error("storage slot name {0} is assigned to more than one slot")]
164    DuplicateStorageSlotName(StorageSlotName),
165    #[error("storage does not contain a slot with name {slot_name}")]
166    StorageSlotNameNotFound { slot_name: StorageSlotName },
167    #[error("storage does not contain a slot with ID {slot_id}")]
168    StorageSlotIdNotFound { slot_id: StorageSlotId },
169    #[error("storage slots must be sorted by slot ID")]
170    UnsortedStorageSlots,
171    #[error("number of storage slots is {0} but max possible number is {max}", max = AccountStorage::MAX_NUM_STORAGE_SLOTS)]
172    StorageTooManySlots(u64),
173    #[error(
174        "account component at index {component_index} is incompatible with account of type {account_type}"
175    )]
176    UnsupportedComponentForAccountType {
177        account_type: AccountType,
178        component_index: usize,
179    },
180    #[error(
181        "failed to apply full state delta to existing account; full state deltas can be converted to accounts directly"
182    )]
183    ApplyFullStateDeltaToAccount,
184    #[error("only account deltas representing a full account can be converted to a full account")]
185    PartialStateDeltaToAccount,
186    #[error("maximum number of storage map leaves exceeded")]
187    MaxNumStorageMapLeavesExceeded(#[source] MerkleError),
188    /// This variant can be used by methods that are not inherent to the account but want to return
189    /// this error type.
190    #[error("{error_msg}")]
191    Other {
192        error_msg: Box<str>,
193        // thiserror will return this when calling Error::source on AccountError.
194        source: Option<Box<dyn Error + Send + Sync + 'static>>,
195    },
196}
197
198impl AccountError {
199    /// Creates a custom error using the [`AccountError::Other`] variant from an error message.
200    pub fn other(message: impl Into<String>) -> Self {
201        let message: String = message.into();
202        Self::Other { error_msg: message.into(), source: None }
203    }
204
205    /// Creates a custom error using the [`AccountError::Other`] variant from an error message and
206    /// a source error.
207    pub fn other_with_source(
208        message: impl Into<String>,
209        source: impl Error + Send + Sync + 'static,
210    ) -> Self {
211        let message: String = message.into();
212        Self::Other {
213            error_msg: message.into(),
214            source: Some(Box::new(source)),
215        }
216    }
217}
218
219// ACCOUNT ID ERROR
220// ================================================================================================
221
222#[derive(Debug, Error)]
223pub enum AccountIdError {
224    #[error("failed to convert bytes into account ID prefix field element")]
225    AccountIdInvalidPrefixFieldElement(#[source] DeserializationError),
226    #[error("failed to convert bytes into account ID suffix field element")]
227    AccountIdInvalidSuffixFieldElement(#[source] DeserializationError),
228    #[error("`{0}` is not a known account storage mode")]
229    UnknownAccountStorageMode(Box<str>),
230    #[error(r#"`{0}` is not a known account type, expected one of "FungibleFaucet", "NonFungibleFaucet", "RegularAccountImmutableCode" or "RegularAccountUpdatableCode""#)]
231    UnknownAccountType(Box<str>),
232    #[error("failed to parse hex string into account ID")]
233    AccountIdHexParseError(#[source] HexParseError),
234    #[error("`{0}` is not a known account ID version")]
235    UnknownAccountIdVersion(u8),
236    #[error("most significant bit of account ID suffix must be zero")]
237    AccountIdSuffixMostSignificantBitMustBeZero,
238    #[error("least significant byte of account ID suffix must be zero")]
239    AccountIdSuffixLeastSignificantByteMustBeZero,
240    #[error("failed to decode bech32 string into account ID")]
241    Bech32DecodeError(#[source] Bech32Error),
242}
243
244// SLOT NAME ERROR
245// ================================================================================================
246
247#[derive(Debug, Error)]
248pub enum StorageSlotNameError {
249    #[error("slot name must only contain characters a..z, A..Z, 0..9, double colon or underscore")]
250    InvalidCharacter,
251    #[error("slot names must be separated by double colons")]
252    UnexpectedColon,
253    #[error("slot name components must not start with an underscore")]
254    UnexpectedUnderscore,
255    #[error(
256        "slot names must contain at least {} components separated by double colons",
257        StorageSlotName::MIN_NUM_COMPONENTS
258    )]
259    TooShort,
260    #[error("slot names must contain at most {} characters", StorageSlotName::MAX_LENGTH)]
261    TooLong,
262}
263
264// ACCOUNT TREE ERROR
265// ================================================================================================
266
267#[derive(Debug, Error)]
268pub enum AccountTreeError {
269    #[error(
270        "account tree contains multiple account IDs that share the same prefix {duplicate_prefix}"
271    )]
272    DuplicateIdPrefix { duplicate_prefix: AccountIdPrefix },
273    #[error(
274        "entries passed to account tree contain multiple state commitments for the same account ID prefix {prefix}"
275    )]
276    DuplicateStateCommitments { prefix: AccountIdPrefix },
277    #[error("untracked account ID {id} used in partial account tree")]
278    UntrackedAccountId { id: AccountId, source: MerkleError },
279    #[error("new tree root after account witness insertion does not match previous tree root")]
280    TreeRootConflict(#[source] MerkleError),
281    #[error("failed to apply mutations to account tree")]
282    ApplyMutations(#[source] MerkleError),
283    #[error("failed to compute account tree mutations")]
284    ComputeMutations(#[source] MerkleError),
285    #[error("provided smt contains an invalid account ID in key {key}")]
286    InvalidAccountIdKey { key: Word, source: AccountIdError },
287    #[error("smt leaf's index is not a valid account ID prefix")]
288    InvalidAccountIdPrefix(#[source] AccountIdError),
289    #[error("account witness merkle path depth {0} does not match AccountTree::DEPTH")]
290    WitnessMerklePathDepthDoesNotMatchAccountTreeDepth(usize),
291}
292
293// ADDRESS ERROR
294// ================================================================================================
295
296#[derive(Debug, Error)]
297pub enum AddressError {
298    #[error("tag length {0} is too large, must be less than or equal to {max}",
299        max = NoteTag::MAX_ACCOUNT_TARGET_TAG_LENGTH
300    )]
301    TagLengthTooLarge(u8),
302    #[error("unknown address interface `{0}`")]
303    UnknownAddressInterface(u16),
304    #[error("failed to decode account ID")]
305    AccountIdDecodeError(#[source] AccountIdError),
306    #[error("address separator must not be included without routing parameters")]
307    TrailingSeparator,
308    #[error("failed to decode bech32 string into an address")]
309    Bech32DecodeError(#[source] Bech32Error),
310    #[error("{error_msg}")]
311    DecodeError {
312        error_msg: Box<str>,
313        // thiserror will return this when calling Error::source on AddressError.
314        source: Option<Box<dyn Error + Send + Sync + 'static>>,
315    },
316    #[error("found unknown routing parameter key {0}")]
317    UnknownRoutingParameterKey(u8),
318}
319
320impl AddressError {
321    /// Creates an [`AddressError::DecodeError`] variant from an error message.
322    pub fn decode_error(message: impl Into<String>) -> Self {
323        let message: String = message.into();
324        Self::DecodeError { error_msg: message.into(), source: None }
325    }
326
327    /// Creates an [`AddressError::DecodeError`] variant from an error message and
328    /// a source error.
329    pub fn decode_error_with_source(
330        message: impl Into<String>,
331        source: impl Error + Send + Sync + 'static,
332    ) -> Self {
333        let message: String = message.into();
334        Self::DecodeError {
335            error_msg: message.into(),
336            source: Some(Box::new(source)),
337        }
338    }
339}
340
341// BECH32 ERROR
342// ================================================================================================
343
344#[derive(Debug, Error)]
345pub enum Bech32Error {
346    #[error(transparent)]
347    DecodeError(Box<dyn Error + Send + Sync + 'static>),
348    #[error("found unknown address type {0} which is not the expected {account_addr} account ID address type",
349      account_addr = AddressType::AccountId as u8
350    )]
351    UnknownAddressType(u8),
352    #[error("expected bech32 data to be of length {expected} but it was of length {actual}")]
353    InvalidDataLength { expected: usize, actual: usize },
354}
355
356// NETWORK ID ERROR
357// ================================================================================================
358
359#[derive(Debug, Error)]
360pub enum NetworkIdError {
361    #[error("failed to parse string into a network ID")]
362    NetworkIdParseError(#[source] Box<dyn Error + Send + Sync + 'static>),
363}
364
365// ACCOUNT DELTA ERROR
366// ================================================================================================
367
368#[derive(Debug, Error)]
369pub enum AccountDeltaError {
370    #[error("storage slot {0} was used as different slot types")]
371    StorageSlotUsedAsDifferentTypes(StorageSlotName),
372    #[error("non fungible vault can neither be added nor removed twice")]
373    DuplicateNonFungibleVaultUpdate(NonFungibleAsset),
374    #[error(
375        "fungible asset issued by faucet {faucet_id} has delta {delta} which overflows when added to current value {current}"
376    )]
377    FungibleAssetDeltaOverflow {
378        faucet_id: AccountId,
379        current: i64,
380        delta: i64,
381    },
382    #[error(
383        "account update of type `{left_update_type}` cannot be merged with account update of type `{right_update_type}`"
384    )]
385    IncompatibleAccountUpdates {
386        left_update_type: &'static str,
387        right_update_type: &'static str,
388    },
389    #[error("account delta could not be applied to account {account_id}")]
390    AccountDeltaApplicationFailed {
391        account_id: AccountId,
392        source: AccountError,
393    },
394    #[error("non-empty account storage or vault delta with zero nonce delta is not allowed")]
395    NonEmptyStorageOrVaultDeltaWithZeroNonceDelta,
396    #[error(
397        "account nonce increment {current} plus the other nonce increment {increment} overflows a felt to {new}"
398    )]
399    NonceIncrementOverflow {
400        current: Felt,
401        increment: Felt,
402        new: Felt,
403    },
404    #[error("account ID {0} in fungible asset delta is not of type fungible faucet")]
405    NotAFungibleFaucetId(AccountId),
406    #[error("cannot merge two full state deltas")]
407    MergingFullStateDeltas,
408}
409
410// STORAGE MAP ERROR
411// ================================================================================================
412
413#[derive(Debug, Error)]
414pub enum StorageMapError {
415    #[error("map entries contain key {key} twice with values {value0} and {value1}")]
416    DuplicateKey {
417        key: StorageMapKey,
418        value0: Word,
419        value1: Word,
420    },
421    #[error("map key {key} is not present in provided SMT proof")]
422    MissingKey { key: StorageMapKey },
423}
424
425// BATCH ACCOUNT UPDATE ERROR
426// ================================================================================================
427
428#[derive(Debug, Error)]
429pub enum BatchAccountUpdateError {
430    #[error(
431        "account update for account {expected_account_id} cannot be merged with update from transaction {transaction} which was executed against account {actual_account_id}"
432    )]
433    AccountUpdateIdMismatch {
434        transaction: TransactionId,
435        expected_account_id: AccountId,
436        actual_account_id: AccountId,
437    },
438    #[error(
439        "final state commitment in account update from transaction {0} does not match initial state of current update"
440    )]
441    AccountUpdateInitialStateMismatch(TransactionId),
442    #[error("failed to merge account delta from transaction {0}")]
443    TransactionUpdateMergeError(TransactionId, #[source] Box<AccountDeltaError>),
444}
445
446// ASSET ERROR
447// ================================================================================================
448
449#[derive(Debug, Error)]
450pub enum AssetError {
451    #[error(
452      "fungible asset amount {0} exceeds the max allowed amount of {max_amount}",
453      max_amount = FungibleAsset::MAX_AMOUNT
454    )]
455    FungibleAssetAmountTooBig(u64),
456    #[error("subtracting {subtrahend} from fungible asset amount {minuend} would underflow")]
457    FungibleAssetAmountNotSufficient { minuend: u64, subtrahend: u64 },
458    #[error(
459        "cannot add fungible asset with issuer {other_issuer} to fungible asset with issuer {original_issuer}"
460    )]
461    FungibleAssetInconsistentFaucetIds {
462        original_issuer: AccountId,
463        other_issuer: AccountId,
464    },
465    #[error("faucet account ID in asset is invalid")]
466    InvalidFaucetAccountId(#[source] Box<dyn Error + Send + Sync + 'static>),
467    #[error(
468      "faucet id {0} of type {id_type} must be of type {expected_ty} for fungible assets",
469      id_type = .0.account_type(),
470      expected_ty = AccountType::FungibleFaucet
471    )]
472    FungibleFaucetIdTypeMismatch(AccountId),
473    #[error(
474        "asset ID prefix and suffix in a non-fungible asset's vault key must match indices 0 and 1 in the value, but asset ID was {asset_id} and value was {value}"
475    )]
476    NonFungibleAssetIdMustMatchValue { asset_id: AssetId, value: Word },
477    #[error("asset ID prefix and suffix in a fungible asset's vault key must be zero but was {0}")]
478    FungibleAssetIdMustBeZero(AssetId),
479    #[error(
480        "the three most significant elements in a fungible asset's value must be zero but provided value was {0}"
481    )]
482    FungibleAssetValueMostSignificantElementsMustBeZero(Word),
483    #[error(
484      "faucet id {0} of type {id_type} must be of type {expected_ty} for non fungible assets",
485      id_type = .0.account_type(),
486      expected_ty = AccountType::NonFungibleFaucet
487    )]
488    NonFungibleFaucetIdTypeMismatch(AccountId),
489    #[error("smt proof in asset witness contains invalid key or value")]
490    AssetWitnessInvalid(#[source] Box<AssetError>),
491}
492
493// TOKEN SYMBOL ERROR
494// ================================================================================================
495
496#[derive(Debug, Error)]
497pub enum TokenSymbolError {
498    #[error("token symbol value {0} cannot exceed {max}", max = TokenSymbol::MAX_ENCODED_VALUE)]
499    ValueTooLarge(u64),
500    #[error("token symbol should have length between 1 and 12 characters, but {0} was provided")]
501    InvalidLength(usize),
502    #[error("token symbol contains a character that is not uppercase ASCII")]
503    InvalidCharacter,
504    #[error("token symbol data left after decoding the specified number of characters")]
505    DataNotFullyDecoded,
506}
507
508// ASSET VAULT ERROR
509// ================================================================================================
510
511#[derive(Debug, Error)]
512pub enum AssetVaultError {
513    #[error("adding fungible asset amounts would exceed maximum allowed amount")]
514    AddFungibleAssetBalanceError(#[source] AssetError),
515    #[error("provided assets contain duplicates")]
516    DuplicateAsset(#[source] MerkleError),
517    #[error("non fungible asset {0} already exists in the vault")]
518    DuplicateNonFungibleAsset(NonFungibleAsset),
519    #[error("fungible asset {0} does not exist in the vault")]
520    FungibleAssetNotFound(FungibleAsset),
521    #[error("faucet id {0} is not a fungible faucet id")]
522    NotAFungibleFaucetId(AccountId),
523    #[error("non fungible asset {0} does not exist in the vault")]
524    NonFungibleAssetNotFound(NonFungibleAsset),
525    #[error("subtracting fungible asset amounts would underflow")]
526    SubtractFungibleAssetBalanceError(#[source] AssetError),
527    #[error("maximum number of asset vault leaves exceeded")]
528    MaxLeafEntriesExceeded(#[source] MerkleError),
529}
530
531// PARTIAL ASSET VAULT ERROR
532// ================================================================================================
533
534#[derive(Debug, Error)]
535pub enum PartialAssetVaultError {
536    #[error("provided SMT entry {entry} is not a valid asset")]
537    InvalidAssetInSmt { entry: Word, source: AssetError },
538    #[error("failed to add asset proof")]
539    FailedToAddProof(#[source] MerkleError),
540    #[error("asset is not tracked in the partial vault")]
541    UntrackedAsset(#[source] MerkleError),
542}
543
544// NOTE ERROR
545// ================================================================================================
546
547#[derive(Debug, Error)]
548pub enum NoteError {
549    #[error("library does not contain a procedure with @note_script attribute")]
550    NoteScriptNoProcedureWithAttribute,
551    #[error("library contains multiple procedures with @note_script attribute")]
552    NoteScriptMultipleProceduresWithAttribute,
553    #[error("procedure at path '{0}' not found in library")]
554    NoteScriptProcedureNotFound(Box<str>),
555    #[error("procedure at path '{0}' does not have @note_script attribute")]
556    NoteScriptProcedureMissingAttribute(Box<str>),
557    #[error("note tag length {0} exceeds the maximum of {max}", max = NoteTag::MAX_ACCOUNT_TARGET_TAG_LENGTH)]
558    NoteTagLengthTooLarge(u8),
559    #[error("duplicate fungible asset from issuer {0} in note")]
560    DuplicateFungibleAsset(AccountId),
561    #[error("duplicate non fungible asset {0} in note")]
562    DuplicateNonFungibleAsset(NonFungibleAsset),
563    #[error("note type {0} is inconsistent with note tag {1}")]
564    InconsistentNoteTag(NoteType, u64),
565    #[error("adding fungible asset amounts would exceed maximum allowed amount")]
566    AddFungibleAssetBalanceError(#[source] AssetError),
567    #[error("note sender is not a valid account ID")]
568    NoteSenderInvalidAccountId(#[source] AccountIdError),
569    #[error("note execution hint after block variant cannot contain u32::MAX")]
570    NoteExecutionHintAfterBlockCannotBeU32Max,
571    #[error("invalid note execution hint payload {1} for tag {0}")]
572    InvalidNoteExecutionHintPayload(u8, u32),
573    #[error(
574    "note type {0} does not match any of the valid note types {public} or {private}",
575    public = NoteType::Public,
576    private = NoteType::Private,
577    )]
578    UnknownNoteType(Box<str>),
579    #[error("note location index {node_index_in_block} is out of bounds 0..={highest_index}")]
580    NoteLocationIndexOutOfBounds {
581        node_index_in_block: u16,
582        highest_index: usize,
583    },
584    #[error("note network execution requires a public note but note is of type {0}")]
585    NetworkExecutionRequiresPublicNote(NoteType),
586    #[error("failed to assemble note script:\n{}", PrintDiagnostic::new(.0))]
587    NoteScriptAssemblyError(Report),
588    #[error("failed to deserialize note script")]
589    NoteScriptDeserializationError(#[source] DeserializationError),
590    #[error("note contains {0} assets which exceeds the maximum of {max}", max = NoteAssets::MAX_NUM_ASSETS)]
591    TooManyAssets(usize),
592    #[error("note contains {0} storage items which exceeds the maximum of {max}", max = MAX_NOTE_STORAGE_ITEMS)]
593    TooManyStorageItems(usize),
594    #[error("invalid note storage length: expected {expected} items, got {actual}")]
595    InvalidNoteStorageLength { expected: usize, actual: usize },
596    #[error("note tag requires a public note but the note is of type {0}")]
597    PublicNoteRequired(NoteType),
598    #[error(
599        "note attachment cannot commit to more than {} elements",
600        NoteAttachmentArray::MAX_NUM_ELEMENTS
601    )]
602    NoteAttachmentArraySizeExceeded(usize),
603    #[error("unknown note attachment kind {0}")]
604    UnknownNoteAttachmentKind(u8),
605    #[error("note attachment of kind None must have attachment scheme None")]
606    AttachmentKindNoneMustHaveAttachmentSchemeNone,
607    #[error(
608        "note attachment kind mismatch: header has {header_kind:?} but attachment has {attachment_kind:?}"
609    )]
610    AttachmentKindMismatch {
611        header_kind: NoteAttachmentKind,
612        attachment_kind: NoteAttachmentKind,
613    },
614    #[error(
615        "note attachment scheme mismatch: header has {header_scheme:?} but attachment has {attachment_scheme:?}"
616    )]
617    AttachmentSchemeMismatch {
618        header_scheme: NoteAttachmentScheme,
619        attachment_scheme: NoteAttachmentScheme,
620    },
621    #[error("{error_msg}")]
622    Other {
623        error_msg: Box<str>,
624        // thiserror will return this when calling Error::source on NoteError.
625        source: Option<Box<dyn Error + Send + Sync + 'static>>,
626    },
627}
628
629impl NoteError {
630    /// Creates a custom error using the [`NoteError::Other`] variant from an error message.
631    pub fn other(message: impl Into<String>) -> Self {
632        let message: String = message.into();
633        Self::Other { error_msg: message.into(), source: None }
634    }
635
636    /// Creates a custom error using the [`NoteError::Other`] variant from an error message and
637    /// a source error.
638    pub fn other_with_source(
639        message: impl Into<String>,
640        source: impl Error + Send + Sync + 'static,
641    ) -> Self {
642        let message: String = message.into();
643        Self::Other {
644            error_msg: message.into(),
645            source: Some(Box::new(source)),
646        }
647    }
648}
649
650// PARTIAL BLOCKCHAIN ERROR
651// ================================================================================================
652
653#[derive(Debug, Error)]
654pub enum PartialBlockchainError {
655    #[error(
656        "block num {block_num} exceeds chain length {chain_length} implied by the partial blockchain"
657    )]
658    BlockNumTooBig {
659        chain_length: usize,
660        block_num: BlockNumber,
661    },
662
663    #[error("duplicate block {block_num} in partial blockchain")]
664    DuplicateBlock { block_num: BlockNumber },
665
666    #[error("partial blockchain does not track authentication paths for block {block_num}")]
667    UntrackedBlock { block_num: BlockNumber },
668
669    #[error(
670        "provided block header with number {block_num} and commitment {block_commitment} is not tracked by partial MMR"
671    )]
672    BlockHeaderCommitmentMismatch {
673        block_num: BlockNumber,
674        block_commitment: Word,
675        source: MmrError,
676    },
677}
678
679impl PartialBlockchainError {
680    pub fn block_num_too_big(chain_length: usize, block_num: BlockNumber) -> Self {
681        Self::BlockNumTooBig { chain_length, block_num }
682    }
683
684    pub fn duplicate_block(block_num: BlockNumber) -> Self {
685        Self::DuplicateBlock { block_num }
686    }
687
688    pub fn untracked_block(block_num: BlockNumber) -> Self {
689        Self::UntrackedBlock { block_num }
690    }
691}
692
693// TRANSACTION SCRIPT ERROR
694// ================================================================================================
695
696#[derive(Debug, Error)]
697pub enum TransactionScriptError {
698    #[error("failed to assemble transaction script:\n{}", PrintDiagnostic::new(.0))]
699    AssemblyError(Report),
700}
701
702// TRANSACTION INPUT ERROR
703// ================================================================================================
704
705#[derive(Debug, Error)]
706pub enum TransactionInputError {
707    #[error("transaction input note with nullifier {0} is a duplicate")]
708    DuplicateInputNote(Nullifier),
709    #[error("partial blockchain has length {actual} which does not match block number {expected}")]
710    InconsistentChainLength {
711        expected: BlockNumber,
712        actual: BlockNumber,
713    },
714    #[error(
715        "partial blockchain has commitment {actual} which does not match the block header's chain commitment {expected}"
716    )]
717    InconsistentChainCommitment { expected: Word, actual: Word },
718    #[error("block in which input note with id {0} was created is not in partial blockchain")]
719    InputNoteBlockNotInPartialBlockchain(NoteId),
720    #[error("input note with id {0} was not created in block {1}")]
721    InputNoteNotInBlock(NoteId, BlockNumber),
722    #[error(
723        "total number of input notes is {0} which exceeds the maximum of {MAX_INPUT_NOTES_PER_TX}"
724    )]
725    TooManyInputNotes(usize),
726}
727
728// TRANSACTION INPUTS EXTRACTION ERROR
729// ===============================================================================================
730
731#[derive(Debug, Error)]
732pub enum TransactionInputsExtractionError {
733    #[error("specified foreign account id matches the transaction input's account id")]
734    AccountNotForeign,
735    #[error("foreign account data not found in advice map for account {0}")]
736    ForeignAccountNotFound(AccountId),
737    #[error("foreign account code not found for account {0}")]
738    ForeignAccountCodeNotFound(AccountId),
739    #[error("storage header data not found in advice map for account {0}")]
740    StorageHeaderNotFound(AccountId),
741    #[error("failed to handle account data")]
742    AccountError(#[from] AccountError),
743    #[error("failed to handle merkle data")]
744    MerkleError(#[from] MerkleError),
745    #[error("failed to handle account tree data")]
746    AccountTreeError(#[from] AccountTreeError),
747    #[error("missing vault root from Merkle store")]
748    MissingVaultRoot,
749    #[error("missing storage map root from Merkle store")]
750    MissingMapRoot,
751    #[error("failed to construct SMT proof")]
752    SmtProofError(#[from] SmtProofError),
753    #[error("failed to construct an asset")]
754    AssetError(#[from] AssetError),
755    #[error("failed to handle storage map data")]
756    StorageMapError(#[from] StorageMapError),
757    #[error("failed to convert elements to leaf index: {0}")]
758    LeafConversionError(String),
759    #[error("failed to construct SMT leaf")]
760    SmtLeafError(#[from] SmtLeafError),
761}
762
763// TRANSACTION OUTPUT ERROR
764// ===============================================================================================
765
766#[derive(Debug, Error)]
767pub enum TransactionOutputError {
768    #[error("transaction output note with id {0} is a duplicate")]
769    DuplicateOutputNote(NoteId),
770    #[error("final account commitment is not in the advice map")]
771    FinalAccountCommitmentMissingInAdviceMap,
772    #[error("fee asset is not a fungible asset")]
773    FeeAssetNotFungibleAsset(#[source] AssetError),
774    #[error("failed to parse final account header")]
775    FinalAccountHeaderParseFailure(#[source] AccountError),
776    #[error(
777        "output notes commitment {expected} from kernel does not match computed commitment {actual}"
778    )]
779    OutputNotesCommitmentInconsistent { expected: Word, actual: Word },
780    #[error("transaction kernel output stack is invalid: {0}")]
781    OutputStackInvalid(String),
782    #[error(
783        "total number of output notes is {0} which exceeds the maximum of {MAX_OUTPUT_NOTES_PER_TX}"
784    )]
785    TooManyOutputNotes(usize),
786    #[error("failed to process account update commitment: {0}")]
787    AccountUpdateCommitment(Box<str>),
788}
789
790// OUTPUT NOTE ERROR
791// ================================================================================================
792
793/// Errors that can occur when creating a
794/// [`PublicOutputNote`](crate::transaction::PublicOutputNote) or
795/// [`PrivateNoteHeader`](crate::transaction::PrivateNoteHeader).
796#[derive(Debug, Error)]
797pub enum OutputNoteError {
798    #[error("note with id {0} is private but expected a public note")]
799    NoteIsPrivate(NoteId),
800    #[error("note with id {0} is public but expected a private note")]
801    NoteIsPublic(NoteId),
802    #[error(
803        "public note with id {note_id} has size {note_size} bytes which exceeds maximum note size of {NOTE_MAX_SIZE}"
804    )]
805    NoteSizeLimitExceeded { note_id: NoteId, note_size: usize },
806}
807
808// TRANSACTION EVENT PARSING ERROR
809// ================================================================================================
810
811#[derive(Debug, Error)]
812pub enum TransactionEventError {
813    #[error("event id {0} is not a valid transaction event")]
814    InvalidTransactionEvent(EventId, Option<&'static str>),
815    #[error("event id {0} is not a transaction kernel event")]
816    NotTransactionEvent(EventId, Option<&'static str>),
817    #[error("event id {0} can only be emitted from the root context")]
818    NotRootContext(TransactionEventId),
819}
820
821// TRANSACTION TRACE PARSING ERROR
822// ================================================================================================
823
824#[derive(Debug, Error)]
825pub enum TransactionTraceParsingError {
826    #[error("trace id {0} is an unknown transaction kernel trace")]
827    UnknownTransactionTrace(u32),
828}
829
830// PROVEN TRANSACTION ERROR
831// ================================================================================================
832
833#[derive(Debug, Error)]
834pub enum ProvenTransactionError {
835    #[error(
836        "proven transaction's final account commitment {tx_final_commitment} and account details commitment {details_commitment} must match"
837    )]
838    AccountFinalCommitmentMismatch {
839        tx_final_commitment: Word,
840        details_commitment: Word,
841    },
842    #[error(
843        "proven transaction's final account ID {tx_account_id} and account details id {details_account_id} must match"
844    )]
845    AccountIdMismatch {
846        tx_account_id: AccountId,
847        details_account_id: AccountId,
848    },
849    #[error("failed to construct input notes for proven transaction")]
850    InputNotesError(TransactionInputError),
851    #[error("private account {0} should not have account details")]
852    PrivateAccountWithDetails(AccountId),
853    #[error("account {0} with public state is missing its account details")]
854    PublicStateAccountMissingDetails(AccountId),
855    #[error("new account {id} with public state must be accompanied by a full state delta")]
856    NewPublicStateAccountRequiresFullStateDelta { id: AccountId, source: AccountError },
857    #[error(
858        "existing account {0} with public state should only provide delta updates instead of full details"
859    )]
860    ExistingPublicStateAccountRequiresDeltaDetails(AccountId),
861    #[error("failed to construct output notes for proven transaction")]
862    OutputNotesError(#[source] TransactionOutputError),
863    #[error(
864        "account update of size {update_size} for account {account_id} exceeds maximum update size of {ACCOUNT_UPDATE_MAX_SIZE}"
865    )]
866    AccountUpdateSizeLimitExceeded {
867        account_id: AccountId,
868        update_size: usize,
869    },
870    #[error("proven transaction neither changed the account state, nor consumed any notes")]
871    EmptyTransaction,
872    #[error("failed to validate account delta in transaction account update")]
873    AccountDeltaCommitmentMismatch(#[source] Box<dyn Error + Send + Sync + 'static>),
874}
875
876// PROPOSED BATCH ERROR
877// ================================================================================================
878
879#[derive(Debug, Error)]
880pub enum ProposedBatchError {
881    #[error(
882        "transaction batch has {0} input notes but at most {MAX_INPUT_NOTES_PER_BATCH} are allowed"
883    )]
884    TooManyInputNotes(usize),
885
886    #[error(
887        "transaction batch has {0} output notes but at most {MAX_OUTPUT_NOTES_PER_BATCH} are allowed"
888    )]
889    TooManyOutputNotes(usize),
890
891    #[error(
892        "transaction batch has {0} account updates but at most {MAX_ACCOUNTS_PER_BATCH} are allowed"
893    )]
894    TooManyAccountUpdates(usize),
895
896    #[error(
897        "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}"
898    )]
899    ExpiredTransaction {
900        transaction_id: TransactionId,
901        transaction_expiration_num: BlockNumber,
902        reference_block_num: BlockNumber,
903    },
904
905    #[error("transaction batch must contain at least one transaction")]
906    EmptyTransactionBatch,
907
908    #[error("transaction {transaction_id} appears twice in the proposed batch input")]
909    DuplicateTransaction { transaction_id: TransactionId },
910
911    #[error(
912        "transaction {second_transaction_id} consumes the note with nullifier {note_nullifier} that is also consumed by another transaction {first_transaction_id} in the batch"
913    )]
914    DuplicateInputNote {
915        note_nullifier: Nullifier,
916        first_transaction_id: TransactionId,
917        second_transaction_id: TransactionId,
918    },
919
920    #[error(
921        "transaction {second_transaction_id} creates the note with id {note_id} that is also created by another transaction {first_transaction_id} in the batch"
922    )]
923    DuplicateOutputNote {
924        note_id: NoteId,
925        first_transaction_id: TransactionId,
926        second_transaction_id: TransactionId,
927    },
928
929    #[error(
930        "note commitment mismatch for note {id}: (input: {input_commitment}, output: {output_commitment})"
931    )]
932    NoteCommitmentMismatch {
933        id: NoteId,
934        input_commitment: Word,
935        output_commitment: Word,
936    },
937
938    #[error("failed to merge transaction delta into account {account_id}")]
939    AccountUpdateError {
940        account_id: AccountId,
941        source: BatchAccountUpdateError,
942    },
943
944    #[error(
945        "unable to prove unauthenticated note inclusion because block {block_number} in which note with id {note_id} was created is not in partial blockchain"
946    )]
947    UnauthenticatedInputNoteBlockNotInPartialBlockchain {
948        block_number: BlockNumber,
949        note_id: NoteId,
950    },
951
952    #[error(
953        "unable to prove unauthenticated note inclusion of note {note_id} in block {block_num}"
954    )]
955    UnauthenticatedNoteAuthenticationFailed {
956        note_id: NoteId,
957        block_num: BlockNumber,
958        source: MerkleError,
959    },
960
961    #[error("partial blockchain has length {actual} which does not match block number {expected}")]
962    InconsistentChainLength {
963        expected: BlockNumber,
964        actual: BlockNumber,
965    },
966
967    #[error(
968        "partial blockchain has root {actual} which does not match block header's root {expected}"
969    )]
970    InconsistentChainRoot { expected: Word, actual: Word },
971
972    #[error(
973        "block {block_reference} referenced by transaction {transaction_id} is not in the partial blockchain"
974    )]
975    MissingTransactionBlockReference {
976        block_reference: Word,
977        transaction_id: TransactionId,
978    },
979}
980
981// PROVEN BATCH ERROR
982// ================================================================================================
983
984#[derive(Debug, Error)]
985pub enum ProvenBatchError {
986    #[error("failed to verify transaction {transaction_id} in transaction batch")]
987    TransactionVerificationFailed {
988        transaction_id: TransactionId,
989        source: Box<dyn Error + Send + Sync + 'static>,
990    },
991    #[error(
992        "batch expiration block number {batch_expiration_block_num} is not greater than the reference block number {reference_block_num}"
993    )]
994    InvalidBatchExpirationBlockNum {
995        batch_expiration_block_num: BlockNumber,
996        reference_block_num: BlockNumber,
997    },
998}
999
1000// PROPOSED BLOCK ERROR
1001// ================================================================================================
1002
1003#[derive(Debug, Error)]
1004pub enum ProposedBlockError {
1005    #[error("block must contain at least one transaction batch")]
1006    EmptyBlock,
1007
1008    #[error("block must contain at most {MAX_BATCHES_PER_BLOCK} transaction batches")]
1009    TooManyBatches,
1010
1011    #[error(
1012        "batch {batch_id} expired at block {batch_expiration_block_num} but the current block number is {current_block_num}"
1013    )]
1014    ExpiredBatch {
1015        batch_id: BatchId,
1016        batch_expiration_block_num: BlockNumber,
1017        current_block_num: BlockNumber,
1018    },
1019
1020    #[error("batch {batch_id} appears twice in the block inputs")]
1021    DuplicateBatch { batch_id: BatchId },
1022
1023    #[error(
1024        "batch {second_batch_id} consumes the note with nullifier {note_nullifier} that is also consumed by another batch {first_batch_id} in the block"
1025    )]
1026    DuplicateInputNote {
1027        note_nullifier: Nullifier,
1028        first_batch_id: BatchId,
1029        second_batch_id: BatchId,
1030    },
1031
1032    #[error(
1033        "batch {second_batch_id} creates the note with ID {note_id} that is also created by another batch {first_batch_id} in the block"
1034    )]
1035    DuplicateOutputNote {
1036        note_id: NoteId,
1037        first_batch_id: BatchId,
1038        second_batch_id: BatchId,
1039    },
1040
1041    #[error(
1042        "timestamp {provided_timestamp} does not increase monotonically compared to timestamp {previous_timestamp} from the previous block header"
1043    )]
1044    TimestampDoesNotIncreaseMonotonically {
1045        provided_timestamp: u32,
1046        previous_timestamp: u32,
1047    },
1048
1049    #[error(
1050        "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}"
1051    )]
1052    ConflictingBatchesUpdateSameAccount {
1053        account_id: AccountId,
1054        initial_state_commitment: Word,
1055        first_batch_id: BatchId,
1056        second_batch_id: BatchId,
1057    },
1058
1059    #[error(
1060        "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"
1061    )]
1062    ChainLengthNotEqualToPreviousBlockNumber {
1063        chain_length: BlockNumber,
1064        prev_block_num: BlockNumber,
1065    },
1066
1067    #[error(
1068        "partial blockchain has commitment {chain_commitment} which does not match the chain commitment {prev_block_chain_commitment} of the previous block {prev_block_num}"
1069    )]
1070    ChainRootNotEqualToPreviousBlockChainCommitment {
1071        chain_commitment: Word,
1072        prev_block_chain_commitment: Word,
1073        prev_block_num: BlockNumber,
1074    },
1075
1076    #[error(
1077        "partial blockchain is missing block {reference_block_num} referenced by batch {batch_id} in the block"
1078    )]
1079    BatchReferenceBlockMissingFromChain {
1080        reference_block_num: BlockNumber,
1081        batch_id: BatchId,
1082    },
1083
1084    #[error(
1085        "note commitment mismatch for note {id}: (input: {input_commitment}, output: {output_commitment})"
1086    )]
1087    NoteCommitmentMismatch {
1088        id: NoteId,
1089        input_commitment: Word,
1090        output_commitment: Word,
1091    },
1092
1093    #[error(
1094        "failed to prove unauthenticated note inclusion because block {block_number} in which note with id {note_id} was created is not in partial blockchain"
1095    )]
1096    UnauthenticatedInputNoteBlockNotInPartialBlockchain {
1097        block_number: BlockNumber,
1098        note_id: NoteId,
1099    },
1100
1101    #[error(
1102        "failed to prove unauthenticated note inclusion of note {note_id} in block {block_num}"
1103    )]
1104    UnauthenticatedNoteAuthenticationFailed {
1105        note_id: NoteId,
1106        block_num: BlockNumber,
1107        source: MerkleError,
1108    },
1109
1110    #[error(
1111        "unauthenticated note with nullifier {nullifier} was not created in the same block and no inclusion proof to authenticate it was provided"
1112    )]
1113    UnauthenticatedNoteConsumed { nullifier: Nullifier },
1114
1115    #[error("block inputs do not contain a proof of inclusion for account {0}")]
1116    MissingAccountWitness(AccountId),
1117
1118    #[error(
1119        "account {account_id} with state {state_commitment} cannot transition to any of the remaining states {}",
1120        remaining_state_commitments.iter().map(Word::to_hex).collect::<Vec<_>>().join(", ")
1121    )]
1122    InconsistentAccountStateTransition {
1123        account_id: AccountId,
1124        state_commitment: Word,
1125        remaining_state_commitments: Vec<Word>,
1126    },
1127
1128    #[error("no proof for nullifier {0} was provided")]
1129    NullifierProofMissing(Nullifier),
1130
1131    #[error("note with nullifier {0} is already spent")]
1132    NullifierSpent(Nullifier),
1133
1134    #[error("failed to merge transaction delta into account {account_id}")]
1135    AccountUpdateError {
1136        account_id: AccountId,
1137        source: Box<AccountDeltaError>,
1138    },
1139
1140    #[error("failed to track account witness")]
1141    AccountWitnessTracking { source: AccountTreeError },
1142
1143    #[error(
1144        "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"
1145    )]
1146    StaleAccountTreeRoot {
1147        prev_block_account_root: Word,
1148        stale_account_root: Word,
1149    },
1150
1151    #[error("account ID prefix already exists in the tree")]
1152    AccountIdPrefixDuplicate { source: AccountTreeError },
1153
1154    #[error(
1155        "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"
1156    )]
1157    StaleNullifierTreeRoot {
1158        prev_block_nullifier_root: Word,
1159        stale_nullifier_root: Word,
1160    },
1161
1162    #[error("nullifier witness has a different root than the current nullifier tree root")]
1163    NullifierWitnessRootMismatch(NullifierTreeError),
1164}
1165
1166// FEE ERROR
1167// ================================================================================================
1168
1169#[derive(Debug, Error)]
1170pub enum FeeError {
1171    #[error("native asset of the chain must be a fungible faucet but was of type {account_type}")]
1172    NativeAssetIdNotFungible { account_type: AccountType },
1173}
1174
1175// NULLIFIER TREE ERROR
1176// ================================================================================================
1177
1178#[derive(Debug, Error)]
1179pub enum NullifierTreeError {
1180    #[error(
1181        "entries passed to nullifier tree contain multiple block numbers for the same nullifier"
1182    )]
1183    DuplicateNullifierBlockNumbers(#[source] MerkleError),
1184
1185    #[error("attempt to mark nullifier {0} as spent but it is already spent")]
1186    NullifierAlreadySpent(Nullifier),
1187
1188    #[error("maximum number of nullifier tree leaves exceeded")]
1189    MaxLeafEntriesExceeded(#[source] MerkleError),
1190
1191    #[error("nullifier {nullifier} is not tracked by the partial nullifier tree")]
1192    UntrackedNullifier {
1193        nullifier: Nullifier,
1194        source: MerkleError,
1195    },
1196
1197    #[error("new tree root after nullifier witness insertion does not match previous tree root")]
1198    TreeRootConflict(#[source] MerkleError),
1199
1200    #[error("failed to compute nullifier tree mutations")]
1201    ComputeMutations(#[source] MerkleError),
1202
1203    #[error("invalid nullifier block number")]
1204    InvalidNullifierBlockNumber(Word),
1205}
1206
1207// AUTH SCHEME ERROR
1208// ================================================================================================
1209
1210#[derive(Debug, Error)]
1211pub enum AuthSchemeError {
1212    #[error("auth scheme identifier `{0}` is not valid")]
1213    InvalidAuthSchemeIdentifier(String),
1214}