Skip to main content

miden_node_store/state/view/
mod.rs

1//! Request-scoped, consistent read view of the store.
2//!
3//! All store reads go through [`StateView`]: it pins one state snapshot for its whole lifetime,
4//! and every block-scoped database query it exposes is bounded by that snapshot's height (via the
5//! [`scoped`] proof types). This makes it impossible to implement a read whose tree and database
6//! halves observe different chain tips — mid-apply, the database may already contain rows for a
7//! block the snapshot cannot prove yet. The only deliberately unscoped reads are the
8//! content-addressed note lookups and the network-account classification.
9//!
10//! The submodules hold the read endpoints, all `impl StateView`; the snapshot internals
11//! ([`StateSnapshot`]) are only visible within this module tree, so no other part of the store
12//! can reach the trees directly.
13
14use std::ops::RangeInclusive;
15use std::sync::Arc;
16
17use miden_protocol::block::{BlockNumber, Blockchain};
18use tracing::Span;
19
20use crate::account_state_forest::{AccountStateForest, AccountStateForestBackendReader};
21use crate::db::Db;
22use crate::errors::RangeBeyondTip;
23use crate::state::State;
24
25mod scoped;
26pub use scoped::{ScopedBlockNum, ScopedBlockRange};
27
28mod snapshot;
29pub(in crate::state) use snapshot::{
30    PublishedGenerations,
31    SNAPSHOTS_LIVE_WARN_THRESHOLD,
32    SnapshotGuard,
33    StateSnapshot,
34};
35
36mod account;
37mod batch_inputs;
38mod block;
39mod block_inputs;
40mod note;
41mod sync;
42
43mod transaction_inputs;
44pub use transaction_inputs::TransactionInputs;
45
46// STATE VIEW
47// ================================================================================================
48
49/// A consistent read view of the store, pinned at its snapshot's block height.
50///
51/// Obtained from [`State::view`]; create one per request and drop it when the request completes.
52/// Holding a view pins a snapshot generation (and thereby the `RocksDB` snapshots backing the
53/// trees), so it must not be stored in long-lived structs; leaked or slow readers are reported by
54/// the store's snapshot-lifetime warnings.
55///
56/// Reads that are technically not block-scoped (e.g. content-addressed note scripts) also live
57/// here so that every read path flows through a single, consistently-scoped type.
58pub struct StateView {
59    snapshot: Arc<StateSnapshot>,
60    db: Arc<Db>,
61}
62
63impl State {
64    /// Returns a read view pinned at the current chain tip (wait-free, no lock required).
65    ///
66    /// The view is frozen: it is unaffected if the writer publishes a new snapshot while it is
67    /// held.
68    ///
69    /// Use this only for one single-expression read (`state.view().get_account(..)`),
70    /// where the temporary view drops at the end of the statement. Two `view()` calls observe
71    /// potentially *different* snapshots — a block can commit between them — so reads that must
72    /// be mutually consistent (e.g. a query and the tip it was served at) must share one view via
73    /// [`Self::with_view`]. Binding a view to a variable is also discouraged: it keeps the
74    /// snapshot generation pinned until the end of the scope.
75    pub fn view(&self) -> StateView {
76        StateView {
77            snapshot: self.latest_snapshot.load_full(),
78            db: Arc::clone(&self.db),
79        }
80    }
81
82    /// Runs a read operation over a view pinned at the current chain tip, dropping the view — and
83    /// releasing its snapshot generation — as soon as the operation completes.
84    ///
85    /// This is the required form whenever multiple reads must observe the *same* snapshot: the
86    /// closure's view is one consistent generation, whereas consecutive [`Self::view`] calls may
87    /// straddle a commit. The typical case is pairing a query with [`StateView::tip`] so a
88    /// response reports exactly the height it was served at.
89    ///
90    /// The closure receives a shared reference, so the view cannot escape the call, and the
91    /// snapshot is not pinned through unrelated work that follows (e.g. response encoding). A
92    /// *single* read doesn't need it — `state.view().get_account(..)` drops its temporary view at
93    /// the end of the statement.
94    ///
95    /// Work in the closure should be kept to low-complexity compute over the view, ideally with no
96    /// I/O and no other `.await` points. Anything slower holds the pinned snapshot, and therefore
97    /// its underlying `RocksDB` snapshot, for as long as it runs. The snapshot's lifetime is logged
98    /// as a warning if held too long, but that is a backstop, not a substitute for keeping closures
99    /// short.
100    pub async fn with_view<R>(&self, f: impl AsyncFnOnce(&StateView) -> R) -> R {
101        let view = self.view();
102        f(&view).await
103    }
104}
105
106impl StateView {
107    /// Returns this view's tip as a scoped block number for tip-bounded database queries.
108    pub fn tip(&self) -> ScopedBlockNum {
109        ScopedBlockNum::new(self.snapshot.latest_block_num())
110    }
111
112    /// Returns the pinned snapshot's blockchain MMR.
113    ///
114    /// The MMR is the only part of the snapshot that is purely in-memory and therefore safe to
115    /// access directly on an async worker thread. The account and nullifier trees may be backed
116    /// by `RocksDB` and are deliberately not reachable here — they must be accessed through
117    /// [`Self::with_inner_read_blocking`].
118    fn blockchain(&self) -> &Blockchain {
119        &self.snapshot.blockchain
120    }
121
122    /// Validates that `block_num` does not exceed this view's chain tip, returning the scoped block
123    /// number required by block-bounded database queries.
124    fn scope_block(&self, block_num: BlockNumber) -> Option<ScopedBlockNum> {
125        (block_num <= *self.tip()).then(|| ScopedBlockNum::new(block_num))
126    }
127
128    /// Validates that `range` does not extend beyond this view's chain tip, returning the scoped
129    /// range required by range-bounded database queries.
130    ///
131    /// Every range-scoped read on this type calls this before touching the database, so callers
132    /// never need to pre-validate ranges themselves.
133    fn scope_range(
134        &self,
135        range: RangeInclusive<BlockNumber>,
136    ) -> Result<ScopedBlockRange, RangeBeyondTip> {
137        let tip = *self.tip();
138        if *range.end() > tip {
139            return Err(RangeBeyondTip { chain_tip: tip, block_to: *range.end() });
140        }
141        Ok(ScopedBlockRange::new(range))
142    }
143
144    /// Runs a synchronous read-only operation over the pinned state snapshot on Tokio's blocking
145    /// path.
146    ///
147    /// The account and nullifier trees may be backed by `RocksDB`, so tree access must not run on
148    /// an async worker thread directly. This helper preserves the current tracing span while
149    /// moving the closure body into `block_in_place`.
150    fn with_inner_read_blocking<R>(&self, f: impl FnOnce(&StateSnapshot) -> R) -> R {
151        let span = Span::current();
152        tokio::task::block_in_place(|| span.in_scope(|| f(&self.snapshot)))
153    }
154
155    /// Runs a synchronous read-only operation over the account state forest snapshot on Tokio's
156    /// blocking path.
157    ///
158    /// See [`Self::with_inner_read_blocking`] for why this uses `block_in_place`.
159    fn with_forest_read_blocking<R>(
160        &self,
161        f: impl FnOnce(&AccountStateForest<AccountStateForestBackendReader>) -> R,
162    ) -> R {
163        self.with_inner_read_blocking(|snapshot| f(&snapshot.forest))
164    }
165}