miden_client/store/mod.rs
1//! Defines the storage interfaces used by the Miden client.
2//!
3//! It provides mechanisms for persisting and retrieving data, such as account states, transaction
4//! history, block headers, notes, and MMR nodes.
5//!
6//! ## Overview
7//!
8//! The storage module is central to the Miden client’s persistence layer. It defines the
9//! [`Store`] trait which abstracts over any concrete storage implementation. The trait exposes
10//! methods to (among others):
11//!
12//! - Retrieve and update transactions, notes, and accounts.
13//! - Store and query block headers along with MMR peaks and authentication nodes.
14//! - Manage note tags for synchronizing with the node.
15//!
16//! These are all used by the Miden client to provide transaction execution in the correct contexts.
17//!
18//! In addition to the main [`Store`] trait, the module provides types for filtering queries, such
19//! as [`TransactionFilter`], [`NoteFilter`], `StorageFilter` to narrow down the set of returned
20//! transactions, account data, or notes. For more advanced usage, see the documentation of
21//! individual methods in the [`Store`] trait.
22
23use alloc::boxed::Box;
24use alloc::collections::{BTreeMap, BTreeSet};
25use alloc::string::{String, ToString};
26use alloc::vec::Vec;
27use core::fmt::Debug;
28
29use miden_protocol::account::{
30 Account,
31 AccountCode,
32 AccountHeader,
33 AccountId,
34 AccountStorage,
35 StorageMapKey,
36 StorageMapWitness,
37 StorageSlot,
38 StorageSlotContent,
39 StorageSlotName,
40};
41use miden_protocol::address::Address;
42use miden_protocol::asset::{Asset, AssetId, AssetVault, AssetWitness};
43use miden_protocol::block::{BlockHeader, BlockNumber};
44use miden_protocol::crypto::merkle::mmr::{Forest, InOrderIndex, MmrPeaks, PartialMmr};
45use miden_protocol::errors::AccountError;
46use miden_protocol::note::{NoteDetailsCommitment, NoteId, NoteScript, NoteTag, Nullifier};
47use miden_protocol::transaction::TransactionId;
48use miden_protocol::{Felt, Word};
49use miden_tx::utils::serde::{Deserializable, Serializable};
50
51use crate::note_transport::{NOTE_TRANSPORT_CURSOR_STORE_SETTING, NoteTransportCursor};
52use crate::rpc::{RPC_LIMITS_STORE_SETTING, RpcLimits};
53use crate::sync::{NoteTagRecord, StateSyncUpdate};
54use crate::transaction::{TransactionRecord, TransactionStatusVariant, TransactionStoreUpdate};
55
56/// Contains [`ClientDataStore`] to automatically implement [`DataStore`] for anything that
57/// implements [`Store`]. This isn't public because it's an implementation detail to instantiate the
58/// executor.
59///
60/// The user is tasked with creating a [`Store`] which the client will wrap into a
61/// [`ClientDataStore`] at creation time.
62pub(crate) mod data_store;
63
64mod errors;
65pub use errors::*;
66
67mod smt_forest;
68pub use smt_forest::AccountSmtForest;
69
70mod account;
71pub use account::{
72 AccountRecord,
73 AccountRecordData,
74 AccountStatus,
75 AccountUpdates,
76 ClientAccountType,
77};
78
79pub use crate::sync::PublicAccountUpdate;
80mod note_record;
81pub use note_record::{
82 InputNoteRecord,
83 InputNoteState,
84 NoteExportType,
85 NoteRecordError,
86 OutputNoteRecord,
87 OutputNoteState,
88 input_note_states,
89};
90
91// SETTING MUTATION
92// ================================================================================================
93
94/// A single mutation against the `settings` KV store, applied as part of an atomic batch via
95/// [`Store::apply_settings_mutations`].
96#[derive(Debug, Clone)]
97pub enum SettingMutation {
98 /// Insert or overwrite `key` with `value`.
99 Set { key: String, value: Vec<u8> },
100 /// Delete `key`.
101 Remove { key: String },
102}
103
104// STORE TRAIT
105// ================================================================================================
106
107/// The [`Store`] trait exposes all methods that the client store needs in order to track the
108/// current state.
109///
110/// All update functions are implied to be atomic. That is, if multiple entities are meant to be
111/// updated as part of any single function and an error is returned during its execution, any
112/// changes that might have happened up to that point need to be rolled back and discarded.
113///
114/// Because the [`Store`]'s ownership is shared between the executor and the client, interior
115/// mutability is expected to be implemented, which is why all methods receive `&self` and
116/// not `&mut self`.
117#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
118#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
119pub trait Store: Send + Sync {
120 /// Returns an identifier for this store (e.g. `IndexedDB` database name, `SQLite` file path).
121 ///
122 /// This allows callers to retrieve store-specific identity information (such as the `IndexedDB`
123 /// database name) for standalone operations like `exportStore`/`importStore`, without making
124 /// import/export a responsibility of the client.
125 fn identifier(&self) -> &str;
126
127 /// Returns the current timestamp tracked by the store, measured in non-leap seconds since
128 /// Unix epoch. If the store implementation is incapable of tracking time, it should return
129 /// `None`.
130 ///
131 /// This method is used to add time metadata to notes' states. This information doesn't have a
132 /// functional impact on the client's operation, it's shown to the user for informational
133 /// purposes.
134 fn get_current_timestamp(&self) -> Option<u64>;
135
136 // TRANSACTIONS
137 // --------------------------------------------------------------------------------------------
138
139 /// Retrieves stored transactions, filtered by [`TransactionFilter`].
140 async fn get_transactions(
141 &self,
142 filter: TransactionFilter,
143 ) -> Result<Vec<TransactionRecord>, StoreError>;
144
145 /// Applies a transaction, atomically updating the current state based on the
146 /// [`TransactionStoreUpdate`].
147 ///
148 /// An update involves:
149 /// - Updating the stored account which is being modified by the transaction.
150 /// - Storing new input/output notes and payback note details as a result of the transaction
151 /// execution.
152 /// - Updating the input notes that are being processed by the transaction.
153 /// - Inserting the new tracked tags into the store.
154 /// - Inserting the transaction into the store to track.
155 async fn apply_transaction(&self, tx_update: TransactionStoreUpdate) -> Result<(), StoreError>;
156
157 /// Applies a batch of [`TransactionStoreUpdate`]s atomically. Semantically equivalent to
158 /// calling [`Store::apply_transaction`] for each update in order, but with an all-or-nothing
159 /// guarantee — on any error no update is visible.
160 ///
161 /// Used by `BatchBuilder::submit` to persist a batch's results. Backends that cannot provide
162 /// true atomicity must document that limitation explicitly in their impl — there is no blanket
163 /// default.
164 async fn apply_transaction_batch(
165 &self,
166 tx_updates: Vec<TransactionStoreUpdate>,
167 ) -> Result<(), StoreError>;
168
169 // NOTES
170 // --------------------------------------------------------------------------------------------
171
172 /// Retrieves the input notes from the store.
173 ///
174 /// When `filter` is [`NoteFilter::Consumed`], notes are sorted by their on-chain execution
175 /// order.
176 async fn get_input_notes(&self, filter: NoteFilter)
177 -> Result<Vec<InputNoteRecord>, StoreError>;
178
179 /// Retrieves the output notes from the store.
180 async fn get_output_notes(
181 &self,
182 filter: NoteFilter,
183 ) -> Result<Vec<OutputNoteRecord>, StoreError>;
184
185 /// Retrieves a single input note at the given offset from the filtered set for the given
186 /// consumer account. Optionally restricts to a block range via `block_start` and
187 /// `block_end`. Returns `None` when the offset is past the end of the matching notes.
188 ///
189 /// # Ordering
190 ///
191 /// Notes are sorted by their per-account on-chain execution order.
192 async fn get_input_note_by_offset(
193 &self,
194 filter: NoteFilter,
195 consumer: AccountId,
196 block_start: Option<BlockNumber>,
197 block_end: Option<BlockNumber>,
198 offset: u32,
199 ) -> Result<Option<InputNoteRecord>, StoreError>;
200
201 /// Returns the nullifiers of all unspent input notes.
202 ///
203 /// The default implementation of this method uses [`Store::get_input_notes`].
204 async fn get_unspent_input_note_nullifiers(&self) -> Result<Vec<Nullifier>, StoreError> {
205 Ok(self
206 .get_input_notes(NoteFilter::Unspent)
207 .await?
208 .iter()
209 .filter_map(InputNoteRecord::nullifier)
210 .collect())
211 }
212
213 /// Inserts the provided input notes into the database. If a note with the same ID already
214 /// exists, it will be replaced.
215 async fn upsert_input_notes(&self, notes: &[InputNoteRecord]) -> Result<(), StoreError>;
216
217 /// Returns the note script associated with the given root.
218 async fn get_note_script(&self, script_root: Word) -> Result<NoteScript, StoreError>;
219
220 /// Inserts the provided note scripts into the database. If a script with the same root already
221 /// exists, it will be replaced.
222 async fn upsert_note_scripts(&self, note_scripts: &[NoteScript]) -> Result<(), StoreError>;
223
224 // CHAIN DATA
225 // --------------------------------------------------------------------------------------------
226
227 /// Retrieves a vector of [`BlockHeader`]s filtered by the provided block numbers.
228 ///
229 /// The returned vector may not contain some or all of the requested block headers. It's up to
230 /// the callee to check whether all requested block headers were found.
231 ///
232 /// For each block header an additional boolean value is returned representing whether the block
233 /// contains notes relevant to the client.
234 async fn get_block_headers(
235 &self,
236 block_numbers: &BTreeSet<BlockNumber>,
237 ) -> Result<Vec<(BlockHeader, BlockRelevance)>, StoreError>;
238
239 /// Retrieves a [`BlockHeader`] corresponding to the provided block number and a boolean value
240 /// that represents whether the block contains notes relevant to the client. Returns `None` if
241 /// the block is not found.
242 ///
243 /// The default implementation of this method uses [`Store::get_block_headers`].
244 async fn get_block_header_by_num(
245 &self,
246 block_number: BlockNumber,
247 ) -> Result<Option<(BlockHeader, BlockRelevance)>, StoreError> {
248 self.get_block_headers(&[block_number].into_iter().collect())
249 .await
250 .map(|mut block_headers_list| block_headers_list.pop())
251 }
252
253 /// Retrieves a list of [`BlockHeader`] that include relevant notes to the client.
254 async fn get_tracked_block_headers(&self) -> Result<Vec<BlockHeader>, StoreError>;
255
256 /// Retrieves the block numbers of block headers that include relevant notes to the client.
257 ///
258 /// This is a lightweight alternative to [`Store::get_tracked_block_headers`] that avoids
259 /// deserializing full block headers when only the block numbers are needed.
260 async fn get_tracked_block_header_numbers(&self) -> Result<BTreeSet<usize>, StoreError>;
261
262 /// Retrieves all MMR authentication nodes based on [`PartialBlockchainFilter`].
263 async fn get_partial_blockchain_nodes(
264 &self,
265 filter: PartialBlockchainFilter,
266 ) -> Result<BTreeMap<InOrderIndex, Word>, StoreError>;
267
268 /// Returns the chain MMR peaks at the current sync height (peaks at `forest = block_num`,
269 /// i.e. excluding `block_num` itself as a leaf).
270 ///
271 /// The peaks' `forest().num_leaves()` equals the current sync height by construction,
272 /// so callers can derive the synced block number from the returned peaks without a
273 /// second query.
274 ///
275 /// Before the first sync, returns an empty [`MmrPeaks`].
276 async fn get_current_blockchain_peaks(&self) -> Result<MmrPeaks, StoreError>;
277
278 /// Inserts a block header together with its MMR authentication nodes in a single
279 /// transaction, so the header and the nodes that rebuild its `PartialMmr` are committed
280 /// together.
281 ///
282 /// The header is inserted-if-not-exists with a one-way `has_client_notes` upgrade: on
283 /// conflict the stored `header` is preserved and the flag only moves from `false` to
284 /// `true`, never back. The MMR nodes are likewise inserted-if-not-exists: an
285 /// `InOrderIndex` already present is left untouched (auth paths of tracked blocks share
286 /// internal nodes, so re-inserting an existing index must be a no-op, not an error).
287 async fn insert_block_header(
288 &self,
289 block_header: &BlockHeader,
290 nodes: &[(InOrderIndex, Word)],
291 has_client_notes: bool,
292 ) -> Result<(), StoreError>;
293
294 /// Prunes irrelevant block data from the store.
295 ///
296 /// This performs three operations atomically:
297 /// 1. Deletes MMR authentication nodes at the given `node_indices`.
298 /// 2. Sets `has_client_notes = false` for `blocks_to_untrack` (blocks whose notes have all been
299 /// consumed).
300 /// 3. Deletes block headers with `has_client_notes = false` that are not the genesis or
301 /// sync-height block.
302 async fn untrack_and_prune_irrelevant_blocks(
303 &self,
304 blocks_to_untrack: &[BlockNumber],
305 node_indices_to_remove: &[InOrderIndex],
306 ) -> Result<(), StoreError>;
307
308 /// Prunes historical account states for the specified account up to the given nonce.
309 ///
310 /// Deletes all historical entries with `replaced_at_nonce <= up_to_nonce` from the
311 /// historical tables (headers, storage, storage map entries, and assets).
312 ///
313 /// Also removes orphaned `account_code` entries that are no longer referenced by any
314 /// account header.
315 ///
316 /// Returns the total number of rows deleted, including historical entries and orphaned
317 /// account code.
318 async fn prune_account_history(
319 &self,
320 account_id: AccountId,
321 up_to_nonce: Felt,
322 ) -> Result<usize, StoreError>;
323
324 // ACCOUNT
325 // --------------------------------------------------------------------------------------------
326
327 /// Returns the account IDs of all accounts stored in the database.
328 async fn get_account_ids(&self) -> Result<Vec<AccountId>, StoreError>;
329
330 /// Returns a list of [`AccountHeader`] of all accounts stored in the database along with their
331 /// statuses.
332 ///
333 /// Said accounts' state is the state after the last performed sync.
334 async fn get_account_headers(&self) -> Result<Vec<(AccountHeader, AccountStatus)>, StoreError>;
335
336 /// Retrieves an [`AccountHeader`] object for the specified [`AccountId`] along with its status.
337 /// Returns `None` if the account is not found.
338 ///
339 /// Said account's state is the state according to the last sync performed.
340 async fn get_account_header(
341 &self,
342 account_id: AccountId,
343 ) -> Result<Option<(AccountHeader, AccountStatus)>, StoreError>;
344
345 /// Returns an [`AccountHeader`] corresponding to the stored account state that matches the
346 /// given commitment. If no account state matches the provided commitment, `None` is returned.
347 async fn get_account_header_by_commitment(
348 &self,
349 account_commitment: Word,
350 ) -> Result<Option<AccountHeader>, StoreError>;
351
352 /// Retrieves a full [`AccountRecord`] object, this contains the account's latest state along
353 /// with its status. Returns `None` if the account is not found.
354 async fn get_account(&self, account_id: AccountId)
355 -> Result<Option<AccountRecord>, StoreError>;
356
357 /// Retrieves the [`AccountCode`] for the specified account.
358 /// Returns `None` if the account is not found.
359 async fn get_account_code(
360 &self,
361 account_id: AccountId,
362 ) -> Result<Option<AccountCode>, StoreError>;
363
364 /// Inserts an [`Account`] to the store, alongside its initial [`Address`].
365 ///
366 /// Tag registration is the caller's responsibility — see [`Self::add_note_tag`].
367 ///
368 /// # Errors
369 ///
370 /// - If the account is new and does not contain a seed
371 async fn insert_account(
372 &self,
373 account: &Account,
374 initial_address: Address,
375 client_account_type: ClientAccountType,
376 ) -> Result<(), StoreError>;
377
378 /// Upserts the account code for a foreign account. This value will be used as a cache of known
379 /// script roots and added to the `GetForeignAccountCode` request.
380 async fn upsert_foreign_account_code(
381 &self,
382 account_id: AccountId,
383 code: AccountCode,
384 ) -> Result<(), StoreError>;
385
386 /// Retrieves the cached account code for various foreign accounts.
387 async fn get_foreign_account_code(
388 &self,
389 account_ids: Vec<AccountId>,
390 ) -> Result<BTreeMap<AccountId, AccountCode>, StoreError>;
391
392 /// Retrieves all [`Address`] objects that correspond to the provided account ID.
393 async fn get_addresses_by_account_id(
394 &self,
395 account_id: AccountId,
396 ) -> Result<Vec<Address>, StoreError>;
397
398 /// Updates an existing [`Account`] with a new state.
399 ///
400 /// # Errors
401 ///
402 /// Returns a `StoreError::AccountDataNotFound` if there is no account for the provided ID.
403 async fn update_account(&self, new_account_state: &Account) -> Result<(), StoreError>;
404
405 /// Adds an [`Address`] to an [`Account`].
406 ///
407 /// Tag registration is the caller's responsibility — see [`Self::add_note_tag`].
408 async fn insert_address(
409 &self,
410 address: Address,
411 account_id: AccountId,
412 ) -> Result<(), StoreError>;
413
414 /// Removes an [`Address`].
415 ///
416 /// Tag removal is the caller's responsibility — see [`Self::remove_note_tag`].
417 async fn remove_address(&self, address: Address) -> Result<(), StoreError>;
418
419 // SETTINGS
420 // --------------------------------------------------------------------------------------------
421
422 /// Adds a value to the `settings` table.
423 async fn set_setting(&self, key: String, value: Vec<u8>) -> Result<(), StoreError>;
424
425 /// Retrieves a value from the `settings` table.
426 async fn get_setting(&self, key: String) -> Result<Option<Vec<u8>>, StoreError>;
427
428 /// Deletes a value from the `settings` table.
429 async fn remove_setting(&self, key: String) -> Result<(), StoreError>;
430
431 /// Returns all the keys from the `settings` table.
432 async fn list_setting_keys(&self) -> Result<Vec<String>, StoreError>;
433
434 /// Applies a batch of [`SettingMutation`]s. Use this when several `settings` entries must stay
435 /// mutually consistent (e.g. a record and its secondary index).
436 async fn apply_settings_mutations(
437 &self,
438 mutations: Vec<SettingMutation>,
439 ) -> Result<(), StoreError>;
440
441 // SYNC
442 // --------------------------------------------------------------------------------------------
443
444 /// Returns the note tag records that the client is interested in.
445 async fn get_note_tags(&self) -> Result<Vec<NoteTagRecord>, StoreError>;
446
447 /// Returns the unique note tags (without source) that the client is interested in.
448 async fn get_unique_note_tags(&self) -> Result<BTreeSet<NoteTag>, StoreError> {
449 Ok(self.get_note_tags().await?.into_iter().map(|r| r.tag).collect())
450 }
451
452 /// Adds a note tag to the list of tags that the client is interested in.
453 ///
454 /// If the tag was already being tracked, returns false since no new tags were actually added.
455 /// Otherwise true.
456 async fn add_note_tag(&self, tag: NoteTagRecord) -> Result<bool, StoreError>;
457
458 /// Removes a note tag from the list of tags that the client is interested in.
459 ///
460 /// If the tag wasn't present in the store returns false since no tag was actually removed.
461 /// Otherwise returns true.
462 async fn remove_note_tag(&self, tag: NoteTagRecord) -> Result<usize, StoreError>;
463
464 /// Returns the block number of the last state sync block.
465 async fn get_sync_height(&self) -> Result<BlockNumber, StoreError>;
466
467 /// Applies the state sync update to the store. An update involves:
468 ///
469 /// - Inserting the new block header to the store alongside new MMR peaks information.
470 /// - Updating the corresponding tracked input/output notes. Consumed notes carry consumption
471 /// metadata — `consumed_block_height`, `consumed_tx_order`, and `consumer_account_id` — in
472 /// their note state. Implementations must persist these fields so that ordered queries (see
473 /// [`Store::get_input_note_by_offset`]) work correctly.
474 /// - Removing note tags that are no longer relevant.
475 /// - Updating transactions in the store, marking as `committed` or `discarded`.
476 /// - In turn, validating private account's state transitions. If a private account's
477 /// commitment locally does not match the `StateSyncUpdate` information, the account may be
478 /// locked.
479 /// - Storing new MMR authentication nodes.
480 /// - Updating the tracked public accounts.
481 async fn apply_state_sync(&self, state_sync_update: StateSyncUpdate) -> Result<(), StoreError>;
482
483 // TRANSPORT
484 // --------------------------------------------------------------------------------------------
485
486 /// Gets the note transport cursor.
487 ///
488 /// This is used to reduce the number of fetched notes from the note transport network.
489 /// If no cursor exists, initializes it to 0.
490 async fn get_note_transport_cursor(&self) -> Result<NoteTransportCursor, StoreError> {
491 let cursor_bytes = if let Some(bytes) =
492 self.get_setting(NOTE_TRANSPORT_CURSOR_STORE_SETTING.into()).await?
493 {
494 bytes
495 } else {
496 // Lazy initialization: create cursor if not present
497 let initial = 0u64.to_be_bytes().to_vec();
498 self.set_setting(NOTE_TRANSPORT_CURSOR_STORE_SETTING.into(), initial.clone())
499 .await?;
500 initial
501 };
502 let array: [u8; 8] = cursor_bytes
503 .as_slice()
504 .try_into()
505 .map_err(|e: core::array::TryFromSliceError| StoreError::ParsingError(e.to_string()))?;
506 let cursor = u64::from_be_bytes(array);
507 Ok(cursor.into())
508 }
509
510 /// Updates the note transport cursor.
511 ///
512 /// This is used to track the last cursor position when fetching notes from the note transport
513 /// network.
514 async fn update_note_transport_cursor(
515 &self,
516 cursor: NoteTransportCursor,
517 ) -> Result<(), StoreError> {
518 let cursor_bytes = cursor.value().to_be_bytes().to_vec();
519 self.set_setting(NOTE_TRANSPORT_CURSOR_STORE_SETTING.into(), cursor_bytes)
520 .await?;
521 Ok(())
522 }
523
524 // RPC LIMITS
525 // --------------------------------------------------------------------------------------------
526
527 /// Gets persisted RPC limits. Returns `None` if not stored.
528 async fn get_rpc_limits(&self) -> Result<Option<RpcLimits>, StoreError> {
529 let Some(bytes) = self.get_setting(RPC_LIMITS_STORE_SETTING.into()).await? else {
530 return Ok(None);
531 };
532 let limits = RpcLimits::read_from_bytes(&bytes)?;
533 Ok(Some(limits))
534 }
535
536 /// Persists RPC limits to the store.
537 async fn set_rpc_limits(&self, limits: RpcLimits) -> Result<(), StoreError> {
538 self.set_setting(RPC_LIMITS_STORE_SETTING.into(), limits.to_bytes()).await
539 }
540
541 // PARTIAL MMR
542 // --------------------------------------------------------------------------------------------
543
544 /// Builds the current view of the chain's [`PartialMmr`]. Because we want to add all new
545 /// authentication nodes that could come from applying the MMR updates, we need to track all
546 /// known leaves thus far.
547 ///
548 /// The default implementation is based on [`Store::get_partial_blockchain_nodes`],
549 /// [`Store::get_current_blockchain_peaks`] and [`Store::get_block_header_by_num`]
550 async fn get_current_partial_mmr(&self) -> Result<PartialMmr, StoreError> {
551 let current_peaks = self.get_current_blockchain_peaks().await?;
552 let current_block_num = u32::try_from(current_peaks.num_leaves())
553 .map_err(|err| StoreError::ParsingError(err.to_string()))?
554 .into();
555
556 let (current_block, has_client_notes) = self
557 .get_block_header_by_num(current_block_num)
558 .await?
559 .ok_or(StoreError::BlockHeaderNotFound(current_block_num))?;
560
561 let mut current_partial_mmr = PartialMmr::from_peaks(current_peaks);
562 let has_client_notes = has_client_notes.into();
563 current_partial_mmr
564 .add(current_block.commitment(), has_client_notes)
565 .map_err(StoreError::MmrError)?;
566
567 // Build tracked_leaves from blocks that have client notes.
568 let mut tracked_leaves = self.get_tracked_block_header_numbers().await?;
569
570 // Also track the latest leaf if it is relevant (it has client notes) _and_ the forest
571 // actually has a single leaf tree bit.
572 if has_client_notes && current_partial_mmr.forest().has_single_leaf_tree() {
573 let latest_leaf = current_partial_mmr.forest().num_leaves().saturating_sub(1);
574 tracked_leaves.insert(latest_leaf);
575 }
576
577 let tracked_nodes = self
578 .get_partial_blockchain_nodes(PartialBlockchainFilter::Forest(
579 current_partial_mmr.forest(),
580 ))
581 .await?;
582
583 let current_partial_mmr =
584 PartialMmr::from_parts(current_partial_mmr.peaks(), tracked_nodes, tracked_leaves)?;
585
586 Ok(current_partial_mmr)
587 }
588
589 // ACCOUNT VAULT AND STORE
590 // --------------------------------------------------------------------------------------------
591
592 /// Retrieves the asset vault for a specific account.
593 async fn get_account_vault(&self, account_id: AccountId) -> Result<AssetVault, StoreError>;
594
595 /// Retrieves a specific asset (by vault id) from the account's vault along with its Merkle
596 /// witness.
597 ///
598 /// The default implementation of this method uses [`Store::get_account_vault`].
599 async fn get_account_asset(
600 &self,
601 account_id: AccountId,
602 vault_id: AssetId,
603 ) -> Result<Option<(Asset, AssetWitness)>, StoreError> {
604 let vault = self.get_account_vault(account_id).await?;
605 let Some(asset) = vault.assets().find(|a| a.id() == vault_id) else {
606 return Ok(None);
607 };
608
609 let witness = vault.open(vault_id);
610
611 Ok(Some((asset, witness)))
612 }
613
614 /// Retrieves the storage for a specific account.
615 ///
616 /// Can take an optional map root to retrieve only part of the storage,
617 /// If it does, it will either return an account storage with a single
618 /// slot (the one requested), or an error if not found.
619 async fn get_account_storage(
620 &self,
621 account_id: AccountId,
622 filter: AccountStorageFilter,
623 ) -> Result<AccountStorage, StoreError>;
624
625 /// Retrieves a storage slot value by name.
626 ///
627 /// For `Value` slots, returns the stored word.
628 /// For `Map` slots, returns the map root.
629 ///
630 /// The default implementation of this method uses [`Store::get_account_storage`].
631 async fn get_account_storage_item(
632 &self,
633 account_id: AccountId,
634 slot_name: StorageSlotName,
635 ) -> Result<Word, StoreError> {
636 let storage = self
637 .get_account_storage(account_id, AccountStorageFilter::SlotName(slot_name.clone()))
638 .await?;
639 storage
640 .get(&slot_name)
641 .map(StorageSlot::value)
642 .ok_or(StoreError::AccountError(AccountError::StorageSlotNameNotFound { slot_name }))
643 }
644
645 /// Retrieves a specific item from the account's storage map along with its Merkle proof.
646 ///
647 /// The default implementation of this method uses [`Store::get_account_storage`].
648 async fn get_account_map_item(
649 &self,
650 account_id: AccountId,
651 slot_name: StorageSlotName,
652 key: StorageMapKey,
653 ) -> Result<(Word, StorageMapWitness), StoreError> {
654 let storage = self
655 .get_account_storage(account_id, AccountStorageFilter::SlotName(slot_name.clone()))
656 .await?;
657 match storage.get(&slot_name).map(StorageSlot::content) {
658 Some(StorageSlotContent::Map(map)) => {
659 let value = map.get(&key);
660 let witness = map.open(&key);
661
662 Ok((value, witness))
663 },
664 Some(_) => Err(StoreError::AccountError(AccountError::StorageSlotNotMap(slot_name))),
665 None => {
666 Err(StoreError::AccountError(AccountError::StorageSlotNameNotFound { slot_name }))
667 },
668 }
669 }
670
671 // PARTIAL ACCOUNTS
672 // --------------------------------------------------------------------------------------------
673
674 /// Retrieves an [`AccountRecord`] object, this contains the account's latest partial
675 /// state along with its status. Returns `None` if the partial account is not found.
676 async fn get_minimal_partial_account(
677 &self,
678 account_id: AccountId,
679 ) -> Result<Option<AccountRecord>, StoreError>;
680}
681
682// PARTIAL BLOCKCHAIN NODE FILTER
683// ================================================================================================
684
685/// Filters for searching specific MMR nodes.
686// TODO: Should there be filters for specific blocks instead of nodes?
687pub enum PartialBlockchainFilter {
688 /// Return all nodes.
689 All,
690 /// Filter by the specified in-order indices.
691 List(Vec<InOrderIndex>),
692 /// Return nodes with in-order indices within the specified forest.
693 Forest(Forest),
694}
695
696// TRANSACTION FILTERS
697// ================================================================================================
698
699/// Filters for narrowing the set of transactions returned by the client's store.
700#[derive(Debug, Clone)]
701pub enum TransactionFilter {
702 /// Return all transactions.
703 All,
704 /// Filter by transactions that haven't yet been committed to the blockchain as per the last
705 /// sync.
706 Uncommitted,
707 /// Return a list of the transaction that matches the provided [`TransactionId`]s.
708 Ids(Vec<TransactionId>),
709 /// Return a list of the expired transactions that were executed before the provided
710 /// [`BlockNumber`]. Transactions created after the provided block number are not
711 /// considered.
712 ///
713 /// A transaction is considered expired if is uncommitted and the transaction's block number
714 /// is less than the provided block number.
715 ExpiredBefore(BlockNumber),
716}
717
718// TRANSACTIONS FILTER HELPERS
719// ================================================================================================
720
721impl TransactionFilter {
722 /// Returns a [String] containing the query for this Filter.
723 pub fn to_query(&self) -> String {
724 const QUERY: &str = "SELECT tx.id, script.script, tx.details, tx.status \
725 FROM transactions AS tx LEFT JOIN transaction_scripts AS script ON tx.script_root = script.script_root";
726 match self {
727 TransactionFilter::All => QUERY.to_string(),
728 TransactionFilter::Uncommitted => format!(
729 "{QUERY} WHERE tx.status_variant = {}",
730 TransactionStatusVariant::Pending as u8,
731 ),
732 TransactionFilter::Ids(_) => {
733 // Use SQLite's array parameter binding
734 format!("{QUERY} WHERE tx.id IN rarray(?)")
735 },
736 TransactionFilter::ExpiredBefore(block_num) => {
737 format!(
738 "{QUERY} WHERE tx.block_num < {} AND tx.status_variant != {} AND tx.status_variant != {}",
739 block_num.as_u32(),
740 TransactionStatusVariant::Discarded as u8,
741 TransactionStatusVariant::Committed as u8
742 )
743 },
744 }
745 }
746}
747
748// NOTE FILTER
749// ================================================================================================
750
751/// Filters for narrowing the set of notes returned by the client's store.
752#[derive(Debug, Clone)]
753pub enum NoteFilter {
754 /// Return a list of all notes ([`InputNoteRecord`] or [`OutputNoteRecord`]).
755 All,
756 /// Return a list of committed notes ([`InputNoteRecord`] or [`OutputNoteRecord`]). These
757 /// represent notes that the blockchain has included in a block.
758 Committed,
759 /// Filter by consumed notes ([`InputNoteRecord`] or [`OutputNoteRecord`]). notes that have
760 /// been used as inputs in transactions.
761 Consumed,
762 /// Return a list of expected notes ([`InputNoteRecord`] or [`OutputNoteRecord`]). These
763 /// represent notes for which the store doesn't have anchor data.
764 Expected,
765 /// Return a list containing any notes that match with the provided [`NoteId`] vector.
766 List(Vec<NoteId>),
767 /// Return a list containing any notes whose details commitment matches one of the provided
768 /// [`NoteDetailsCommitment`] vector. Unlike [`NoteFilter::List`], this matches the
769 /// metadata-independent details commitment, so it also resolves metadata-less notes (which
770 /// have a NULL `note_id`).
771 DetailsCommitments(Vec<NoteDetailsCommitment>),
772 /// Return a list containing any notes that match the provided [`Nullifier`] vector.
773 Nullifiers(Vec<Nullifier>),
774 /// Return a list of notes that are currently being processed. This filter doesn't apply to
775 /// output notes.
776 Processing,
777 /// Return a list containing the note that matches with the provided [`NoteId`]. The query will
778 /// return an error if the note isn't found.
779 Unique(NoteId),
780 /// Return a list containing notes that haven't been nullified yet, this includes expected,
781 /// committed, processing and unverified notes.
782 Unspent,
783 /// Return a list containing notes with unverified inclusion proofs. This filter doesn't apply
784 /// to output notes.
785 Unverified,
786}
787
788// BLOCK RELEVANCE
789// ================================================================================================
790
791/// Expresses metadata about the block header.
792#[derive(Debug, Clone)]
793pub enum BlockRelevance {
794 /// The block header includes notes that the client may consume.
795 HasNotes,
796 /// The block header does not contain notes relevant to the client.
797 Irrelevant,
798}
799
800impl From<BlockRelevance> for bool {
801 fn from(val: BlockRelevance) -> Self {
802 match val {
803 BlockRelevance::HasNotes => true,
804 BlockRelevance::Irrelevant => false,
805 }
806 }
807}
808
809impl From<bool> for BlockRelevance {
810 fn from(has_notes: bool) -> Self {
811 if has_notes {
812 BlockRelevance::HasNotes
813 } else {
814 BlockRelevance::Irrelevant
815 }
816 }
817}
818
819// STORAGE FILTER
820// ================================================================================================
821
822/// Filters for narrowing the storage slots returned by the client's store.
823#[derive(Debug, Clone)]
824pub enum AccountStorageFilter {
825 /// Return an [`AccountStorage`] with all available slots.
826 All,
827 /// Return an [`AccountStorage`] with a single slot that matches the provided [`Word`] map root.
828 Root(Word),
829 /// Return an [`AccountStorage`] with a single slot that matches the provided slot name.
830 SlotName(StorageSlotName),
831 /// Return an [`AccountStorage`] containing only the slots whose names are in the provided
832 /// list. Useful to avoid loading the full storage when only a known subset of slots is needed
833 /// (e.g. when applying a delta to a large account).
834 SlotNames(Vec<StorageSlotName>),
835}