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, 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;
52
53const STORAGE_MAP_VALUE_PER_ROW_BYTES: usize =
54 2 * size_of::<Word>() + size_of::<u32>() + size_of::<u8>();
55
56pub(crate) fn default_storage_map_entries_limit() -> usize {
57 MAX_RESPONSE_PAYLOAD_BYTES / STORAGE_MAP_VALUE_PER_ROW_BYTES
58}
59
60mod migrations;
61#[cfg(test)]
62pub(crate) use migrations::bootstrap_database;
63
64#[cfg(test)]
65mod tests;
66
67#[cfg(test)]
68mod test_db;
69#[cfg(test)]
70pub(crate) use test_db::TestDb;
71
72pub(crate) mod queries;
74
75pub(crate) mod pagination;
76
77mod utils;
78
79pub type Result<T, E = DatabaseError> = std::result::Result<T, E>;
80
81#[derive(Copy, Clone, Debug, PartialEq, Eq)]
83pub struct DatabaseOptions {
84 pub connection_pool_size: NonZeroUsize,
86}
87
88impl Default for DatabaseOptions {
89 fn default() -> Self {
90 Self {
91 connection_pool_size: miden_node_db::default_connection_pool_size(),
92 }
93 }
94}
95
96pub struct Db {
101 writer: DbWriter,
102 reader: DbReader,
103}
104
105fn insert_genesis(tx: &WriteTx<'_>, genesis: GenesisBlock) -> Result<()> {
107 let (genesis_block, protocol_config) = genesis.into_parts();
108 let new_account_ids = genesis_block
110 .body()
111 .updated_accounts()
112 .iter()
113 .map(BlockAccountUpdate::account_id)
114 .collect();
115 queries::insert_protocol_config(tx, &protocol_config, BlockNumber::GENESIS)?;
116 queries::apply_block(
117 tx,
118 &genesis_block,
119 &[],
120 &PrecomputedPublicAccountStates::new(),
121 &new_account_ids,
122 )?;
123 Ok(())
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[repr(transparent)]
132pub struct BlockHeaderCommitment(pub(crate) Word);
133
134impl BlockHeaderCommitment {
135 pub fn new(header: &BlockHeader) -> Self {
136 Self(header.commitment())
137 }
138
139 pub fn word(self) -> Word {
140 self.0
141 }
142}
143
144#[derive(Debug, Clone)]
148pub struct AccountVaultValue {
149 pub block_num: BlockNumber,
150 pub vault_key: AssetId,
151 pub asset: Option<Asset>,
153}
154
155#[derive(Debug, PartialEq)]
156pub struct NullifierInfo {
157 pub nullifier: Nullifier,
158 pub block_num: BlockNumber,
159}
160
161impl PartialEq<(Nullifier, BlockNumber)> for NullifierInfo {
162 fn eq(&self, (nullifier, block_num): &(Nullifier, BlockNumber)) -> bool {
163 &self.nullifier == nullifier && &self.block_num == block_num
164 }
165}
166
167#[derive(Debug, PartialEq)]
168pub struct TransactionRecord {
169 pub block_num: BlockNumber,
170 pub header: TransactionHeader,
171 pub output_note_proofs: Vec<NoteSyncRecord>,
174 pub consumed_note_refs: Vec<(Nullifier, NoteId)>,
177}
178
179#[derive(Debug, Clone, PartialEq)]
180pub struct NoteRecord {
181 pub block_num: BlockNumber,
182 pub note_index: BlockNoteIndex,
183 pub note_id: Word,
184 pub metadata: NoteMetadata,
185 pub details: Option<NoteDetails>,
186 pub attachments: NoteAttachments,
187 pub inclusion_path: SparseMerklePath,
188}
189
190#[derive(Debug, PartialEq)]
191pub struct NoteSyncUpdate {
192 pub notes: Vec<NoteSyncRecord>,
193 pub block_header: BlockHeader,
194}
195
196#[derive(Debug, Clone, PartialEq)]
197pub struct NoteSyncRecord {
198 pub block_num: BlockNumber,
199 pub note_index: BlockNoteIndex,
200 pub note_id: NoteId,
201 pub metadata: NoteMetadata,
202 pub attachments: NoteAttachments,
203 pub inclusion_path: SparseMerklePath,
204}
205
206impl From<NoteRecord> for NoteSyncRecord {
207 fn from(note: NoteRecord) -> Self {
208 Self {
209 block_num: note.block_num,
210 note_index: note.note_index,
211 note_id: NoteId::from_raw(note.note_id),
212 metadata: note.metadata,
213 attachments: note.attachments,
214 inclusion_path: note.inclusion_path,
215 }
216 }
217}
218
219impl Db {
220 #[instrument(
222 name = "bootstrap",
223 fields(path = database_filepath),
224 err,
225 )]
226 pub async fn bootstrap(
227 database_filepath: PathBuf,
228 genesis: GenesisBlock,
229 ) -> anyhow::Result<()> {
230 migrations::bootstrap_database(&database_filepath)
231 .context("failed to bootstrap database schema")?;
232
233 let (writer, _reader) = miden_node_db::sqlite::open(&database_filepath)
234 .context("failed to open a database connection")?;
235
236 writer
238 .write("insert genesis block", move |tx| insert_genesis(tx, genesis))
239 .await
240 .context("failed to insert genesis block")?;
241 Ok(())
242 }
243
244 #[instrument]
246 pub async fn load(database_filepath: PathBuf) -> Result<Self, DatabaseError> {
247 Self::load_with_pool_size(database_filepath, miden_node_db::default_connection_pool_size())
248 .await
249 }
250
251 #[instrument]
254 pub async fn load_with_pool_size(
255 database_filepath: PathBuf,
256 connection_pool_size: NonZeroUsize,
257 ) -> Result<Self, DatabaseError> {
258 verify_latest_schema(&database_filepath)?;
259
260 let (writer, reader) =
261 miden_node_db::sqlite::open_with_pool_size(&database_filepath, connection_pool_size)?;
262 info!(
263 "Connected to the database",
264 path = database_filepath,
265 db.sqlite.connection_pool_size = connection_pool_size.get()
266 );
267
268 Ok(Self { writer, reader })
269 }
270
271 #[cfg(test)]
273 pub(crate) fn writer(&self) -> &DbWriter {
274 &self.writer
275 }
276
277 #[instrument(level = "debug", err(level = "debug"))]
279 pub async fn select_protocol_config_by_commitment(
280 &self,
281 commitment: Word,
282 ) -> Result<Option<ProtocolConfig>> {
283 self.reader
284 .read("protocol config by commitment", move |tx| {
285 queries::select_protocol_config_by_commitment(tx, commitment)
286 })
287 .await
288 }
289
290 pub async fn select_protocol_config_commitment_at(
292 &self,
293 block_number: ScopedBlockNum,
294 ) -> Result<Option<Word>> {
295 self.reader
296 .read("protocol config commitment at block", move |tx| {
297 queries::select_protocol_config_commitment_at(tx, *block_number)
298 })
299 .await
300 }
301
302 #[instrument]
304 pub fn migrate(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
305 migrate_database(database_filepath.as_ref())?;
306 Ok(())
307 }
308
309 #[instrument(level = "debug", err(level = "debug"))]
311 pub(crate) async fn page<Q: Paginated>(
312 &self,
313 query: Q,
314 next: Q::Cursor,
315 ) -> Result<Page<Q::Item, Q::Cursor>> {
316 self.reader
317 .read(std::any::type_name::<Q>(), move |tx| query.page(tx, &next))
318 .await
319 }
320
321 pub(crate) fn pages<Q: Paginated>(
328 &self,
329 query: Q,
330 start: Q::Cursor,
331 ) -> impl Stream<Item = Result<Vec<Q::Item>>> + Send + use<Q> {
332 let reader = self.reader.clone();
333 let query = Arc::new(query);
334 futures::stream::try_unfold(Some(start), move |state: Option<Q::Cursor>| {
336 let reader = reader.clone();
337 let query = Arc::clone(&query);
338 async move {
339 let Some(next) = state else {
340 return Ok(None);
341 };
342 let page = reader
343 .read(std::any::type_name::<Q>(), move |tx| query.page(tx, &next))
344 .await?;
345 if page.items.is_empty() {
346 return Ok(None);
347 }
348 Ok::<_, DatabaseError>(Some((page.items, page.next)))
349 }
350 })
351 }
352
353 #[instrument(level = "debug", err(level = "debug"))]
357 pub async fn select_block_header_by_block_num(
358 &self,
359 maybe_block_number: Option<ScopedBlockNum>,
360 ) -> Result<Option<BlockHeader>> {
361 self.reader
362 .read("block headers by block number", move |tx| {
363 queries::select_block_header_by_block_num(
364 tx,
365 maybe_block_number.map(|block_number| *block_number),
366 )
367 })
368 .await
369 }
370
371 pub(crate) async fn select_genesis_block_header(&self) -> Result<Option<BlockHeader>> {
373 self.reader
374 .read("genesis block header", |tx| {
375 queries::select_block_header_by_block_num(tx, Some(BlockNumber::GENESIS))
376 })
377 .await
378 }
379
380 #[instrument(level = "debug", err(level = "debug"))]
383 pub async fn select_block_header_and_signatures_by_block_num(
384 &self,
385 block_number: ScopedBlockNum,
386 ) -> Result<Option<(BlockHeader, BlockSignatures)>> {
387 self.reader
388 .read("block headers and signatures by block number", move |tx| {
389 queries::select_block_header_and_signatures_by_block_num(tx, *block_number)
390 })
391 .await
392 }
393
394 #[instrument(level = "debug", err(level = "debug"))]
396 pub async fn select_block_headers(
397 &self,
398 blocks: impl Iterator<Item = ScopedBlockNum> + Send + 'static,
399 ) -> Result<Vec<BlockHeader>> {
400 self.reader
401 .read("block headers from given block numbers", move |tx| {
402 queries::select_block_headers(tx, blocks.map(|block| *block))
403 })
404 .await
405 }
406
407 #[instrument(level = "debug", err(level = "debug"))]
409 pub async fn select_all_block_header_commitments(&self) -> Result<Vec<BlockHeaderCommitment>> {
410 self.reader
411 .read("all block headers", queries::select_all_block_header_commitments)
412 .await
413 }
414
415 #[instrument(level = "debug", err(level = "debug"))]
417 pub async fn select_account(&self, id: AccountId) -> Result<AccountInfo> {
418 self.reader
419 .read("Get account details", move |tx| queries::select_account(tx, id))
420 .await
421 }
422
423 #[instrument(level = "debug", err(level = "debug"))]
425 pub async fn filter_network_accounts(
426 &self,
427 account_ids: Vec<AccountId>,
428 ) -> Result<HashSet<AccountId>> {
429 self.reader
430 .read("Filter network accounts", move |tx| {
431 queries::filter_network_accounts(tx, &account_ids)
432 })
433 .await
434 }
435
436 #[instrument]
440 pub async fn select_account_code_by_commitment(
441 &self,
442 code_commitment: Word,
443 ) -> Result<Option<miden_protocol::account::AccountCode>> {
444 self.reader
445 .read("Get account code by commitment", move |tx| {
446 queries::select_account_code_by_commitment(tx, code_commitment)?
447 .map(|bytes| {
448 miden_node_persistence::decode::<miden_protocol::account::AccountCode>(
449 &bytes,
450 )
451 })
452 .transpose()
453 .map_err(DatabaseError::from)
454 })
455 .await
456 }
457
458 #[instrument]
463 pub async fn select_account_header_with_storage_header_at_block(
464 &self,
465 account_id: AccountId,
466 block_num: ScopedBlockNum,
467 ) -> Result<Option<(AccountHeader, AccountStorageHeader)>> {
468 self.reader
469 .read("Get account header with storage header at block", move |tx| {
470 queries::select_account_header_with_storage_header_at_block(
471 tx, account_id, *block_num,
472 )
473 })
474 .await
475 }
476
477 #[instrument(level = "debug", err(level = "debug"))]
480 pub async fn select_notes_by_id(&self, note_ids: Vec<NoteId>) -> Result<Vec<NoteRecord>> {
481 self.reader
482 .read("note by id", move |tx| queries::select_notes_by_id(tx, note_ids.as_slice()))
483 .await
484 }
485
486 #[instrument(level = "debug", err(level = "debug"))]
488 pub async fn select_existing_note_ids(
489 &self,
490 note_ids: Vec<NoteId>,
491 up_to_block: ScopedBlockNum,
492 ) -> Result<HashSet<NoteId>> {
493 self.reader
494 .read("existing note IDs", move |tx| {
495 queries::select_existing_note_ids(tx, note_ids.as_slice(), *up_to_block)
496 })
497 .await
498 }
499
500 #[instrument(level = "debug", err(level = "debug"))]
503 pub async fn select_note_inclusion_proofs(
504 &self,
505 note_commitments: BTreeSet<Word>,
506 up_to_block: ScopedBlockNum,
507 ) -> Result<BTreeMap<NoteId, NoteInclusionProof>> {
508 self.reader
509 .read("block note inclusion proofs by commitment", move |tx| {
510 queries::select_note_inclusion_proofs(tx, ¬e_commitments, *up_to_block)
511 })
512 .await
513 }
514
515 #[expect(
531 clippy::too_many_arguments,
532 reason = "the arguments are the block and the state that the writer precomputed for it"
533 )]
534 #[instrument(err)]
535 pub(crate) async fn apply_block(
536 &self,
537 signed_block: SignedBlock,
538 activated_protocol_config: Option<ProtocolConfig>,
539 notes: Vec<(NoteRecord, Option<Nullifier>)>,
540 precomputed_public_states: PrecomputedPublicAccountStates,
541 new_account_ids: BTreeSet<AccountId>,
542 unresolved_note_nullifiers: Vec<Nullifier>,
543 prune_tip: BlockNumber,
544 ) -> Result<BTreeMap<Nullifier, NoteId>> {
545 self.writer
546 .write::<_, DatabaseError, _>("apply block", move |tx| {
547 if let Some(protocol_config) = activated_protocol_config.as_ref() {
548 queries::insert_protocol_config(
549 tx,
550 protocol_config,
551 signed_block.header().block_num(),
552 )?;
553 }
554 queries::apply_block(
555 tx,
556 &signed_block,
557 ¬es,
558 &precomputed_public_states,
559 &new_account_ids,
560 )?;
561 queries::prune_history(tx, prune_tip)?;
562 Ok(())
563 })
564 .await?;
565
566 Ok(self.resolve_consumed_note_ids(unresolved_note_nullifiers).await)
567 }
568
569 async fn resolve_consumed_note_ids(
574 &self,
575 nullifiers: Vec<Nullifier>,
576 ) -> BTreeMap<Nullifier, NoteId> {
577 let mut resolved_note_ids = BTreeMap::new();
578 for chunk in nullifiers.chunks(QueryParamNoteCommitmentLimit::LIMIT) {
579 let chunk = chunk.to_vec();
580 let count = chunk.len();
581 let result = self
582 .reader
583 .read("resolve consumed note ids", move |tx| {
584 queries::select_note_ids_by_nullifier(tx, &chunk)
585 })
586 .await;
587
588 match result {
589 Ok(note_ids) => resolved_note_ids.extend(note_ids),
590 Err(err) => {
591 warn!(
592 &err,
593 "Failed to resolve consumed note IDs for lifecycle events",
594 note.nullifier.count = count
595 );
596 break;
597 },
598 }
599 }
600
601 resolved_note_ids
602 }
603
604 #[instrument]
613 pub(crate) async fn reconstruct_storage_map_from_db(
614 &self,
615 account_id: AccountId,
616 slot_name: miden_protocol::account::StorageSlotName,
617 block_num: ScopedBlockNum,
618 entries_limit: Option<usize>,
619 ) -> Result<miden_node_proto::domain::account::AccountStorageMapDetails> {
620 use miden_node_proto::domain::account::{AccountStorageMapDetails, StorageMapEntries};
621 use miden_protocol::EMPTY_WORD;
622
623 let entries_limit = entries_limit.unwrap_or_else(default_storage_map_entries_limit);
626 let query =
627 queries::AccountStorageMapValuesPaged::new(account_id, block_num, entries_limit);
628
629 let mut values = Vec::new();
630 let mut pages = pin!(self.pages(query, BlockNumber::GENESIS));
631 loop {
632 match pages.try_next().await {
633 Ok(Some(page)) => values.extend(page),
634 Ok(None) => break,
635 Err(DatabaseError::BlockExceedsPageLimit { .. }) => {
638 return Ok(AccountStorageMapDetails::limit_exceeded(slot_name));
639 },
640 Err(err) => return Err(err),
641 }
642 }
643
644 let mut latest_values = BTreeMap::<StorageMapKey, Word>::new();
646 for value in values {
647 if value.slot_name == slot_name {
648 let raw_key = value.key;
649 latest_values.insert(raw_key, value.value);
650 }
651 }
652
653 latest_values.retain(|_, v| *v != EMPTY_WORD);
655
656 if latest_values.len() > AccountStorageMapDetails::MAX_RETURN_ENTRIES {
657 return Ok(AccountStorageMapDetails::limit_exceeded(slot_name));
658 }
659
660 let entries = latest_values.into_iter().collect::<Vec<_>>();
661 Ok(AccountStorageMapDetails {
662 slot_name,
663 entries: StorageMapEntries::AllEntries(entries),
664 })
665 }
666
667 #[instrument]
672 pub async fn select_vault_at_block(
673 &self,
674 account_id: AccountId,
675 block_num: ScopedBlockNum,
676 ) -> Result<Vec<Asset>, DatabaseError> {
677 self.reader
678 .read("select vault at block", move |tx| {
679 queries::select_vault_at_block(tx, account_id, *block_num)
680 })
681 .await
682 }
683
684 pub async fn select_note_script_by_root(&self, root: Word) -> Result<Option<NoteScript>> {
686 self.reader
687 .read("note script by root", move |tx| queries::select_note_script_by_root(tx, root))
688 .await
689 }
690}