1use std::collections::{BTreeMap, BTreeSet, HashSet};
2use std::mem::size_of;
3use std::num::NonZeroUsize;
4use std::path::{Path, PathBuf};
5use std::pin::pin;
6use std::sync::Arc;
7
8use anyhow::Context;
9use futures::{Stream, TryStreamExt};
10use miden_node_db::sqlite::{DbReader, DbWriter, WriteTx};
11use miden_node_proto::domain::account::AccountInfo;
12use miden_node_tracing::{info, miden_instrument, warn};
13use miden_node_utils::limiter::{
14 MAX_RESPONSE_PAYLOAD_BYTES,
15 QueryParamLimiter,
16 QueryParamNoteCommitmentLimit,
17};
18use miden_protocol::Word;
19use miden_protocol::account::{AccountHeader, AccountId, AccountStorageHeader, StorageMapKey};
20use miden_protocol::asset::{Asset, AssetId};
21use miden_protocol::block::{
22 BlockAccountUpdate,
23 BlockHeader,
24 BlockNoteIndex,
25 BlockNumber,
26 BlockSignatures,
27 SignedBlock,
28};
29use miden_protocol::crypto::merkle::SparseMerklePath;
30use miden_protocol::note::{
31 NoteAttachments,
32 NoteDetails,
33 NoteId,
34 NoteInclusionProof,
35 NoteMetadata,
36 NoteScript,
37 Nullifier,
38};
39use miden_protocol::protocol_config::ProtocolConfig;
40use miden_protocol::transaction::TransactionHeader;
41
42use crate::db::migrations::{migrate_database, verify_latest_schema};
43use crate::db::pagination::{Page, Paginated};
44pub use crate::db::queries::{
45 HISTORICAL_BLOCK_RETENTION,
46 PrecomputedPublicAccountState,
47 PrecomputedPublicAccountStates,
48};
49use crate::errors::DatabaseError;
50use crate::genesis::GenesisBlock;
51use crate::state::ScopedBlockNum;
52use crate::{COMPONENT, LOG_TARGET};
53
54const STORAGE_MAP_VALUE_PER_ROW_BYTES: usize =
55 2 * size_of::<Word>() + size_of::<u32>() + size_of::<u8>();
56
57pub(crate) fn default_storage_map_entries_limit() -> usize {
58 MAX_RESPONSE_PAYLOAD_BYTES / STORAGE_MAP_VALUE_PER_ROW_BYTES
59}
60
61mod migrations;
62#[cfg(test)]
63pub(crate) use migrations::bootstrap_database;
64
65#[cfg(test)]
66mod tests;
67
68#[cfg(test)]
69mod test_db;
70#[cfg(test)]
71pub(crate) use test_db::TestDb;
72
73pub(crate) mod queries;
75
76pub(crate) mod pagination;
77
78mod utils;
79
80pub type Result<T, E = DatabaseError> = std::result::Result<T, E>;
81
82#[derive(Copy, Clone, Debug, PartialEq, Eq)]
84pub struct DatabaseOptions {
85 pub connection_pool_size: NonZeroUsize,
87}
88
89impl Default for DatabaseOptions {
90 fn default() -> Self {
91 Self {
92 connection_pool_size: miden_node_db::default_connection_pool_size(),
93 }
94 }
95}
96
97pub struct Db {
102 writer: DbWriter,
103 reader: DbReader,
104}
105
106fn insert_genesis(tx: &WriteTx<'_>, genesis: GenesisBlock) -> Result<()> {
108 let (genesis_block, protocol_config) = genesis.into_parts();
109 let new_account_ids = genesis_block
111 .body()
112 .updated_accounts()
113 .iter()
114 .map(BlockAccountUpdate::account_id)
115 .collect();
116 queries::insert_protocol_config(tx, &protocol_config, BlockNumber::GENESIS)?;
117 queries::apply_block(
118 tx,
119 &genesis_block,
120 &[],
121 &PrecomputedPublicAccountStates::new(),
122 &new_account_ids,
123 )?;
124 Ok(())
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[repr(transparent)]
133pub struct BlockHeaderCommitment(pub(crate) Word);
134
135impl BlockHeaderCommitment {
136 pub fn new(header: &BlockHeader) -> Self {
137 Self(header.commitment())
138 }
139
140 pub fn word(self) -> Word {
141 self.0
142 }
143}
144
145#[derive(Debug, Clone)]
149pub struct AccountVaultValue {
150 pub block_num: BlockNumber,
151 pub vault_key: AssetId,
152 pub asset: Option<Asset>,
154}
155
156#[derive(Debug, PartialEq)]
157pub struct NullifierInfo {
158 pub nullifier: Nullifier,
159 pub block_num: BlockNumber,
160}
161
162impl PartialEq<(Nullifier, BlockNumber)> for NullifierInfo {
163 fn eq(&self, (nullifier, block_num): &(Nullifier, BlockNumber)) -> bool {
164 &self.nullifier == nullifier && &self.block_num == block_num
165 }
166}
167
168#[derive(Debug, PartialEq)]
169pub struct TransactionRecord {
170 pub block_num: BlockNumber,
171 pub header: TransactionHeader,
172 pub output_note_proofs: Vec<NoteSyncRecord>,
175 pub consumed_note_refs: Vec<(Nullifier, NoteId)>,
178}
179
180#[derive(Debug, Clone, PartialEq)]
181pub struct NoteRecord {
182 pub block_num: BlockNumber,
183 pub note_index: BlockNoteIndex,
184 pub note_id: Word,
185 pub metadata: NoteMetadata,
186 pub details: Option<NoteDetails>,
187 pub attachments: NoteAttachments,
188 pub inclusion_path: SparseMerklePath,
189}
190
191#[derive(Debug, PartialEq)]
192pub struct NoteSyncUpdate {
193 pub notes: Vec<NoteSyncRecord>,
194 pub block_header: BlockHeader,
195}
196
197#[derive(Debug, Clone, PartialEq)]
198pub struct NoteSyncRecord {
199 pub block_num: BlockNumber,
200 pub note_index: BlockNoteIndex,
201 pub note_id: NoteId,
202 pub metadata: NoteMetadata,
203 pub attachments: NoteAttachments,
204 pub inclusion_path: SparseMerklePath,
205}
206
207impl From<NoteRecord> for NoteSyncRecord {
208 fn from(note: NoteRecord) -> Self {
209 Self {
210 block_num: note.block_num,
211 note_index: note.note_index,
212 note_id: NoteId::from_raw(note.note_id),
213 metadata: note.metadata,
214 attachments: note.attachments,
215 inclusion_path: note.inclusion_path,
216 }
217 }
218}
219
220impl Db {
221 #[miden_instrument(
223 target = COMPONENT,
224 name = "store.database.bootstrap",
225 fields(path = database_filepath),
226 err,
227 )]
228 pub async fn bootstrap(
229 database_filepath: PathBuf,
230 genesis: GenesisBlock,
231 ) -> anyhow::Result<()> {
232 migrations::bootstrap_database(&database_filepath)
233 .context("failed to bootstrap database schema")?;
234
235 let (writer, _reader) = miden_node_db::sqlite::open(&database_filepath)
236 .context("failed to open a database connection")?;
237
238 writer
240 .write("insert genesis block", move |tx| insert_genesis(tx, genesis))
241 .await
242 .context("failed to insert genesis block")?;
243 Ok(())
244 }
245
246 #[miden_instrument(
248 target = COMPONENT,
249 )]
250 pub async fn load(database_filepath: PathBuf) -> Result<Self, DatabaseError> {
251 Self::load_with_pool_size(database_filepath, miden_node_db::default_connection_pool_size())
252 .await
253 }
254
255 #[miden_instrument(
258 target = COMPONENT,
259 )]
260 pub async fn load_with_pool_size(
261 database_filepath: PathBuf,
262 connection_pool_size: NonZeroUsize,
263 ) -> Result<Self, DatabaseError> {
264 verify_latest_schema(&database_filepath)?;
265
266 let (writer, reader) =
267 miden_node_db::sqlite::open_with_pool_size(&database_filepath, connection_pool_size)?;
268 info!(
269 target: LOG_TARGET,
270 "Connected to the database",
271 path = database_filepath,
272 db.sqlite.connection_pool_size = connection_pool_size.get()
273 );
274
275 Ok(Self { writer, reader })
276 }
277
278 #[cfg(test)]
280 pub(crate) fn writer(&self) -> &DbWriter {
281 &self.writer
282 }
283
284 #[miden_instrument(
286 level = "debug",
287 target = COMPONENT,
288 err(level = "debug"),
289 )]
290 pub async fn select_protocol_config_by_commitment(
291 &self,
292 commitment: Word,
293 ) -> Result<Option<ProtocolConfig>> {
294 self.reader
295 .read("protocol config by commitment", move |tx| {
296 queries::select_protocol_config_by_commitment(tx, commitment)
297 })
298 .await
299 }
300
301 pub async fn select_protocol_config_commitment_at(
303 &self,
304 block_number: ScopedBlockNum,
305 ) -> Result<Option<Word>> {
306 self.reader
307 .read("protocol config commitment at block", move |tx| {
308 queries::select_protocol_config_commitment_at(tx, *block_number)
309 })
310 .await
311 }
312
313 #[miden_instrument(
315 target = COMPONENT,
316 )]
317 pub fn migrate(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
318 migrate_database(database_filepath.as_ref())?;
319 Ok(())
320 }
321
322 #[miden_instrument(
324 level = "debug",
325 target = COMPONENT,
326 err(level = "debug"),
327 )]
328 pub(crate) async fn page<Q: Paginated>(
329 &self,
330 query: Q,
331 next: Q::Cursor,
332 ) -> Result<Page<Q::Item, Q::Cursor>> {
333 self.reader
334 .read(std::any::type_name::<Q>(), move |tx| query.page(tx, &next))
335 .await
336 }
337
338 pub(crate) fn pages<Q: Paginated>(
345 &self,
346 query: Q,
347 start: Q::Cursor,
348 ) -> impl Stream<Item = Result<Vec<Q::Item>>> + Send + use<Q> {
349 let reader = self.reader.clone();
350 let query = Arc::new(query);
351 futures::stream::try_unfold(Some(start), move |state: Option<Q::Cursor>| {
353 let reader = reader.clone();
354 let query = Arc::clone(&query);
355 async move {
356 let Some(next) = state else {
357 return Ok(None);
358 };
359 let page = reader
360 .read(std::any::type_name::<Q>(), move |tx| query.page(tx, &next))
361 .await?;
362 if page.items.is_empty() {
363 return Ok(None);
364 }
365 Ok::<_, DatabaseError>(Some((page.items, page.next)))
366 }
367 })
368 }
369
370 #[miden_instrument(
374 level = "debug",
375 target = COMPONENT,
376 err(level = "debug"),
377 )]
378 pub async fn select_block_header_by_block_num(
379 &self,
380 maybe_block_number: Option<ScopedBlockNum>,
381 ) -> Result<Option<BlockHeader>> {
382 self.reader
383 .read("block headers by block number", move |tx| {
384 queries::select_block_header_by_block_num(
385 tx,
386 maybe_block_number.map(|block_number| *block_number),
387 )
388 })
389 .await
390 }
391
392 pub(crate) async fn select_genesis_block_header(&self) -> Result<Option<BlockHeader>> {
394 self.reader
395 .read("genesis block header", |tx| {
396 queries::select_block_header_by_block_num(tx, Some(BlockNumber::GENESIS))
397 })
398 .await
399 }
400
401 #[miden_instrument(
404 level = "debug",
405 target = COMPONENT,
406 err(level = "debug"),
407 )]
408 pub async fn select_block_header_and_signatures_by_block_num(
409 &self,
410 block_number: ScopedBlockNum,
411 ) -> Result<Option<(BlockHeader, BlockSignatures)>> {
412 self.reader
413 .read("block headers and signatures by block number", move |tx| {
414 queries::select_block_header_and_signatures_by_block_num(tx, *block_number)
415 })
416 .await
417 }
418
419 #[miden_instrument(
421 level = "debug",
422 target = COMPONENT,
423 err(level = "debug"),
424 )]
425 pub async fn select_block_headers(
426 &self,
427 blocks: impl Iterator<Item = ScopedBlockNum> + Send + 'static,
428 ) -> Result<Vec<BlockHeader>> {
429 self.reader
430 .read("block headers from given block numbers", move |tx| {
431 queries::select_block_headers(tx, blocks.map(|block| *block))
432 })
433 .await
434 }
435
436 #[miden_instrument(
438 level = "debug",
439 target = COMPONENT,
440 err(level = "debug"),
441 )]
442 pub async fn select_all_block_header_commitments(&self) -> Result<Vec<BlockHeaderCommitment>> {
443 self.reader
444 .read("all block headers", queries::select_all_block_header_commitments)
445 .await
446 }
447
448 #[miden_instrument(
450 level = "debug",
451 target = COMPONENT,
452 err(level = "debug"),
453 )]
454 pub async fn select_account(&self, id: AccountId) -> Result<AccountInfo> {
455 self.reader
456 .read("Get account details", move |tx| queries::select_account(tx, id))
457 .await
458 }
459
460 #[miden_instrument(
462 level = "debug",
463 target = COMPONENT,
464 err(level = "debug"),
465 )]
466 pub async fn filter_network_accounts(
467 &self,
468 account_ids: Vec<AccountId>,
469 ) -> Result<HashSet<AccountId>> {
470 self.reader
471 .read("Filter network accounts", move |tx| {
472 queries::filter_network_accounts(tx, &account_ids)
473 })
474 .await
475 }
476
477 #[miden_instrument(
481 target = COMPONENT,
482 )]
483 pub async fn select_account_code_by_commitment(
484 &self,
485 code_commitment: Word,
486 ) -> Result<Option<miden_protocol::account::AccountCode>> {
487 self.reader
488 .read("Get account code by commitment", move |tx| {
489 queries::select_account_code_by_commitment(tx, code_commitment)?
490 .map(|bytes| {
491 miden_node_persistence::decode::<miden_protocol::account::AccountCode>(
492 &bytes,
493 )
494 })
495 .transpose()
496 .map_err(DatabaseError::from)
497 })
498 .await
499 }
500
501 #[miden_instrument(
506 target = COMPONENT,
507 )]
508 pub async fn select_account_header_with_storage_header_at_block(
509 &self,
510 account_id: AccountId,
511 block_num: ScopedBlockNum,
512 ) -> Result<Option<(AccountHeader, AccountStorageHeader)>> {
513 self.reader
514 .read("Get account header with storage header at block", move |tx| {
515 queries::select_account_header_with_storage_header_at_block(
516 tx, account_id, *block_num,
517 )
518 })
519 .await
520 }
521
522 #[miden_instrument(
525 level = "debug",
526 target = COMPONENT,
527 err(level = "debug"),
528 )]
529 pub async fn select_notes_by_id(&self, note_ids: Vec<NoteId>) -> Result<Vec<NoteRecord>> {
530 self.reader
531 .read("note by id", move |tx| queries::select_notes_by_id(tx, note_ids.as_slice()))
532 .await
533 }
534
535 #[miden_instrument(
537 level = "debug",
538 target = COMPONENT,
539 err(level = "debug"),
540 )]
541 pub async fn select_existing_note_ids(
542 &self,
543 note_ids: Vec<NoteId>,
544 up_to_block: ScopedBlockNum,
545 ) -> Result<HashSet<NoteId>> {
546 self.reader
547 .read("existing note IDs", move |tx| {
548 queries::select_existing_note_ids(tx, note_ids.as_slice(), *up_to_block)
549 })
550 .await
551 }
552
553 #[miden_instrument(
556 level = "debug",
557 target = COMPONENT,
558 err(level = "debug"),
559 )]
560 pub async fn select_note_inclusion_proofs(
561 &self,
562 note_commitments: BTreeSet<Word>,
563 up_to_block: ScopedBlockNum,
564 ) -> Result<BTreeMap<NoteId, NoteInclusionProof>> {
565 self.reader
566 .read("block note inclusion proofs by commitment", move |tx| {
567 queries::select_note_inclusion_proofs(tx, ¬e_commitments, *up_to_block)
568 })
569 .await
570 }
571
572 #[expect(
588 clippy::too_many_arguments,
589 reason = "the arguments are the block and the state that the writer precomputed for it"
590 )]
591 #[miden_instrument(
592 target = COMPONENT,
593 err,
594 )]
595 pub(crate) async fn apply_block(
596 &self,
597 signed_block: SignedBlock,
598 activated_protocol_config: Option<ProtocolConfig>,
599 notes: Vec<(NoteRecord, Option<Nullifier>)>,
600 precomputed_public_states: PrecomputedPublicAccountStates,
601 new_account_ids: BTreeSet<AccountId>,
602 unresolved_note_nullifiers: Vec<Nullifier>,
603 prune_tip: BlockNumber,
604 ) -> Result<BTreeMap<Nullifier, NoteId>> {
605 self.writer
606 .write::<_, DatabaseError, _>("apply block", move |tx| {
607 if let Some(protocol_config) = activated_protocol_config.as_ref() {
608 queries::insert_protocol_config(
609 tx,
610 protocol_config,
611 signed_block.header().block_num(),
612 )?;
613 }
614 queries::apply_block(
615 tx,
616 &signed_block,
617 ¬es,
618 &precomputed_public_states,
619 &new_account_ids,
620 )?;
621 queries::prune_history(tx, prune_tip)?;
622 Ok(())
623 })
624 .await?;
625
626 Ok(self.resolve_consumed_note_ids(unresolved_note_nullifiers).await)
627 }
628
629 async fn resolve_consumed_note_ids(
634 &self,
635 nullifiers: Vec<Nullifier>,
636 ) -> BTreeMap<Nullifier, NoteId> {
637 let mut resolved_note_ids = BTreeMap::new();
638 for chunk in nullifiers.chunks(QueryParamNoteCommitmentLimit::LIMIT) {
639 let chunk = chunk.to_vec();
640 let count = chunk.len();
641 let result = self
642 .reader
643 .read("resolve consumed note ids", move |tx| {
644 queries::select_note_ids_by_nullifier(tx, &chunk)
645 })
646 .await;
647
648 match result {
649 Ok(note_ids) => resolved_note_ids.extend(note_ids),
650 Err(err) => {
651 warn!(
652 &err,
653 target: COMPONENT,
654 "Failed to resolve consumed note IDs for lifecycle events",
655 note.nullifier.count = count
656 );
657 break;
658 },
659 }
660 }
661
662 resolved_note_ids
663 }
664
665 #[miden_instrument(
674 target = COMPONENT,
675 )]
676 pub(crate) async fn reconstruct_storage_map_from_db(
677 &self,
678 account_id: AccountId,
679 slot_name: miden_protocol::account::StorageSlotName,
680 block_num: ScopedBlockNum,
681 entries_limit: Option<usize>,
682 ) -> Result<miden_node_proto::domain::account::AccountStorageMapDetails> {
683 use miden_node_proto::domain::account::{AccountStorageMapDetails, StorageMapEntries};
684 use miden_protocol::EMPTY_WORD;
685
686 let entries_limit = entries_limit.unwrap_or_else(default_storage_map_entries_limit);
689 let query =
690 queries::AccountStorageMapValuesPaged::new(account_id, block_num, entries_limit);
691
692 let mut values = Vec::new();
693 let mut pages = pin!(self.pages(query, BlockNumber::GENESIS));
694 loop {
695 match pages.try_next().await {
696 Ok(Some(page)) => values.extend(page),
697 Ok(None) => break,
698 Err(DatabaseError::BlockExceedsPageLimit { .. }) => {
701 return Ok(AccountStorageMapDetails::limit_exceeded(slot_name));
702 },
703 Err(err) => return Err(err),
704 }
705 }
706
707 let mut latest_values = BTreeMap::<StorageMapKey, Word>::new();
709 for value in values {
710 if value.slot_name == slot_name {
711 let raw_key = value.key;
712 latest_values.insert(raw_key, value.value);
713 }
714 }
715
716 latest_values.retain(|_, v| *v != EMPTY_WORD);
718
719 if latest_values.len() > AccountStorageMapDetails::MAX_RETURN_ENTRIES {
720 return Ok(AccountStorageMapDetails::limit_exceeded(slot_name));
721 }
722
723 let entries = latest_values.into_iter().collect::<Vec<_>>();
724 Ok(AccountStorageMapDetails {
725 slot_name,
726 entries: StorageMapEntries::AllEntries(entries),
727 })
728 }
729
730 #[miden_instrument(
735 target = COMPONENT,
736 )]
737 pub async fn select_vault_at_block(
738 &self,
739 account_id: AccountId,
740 block_num: ScopedBlockNum,
741 ) -> Result<Vec<Asset>, DatabaseError> {
742 self.reader
743 .read("select vault at block", move |tx| {
744 queries::select_vault_at_block(tx, account_id, *block_num)
745 })
746 .await
747 }
748
749 pub async fn select_note_script_by_root(&self, root: Word) -> Result<Option<NoteScript>> {
751 self.reader
752 .read("note script by root", move |tx| queries::select_note_script_by_root(tx, root))
753 .await
754 }
755}