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