Skip to main content

miden_node_store/
errors.rs

1use std::io;
2
3use miden_node_proto::domain::block::InvalidBlockRange;
4use miden_node_proto::errors::ConversionError;
5use miden_node_utils::limiter::QueryLimitError;
6use miden_protocol::Word;
7use miden_protocol::account::{AccountId, StorageSlotName};
8use miden_protocol::block::BlockNumber;
9use miden_protocol::crypto::merkle::MerkleError;
10use miden_protocol::crypto::merkle::mmr::MmrError;
11use miden_protocol::crypto::merkle::smt::{LargeSmtForestError, LineageId};
12use miden_protocol::crypto::utils::DeserializationError;
13use miden_protocol::errors::{
14    AccountDeltaError,
15    AccountError,
16    AccountTreeError,
17    AssetError,
18    AssetVaultError,
19    NoteError,
20    NullifierTreeError,
21    StorageMapError,
22};
23use miden_protocol::note::Nullifier;
24use miden_protocol::transaction::OutputNote;
25use thiserror::Error;
26use tokio::sync::oneshot::error::RecvError;
27
28/// Errors produced while preparing or rebuilding account-state forest updates.
29///
30/// The underlying [`LargeSmtForestError`] is preserved so callers can distinguish fatal backend
31/// failures from invalid update preparation.
32#[derive(Debug, Error)]
33pub enum AccountStateForestUpdateError {
34    /// The patch of a new account attempted to create an existing vault lineage.
35    #[error("account {account_id} vault lineage already exists")]
36    VaultLineageAlreadyExists { account_id: AccountId },
37    /// The patch of a new account attempted to create an existing storage-map lineage.
38    #[error("account {account_id} storage map lineage for slot {slot_name} already exists")]
39    StorageLineageAlreadyExists {
40        account_id: AccountId,
41        slot_name: miden_protocol::account::StorageSlotName,
42    },
43    /// The forest mutation set did not contain a root for a lineage it was expected to update.
44    #[error("computed forest mutations are missing lineage {lineage}")]
45    MissingComputedRoot { lineage: LineageId },
46    /// The forest backend failed while computing, reading, or applying mutations.
47    #[error(transparent)]
48    Forest(#[from] LargeSmtForestError),
49}
50
51// DATABASE ERRORS
52// =================================================================================================
53
54#[derive(Debug, Error)]
55pub enum DatabaseError {
56    #[error("invalid persisted protobuf value")]
57    Persistence(#[from] miden_node_persistence::PersistenceError),
58    // ERRORS WITH AUTOMATIC CONVERSIONS FROM NESTED ERROR TYPES
59    // ---------------------------------------------------------------------------------------------
60    #[error("account error")]
61    AccountError(#[from] AccountError),
62    #[error("asset vault error")]
63    AssetVaultError(#[from] AssetVaultError),
64    #[error("asset error")]
65    AssetError(#[from] AssetError),
66    #[error("closed channel")]
67    ClosedChannel(#[from] RecvError),
68    #[error("database error")]
69    DatabaseError(#[from] miden_node_db::DatabaseError),
70    #[error("deserialization failed")]
71    DeserializationError(#[from] DeserializationError),
72    #[error("I/O error")]
73    IoError(#[from] io::Error),
74    #[error("merkle error")]
75    MerkleError(#[from] MerkleError),
76    #[error("note error")]
77    NoteError(#[from] NoteError),
78    #[error("storage map error")]
79    StorageMapError(#[from] StorageMapError),
80    #[error(transparent)]
81    QueryParamLimit(#[from] QueryLimitError),
82    #[error(transparent)]
83    RangeBeyondTip(#[from] RangeBeyondTip),
84    #[error(transparent)]
85    RangeBelowRetention(#[from] RangeBelowRetention),
86
87    // OTHER ERRORS
88    // ---------------------------------------------------------------------------------------------
89    #[error("account commitment mismatch (expected {expected}, but calculated is {calculated})")]
90    AccountCommitmentsMismatch { expected: Word, calculated: Word },
91    #[error(
92        "protocol config commitment mismatch (expected {expected}, but calculated is {calculated})"
93    )]
94    ProtocolConfigCommitmentMismatch { expected: Word, calculated: Word },
95    #[error("protocol config {0} is missing")]
96    ProtocolConfigNotFound(Word),
97    #[error("account {0} not found")]
98    AccountNotFoundInDb(AccountId),
99    #[error("account {0} already exists")]
100    AccountAlreadyExistsInDb(AccountId),
101    #[error("accounts {0:?} not found")]
102    AccountsNotFoundInDb(Vec<AccountId>),
103    #[error("account {0} is not on the chain")]
104    AccountNotPublic(AccountId),
105    #[error("invalid block parameters: block_from ({from}) > block_to ({to})")]
106    InvalidBlockRange { from: BlockNumber, to: BlockNumber },
107    #[error(
108        "transactions for block {block_num} would exceed maximum response size, \
109         use a stricter filter to reduce the number of transactions returned"
110    )]
111    TransactionPageExceedsPayloadLimit { block_num: BlockNumber },
112    #[error("block {block_num} holds more rows than one page can return")]
113    BlockExceedsPageLimit { block_num: BlockNumber },
114    #[error("data corrupted: {0}")]
115    DataCorrupted(String),
116    #[error("storage root not found for account {account_id}, slot {slot_name}, block {block_num}")]
117    StorageRootNotFound {
118        account_id: AccountId,
119        slot_name: String,
120        block_num: BlockNumber,
121    },
122}
123
124// INITIALIZATION ERRORS
125// =================================================================================================
126
127#[derive(Error, Debug)]
128pub enum StateInitializationError {
129    #[error("account tree IO error: {0}")]
130    AccountTreeIoError(String),
131    #[error("nullifier tree IO error: {0}")]
132    NullifierTreeIoError(String),
133    #[error("account state forest IO error: {0}")]
134    AccountStateForestIoError(String),
135    #[error("failed to rebuild account state forest")]
136    AccountStateForestRebuild(#[source] AccountStateForestUpdateError),
137    #[error("database error")]
138    DatabaseError(#[from] DatabaseError),
139    #[error("failed to create nullifier tree")]
140    FailedToCreateNullifierTree(#[from] NullifierTreeError),
141    #[error("failed to create accounts tree")]
142    FailedToCreateAccountsTree(#[source] AccountTreeError),
143    #[error("failed to load data directory")]
144    DataDirectoryLoadError(#[source] std::io::Error),
145    #[error("failed to load block store")]
146    BlockStoreLoadError(#[source] std::io::Error),
147    #[error("failed to load proven tip")]
148    ProvenTipLoadError(#[source] std::io::Error),
149    #[error("failed to load database")]
150    DatabaseLoadError(#[source] DatabaseError),
151    #[error(
152        "{tree_name} SMT root ({tree_root:?}) does not match expected root from block {block_num} \
153         ({block_root:?}). Delete the tree storage directories and restart the node to rebuild \
154         from the database."
155    )]
156    TreeStorageDiverged {
157        tree_name: &'static str,
158        block_num: BlockNumber,
159        tree_root: Word,
160        block_root: Word,
161    },
162    #[error("loaded chain MMR cannot produce peaks for block {block_num}")]
163    ChainMmrLoadError {
164        block_num: BlockNumber,
165        #[source]
166        source: MmrError,
167    },
168    #[error(
169        "chain MMR commitment ({chain_mmr_commitment:?}) does not match expected chain commitment \
170         from block {block_num} ({block_header_commitment:?})"
171    )]
172    ChainMmrStorageDiverged {
173        block_num: BlockNumber,
174        chain_mmr_commitment: Word,
175        block_header_commitment: Word,
176    },
177    #[error(
178        "account state forest root ({forest_root}) does not match SQLite root \
179         ({database_root}) for account {account_id}, slot {slot_name:?}. Delete the account \
180         state forest storage directory and restart the node to rebuild from the database."
181    )]
182    AccountStateForestStorageDiverged {
183        account_id: AccountId,
184        slot_name: Option<String>,
185        forest_root: Word,
186        database_root: Word,
187    },
188    #[error("public account {0} is missing details in database")]
189    PublicAccountMissingDetails(AccountId),
190    #[error("failed to convert account to delta: {0}")]
191    AccountToDeltaConversionFailed(String),
192    #[error("genesis block missing. The database should be bootstrapped first.")]
193    GenesisBlockMissing,
194    #[error(
195        "genesis protocol config {commitment} is missing. Rebootstrap the database from genesis."
196    )]
197    GenesisProtocolConfigMissing { commitment: Word },
198}
199
200// ENDPOINT ERRORS
201// =================================================================================================
202#[derive(Error, Debug)]
203pub enum InvalidBlockError {
204    #[error("duplicated nullifiers {0:?}")]
205    DuplicatedNullifiers(Vec<Nullifier>),
206    #[error("invalid output note type: {0:?}")]
207    InvalidOutputNoteType(Box<OutputNote>),
208    #[error("invalid block tx commitment: expected {expected}, but got {actual}")]
209    InvalidBlockTxCommitment { expected: Word, actual: Word },
210    #[error("received invalid account tree root")]
211    NewBlockInvalidAccountRoot,
212    #[error("new block number must be 1 greater than the current block number")]
213    NewBlockInvalidBlockNum {
214        expected: BlockNumber,
215        submitted: BlockNumber,
216    },
217    #[error("new block chain commitment is not consistent with chain MMR")]
218    NewBlockInvalidChainCommitment,
219    #[error("received invalid note root")]
220    NewBlockInvalidNoteRoot,
221    #[error("received invalid nullifier root")]
222    NewBlockInvalidNullifierRoot,
223    #[error("new block `prev_block_commitment` must match the chain's tip")]
224    NewBlockInvalidPrevCommitment,
225    #[error("nullifier in new block is already spent")]
226    NewBlockNullifierAlreadySpent(#[source] NullifierTreeError),
227    #[error("duplicate account ID prefix in new block")]
228    NewBlockDuplicateAccountIdPrefix(#[source] AccountTreeError),
229    #[error("failed to build note tree: {0}")]
230    FailedToBuildNoteTree(String),
231}
232
233#[derive(Error, Debug)]
234pub enum ApplyBlockError {
235    // ERRORS WITH AUTOMATIC CONVERSIONS FROM NESTED ERROR TYPES
236    // ---------------------------------------------------------------------------------------------
237    #[error("database error")]
238    DatabaseError(#[from] DatabaseError),
239    #[error("I/O error")]
240    IoError(#[from] io::Error),
241    #[error("task join error")]
242    TokioJoinError(#[from] tokio::task::JoinError),
243    #[error("invalid block error")]
244    InvalidBlockError(#[from] InvalidBlockError),
245
246    // OTHER ERRORS
247    // ---------------------------------------------------------------------------------------------
248    #[error("block applying was cancelled because the writer task dropped the result channel")]
249    ClosedChannel(#[from] RecvError),
250    #[error("account state forest update preparation failed")]
251    AccountStateForestPreparation(#[source] AccountStateForestUpdateError),
252    #[error("database doesn't have any block header data")]
253    DbBlockHeaderEmpty,
254    #[error("database update failed: {0}")]
255    DbUpdateTaskFailed(String),
256    #[error("failed to send block to the writer task: {0}")]
257    WriterTaskSendFailed(String),
258}
259
260#[derive(Error, Debug)]
261pub enum ApplyBlockWithProvingInputsError {
262    #[error("failed to save block proving inputs")]
263    SaveProvingInputs(#[source] io::Error),
264    #[error("failed to apply block")]
265    ApplyBlock(#[source] ApplyBlockError),
266}
267
268/// A requested block range extends beyond the chain tip of the state view serving the request.
269#[derive(Error, Debug)]
270#[error("block_to ({block_to}) is greater than chain tip ({chain_tip})")]
271pub struct RangeBeyondTip {
272    pub chain_tip: BlockNumber,
273    pub block_to: BlockNumber,
274}
275
276/// A requested block range ends below the oldest block for which the store keeps account history.
277#[derive(Error, Debug)]
278#[error("block_to ({block_to}) is older than the oldest retained block ({oldest_retained})")]
279pub struct RangeBelowRetention {
280    pub oldest_retained: BlockNumber,
281    pub block_to: BlockNumber,
282}
283
284#[derive(Error, Debug)]
285pub enum GetBlockHeaderError {
286    #[error("database error")]
287    DatabaseError(#[from] DatabaseError),
288    #[error("error retrieving the merkle proof for the block")]
289    MmrError(#[from] MmrError),
290}
291
292#[derive(Error, Debug)]
293pub enum StateSyncError {
294    #[error("database error")]
295    DatabaseError(#[from] DatabaseError),
296    #[error("block headers table is empty")]
297    EmptyBlockHeadersTable,
298    #[error("failed to build MMR delta")]
299    FailedToBuildMmrDelta(#[from] MmrError),
300    #[error(transparent)]
301    RangeBeyondTip(#[from] RangeBeyondTip),
302}
303
304#[derive(Error, Debug)]
305pub enum NoteSyncError {
306    #[error("database error")]
307    DatabaseError(#[from] DatabaseError),
308    #[error("database error")]
309    UnderlyingDatabaseError(#[from] miden_node_db::DatabaseError),
310    #[error("error retrieving the merkle proof for the block")]
311    MmrError(#[from] MmrError),
312    #[error("invalid block range")]
313    InvalidBlockRange(#[from] InvalidBlockRange),
314    #[error(transparent)]
315    RangeBeyondTip(#[from] RangeBeyondTip),
316    #[error("malformed note tags")]
317    DeserializationFailed(#[from] ConversionError),
318}
319
320#[derive(Error, Debug)]
321pub enum GetNoteInclusionProofsError {
322    #[error("failed to select note inclusion proofs")]
323    SelectNoteInclusionProofError(#[source] DatabaseError),
324    #[error("reference block {reference_block} is newer than the latest block {latest_block_num}")]
325    ReferenceBlockAfterTip {
326        reference_block: BlockNumber,
327        latest_block_num: BlockNumber,
328    },
329}
330
331#[derive(Error, Debug)]
332pub enum GetBlockInclusionProofsError {
333    #[error("failed to select block headers")]
334    SelectBlockHeaderError(#[source] DatabaseError),
335    #[error("reference block {reference_block} is newer than the latest block {latest_block_num}")]
336    ReferenceBlockAfterTip {
337        reference_block: BlockNumber,
338        latest_block_num: BlockNumber,
339    },
340    #[error("block {block_num} is newer than the reference block {reference_block}")]
341    BlockAfterReferenceBlock {
342        block_num: BlockNumber,
343        reference_block: BlockNumber,
344    },
345}
346
347// GET ACCOUNT ERRORS
348// ================================================================================================
349
350#[derive(Debug, Error)]
351pub enum GetAccountError {
352    #[error("database error")]
353    DatabaseError(#[from] DatabaseError),
354    #[error("malformed request")]
355    DeserializationFailed(#[from] ConversionError),
356    #[error("account {0} not found at block {1}")]
357    AccountNotFound(AccountId, BlockNumber),
358    #[error("account {0} is not public")]
359    AccountNotPublic(AccountId),
360    #[error("block {0} is unknown")]
361    UnknownBlock(BlockNumber),
362    #[error("block {0} has been pruned")]
363    BlockPruned(BlockNumber),
364    #[error("account {account_id} has no storage slot {slot_name} at block {block_num}")]
365    StorageSlotNotFound {
366        account_id: AccountId,
367        slot_name: StorageSlotName,
368        block_num: BlockNumber,
369    },
370    #[error(
371        "storage slot {slot_name} of account {account_id} is not a map slot at block {block_num}"
372    )]
373    StorageSlotNotMap {
374        account_id: AccountId,
375        slot_name: StorageSlotName,
376        block_num: BlockNumber,
377    },
378}
379
380// Do not scope for `cfg(test)` - if it the traitbounds don't suffice the issue will already appear
381// in the compilation of the library or binary, which would prevent getting to compiling the
382// following code.
383mod compile_tests {
384    use std::marker::PhantomData;
385
386    use super::{
387        AccountDeltaError,
388        AccountError,
389        DatabaseError,
390        DeserializationError,
391        NoteError,
392        RecvError,
393        StateInitializationError,
394    };
395
396    /// Ensure all enum variants remain compat with the desired trait bounds. Otherwise one gets
397    /// very unwieldy errors.
398    #[expect(dead_code)]
399    fn assumed_trait_bounds_upheld() {
400        fn ensure_is_error<E>(_phony: PhantomData<E>)
401        where
402            E: std::error::Error + Send + Sync + 'static,
403        {
404        }
405
406        ensure_is_error::<AccountError>(PhantomData);
407        ensure_is_error::<AccountDeltaError>(PhantomData);
408        ensure_is_error::<RecvError>(PhantomData);
409        ensure_is_error::<DeserializationError>(PhantomData);
410        ensure_is_error::<NoteError>(PhantomData);
411        ensure_is_error::<hex::FromHexError>(PhantomData);
412
413        ensure_is_error::<DatabaseError>(PhantomData);
414        ensure_is_error::<StateInitializationError>(PhantomData);
415    }
416}