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