1use 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, miden_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::{COMPONENT, DataDirectory, DatabaseOptions};
37
38async 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
51const BLOCK_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(512).unwrap();
53
54const PROOF_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(512).unwrap();
56
57#[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 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
105impl State {
109 #[miden_instrument(
115 target = COMPONENT,
116 )]
117 pub async fn load(
118 data_path: &Path,
119 storage_options: StorageOptions,
120 ) -> Result<LoadedState, StateInitializationError> {
121 Self::load_with_database_options(data_path, storage_options, DatabaseOptions::default())
122 .await
123 }
124
125 #[miden_instrument(
131 target = COMPONENT,
132 )]
133 pub async fn load_with_database_options(
134 data_path: &Path,
135 storage_options: StorageOptions,
136 database_options: DatabaseOptions,
137 ) -> Result<LoadedState, StateInitializationError> {
138 let data_directory = DataDirectory::load(data_path.to_path_buf())
139 .map_err(StateInitializationError::DataDirectoryLoadError)?;
140
141 let block_store = Arc::new(
142 BlockStore::load(data_directory.block_store_dir())
143 .map_err(StateInitializationError::BlockStoreLoadError)?,
144 );
145
146 let database_filepath = data_directory.database_path();
147 let db = Arc::new(
148 Db::load_with_pool_size(
149 database_filepath.clone(),
150 database_options.connection_pool_size,
151 )
152 .await
153 .map_err(StateInitializationError::DatabaseLoadError)?,
154 );
155
156 let genesis_header = db
157 .select_genesis_block_header()
158 .await?
159 .ok_or(StateInitializationError::GenesisBlockMissing)?;
160 let genesis_protocol_config_commitment = genesis_header.protocol_config_commitment();
161 if db
162 .select_protocol_config_by_commitment(genesis_protocol_config_commitment)
163 .await?
164 .is_none()
165 {
166 return Err(StateInitializationError::GenesisProtocolConfigMissing {
167 commitment: genesis_protocol_config_commitment,
168 });
169 }
170
171 let latest_block_num = db
174 .select_block_header_by_block_num(None)
175 .await?
176 .ok_or(StateInitializationError::GenesisBlockMissing)?
177 .block_num();
178
179 let apply_block_thread_priority = storage_options.apply_block_thread_priority;
180
181 let (account_storage_config, nullifier_storage_config, forest_storage_config) = (
182 storage_options.account_tree.into(),
183 storage_options.nullifier_tree.into(),
184 storage_options.account_state_forest.into(),
185 );
186
187 let mmr_task = tokio::spawn(
193 {
194 let db = Arc::clone(&db);
195 async move { load_mmr(&db).await }
196 }
197 .in_current_span(),
198 );
199 let account_tree_task = tokio::spawn(
200 {
201 let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
202 async move {
203 let storage = join_load_task(spawn_blocking_in_current_span(move || {
204 open_tree_storage(&path, &account_storage_config, ACCOUNT_TREE_STORAGE_DIR)
205 }))
206 .await?;
207 load_account_tree(storage, &db).await
208 }
209 }
210 .in_current_span(),
211 );
212 let nullifier_tree_task = tokio::spawn(
213 {
214 let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
215 async move {
216 let storage = join_load_task(spawn_blocking_in_current_span(move || {
217 open_tree_storage(
218 &path,
219 &nullifier_storage_config,
220 NULLIFIER_TREE_STORAGE_DIR,
221 )
222 }))
223 .await?;
224 load_nullifier_tree(storage, &db).await
225 }
226 }
227 .in_current_span(),
228 );
229 let forest_task = tokio::spawn(
230 {
231 let (db, path) = (Arc::clone(&db), data_path.to_path_buf());
232 async move {
233 let storage = join_load_task(spawn_blocking_in_current_span(move || {
234 open_account_state_forest_storage(
235 &path,
236 &forest_storage_config,
237 ACCOUNT_STATE_FOREST_STORAGE_DIR,
238 )
239 }))
240 .await?;
241 let forest = load_account_state_forest(storage, &db, latest_block_num).await?;
242 verify_account_state_forest_consistency(&forest, &db).await?;
243 Ok(forest)
244 }
245 }
246 .in_current_span(),
247 );
248 let (blockchain, account_tree, nullifier_tree, forest) = tokio::try_join!(
249 join_load_task(mmr_task),
250 join_load_task(account_tree_task),
251 join_load_task(nullifier_tree_task),
252 join_load_task(forest_task),
253 )?;
254
255 verify_tree_consistency(account_tree.root(), nullifier_tree.root(), &db).await?;
259
260 let account_tree = AccountTreeWithHistory::new(account_tree, latest_block_num);
261
262 let proven_tip_init = block_store
264 .load_proven_tip()
265 .map_err(StateInitializationError::ProvenTipLoadError)?;
266 let (proven_tip, _rx) = ProvenTipWriter::new(proven_tip_init);
267
268 let (committed_tip_tx, _rx) = watch::channel(latest_block_num);
270 let committed_tip_tx = Arc::new(committed_tip_tx);
271
272 let block_cache = BlockCache::new(BLOCK_CACHE_CAPACITY);
273 let proof_cache = ProofCache::new(PROOF_CACHE_CAPACITY);
274
275 let initial_snapshot = Arc::new(StateSnapshot::new(
277 nullifier_tree
278 .reader()
279 .map_err(|e| StateInitializationError::NullifierTreeIoError(e.as_report()))?,
280 blockchain.clone(),
281 account_tree.reader(),
282 forest
283 .reader()
284 .map_err(|e| StateInitializationError::AccountStateForestIoError(e.as_report()))?,
285 ));
286 let latest_snapshot = Arc::new(ArcSwap::from(initial_snapshot));
287
288 let (write_tx, write_rx) = mpsc::channel(1);
293 let block_writer = WriteWorker::new(
294 Arc::clone(&db),
295 Arc::clone(&block_store),
296 Arc::clone(&latest_snapshot),
297 Arc::clone(&committed_tip_tx),
298 block_cache.clone(),
299 write_rx,
300 nullifier_tree,
301 account_tree,
302 blockchain,
303 forest,
304 apply_block_thread_priority,
305 );
306 let state = Self {
307 data_directory: data_path.to_path_buf(),
308 db,
309 block_store,
310 latest_snapshot,
311 proven_tip,
312 committed_tip_tx,
313 block_cache,
314 proof_cache,
315 };
316
317 Ok(LoadedState { state, writer: block_writer, write_tx })
318 }
319
320 #[doc(hidden)]
331 pub async fn for_tests(data_path: &Path) -> (Arc<Self>, BlockWriter, ProofWriter) {
332 let (state, block_writer, proof_writer, _writer_task) =
333 Self::load(data_path, StorageOptions::default())
334 .await
335 .expect("state should load")
336 .start(CancellationToken::new());
337 (state, block_writer, proof_writer)
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use miden_node_db::sqlite::DbWriter;
344 use miden_node_utils::clap::StorageOptions;
345 use miden_node_utils::fee::{test_fee_params, test_protocol_config};
346 use miden_protocol::block::ValidatorConfig;
347 use miden_protocol::testing::random_secret_key::random_secret_key;
348
349 use super::State;
350 use crate::DataDirectory;
351 use crate::errors::{DatabaseError, StateInitializationError};
352 use crate::genesis::GenesisState;
353
354 async fn bootstrap_store(path: &std::path::Path) -> miden_protocol::Word {
355 let signer = random_secret_key();
356 let genesis = GenesisState::new(
357 Vec::new(),
358 test_fee_params(),
359 0,
360 ValidatorConfig::new(vec![signer.public_key()], 1).unwrap(),
361 test_protocol_config(),
362 )
363 .into_block()
364 .unwrap();
365 let commitment = genesis.protocol_config().to_commitment();
366 State::bootstrap(genesis, path).await.unwrap();
367 commitment
368 }
369
370 fn database_writer(path: &std::path::Path) -> DbWriter {
371 let database_path = DataDirectory::load(path.to_path_buf()).unwrap().database_path();
372 let (writer, _reader) = miden_node_db::sqlite::open(&database_path).unwrap();
373 writer
374 }
375
376 #[tokio::test]
377 async fn load_rejects_missing_genesis_protocol_config() {
378 let temp_dir = tempfile::tempdir().unwrap();
379 let commitment = bootstrap_store(temp_dir.path()).await;
380 database_writer(temp_dir.path())
381 .write::<_, DatabaseError, _>("delete genesis protocol config", move |tx| {
382 tx.execute("DELETE FROM protocol_configs WHERE commitment = ?1", &[&commitment])?;
383 Ok(())
384 })
385 .await
386 .unwrap();
387
388 let error = State::load(temp_dir.path(), StorageOptions::default())
389 .await
390 .err()
391 .expect("state load should fail");
392 assert!(matches!(
393 error,
394 StateInitializationError::GenesisProtocolConfigMissing { commitment: actual }
395 if actual == commitment
396 ));
397 }
398
399 #[tokio::test]
400 async fn load_rejects_corrupt_genesis_protocol_config() {
401 let temp_dir = tempfile::tempdir().unwrap();
402 let commitment = bootstrap_store(temp_dir.path()).await;
403 let mut bytes = miden_node_persistence::encode(&test_protocol_config());
404 bytes.push(0xff);
405 database_writer(temp_dir.path())
406 .write::<_, DatabaseError, _>("corrupt genesis protocol config", move |tx| {
407 tx.execute(
408 "UPDATE protocol_configs SET protocol_config = ?1 WHERE commitment = ?2",
409 &[&bytes, &commitment],
410 )?;
411 Ok(())
412 })
413 .await
414 .unwrap();
415
416 let error = State::load(temp_dir.path(), StorageOptions::default())
417 .await
418 .err()
419 .expect("state load should fail");
420 assert!(matches!(
421 error,
422 StateInitializationError::DatabaseError(DatabaseError::Persistence(_))
423 ));
424 }
425
426 #[tokio::test]
427 async fn state_view_returns_genesis_protocol_config() {
428 let temp_dir = tempfile::tempdir().unwrap();
429 let commitment = bootstrap_store(temp_dir.path()).await;
430
431 let loaded = State::load(temp_dir.path(), StorageOptions::default()).await.unwrap();
432 let protocol_config = loaded.state.view().get_protocol_config(commitment).await.unwrap();
433
434 assert_eq!(protocol_config, Some(test_protocol_config()));
435 }
436}