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, 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
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 #[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 #[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 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 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_tree_consistency(account_tree.root(), nullifier_tree.root(), &db).await?;
255
256 let account_tree = AccountTreeWithHistory::new(account_tree, latest_block_num);
257
258 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 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 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 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 #[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}