miden-node-store 0.18.0

Miden node's state store component
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! Tree loading logic for the store state.
//!
//! This module handles loading and initializing the Merkle trees (account tree, nullifier tree,
//! and SMT forest) from `RocksDB`. Existing trees are loaded from disk; empty storage is rebuilt from
//! SQLite and persisted. Consistency checks detect divergence between `RocksDB` and SQLite after
//! loading.

use std::num::NonZeroUsize;
use std::path::Path;
use std::pin::pin;

use futures::TryStreamExt;
use miden_crypto::merkle::mmr::Mmr;
use miden_crypto::merkle::smt::{
    Backend,
    ForestPersistentBackend,
    PersistentBackendConfig,
    RocksDbStorage,
    SmtStorageReader,
};
use miden_node_tracing::{info, miden_instrument};
use miden_node_utils::clap::RocksDbOptions;
use miden_protocol::account::{AccountId, AccountStorageHeader, StorageSlotType};
use miden_protocol::block::account_tree::{AccountIdKey, AccountTree};
use miden_protocol::block::nullifier_tree::NullifierTree;
use miden_protocol::block::{BlockHeader, BlockNumber, Blockchain};
use miden_protocol::crypto::merkle::smt::{LargeSmt, LargeSmtError, SmtStorage};
use miden_protocol::{Felt, Word};

use crate::account_state_forest::AccountStateForest;
use crate::db::queries::{
    AccountCommitmentsPaged,
    NullifiersPaged,
    PublicAccountIdsPaged,
    PublicAccountStateRootsPaged,
};
use crate::db::{BlockHeaderCommitment, Db};
use crate::errors::{DatabaseError, StateInitializationError};
use crate::{COMPONENT, LOG_TARGET};

// CONSTANTS
// ================================================================================================

/// Directory name for the account tree storage within the data directory.
pub const ACCOUNT_TREE_STORAGE_DIR: &str = "accounttree";

/// Directory name for the nullifier tree storage within the data directory.
pub const NULLIFIER_TREE_STORAGE_DIR: &str = "nullifiertree";

/// Directory name for the account state forest storage within the data directory.
pub const ACCOUNT_STATE_FOREST_STORAGE_DIR: &str = "accountstateforest";

/// Page size for loading account commitments from the database during tree rebuilding. This limits
/// memory usage when rebuilding trees with millions of accounts.
const ACCOUNT_COMMITMENTS_PAGE_SIZE: NonZeroUsize = NonZeroUsize::new(10_000).unwrap();

/// Page size for loading nullifiers from the database during tree rebuilding. This limits memory
/// usage when rebuilding trees with millions of nullifiers.
const NULLIFIERS_PAGE_SIZE: NonZeroUsize = NonZeroUsize::new(10_000).unwrap();

/// Page size for loading public account IDs from the database during forest rebuilding. This limits
/// memory usage when rebuilding with millions of public accounts.
const PUBLIC_ACCOUNT_IDS_PAGE_SIZE: NonZeroUsize = NonZeroUsize::new(1_000).unwrap();

// STORAGE TYPE ALIAS
// ================================================================================================

/// The storage backend for trees.
pub type TreeStorage = RocksDbStorage;

/// The read-only snapshot storage backend for trees, used by in-memory state snapshots.
pub type TreeStorageReader = <TreeStorage as SmtStorage>::Reader;

// ERROR CONVERSION
// ================================================================================================

/// Converts a `LargeSmtError` into a `StateInitializationError`.
pub fn account_tree_large_smt_error_to_init_error(e: LargeSmtError) -> StateInitializationError {
    use miden_node_tracing::ErrorReport;
    match e {
        LargeSmtError::Merkle(merkle_error) => {
            StateInitializationError::DatabaseError(DatabaseError::MerkleError(merkle_error))
        },
        LargeSmtError::Storage(err) => {
            StateInitializationError::AccountTreeIoError(err.as_report())
        },
        err @ (LargeSmtError::RootMismatch { .. } | LargeSmtError::StorageNotEmpty) => {
            StateInitializationError::AccountTreeIoError(err.as_report())
        },
    }
}

/// Converts a block number to the leaf value format used in the nullifier tree.
///
/// This matches the format used by `NullifierBlock::from(BlockNumber)::into()`,
/// which is `[Felt::from(block_num), 0, 0, 0]`.
fn block_num_to_nullifier_leaf(block_num: BlockNumber) -> Word {
    Word::from([Felt::from(block_num), Felt::ZERO, Felt::ZERO, Felt::ZERO])
}

// PERSISTENT STORAGE LOADING
// ================================================================================================

/// Opens `RocksDB` storage for an account or nullifier tree.
#[miden_instrument(
    target = COMPONENT,
    name = "open_tree_storage",
    fields(path = domain),
)]
pub fn open_tree_storage(
    data_dir: &Path,
    storage_options: &RocksDbOptions,
    domain: &'static str,
) -> Result<RocksDbStorage, StateInitializationError> {
    let storage_path = data_dir.join(domain);
    let config = storage_options.with_path(&storage_path);
    fs_err::create_dir_all(&storage_path)
        .map_err(|e| StateInitializationError::AccountTreeIoError(e.to_string()))?;
    RocksDbStorage::open(config)
        .map_err(|e| StateInitializationError::AccountTreeIoError(e.to_string()))
}

/// Loads the account tree from `RocksDB`, populating empty storage from SQLite.
#[miden_instrument(
    target = COMPONENT,
)]
pub async fn load_account_tree(
    storage: RocksDbStorage,
    db: &Db,
) -> Result<AccountTree<LargeSmt<RocksDbStorage>>, StateInitializationError> {
    let has_data = storage
        .has_leaves()
        .map_err(|e| StateInitializationError::AccountTreeIoError(e.to_string()))?;
    if has_data {
        let smt = load_smt(storage)?;
        return AccountTree::new(smt).map_err(StateInitializationError::FailedToCreateAccountsTree);
    }

    info!(target: LOG_TARGET, "RocksDB account tree storage is empty, populating from SQLite");

    let mut smt = LargeSmt::with_entries(storage, std::iter::empty())
        .map_err(account_tree_large_smt_error_to_init_error)?;

    // Load account commitments in pages to avoid loading millions of entries at once
    let mut pages =
        pin!(db.pages(AccountCommitmentsPaged { page_size: ACCOUNT_COMMITMENTS_PAGE_SIZE }, None));
    while let Some(commitments) = pages.try_next().await? {
        let entries = commitments
            .into_iter()
            .map(|(id, commitment)| (AccountIdKey::from(id).as_word(), commitment));

        let mutations = smt
            .compute_mutations(entries)
            .map_err(account_tree_large_smt_error_to_init_error)?;
        smt.apply_mutations(mutations)
            .map_err(account_tree_large_smt_error_to_init_error)?;
    }

    AccountTree::new(smt).map_err(StateInitializationError::FailedToCreateAccountsTree)
}

/// Loads the nullifier tree from `RocksDB`, populating empty storage from SQLite.
#[miden_instrument(
    target = COMPONENT,
)]
pub async fn load_nullifier_tree(
    storage: RocksDbStorage,
    db: &Db,
) -> Result<NullifierTree<LargeSmt<RocksDbStorage>>, StateInitializationError> {
    let has_data = storage
        .has_leaves()
        .map_err(|e| StateInitializationError::NullifierTreeIoError(e.to_string()))?;
    if has_data {
        let smt = load_smt(storage)?;
        return Ok(NullifierTree::new_unchecked(smt));
    }

    info!(target: LOG_TARGET, "RocksDB nullifier tree storage is empty, populating from SQLite");

    let mut smt = LargeSmt::with_entries(storage, std::iter::empty())
        .map_err(account_tree_large_smt_error_to_init_error)?;

    // Load nullifiers in pages to avoid loading millions of entries at once
    let mut pages = pin!(db.pages(NullifiersPaged { page_size: NULLIFIERS_PAGE_SIZE }, None));
    while let Some(nullifiers) = pages.try_next().await? {
        let entries = nullifiers
            .into_iter()
            .map(|info| (info.nullifier.as_word(), block_num_to_nullifier_leaf(info.block_num)));

        let mutations = smt
            .compute_mutations(entries)
            .map_err(account_tree_large_smt_error_to_init_error)?;
        smt.apply_mutations(mutations)
            .map_err(account_tree_large_smt_error_to_init_error)?;
    }

    Ok(NullifierTree::new_unchecked(smt))
}

/// Opens `RocksDB` storage for the account state forest.
#[miden_instrument(
    target = COMPONENT,
    name = "open_forest_storage",
    fields(path = domain),
)]
pub fn open_account_state_forest_storage(
    data_dir: &Path,
    storage_options: &RocksDbOptions,
    domain: &'static str,
) -> Result<ForestPersistentBackend, StateInitializationError> {
    let storage_path = data_dir.join(domain);
    fs_err::create_dir_all(&storage_path)
        .map_err(|e| StateInitializationError::AccountStateForestIoError(e.to_string()))?;

    let max_open_files = usize::try_from(storage_options.max_open_fds).map_err(|_| {
        StateInitializationError::AccountStateForestIoError(format!(
            "invalid account state forest RocksDB max_open_fds: {}",
            storage_options.max_open_fds
        ))
    })?;
    let config = PersistentBackendConfig::new(&storage_path)
        .map_err(|e| StateInitializationError::AccountStateForestIoError(e.to_string()))?
        .with_cache_size_bytes(storage_options.cache_size_in_bytes)
        .with_max_open_files(max_open_files);

    ForestPersistentBackend::load(config)
        .map_err(|e| StateInitializationError::AccountStateForestIoError(e.to_string()))
}

/// Loads the account state forest from `RocksDB`, populating empty storage from SQLite.
#[miden_instrument(
    target = COMPONENT,
    fields(
        block.number = block_num,
    ),
)]
pub async fn load_account_state_forest(
    storage: ForestPersistentBackend,
    db: &Db,
    block_num: BlockNumber,
) -> Result<AccountStateForest<ForestPersistentBackend>, StateInitializationError> {
    let mut forest = AccountStateForest::from_backend(storage)
        .map_err(|e| StateInitializationError::AccountStateForestIoError(e.to_string()))?;

    if forest.lineage_count() != 0 {
        return Ok(forest);
    }

    info!(
        target: LOG_TARGET,
        "RocksDB account state forest storage is empty, populating from SQLite"
    );
    rebuild_account_state_forest(&mut forest, db, block_num).await?;
    Ok(forest)
}

// HELPER FUNCTIONS
// ================================================================================================

/// Loads an SMT from persistent storage.
pub fn load_smt<S: SmtStorage>(storage: S) -> Result<LargeSmt<S>, StateInitializationError> {
    LargeSmt::load(storage).map_err(account_tree_large_smt_error_to_init_error)
}

// TREE LOADING FUNCTIONS
// ================================================================================================

/// Loads the blockchain MMR from all block headers in the database.
#[miden_instrument(
    target = COMPONENT,
)]
pub async fn load_mmr(db: &Db) -> Result<Blockchain, StateInitializationError> {
    let latest_header = db.select_block_header_by_block_num(None).await?;
    let block_commitments = db.select_all_block_header_commitments().await?;

    // SAFETY: We assume the loaded MMR is valid and does not have more than u32::MAX entries.
    let mmr = Mmr::try_from_iter(block_commitments.into_iter().map(BlockHeaderCommitment::word))
        .expect("loaded MMR exceeds maximum allowed size");
    let chain_mmr = Blockchain::from_mmr_unchecked(mmr);

    verify_chain_mmr_consistency(&chain_mmr, latest_header.as_ref())?;

    Ok(chain_mmr)
}

fn verify_chain_mmr_consistency(
    chain_mmr: &Blockchain,
    latest_header: Option<&BlockHeader>,
) -> Result<(), StateInitializationError> {
    let Some(latest_header) = latest_header else {
        return Err(StateInitializationError::GenesisBlockMissing);
    };

    let block_num = latest_header.block_num();
    let expected_chain_commitment = latest_header.chain_commitment();
    let actual_chain_commitment = chain_mmr
        .peaks_at(block_num)
        .map_err(|source| StateInitializationError::ChainMmrLoadError { block_num, source })?
        .hash_peaks();

    if actual_chain_commitment != expected_chain_commitment {
        return Err(StateInitializationError::ChainMmrStorageDiverged {
            block_num,
            chain_mmr_commitment: actual_chain_commitment,
            block_header_commitment: expected_chain_commitment,
        });
    }

    Ok(())
}

/// Rebuilds SMT forest with storage map and vault Merkle paths for all public accounts.
#[miden_instrument(
    target = COMPONENT,
    fields(
        block.number = block_num,
    ),
)]
pub async fn rebuild_account_state_forest(
    forest: &mut AccountStateForest<impl Backend>,
    db: &Db,
    block_num: BlockNumber,
) -> Result<(), StateInitializationError> {
    use miden_protocol::account::AccountPatch;

    let mut pages =
        pin!(db.pages(PublicAccountIdsPaged { page_size: PUBLIC_ACCOUNT_IDS_PAGE_SIZE }, None));
    while let Some(account_ids) = pages.try_next().await? {
        let mut patches = Vec::with_capacity(account_ids.len());
        for account_id in account_ids {
            // TODO: Loading the full account from the database is inefficient and will need to go
            // away. <https://github.com/0xMiden/node/issues/1556>
            let account_info = db.select_account(account_id).await?;
            let account = account_info
                .details
                .ok_or(StateInitializationError::PublicAccountMissingDetails(account_id))?;

            // Convert the full account to a full-state patch
            let patch = AccountPatch::try_from(account).map_err(|e| {
                StateInitializationError::AccountToDeltaConversionFailed(e.to_string())
            })?;

            patches.push(patch);
        }

        forest
            .apply_rebuild_updates(block_num, patches)
            .map_err(StateInitializationError::AccountStateForestRebuild)?;
    }

    Ok(())
}

// CONSISTENCY VERIFICATION
// ================================================================================================

/// Verifies that tree roots match the expected roots from the latest block header.
///
/// This detects divergence between `RocksDB` and SQLite caused by corruption or incomplete shutdown.
///
/// # Arguments
/// * `account_tree_root` - Root of the loaded account tree
/// * `nullifier_tree_root` - Root of the loaded nullifier tree
/// * `db` - Database connection to fetch the latest block header
///
/// # Errors
/// Returns `StateInitializationError::TreeStorageDiverged` if any root doesn't match.
#[miden_instrument(
    target = COMPONENT,
)]
pub async fn verify_tree_consistency(
    account_tree_root: Word,
    nullifier_tree_root: Word,
    db: &Db,
) -> Result<(), StateInitializationError> {
    // Fetch the latest block header to get the expected roots
    let latest_header = db.select_block_header_by_block_num(None).await?;

    let (block_num, expected_account_root, expected_nullifier_root) = latest_header
        .map(|header| (header.block_num(), header.account_root(), header.nullifier_root()))
        .unwrap_or_default();

    // Verify account tree root
    if account_tree_root != expected_account_root {
        return Err(StateInitializationError::TreeStorageDiverged {
            tree_name: "Account",
            block_num,
            tree_root: account_tree_root,
            block_root: expected_account_root,
        });
    }

    // Verify nullifier tree root
    if nullifier_tree_root != expected_nullifier_root {
        return Err(StateInitializationError::TreeStorageDiverged {
            tree_name: "Nullifier",
            block_num,
            tree_root: nullifier_tree_root,
            block_root: expected_nullifier_root,
        });
    }

    Ok(())
}

/// Verifies that the account state forest matches latest public account roots from SQLite.
///
/// This check ensures persisted account state forest has not diverged from the latest
/// account states in SQLite. When the forest is rebuilt from SQLite, it will naturally
/// match; when loaded from `RocksDB`, this catches corruption or incomplete shutdown.
#[miden_instrument(
    target = COMPONENT,
)]
pub async fn verify_account_state_forest_consistency(
    forest: &AccountStateForest<impl Backend + Sync>,
    db: &Db,
) -> Result<(), StateInitializationError> {
    use rayon::iter::{IntoParallelIterator, ParallelIterator};

    let mut pages = pin!(
        db.pages(PublicAccountStateRootsPaged { page_size: PUBLIC_ACCOUNT_IDS_PAGE_SIZE }, None)
    );
    while let Some(accounts) = pages.try_next().await? {
        // Per-account checks are independent, so verify each page in parallel.
        accounts.into_par_iter().try_for_each(|account| {
            verify_account_state_forest_record(
                forest,
                account.account_id,
                account.vault_root,
                &account.storage_header,
            )
        })?;
    }

    Ok(())
}

fn verify_account_state_forest_record(
    forest: &AccountStateForest<impl Backend>,
    account_id: AccountId,
    vault_root: Word,
    storage_header: &AccountStorageHeader,
) -> Result<(), StateInitializationError> {
    let forest_vault_root = forest.get_latest_vault_root(account_id);
    if forest_vault_root != vault_root {
        return Err(StateInitializationError::AccountStateForestStorageDiverged {
            account_id,
            slot_name: None,
            forest_root: forest_vault_root,
            database_root: vault_root,
        });
    }

    for slot in storage_header.slots() {
        if slot.slot_type() != StorageSlotType::Map {
            continue;
        }

        let forest_root = forest.get_latest_storage_map_root(account_id, slot.name());
        let database_root = slot.value();
        if forest_root != database_root {
            return Err(StateInitializationError::AccountStateForestStorageDiverged {
                account_id,
                slot_name: Some(slot.name().to_string()),
                forest_root,
                database_root,
            });
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use miden_protocol::account::{
        AccountId,
        AccountStorageHeader,
        StorageSlotHeader,
        StorageSlotName,
        StorageSlotType,
    };
    use miden_protocol::block::BlockHeader;
    use miden_protocol::crypto::dsa::ecdsa_k256_keccak::SigningKey;
    use miden_protocol::crypto::merkle::mmr::Mmr;
    use miden_protocol::testing::account_id::ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE;

    use super::*;

    fn build_headers(count: u32) -> Vec<BlockHeader> {
        let mut mmr = Mmr::new();
        let mut headers = Vec::new();

        for block_num in 0..count {
            let chain_commitment = mmr.peaks().hash_peaks();
            let header = BlockHeader::mock(block_num, Some(chain_commitment), None, &[]);
            mmr.add(header.commitment()).expect("test MMR should accept block commitment");
            headers.push(header);
        }

        headers
    }

    #[test]
    fn chain_mmr_consistency_accepts_valid_loaded_chain() {
        let headers = build_headers(5);
        let mmr = Mmr::try_from_iter(headers.iter().map(BlockHeader::commitment))
            .expect("test MMR should build");
        let blockchain = Blockchain::from_mmr_unchecked(mmr);

        verify_chain_mmr_consistency(&blockchain, headers.last())
            .expect("valid loaded chain MMR should match latest header chain commitment");
    }

    #[test]
    fn chain_mmr_consistency_rejects_corrupted_loaded_chain() {
        let headers = build_headers(5);
        let mut commitments = headers.iter().map(BlockHeader::commitment).collect::<Vec<_>>();
        commitments[2] = Word::from([42, 0, 0, 0u32]);

        let mmr = Mmr::try_from_iter(commitments).expect("test MMR should build");
        let blockchain = Blockchain::from_mmr_unchecked(mmr);

        let error = verify_chain_mmr_consistency(&blockchain, headers.last())
            .expect_err("corrupted chain MMR should be rejected");

        assert_matches::assert_matches!(
            error,
            StateInitializationError::ChainMmrStorageDiverged {
                block_num,
                chain_mmr_commitment,
                block_header_commitment,
            } if block_num == headers.last().unwrap().block_num()
                && chain_mmr_commitment != block_header_commitment
                && block_header_commitment == headers.last().unwrap().chain_commitment()
        );
    }

    #[tokio::test]
    #[miden_node_test_macro::enable_logging]
    async fn load_mmr_rejects_chain_mmr_mismatch_from_database() {
        let temp_dir = tempfile::tempdir().expect("temp directory should be created");
        let db_path = temp_dir.path().join("store.sqlite");
        crate::db::bootstrap_database(&db_path).expect("test database should bootstrap");

        let headers = build_headers(5);
        let signing_key = SigningKey::new();
        let db = crate::db::Db::load(db_path).await.expect("test database should load");

        db.writer()
            .write::<_, DatabaseError, _>("insert corrupted block headers", move |tx| {
                for header in &headers {
                    let signatures = miden_protocol::block::BlockSignatures::new(vec![
                        signing_key.sign(header.commitment()),
                    ])
                    .expect("one signature is within bounds");
                    crate::db::queries::insert_block_header(tx, header, &signatures)?;
                }

                // Corrupt the stored commitment of one header so it disagrees with the header it
                // was stored alongside.
                tx.execute(
                    "UPDATE block_headers SET commitment = ?1 WHERE block_num = ?2",
                    &[&Word::from([42, 0, 0, 0u32]), &BlockNumber::from(2)],
                )?;

                Ok(())
            })
            .await
            .expect("test block headers should be inserted");

        let error = load_mmr(&db)
            .await
            .expect_err("startup MMR load should reject inconsistent block headers");

        assert_matches::assert_matches!(
            error,
            StateInitializationError::ChainMmrStorageDiverged { .. }
        );
    }

    #[test]
    fn account_state_forest_consistency_detects_storage_map_root_mismatch() {
        let account_id = AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE)
            .expect("test account ID should be valid");
        let slot_name =
            StorageSlotName::new("account::balances").expect("slot name should be valid");
        let expected_storage_root = Word::from([1, 0, 0, 0u32]);
        let storage_header = AccountStorageHeader::new(vec![StorageSlotHeader::new(
            slot_name.clone(),
            StorageSlotType::Map,
            expected_storage_root,
        )])
        .expect("storage header should be valid");
        let forest = AccountStateForest::new();

        let error = verify_account_state_forest_record(
            &forest,
            account_id,
            AccountStateForest::empty_smt_root(),
            &storage_header,
        )
        .expect_err("storage map root mismatch should be detected");

        assert_matches::assert_matches!(
            error,
            StateInitializationError::AccountStateForestStorageDiverged {
                account_id: actual_account_id,
                slot_name: Some(actual_slot_name),
                forest_root,
                database_root,
            } if actual_account_id == account_id
                && actual_slot_name == slot_name.to_string()
                && forest_root == AccountStateForest::empty_smt_root()
                && database_root == expected_storage_root
        );
    }

    #[test]
    fn account_state_forest_consistency_detects_vault_root_mismatch() {
        let account_id = AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE)
            .expect("test account ID should be valid");
        let expected_vault_root = Word::from([2, 0, 0, 0u32]);
        let storage_header =
            AccountStorageHeader::new(Vec::new()).expect("storage header should be valid");
        let forest = AccountStateForest::new();

        let error = verify_account_state_forest_record(
            &forest,
            account_id,
            expected_vault_root,
            &storage_header,
        )
        .expect_err("vault root mismatch should be detected");

        assert_matches::assert_matches!(
            error,
            StateInitializationError::AccountStateForestStorageDiverged {
                account_id: actual_account_id,
                slot_name: None,
                forest_root,
                database_root,
            } if actual_account_id == account_id
                && forest_root == AccountStateForest::empty_smt_root()
                && database_root == expected_vault_root
        );
    }
}