Skip to main content

miden_node_store/db/
mod.rs

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
72/// Query functions on the `miden-node-db` SQLite framework.
73pub(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/// Database options used by the store state.
82#[derive(Copy, Clone, Debug, PartialEq, Eq)]
83pub struct DatabaseOptions {
84    /// Maximum number of SQLite connections in the connection pool.
85    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
96/// The Store's database.
97///
98/// Every write serializes on the single framework writer connection. Every read runs on the
99/// framework reader pool.
100pub struct Db {
101    writer: DbWriter,
102    reader: DbReader,
103}
104
105/// Inserts the genesis block and the protocol configuration that it activates.
106fn insert_genesis(tx: &WriteTx<'_>, genesis: GenesisBlock) -> Result<()> {
107    let (genesis_block, protocol_config) = genesis.into_parts();
108    // The genesis block has no transactions, but it creates every account it contains.
109    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/// The commitment of a [`BlockHeader`], stored alongside the header it belongs to.
127///
128/// Keeping it in its own column lets the chain MMR be rebuilt at startup without deserializing
129/// every header.
130#[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/// Describes the value of an asset for an account ID at `block_num` specifically.
145///
146/// If `asset` is `None`, the asset was removed.
147#[derive(Debug, Clone)]
148pub struct AccountVaultValue {
149    pub block_num: BlockNumber,
150    pub vault_key: AssetId,
151    /// None if the asset was removed
152    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    /// Inclusion proofs for committed output notes. Notes in `header.output_notes()` without a
172    /// corresponding proof here were erased (created and consumed within the same batch).
173    pub output_note_proofs: Vec<NoteSyncRecord>,
174    /// Maps each consumed input note's nullifier to its note ID, for public notes the node could
175    /// resolve. This is to enable the recover of notes by their id.
176    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    /// Creates a new database and inserts the genesis block.
221    #[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        // Insert genesis block data.
237        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    /// Open a connection to the DB after verifying that it is at the latest schema version.
245    #[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    /// Open a connection to the DB with a specific pool size after verifying that it is at the
252    /// latest schema version.
253    #[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    /// The write handle, for tests that need to seed or corrupt rows no production method writes.
272    #[cfg(test)]
273    pub(crate) fn writer(&self) -> &DbWriter {
274        &self.writer
275    }
276
277    /// Selects a protocol configuration by its commitment.
278    #[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    /// Selects the configuration commitment active at the specified block.
291    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    /// Applies all pending migrations to an existing DB.
303    #[instrument]
304    pub fn migrate(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
305        migrate_database(database_filepath.as_ref())?;
306        Ok(())
307    }
308
309    /// Reads the page of `query` that starts at `next`.
310    #[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    /// Streams the items of every non-empty page of `query` in order, starting at `start` and
322    /// ending after the page whose `next` is `None`.
323    ///
324    /// Each page runs in its own read transaction, so no reader connection stays checked out
325    /// between pages. As a consequence, different pages can observe different snapshots of the
326    /// database.
327    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        // The state holds where the next page starts, or `None` once the last page is read.
335        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    /// Search for a [`BlockHeader`] from the database by its `block_num`.
354    ///
355    /// When `block_number` is [None], the latest block header is returned.
356    #[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    /// Selects the genesis block header for state initialization.
372    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    /// Search for a [`BlockHeader`] and its [`BlockSignatures`] from the database by its
381    /// `block_num`.
382    #[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    /// Loads multiple block headers from the DB.
395    #[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    /// Loads all the block headers from the DB.
408    #[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    /// Loads public account details from the DB.
416    #[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    /// Returns the subset of the provided account IDs that classify as network accounts.
424    #[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    /// Queries the account code by its commitment hash.
437    ///
438    /// Returns `None` if no code exists with that commitment.
439    #[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    /// Queries the account header and storage header for a specific account at a block.
459    ///
460    /// Returns both in a single query to avoid querying the database twice.
461    /// Returns `None` if the account doesn't exist at that block.
462    #[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    /// Loads all the [`miden_protocol::note::Note`]s matching a certain [`NoteId`] from the
478    /// database.
479    #[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    /// Returns the requested note IDs that the database contains at or before `up_to_block`.
487    #[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    /// Loads inclusion proofs for notes matching the given note commitments that were committed at
501    /// or before `up_to_block`.
502    #[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, &note_commitments, *up_to_block)
511            })
512            .await
513    }
514
515    /// Inserts the data of a new block into the DB.
516    ///
517    /// The transaction is committed when this method returns. Synchronization with the in-memory
518    /// trees is handled by the block writer task; see [`super::state::State::apply_block`].
519    ///
520    /// Account history is pruned in the same transaction against `prune_tip`: the effective tip
521    /// for retention, which lags the actual tip while old snapshot generations are still pinned
522    /// by readers (SQLite reads have no point-in-time protection, unlike the `RocksDB`-backed
523    /// trees).
524    ///
525    /// Consumed note IDs omitted from transaction headers are resolved from
526    /// `unresolved_note_nullifiers` on a best-effort basis. The returned mapping is used only for
527    /// lifecycle events and never affects block application. `unresolved_note_nullifiers` is empty
528    /// when neither INFO nor DEBUG lifecycle events are enabled.
529    // TODO: This span is logged in a root span, we should connect it to the parent one.
530    #[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                    &notes,
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    /// Maps consumed nullifiers back to their note IDs for lifecycle events, on a best-effort
570    /// basis.
571    ///
572    /// A failed lookup is logged and abandoned: the caller uses this only for reporting.
573    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    /// Reconstructs storage map details from the database for a specific slot at a block.
605    ///
606    /// Used as fallback when `AccountStateForest` cache misses (historical or evicted queries).
607    /// Rebuilds all entries by querying the DB and filtering to the specific slot.
608    ///
609    /// Returns:
610    ///     - `::LimitExceeded` when too many entries are present
611    ///     - `::AllEntries` if the size is less than or equal given `entries_limit`, if any
612    #[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        // TODO this remains expensive with a large history until we implement pruning for DB
624        // columns
625        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                // A single block holds more entries than fit in a page, as with genesis accounts
636                // that have large storage maps.
637                Err(DatabaseError::BlockExceedsPageLimit { .. }) => {
638                    return Ok(AccountStorageMapDetails::limit_exceeded(slot_name));
639                },
640                Err(err) => return Err(err),
641            }
642        }
643
644        // Filter to the specific slot and collect latest values per key
645        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        // Remove EMPTY_WORD entries (deletions)
654        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    /// Reconstructs the account vault from the database for a specific account at a block.
668    ///
669    /// Used as fallback when the `AccountStateForest` vault-key cache misses (historical or evicted
670    /// queries). Returns the latest asset for each vault key at or before `block_num`.
671    #[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    /// Returns the script for a note by its root.
685    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}