Skip to main content

miden_node_store/state/
lifecycle.rs

1//! Store lifecycle: loading the state, starting its write worker, and stopping the store.
2
3use std::num::NonZeroUsize;
4use std::path::Path;
5use std::sync::Arc;
6
7use arc_swap::ArcSwap;
8use miden_node_tracing::spawn::spawn_blocking_in_current_span;
9use miden_node_tracing::{ErrorReport, instrument};
10use miden_node_utils::clap::StorageOptions;
11use miden_node_utils::shutdown::CancellationToken;
12use tokio::sync::{mpsc, watch};
13use tokio::task::JoinHandle;
14use tracing::Instrument;
15
16use crate::accounts::AccountTreeWithHistory;
17use crate::blocks::BlockStore;
18use crate::db::Db;
19use crate::errors::StateInitializationError;
20use crate::proven_tip::ProvenTipWriter;
21use crate::state::loader::{
22    ACCOUNT_STATE_FOREST_STORAGE_DIR,
23    ACCOUNT_TREE_STORAGE_DIR,
24    NULLIFIER_TREE_STORAGE_DIR,
25    load_account_state_forest,
26    load_account_tree,
27    load_mmr,
28    load_nullifier_tree,
29    open_account_state_forest_storage,
30    open_tree_storage,
31    verify_account_state_forest_consistency,
32    verify_tree_consistency,
33};
34use crate::state::writer::{WriteRequest, WriteWorker, WriterTask};
35use crate::state::{BlockCache, BlockWriter, ProofCache, ProofWriter, State, StateSnapshot};
36use crate::{DataDirectory, DatabaseOptions};
37
38/// Awaits a spawned load task, forwarding its result.
39///
40/// The load tasks are never aborted, so a join error is a panic from the task; it is resumed on
41/// the caller so panics keep propagating as panics.
42async fn join_load_task<T>(
43    handle: JoinHandle<Result<T, StateInitializationError>>,
44) -> Result<T, StateInitializationError> {
45    match handle.await {
46        Ok(result) => result,
47        Err(err) => std::panic::resume_unwind(err.into_panic()),
48    }
49}
50
51/// Number of recent committed blocks held in the in-memory cache for replica subscriptions.
52const BLOCK_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(512).unwrap();
53
54/// Number of recent block proofs held in the in-memory cache for replica subscriptions.
55const PROOF_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(512).unwrap();
56
57// LOADED STATE
58// ================================================================================================
59
60/// A loaded store state whose write worker has not been started yet.
61///
62/// Returned by [`State::load`]. [`Self::start`] spawns the writer and yields the read-only
63/// [`State`] together with the write capabilities; since this is the only way to obtain a
64/// [`BlockWriter`], [`BlockWriter::apply_block`] can always make progress.
65#[must_use = "call `start` to spawn the write worker and obtain the state"]
66pub struct LoadedState {
67    state: State,
68    writer: WriteWorker,
69    write_tx: mpsc::Sender<WriteRequest>,
70}
71
72impl LoadedState {
73    /// Spawns the write worker onto the current runtime and returns the read-only state together
74    /// with the write capabilities and the writer task's handle.
75    ///
76    /// [`Arc<State>`] is the read-only view shared with every component that queries or
77    /// subscribes; it exposes no mutating methods. [`BlockWriter`] and [`ProofWriter`] are the
78    /// only handles able to mutate the store — hand them to the single task driving each write
79    /// path (block production or sync, and proof scheduling or sync respectively). The
80    /// capabilities expose no read access: tasks that both read and write receive the
81    /// [`Arc<State>`] alongside their capability.
82    ///
83    /// The writer exits once `shutdown` is cancelled or the [`BlockWriter`] (holding the only
84    /// request sender) is dropped — an in-flight block write always completes first. Awaiting the
85    /// returned handle after either event guarantees the writer has released the tree storage it
86    /// owns; a join error carries a writer panic.
87    ///
88    /// Callers without a token to cancel should pass [`CancellationToken::new`] and stop the store
89    /// via [`BlockWriter::stop`] instead of dropping and joining by hand.
90    pub fn start(
91        self,
92        shutdown: CancellationToken,
93    ) -> (Arc<State>, BlockWriter, ProofWriter, WriterTask) {
94        let writer_task = tokio::spawn(self.writer.run(shutdown));
95        let state = Arc::new(self.state);
96        let block_writer = BlockWriter {
97            block_store: Arc::clone(&state.block_store),
98            write_tx: self.write_tx,
99        };
100        let proof_writer = ProofWriter { state: Arc::clone(&state) };
101        (state, block_writer, proof_writer, WriterTask(writer_task))
102    }
103}
104
105// LOAD
106// ================================================================================================
107
108impl State {
109    /// Loads the state from the data directory.
110    ///
111    /// The loaded state owns all store data structures and exposes subscription methods for
112    /// sequencer and replica tasks. Call [`LoadedState::start`] on the result to spawn the block
113    /// writer and obtain the usable [`State`].
114    #[instrument]
115    pub async fn load(
116        data_path: &Path,
117        storage_options: StorageOptions,
118    ) -> Result<LoadedState, StateInitializationError> {
119        Self::load_with_database_options(data_path, storage_options, DatabaseOptions::default())
120            .await
121    }
122
123    /// Loads the state from the data directory using explicit database options.
124    ///
125    /// The loaded state owns all store data structures and exposes subscription methods for
126    /// sequencer and replica tasks. Call [`LoadedState::start`] on the result to spawn the block
127    /// writer and obtain the usable [`State`].
128    #[instrument]
129    pub async fn load_with_database_options(
130        data_path: &Path,
131        storage_options: StorageOptions,
132        database_options: DatabaseOptions,
133    ) -> Result<LoadedState, StateInitializationError> {
134        let data_directory = DataDirectory::load(data_path.to_path_buf())
135            .map_err(StateInitializationError::DataDirectoryLoadError)?;
136
137        let block_store = Arc::new(
138            BlockStore::load(data_directory.block_store_dir())
139                .map_err(StateInitializationError::BlockStoreLoadError)?,
140        );
141
142        let database_filepath = data_directory.database_path();
143        let db = Arc::new(
144            Db::load_with_pool_size(
145                database_filepath.clone(),
146                database_options.connection_pool_size,
147            )
148            .await
149            .map_err(StateInitializationError::DatabaseLoadError)?,
150        );
151
152        let genesis_header = db
153            .select_genesis_block_header()
154            .await?
155            .ok_or(StateInitializationError::GenesisBlockMissing)?;
156        let genesis_protocol_config_commitment = genesis_header.protocol_config_commitment();
157        if db
158            .select_protocol_config_by_commitment(genesis_protocol_config_commitment)
159            .await?
160            .is_none()
161        {
162            return Err(StateInitializationError::GenesisProtocolConfigMissing {
163                commitment: genesis_protocol_config_commitment,
164            });
165        }
166
167        // The chain tip drives forest loading and the account tree history below; `load_mmr`'s
168        // consistency check also pins the chain MMR to this header.
169        let latest_block_num = db
170            .select_block_header_by_block_num(None)
171            .await?
172            .ok_or(StateInitializationError::GenesisBlockMissing)?
173            .block_num();
174
175        let apply_block_thread_priority = storage_options.apply_block_thread_priority;
176
177        let (account_storage_config, nullifier_storage_config, forest_storage_config) = (
178            storage_options.account_tree.into(),
179            storage_options.nullifier_tree.into(),
180            storage_options.account_state_forest.into(),
181        );
182
183        // The four structures live in independent storages and the database pool supports
184        // concurrent readers, so open and load them concurrently. Each branch is a spawned task
185        // because loading has long synchronous sections (RocksDB opens, MMR hashing, SMT top
186        // reconstruction) that would serialize if polled from a single task. Spawning is eager, so
187        // all four run from this point; the join below only collects their results.
188        let mmr_task = tokio::spawn(
189            {
190                let db = Arc::clone(&db);
191                async move { load_mmr(&db).await }
192            }
193            .in_current_span(),
194        );
195        let account_tree_task = tokio::spawn(
196            {
197                let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
198                async move {
199                    let storage = join_load_task(spawn_blocking_in_current_span(move || {
200                        open_tree_storage(&path, &account_storage_config, ACCOUNT_TREE_STORAGE_DIR)
201                    }))
202                    .await?;
203                    load_account_tree(storage, &db).await
204                }
205            }
206            .in_current_span(),
207        );
208        let nullifier_tree_task = tokio::spawn(
209            {
210                let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
211                async move {
212                    let storage = join_load_task(spawn_blocking_in_current_span(move || {
213                        open_tree_storage(
214                            &path,
215                            &nullifier_storage_config,
216                            NULLIFIER_TREE_STORAGE_DIR,
217                        )
218                    }))
219                    .await?;
220                    load_nullifier_tree(storage, &db).await
221                }
222            }
223            .in_current_span(),
224        );
225        let forest_task = tokio::spawn(
226            {
227                let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
228                async move {
229                    let storage = join_load_task(spawn_blocking_in_current_span(move || {
230                        open_account_state_forest_storage(
231                            &path,
232                            &forest_storage_config,
233                            ACCOUNT_STATE_FOREST_STORAGE_DIR,
234                        )
235                    }))
236                    .await?;
237                    let forest = load_account_state_forest(storage, &db, latest_block_num).await?;
238                    verify_account_state_forest_consistency(&forest, &db).await?;
239                    Ok(forest)
240                }
241            }
242            .in_current_span(),
243        );
244        let (blockchain, account_tree, nullifier_tree, forest) = tokio::try_join!(
245            join_load_task(mmr_task),
246            join_load_task(account_tree_task),
247            join_load_task(nullifier_tree_task),
248            join_load_task(forest_task),
249        )?;
250
251        // Verify that tree roots match the expected roots from the database. This catches any
252        // divergence between persistent storage and the database caused by corruption or incomplete
253        // shutdown.
254        verify_tree_consistency(account_tree.root(), nullifier_tree.root(), &db).await?;
255
256        let account_tree = AccountTreeWithHistory::new(account_tree, latest_block_num);
257
258        // Initialize the proven tip from the block store.
259        let proven_tip_init = block_store
260            .load_proven_tip()
261            .map_err(StateInitializationError::ProvenTipLoadError)?;
262        let (proven_tip, _rx) = ProvenTipWriter::new(proven_tip_init);
263
264        // Committed-tip watch: fires after each successful apply_block.
265        let (committed_tip_tx, _rx) = watch::channel(latest_block_num);
266        let committed_tip_tx = Arc::new(committed_tip_tx);
267
268        let block_cache = BlockCache::new(BLOCK_CACHE_CAPACITY);
269        let proof_cache = ProofCache::new(PROOF_CACHE_CAPACITY);
270
271        // Create the initial snapshot from reader views of the just-loaded trees.
272        let initial_snapshot = Arc::new(StateSnapshot::new(
273            nullifier_tree
274                .reader()
275                .map_err(|e| StateInitializationError::NullifierTreeIoError(e.as_report()))?,
276            blockchain.clone(),
277            account_tree.reader(),
278            forest
279                .reader()
280                .map_err(|e| StateInitializationError::AccountStateForestIoError(e.as_report()))?,
281        ));
282        let latest_snapshot = Arc::new(ArcSwap::from(initial_snapshot));
283
284        // Assemble the write worker. It owns the writable trees and processes write requests
285        // serially, publishing a new snapshot after each committed block. The caller runs it; it
286        // exits when the shutdown token is cancelled or the `BlockWriter` (holding the only request
287        // sender) is dropped.
288        let (write_tx, write_rx) = mpsc::channel(1);
289        let block_writer = WriteWorker::new(
290            Arc::clone(&db),
291            Arc::clone(&block_store),
292            Arc::clone(&latest_snapshot),
293            Arc::clone(&committed_tip_tx),
294            block_cache.clone(),
295            write_rx,
296            nullifier_tree,
297            account_tree,
298            blockchain,
299            forest,
300            apply_block_thread_priority,
301        );
302        let state = Self {
303            data_directory: data_path.to_path_buf(),
304            db,
305            block_store,
306            latest_snapshot,
307            proven_tip,
308            committed_tip_tx,
309            block_cache,
310            proof_cache,
311        };
312
313        Ok(LoadedState { state, writer: block_writer, write_tx })
314    }
315
316    /// Loads the state with default options and starts its write worker, detaching the worker
317    /// task.
318    ///
319    /// Test-only helper for tests in sibling crates that don't manage the writer's lifecycle:
320    /// the detached writer exits once the returned [`BlockWriter`] is dropped. Hidden from public
321    /// docs and not part of the stable API.
322    ///
323    /// # Panics
324    ///
325    /// Panics if the state fails to load.
326    #[doc(hidden)]
327    pub async fn for_tests(data_path: &Path) -> (Arc<Self>, BlockWriter, ProofWriter) {
328        let (state, block_writer, proof_writer, _writer_task) =
329            Self::load(data_path, StorageOptions::default())
330                .await
331                .expect("state should load")
332                .start(CancellationToken::new());
333        (state, block_writer, proof_writer)
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use miden_node_db::sqlite::DbWriter;
340    use miden_node_utils::clap::StorageOptions;
341    use miden_node_utils::fee::{test_fee_params, test_protocol_config};
342    use miden_protocol::block::ValidatorConfig;
343    use miden_protocol::testing::random_secret_key::random_secret_key;
344
345    use super::State;
346    use crate::DataDirectory;
347    use crate::errors::{DatabaseError, StateInitializationError};
348    use crate::genesis::GenesisState;
349
350    async fn bootstrap_store(path: &std::path::Path) -> miden_protocol::Word {
351        let signer = random_secret_key();
352        let genesis = GenesisState::new(
353            Vec::new(),
354            test_fee_params(),
355            0,
356            ValidatorConfig::new(vec![signer.public_key()], 1).unwrap(),
357            test_protocol_config(),
358        )
359        .into_block()
360        .unwrap();
361        let commitment = genesis.protocol_config().to_commitment();
362        State::bootstrap(genesis, path).await.unwrap();
363        commitment
364    }
365
366    fn database_writer(path: &std::path::Path) -> DbWriter {
367        let database_path = DataDirectory::load(path.to_path_buf()).unwrap().database_path();
368        let (writer, _reader) = miden_node_db::sqlite::open(&database_path).unwrap();
369        writer
370    }
371
372    #[tokio::test]
373    async fn load_rejects_missing_genesis_protocol_config() {
374        let temp_dir = tempfile::tempdir().unwrap();
375        let commitment = bootstrap_store(temp_dir.path()).await;
376        database_writer(temp_dir.path())
377            .write::<_, DatabaseError, _>("delete genesis protocol config", move |tx| {
378                tx.execute("DELETE FROM protocol_configs WHERE commitment = ?1", &[&commitment])?;
379                Ok(())
380            })
381            .await
382            .unwrap();
383
384        let error = State::load(temp_dir.path(), StorageOptions::default())
385            .await
386            .err()
387            .expect("state load should fail");
388        assert!(matches!(
389            error,
390            StateInitializationError::GenesisProtocolConfigMissing { commitment: actual }
391                if actual == commitment
392        ));
393    }
394
395    #[tokio::test]
396    async fn load_rejects_corrupt_genesis_protocol_config() {
397        let temp_dir = tempfile::tempdir().unwrap();
398        let commitment = bootstrap_store(temp_dir.path()).await;
399        let mut bytes = miden_node_persistence::encode(&test_protocol_config());
400        bytes.push(0xff);
401        database_writer(temp_dir.path())
402            .write::<_, DatabaseError, _>("corrupt genesis protocol config", move |tx| {
403                tx.execute(
404                    "UPDATE protocol_configs SET protocol_config = ?1 WHERE commitment = ?2",
405                    &[&bytes, &commitment],
406                )?;
407                Ok(())
408            })
409            .await
410            .unwrap();
411
412        let error = State::load(temp_dir.path(), StorageOptions::default())
413            .await
414            .err()
415            .expect("state load should fail");
416        assert!(matches!(
417            error,
418            StateInitializationError::DatabaseError(DatabaseError::Persistence(_))
419        ));
420    }
421
422    #[tokio::test]
423    async fn state_view_returns_genesis_protocol_config() {
424        let temp_dir = tempfile::tempdir().unwrap();
425        let commitment = bootstrap_store(temp_dir.path()).await;
426
427        let loaded = State::load(temp_dir.path(), StorageOptions::default()).await.unwrap();
428        let protocol_config = loaded.state.view().get_protocol_config(commitment).await.unwrap();
429
430        assert_eq!(protocol_config, Some(test_protocol_config()));
431    }
432}