miden_objects/asset/vault/
partial.rs

1use alloc::vec::Vec;
2
3use miden_crypto::merkle::{InnerNodeInfo, SmtLeaf, SmtProof};
4use vm_core::utils::{Deserializable, Serializable};
5use vm_processor::Digest;
6
7use super::AssetVault;
8
9/// A partial representation of an asset vault, containing only proofs for a subset of assets.
10///
11/// Partial vault is used to provide verifiable access to specific assets in a vault
12/// without the need to provide the full vault data. It contains all required data for loading
13/// vault data into the transaction kernel for transaction execution.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct PartialVault {
16    /// Root of the asset vault tree.
17    root: Digest,
18    /// Merkle proofs for assets in an account, typically a subset of all assets.
19    vault_proofs: Vec<SmtProof>,
20}
21
22impl PartialVault {
23    /// Returns a new instance of partial vault with the specified root and vault proofs.
24    pub fn new(root: Digest, vault_proofs: Vec<SmtProof>) -> Self {
25        PartialVault { root, vault_proofs }
26    }
27
28    /// Returns the root of the partial vault.
29    pub fn root(&self) -> Digest {
30        self.root
31    }
32
33    /// Returns an iterator over all inner nodes in the Sparse Merkle Tree proofs.
34    ///
35    /// This is useful for reconstructing parts of the Sparse Merkle Tree or for
36    /// verification purposes.
37    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
38        self.vault_proofs.iter().flat_map(|proof| {
39            let leaf = proof.leaf();
40            proof.path().inner_nodes(leaf.index().value(), leaf.hash()).unwrap()
41        })
42    }
43
44    /// Returns an iterator over all leaves in the Sparse Merkle Tree proofs.
45    ///
46    /// Each item returned is a tuple containing the leaf index and a reference to the leaf.
47    pub fn leaves(&self) -> impl Iterator<Item = &SmtLeaf> {
48        self.vault_proofs.iter().map(SmtProof::leaf)
49    }
50}
51
52impl From<&AssetVault> for PartialVault {
53    fn from(value: &AssetVault) -> Self {
54        let root = value.root();
55        let vault_proofs: Vec<SmtProof> = value
56            .asset_tree()
57            .entries()
58            .map(|(key, _)| value.asset_tree().open(key))
59            .collect();
60
61        PartialVault { root, vault_proofs }
62    }
63}
64
65impl Serializable for PartialVault {
66    fn write_into<W: vm_core::utils::ByteWriter>(&self, target: &mut W) {
67        target.write(self.root);
68        target.write(&self.vault_proofs);
69    }
70}
71
72impl Deserializable for PartialVault {
73    fn read_from<R: vm_core::utils::ByteReader>(
74        source: &mut R,
75    ) -> Result<Self, vm_processor::DeserializationError> {
76        let root = source.read()?;
77        let vault_proofs = source.read()?;
78
79        Ok(PartialVault { root, vault_proofs })
80    }
81}