Skip to main content

miden_node_store/state/view/account/
mod.rs

1use std::collections::HashSet;
2
3use miden_node_proto::domain::account::{
4    AccountDetailRequest,
5    AccountDetails,
6    AccountStorageDetails,
7    AccountStorageMapDetails,
8    AccountStorageRequest,
9    AccountVaultDetails,
10    AccountVaultRequest,
11    GetAccountRequest,
12    GetAccountResponse,
13    SlotData,
14    StorageMapEntries,
15    StorageMapRequest,
16};
17use miden_node_tracing::instrument;
18use miden_protocol::account::{AccountId, AccountStorageHeader, StorageSlotName, StorageSlotType};
19use miden_protocol::block::BlockNumber;
20use miden_protocol::block::account_tree::AccountWitness;
21
22use super::{ScopedBlockNum, StateView};
23use crate::account_state_forest::AccountStorageMapResult;
24use crate::errors::{DatabaseError, GetAccountError};
25
26impl StateView {
27    /// Returns an account witness and optionally account details at a specific block.
28    ///
29    /// The witness is a Merkle proof of inclusion in the account tree, proving the account's
30    /// state commitment. If `details` is requested, the method also returns the account's code,
31    /// vault assets, and storage data. Account details are only available for public accounts.
32    ///
33    /// If `block_num` is provided, returns the state at that historical block; otherwise, returns
34    /// the latest state. Note that historical states are only available for recent blocks close
35    /// to the chain tip.
36    #[instrument]
37    pub async fn get_account(
38        &self,
39        get_account_request: GetAccountRequest,
40    ) -> Result<GetAccountResponse, GetAccountError> {
41        let GetAccountRequest { block_num, account_id, details } = get_account_request;
42
43        if details.is_some() && !account_id.is_public() {
44            return Err(GetAccountError::AccountNotPublic(account_id));
45        }
46
47        let (scoped_block, witness) = self.get_account_witness(block_num, account_id).await?;
48
49        let details = if let Some(request) = details {
50            Some(
51                self.fetch_public_account_details(account_id, scoped_block, &witness, request)
52                    .await?,
53            )
54        } else {
55            None
56        };
57
58        Ok(GetAccountResponse {
59            block_num: *scoped_block,
60            witness,
61            details,
62        })
63    }
64
65    /// Returns an account witness (Merkle proof of inclusion in the account tree) together with
66    /// the resolved block as a scoped block number.
67    ///
68    /// If `block_num` is provided, returns the witness at that historical block; otherwise,
69    /// returns the witness at the latest block. The tree resolution doubles as the tip
70    /// validation, so the returned block is ready for block-bounded database queries.
71    #[instrument]
72    async fn get_account_witness(
73        &self,
74        block_num: Option<BlockNumber>,
75        account_id: AccountId,
76    ) -> Result<(ScopedBlockNum, AccountWitness), GetAccountError> {
77        // Historical query: scope the requested block up front — a block beyond this view's tip is
78        // unknown, so a missing tree entry below can only mean it was pruned.
79        if let Some(requested_block) = block_num {
80            let scoped_block = self
81                .scope_block(requested_block)
82                .ok_or(GetAccountError::UnknownBlock(requested_block))?;
83            let witness = self
84                .with_inner_read_blocking(|inner_state| {
85                    inner_state.account_tree.open_at(account_id, *scoped_block)
86                })
87                .ok_or(GetAccountError::BlockPruned(*scoped_block))?;
88            Ok((scoped_block, witness))
89        } else {
90            // Latest query: the tree's latest state is the view's tip.
91            let witness = self.with_inner_read_blocking(|inner_state| {
92                inner_state.account_tree.open_latest(account_id)
93            });
94            Ok((self.tip(), witness))
95        }
96    }
97
98    /// Returns storage map details from the forest for a specific account and storage slot.
99    ///
100    /// The forest can only be used if all hashed keys in the storage map are known in the
101    /// reverse-key LRU cache. If any hashed key is unknown, the method returns `Ok(None)` to signal
102    /// that the caller should fall back to reconstructing the storage map details from the
103    /// database.
104    #[instrument]
105    fn get_storage_map_details_from_forest(
106        &self,
107        account_id: AccountId,
108        slot_name: &StorageSlotName,
109        block_num: ScopedBlockNum,
110    ) -> Result<Option<AccountStorageMapDetails>, DatabaseError> {
111        self.with_forest_read_blocking(|forest| {
112            match forest
113                .get_storage_map_details_for_all_entries(account_id, slot_name.clone(), *block_num)
114                .map_err(DatabaseError::MerkleError)?
115            {
116                AccountStorageMapResult::NotFound => Err(DatabaseError::StorageRootNotFound {
117                    account_id,
118                    slot_name: slot_name.to_string(),
119                    block_num: *block_num,
120                }),
121                AccountStorageMapResult::Details(details) => Ok(Some(details)),
122                AccountStorageMapResult::CannotReconstructKeysFromCache => Ok(None),
123            }
124        })
125    }
126
127    /// Returns vault details by reconstructing the vault from the database.
128    async fn reconstruct_vault_details_from_db(
129        &self,
130        account_id: AccountId,
131        block_num: ScopedBlockNum,
132    ) -> Result<AccountVaultDetails, DatabaseError> {
133        let assets = self.db.select_vault_at_block(account_id, block_num).await?;
134
135        if assets.len() > AccountVaultDetails::MAX_RETURN_ENTRIES {
136            return Ok(AccountVaultDetails::LimitExceeded);
137        }
138
139        let keys = assets.iter().map(miden_protocol::asset::Asset::id);
140
141        // The reverse-key caches are shared between the writer and all snapshots, so caching via
142        // the current snapshot's forest is visible everywhere.
143        self.with_forest_read_blocking(|forest| {
144            forest
145                .vault_key_cache
146                .put_many(keys.into_iter().map(|raw_key| (raw_key.hash(), raw_key)));
147        });
148
149        Ok(AccountVaultDetails::from_assets(assets))
150    }
151
152    /// Returns storage map details by reconstructing the storage map from the database.
153    async fn reconstruct_storage_map_details_from_db(
154        &self,
155        account_id: AccountId,
156        slot_name: StorageSlotName,
157        block_num: ScopedBlockNum,
158    ) -> Result<AccountStorageMapDetails, DatabaseError> {
159        let details = self
160            .db
161            .reconstruct_storage_map_from_db(
162                account_id,
163                slot_name,
164                block_num,
165                Some(AccountStorageMapDetails::MAX_RETURN_ENTRIES),
166            )
167            .await?;
168
169        if let StorageMapEntries::AllEntries(entries) = &details.entries {
170            self.with_forest_read_blocking(|forest| {
171                forest.cache_storage_map_keys(entries.iter().map(|(raw_key, _)| *raw_key));
172            });
173        }
174
175        Ok(details)
176    }
177
178    /// Fetches the account details (code, vault, storage) for a public account at the specified
179    /// block.
180    ///
181    /// This method queries the database to fetch the account state and processes the detail
182    /// request to return only the requested information.
183    ///
184    /// For specific key queries (`SlotData::MapKeys`), the forest is used to provide SMT proofs.
185    /// Returns an error if the forest doesn't have data for the requested slot.
186    /// All-entries queries (`SlotData::All`) use the forest when all hashed keys are known in the
187    /// reverse-key LRU cache, otherwise they fall back to database reconstruction.
188    #[instrument]
189    async fn fetch_public_account_details(
190        &self,
191        account_id: AccountId,
192        scoped_block: ScopedBlockNum,
193        witness: &AccountWitness,
194        detail_request: AccountDetailRequest,
195    ) -> Result<AccountDetails, GetAccountError> {
196        let AccountDetailRequest {
197            code_commitment,
198            vault_request,
199            storage_request,
200        } = detail_request;
201
202        if !account_id.is_public() {
203            return Err(GetAccountError::AccountNotPublic(account_id));
204        }
205
206        // Query account header and storage header together in a single DB call
207        let (account_header, storage_header) = self
208            .db
209            .select_account_header_with_storage_header_at_block(account_id, scoped_block)
210            .await?
211            .ok_or(GetAccountError::AccountNotFound(account_id, *scoped_block))?;
212
213        let should_apply_response_budget =
214            matches!(&storage_request, AccountStorageRequest::AllStorageMaps);
215        let storage_requests = expand_account_storage_request(storage_request, &storage_header);
216        validate_storage_map_requests(
217            account_id,
218            scoped_block,
219            &storage_requests,
220            &storage_header,
221        )?;
222
223        let account_code = match code_commitment {
224            Some(commitment) if commitment == account_header.code_commitment() => None,
225            Some(_) => {
226                self.db
227                    .select_account_code_by_commitment(account_header.code_commitment())
228                    .await?
229            },
230            None => None,
231        };
232
233        let vault_details = match vault_request {
234            AccountVaultRequest::All(commitment) if commitment == account_header.vault_root() => {
235                AccountVaultDetails::empty()
236            },
237            AccountVaultRequest::All(_) => {
238                let forest_details = self.with_forest_read_blocking(|forest| {
239                    forest.get_vault_details(account_id, *scoped_block).map_err(|err| {
240                        DatabaseError::DataCorrupted(format!(
241                            "failed to reconstruct vault for account {account_id} at block {}: {err}",
242                            *scoped_block,
243                        ))
244                    })
245                })?;
246
247                match forest_details {
248                    Some(details) => details,
249                    None => {
250                        self.reconstruct_vault_details_from_db(account_id, scoped_block).await?
251                    },
252                }
253            },
254            AccountVaultRequest::None => AccountVaultDetails::empty(),
255            AccountVaultRequest::Assets(asset_ids) => self.with_forest_read_blocking(|forest| {
256                forest
257                    .get_vault_details_for_assets(account_id, *scoped_block, asset_ids)
258                    .map_err(|err| {
259                        DatabaseError::DataCorrupted(format!(
260                            "failed to open vault for account {account_id} at block {}: {err}",
261                            *scoped_block,
262                        ))
263                    })
264            })?,
265        };
266
267        // Split storage map requests into two categories:
268        // - slots with explicit keys (including proofs)
269        // - slots with "all entries"
270        let mut storage_map_details =
271            Vec::<AccountStorageMapDetails>::with_capacity(storage_requests.len());
272        let mut map_keys_requests = Vec::new();
273        let mut all_entries_requests = Vec::new();
274        let mut storage_request_slots = Vec::with_capacity(storage_requests.len());
275
276        for (index, StorageMapRequest { slot_name, slot_data }) in
277            storage_requests.into_iter().enumerate()
278        {
279            storage_request_slots.push(slot_name.clone());
280            match slot_data {
281                SlotData::MapKeys(keys) => {
282                    map_keys_requests.push((index, slot_name, keys));
283                },
284                SlotData::All => {
285                    all_entries_requests.push((index, slot_name));
286                },
287            }
288        }
289
290        let mut storage_map_details_by_index = vec![None; storage_request_slots.len()];
291
292        // Handle slots with explicit key requests
293        if !map_keys_requests.is_empty() {
294            self.with_forest_read_blocking(|forest| {
295                for (index, slot_name, keys) in map_keys_requests {
296                    let details = forest
297                        .get_storage_map_details_for_keys(
298                            account_id,
299                            slot_name.clone(),
300                            *scoped_block,
301                            keys,
302                        )
303                        .ok_or_else(|| DatabaseError::StorageRootNotFound {
304                            account_id,
305                            slot_name: slot_name.to_string(),
306                            block_num: *scoped_block,
307                        })?
308                        .map_err(DatabaseError::MerkleError)?;
309                    storage_map_details_by_index[index] = Some(details);
310                }
311                Ok::<(), DatabaseError>(())
312            })?;
313        }
314
315        // Handle slots with "all entries" requests
316        for (index, slot_name) in all_entries_requests {
317            let details = match self.get_storage_map_details_from_forest(
318                account_id,
319                &slot_name,
320                scoped_block,
321            )? {
322                Some(details) => details,
323                None => {
324                    self.reconstruct_storage_map_details_from_db(
325                        account_id,
326                        slot_name,
327                        scoped_block,
328                    )
329                    .await?
330                },
331            };
332            storage_map_details_by_index[index] = Some(details);
333        }
334
335        for (details, slot_name) in
336            storage_map_details_by_index.into_iter().zip(storage_request_slots.iter())
337        {
338            let details = details.ok_or_else(|| DatabaseError::StorageRootNotFound {
339                account_id,
340                slot_name: slot_name.to_string(),
341                block_num: *scoped_block,
342            })?;
343            storage_map_details.push(details);
344        }
345
346        // In case of an "all storage maps" request we have to be careful: even with the per-slot
347        // limit of [`AccountStorageMapDetails::MAX_RETURN_ENTRIES`] we might go over the response
348        // size limit. Here we make sure that we're within that limit by potentially truncating the
349        // response.
350        if should_apply_response_budget {
351            return Ok(apply_all_storage_maps_response_budget(
352                *scoped_block,
353                witness,
354                account_header,
355                account_code,
356                vault_details,
357                storage_header,
358                storage_map_details,
359                storage_request_slots,
360                MAX_ALL_STORAGE_MAPS_RESPONSE_PAYLOAD_WITH_BUDGET_RESERVED_FOR_LIMIT_EXCEEDED_SLOTS,
361            ));
362        }
363
364        Ok(AccountDetails {
365            account_header,
366            account_code,
367            vault_details,
368            storage_details: AccountStorageDetails {
369                header: storage_header,
370                map_details: storage_map_details,
371            },
372        })
373    }
374}
375
376// HELPERS
377// ================================================================================================
378
379/// Expand [`AccountStorageRequest`] to a vector of slot requests.
380fn expand_account_storage_request(
381    storage_request: AccountStorageRequest,
382    storage_header: &AccountStorageHeader,
383) -> Vec<StorageMapRequest> {
384    match storage_request {
385        AccountStorageRequest::None => Vec::new(),
386        AccountStorageRequest::Explicit(requests) => requests,
387        AccountStorageRequest::AllStorageMaps => storage_header
388            .slots()
389            .filter(|slot| slot.slot_type() == StorageSlotType::Map)
390            .map(|slot| StorageMapRequest {
391                slot_name: slot.name().clone(),
392                slot_data: SlotData::All,
393            })
394            .collect(),
395    }
396}
397
398/// Validates that each requested slot exists in the account storage and is a map slot.
399///
400/// A request for a missing slot or a value slot is a client error. The forest has no map root for
401/// such a slot, so a forest lookup cannot tell this case apart from a missing storage root.
402fn validate_storage_map_requests(
403    account_id: AccountId,
404    block_num: ScopedBlockNum,
405    requests: &[StorageMapRequest],
406    storage_header: &AccountStorageHeader,
407) -> Result<(), GetAccountError> {
408    for StorageMapRequest { slot_name, .. } in requests {
409        let slot = storage_header.find_slot_header_by_name(slot_name).ok_or_else(|| {
410            GetAccountError::StorageSlotNotFound {
411                account_id,
412                slot_name: slot_name.clone(),
413                block_num: *block_num,
414            }
415        })?;
416        if slot.slot_type() != StorageSlotType::Map {
417            return Err(GetAccountError::StorageSlotNotMap {
418                account_id,
419                slot_name: slot_name.clone(),
420                block_num: *block_num,
421            });
422        }
423    }
424    Ok(())
425}
426
427mod response_budget;
428use response_budget::{
429    MAX_ALL_STORAGE_MAPS_RESPONSE_PAYLOAD_WITH_BUDGET_RESERVED_FOR_LIMIT_EXCEEDED_SLOTS,
430    apply_all_storage_maps_response_budget,
431};
432
433// NETWORK ACCOUNT CLASSIFICATION
434// ================================================================================================
435
436impl StateView {
437    /// Filters `account_ids` down to the subset classified as network accounts.
438    pub async fn filter_network_accounts(
439        &self,
440        account_ids: &[AccountId],
441    ) -> Result<HashSet<AccountId>, DatabaseError> {
442        self.db.filter_network_accounts(account_ids.to_vec()).await
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use miden_node_utils::fee::{test_fee_params, test_protocol_config};
449    use miden_protocol::account::auth::{AuthScheme, PublicKeyCommitment};
450    use miden_protocol::account::component::AccountComponentMetadata;
451    use miden_protocol::account::{
452        Account,
453        AccountBuilder,
454        AccountComponent,
455        AccountType,
456        StorageMap,
457        StorageMapKey,
458        StorageSlot,
459    };
460    use miden_protocol::block::ValidatorConfig;
461    use miden_protocol::testing::random_secret_key::random_secret_key;
462    use miden_protocol::{EMPTY_WORD, Word};
463    use miden_standards::account::auth::{Approver, AuthSingleSig};
464    use miden_standards::code_builder::CodeBuilder;
465
466    use super::*;
467    use crate::GenesisState;
468    use crate::state::State;
469
470    fn value_slot_name() -> StorageSlotName {
471        StorageSlotName::new("test::value").unwrap()
472    }
473
474    fn map_slot_name() -> StorageSlotName {
475        StorageSlotName::new("test::map").unwrap()
476    }
477
478    /// Returns a public account with one value slot and one map slot.
479    fn account_with_value_and_map_slots() -> Account {
480        let storage_map = StorageMap::with_entries(vec![(
481            StorageMapKey::from_index(1),
482            Word::from([1u32, 2, 3, 4]),
483        )])
484        .unwrap();
485        let component_storage = vec![
486            StorageSlot::with_value(value_slot_name(), Word::from([5u32, 6, 7, 8])),
487            StorageSlot::with_map(map_slot_name(), storage_map),
488        ];
489        let component_code = CodeBuilder::default()
490            .compile_component_code(
491                "test::interface",
492                "@account_procedure pub proc test push.1 end",
493            )
494            .unwrap();
495        let component = AccountComponent::new(
496            component_code,
497            component_storage,
498            AccountComponentMetadata::new("test"),
499        )
500        .unwrap();
501
502        AccountBuilder::new([3u8; 32])
503            .account_type(AccountType::Public)
504            .with_component(component)
505            .with_component(AuthSingleSig::new(Approver::new(
506                PublicKeyCommitment::from(EMPTY_WORD),
507                AuthScheme::Falcon512Poseidon2,
508            )))
509            .build_existing()
510            .unwrap()
511    }
512
513    async fn bootstrap_store(path: &std::path::Path, account: Account) {
514        let signer = random_secret_key();
515        let genesis_block = GenesisState::new(
516            vec![account],
517            test_fee_params(),
518            1,
519            ValidatorConfig::new(vec![signer.public_key()], 1)
520                .expect("validator config should be valid"),
521            test_protocol_config(),
522        )
523        .into_block()
524        .expect("genesis block should be created");
525
526        State::bootstrap(genesis_block, path).await.expect("store should bootstrap");
527    }
528
529    fn storage_request(account_id: AccountId, request: StorageMapRequest) -> GetAccountRequest {
530        GetAccountRequest {
531            account_id,
532            block_num: None,
533            details: Some(AccountDetailRequest {
534                code_commitment: None,
535                vault_request: AccountVaultRequest::None,
536                storage_request: AccountStorageRequest::Explicit(vec![request]),
537            }),
538        }
539    }
540
541    /// A storage request that names a missing slot, or a value slot, is a client error. It must not
542    /// surface as a database inconsistency.
543    #[tokio::test(flavor = "multi_thread")]
544    async fn explicit_storage_request_for_an_invalid_slot_is_a_request_error() {
545        let account = account_with_value_and_map_slots();
546        let account_id = account.id();
547        let data_directory = tempfile::tempdir().expect("tempdir should be created");
548        bootstrap_store(data_directory.path(), account).await;
549        let (state, _block_writer, _proof_writer) = State::for_tests(data_directory.path()).await;
550
551        let missing_slot = StorageSlotName::new("test::missing").unwrap();
552        let map_keys = SlotData::MapKeys(vec![StorageMapKey::from_index(1)]);
553
554        for slot_data in [SlotData::All, map_keys.clone()] {
555            let request = StorageMapRequest {
556                slot_name: missing_slot.clone(),
557                slot_data: slot_data.clone(),
558            };
559            let result = state.view().get_account(storage_request(account_id, request)).await;
560            assert!(
561                matches!(
562                    &result,
563                    Err(GetAccountError::StorageSlotNotFound { account_id: id, slot_name, .. })
564                        if *id == account_id && *slot_name == missing_slot
565                ),
566                "missing slot with {slot_data:?} must be a request error, got {:?}",
567                result.map(|_| ())
568            );
569
570            let request = StorageMapRequest {
571                slot_name: value_slot_name(),
572                slot_data: slot_data.clone(),
573            };
574            let result = state.view().get_account(storage_request(account_id, request)).await;
575            assert!(
576                matches!(
577                    &result,
578                    Err(GetAccountError::StorageSlotNotMap { account_id: id, slot_name, .. })
579                        if *id == account_id && *slot_name == value_slot_name()
580                ),
581                "value slot with {slot_data:?} must be a request error, got {:?}",
582                result.map(|_| ())
583            );
584        }
585
586        // Requests for the map slot still succeed.
587        for slot_data in [SlotData::All, map_keys] {
588            let request = StorageMapRequest { slot_name: map_slot_name(), slot_data };
589            let response = state
590                .view()
591                .get_account(storage_request(account_id, request))
592                .await
593                .expect("map slot request should succeed");
594            let details = response.details.expect("details should be returned");
595            assert_eq!(details.storage_details.map_details.len(), 1);
596            assert_eq!(details.storage_details.map_details[0].slot_name, map_slot_name());
597        }
598    }
599}