Skip to main content

miden_protocol/account/component/
mod.rs

1use alloc::vec::Vec;
2
3use miden_mast_package::Package;
4use miden_processor::mast::MastNodeExt;
5
6mod metadata;
7pub use metadata::*;
8
9pub mod storage;
10pub use storage::*;
11
12mod code;
13pub use code::AccountComponentCode;
14
15use crate::MastForest;
16use crate::account::{AccountProcedureRoot, StorageSlot};
17use crate::assembly::Path;
18use crate::errors::AccountError;
19
20/// The attribute name used to mark the authentication procedure in an account component.
21const AUTH_SCRIPT_ATTRIBUTE: &str = "auth_script";
22
23/// The attribute name used to mark a procedure as a member of an account component's interface.
24const ACCOUNT_PROCEDURE_ATTRIBUTE: &str = "account_procedure";
25
26// ACCOUNT COMPONENT
27// ================================================================================================
28
29/// An [`AccountComponent`] defines a [`Package`] of code and the initial value and types of the
30/// [`StorageSlot`]s it accesses.
31///
32/// One or more components can be used to build [`AccountCode`](crate::account::AccountCode) and
33/// [`AccountStorage`](crate::account::AccountStorage).
34///
35/// Each component is independent of other components and can only access its own storage slots.
36/// Each component defines its own storage layout starting at index 0 up to the length of the
37/// storage slots vector.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct AccountComponent {
40    pub(super) code: AccountComponentCode,
41    pub(super) storage_slots: Vec<StorageSlot>,
42    pub(super) metadata: AccountComponentMetadata,
43}
44
45impl AccountComponent {
46    // CONSTRUCTORS
47    // --------------------------------------------------------------------------------------------
48
49    /// Returns a new [`AccountComponent`] constructed from the provided `library`,
50    /// `storage_slots`, and `metadata`.
51    ///
52    /// Procedures exported from the provided code that are marked with the `@account_procedure`
53    /// attribute or with `@auth_script` will become members of the account's public interface when
54    /// added to an [`AccountCode`](crate::account::AccountCode).
55    ///
56    /// # Errors
57    ///
58    /// The following list of errors is exhaustive and can be relied upon for `expect`ing the call
59    /// to this function. It is recommended that custom components ensure these conditions by design
60    /// or in their fallible constructors.
61    ///
62    /// Returns an error if:
63    /// - The number of given [`StorageSlot`]s exceeds 255.
64    pub fn new(
65        code: impl Into<AccountComponentCode>,
66        storage_slots: Vec<StorageSlot>,
67        metadata: AccountComponentMetadata,
68    ) -> Result<Self, AccountError> {
69        // Check that we have less than 256 storage slots.
70        u8::try_from(storage_slots.len())
71            .map_err(|_| AccountError::StorageTooManySlots(storage_slots.len() as u64))?;
72
73        Ok(Self {
74            code: code.into(),
75            storage_slots,
76            metadata,
77        })
78    }
79
80    /// Creates an [`AccountComponent`] from a [`Package`] using [`InitStorageData`].
81    ///
82    /// This method provides type safety by leveraging the component's metadata to validate
83    /// storage initialization data. The package must contain explicit account component metadata.
84    ///
85    /// # Arguments
86    ///
87    /// * `package` - The package containing the account component metadata
88    /// * `init_storage_data` - The initialization data for storage slots
89    ///
90    /// # Errors
91    ///
92    /// Returns an error if:
93    /// - The package does not contain account component metadata
94    /// - The metadata cannot be deserialized from the package
95    /// - The storage initialization fails due to invalid or missing data
96    /// - The component creation fails
97    pub fn from_package(
98        package: &Package,
99        init_storage_data: &InitStorageData,
100    ) -> Result<Self, AccountError> {
101        let metadata = AccountComponentMetadata::try_from(package)?;
102        let library = package.clone();
103
104        let component_code = AccountComponentCode::from(library);
105        Self::from_library(&component_code, &metadata, init_storage_data)
106    }
107
108    /// Creates an [`AccountComponent`] from an [`AccountComponentCode`] and
109    /// [`AccountComponentMetadata`].
110    ///
111    /// This method provides type safety by leveraging the component's metadata to validate
112    /// the passed storage initialization data ([`InitStorageData`]).
113    ///
114    /// # Arguments
115    ///
116    /// * `library` - The component's assembled code
117    /// * `metadata` - The component's metadata, which describes the storage layout
118    /// * `init_storage_data` - The initialization data for storage slots
119    ///
120    /// # Errors
121    ///
122    /// Returns an error if:
123    /// - The storage initialization fails due to invalid or missing data
124    /// - The component creation fails
125    pub fn from_library(
126        library: &AccountComponentCode,
127        metadata: &AccountComponentMetadata,
128        init_storage_data: &InitStorageData,
129    ) -> Result<Self, AccountError> {
130        let storage_slots = metadata
131            .storage_schema()
132            .build_storage_slots(init_storage_data)
133            .map_err(|err| {
134                AccountError::other_with_source("failed to instantiate account component", err)
135            })?;
136
137        AccountComponent::new(library.clone(), storage_slots, metadata.clone())
138    }
139
140    // ACCESSORS
141    // --------------------------------------------------------------------------------------------
142
143    /// Returns the number of storage slots accessible from this component.
144    pub fn storage_size(&self) -> u8 {
145        u8::try_from(self.storage_slots.len())
146            .expect("storage slots len should fit in u8 per the constructor")
147    }
148
149    /// Returns a reference to the underlying [`AccountComponentCode`] of this component.
150    pub fn component_code(&self) -> &AccountComponentCode {
151        &self.code
152    }
153
154    /// Returns a reference to the underlying [`MastForest`] of this component.
155    pub fn mast_forest(&self) -> &MastForest {
156        self.code.mast_forest()
157    }
158
159    /// Returns a slice of the underlying [`StorageSlot`]s of this component.
160    pub fn storage_slots(&self) -> &[StorageSlot] {
161        self.storage_slots.as_slice()
162    }
163
164    /// Returns the component metadata.
165    pub fn metadata(&self) -> &AccountComponentMetadata {
166        &self.metadata
167    }
168
169    /// Returns the storage schema associated with this component.
170    pub fn storage_schema(&self) -> &StorageSchema {
171        self.metadata.storage_schema()
172    }
173
174    /// Returns an iterator over ([`AccountProcedureRoot`], is_auth) for all interface procedures
175    /// in this component.
176    ///
177    /// A procedure is considered an authentication procedure if it has the `@auth_script`
178    /// attribute. A procedure is part of the component interface if it has either the
179    /// `@account_procedure` or `@auth_script` attributes.
180    pub fn procedures(&self) -> impl Iterator<Item = (AccountProcedureRoot, bool)> + '_ {
181        self.code.exports().map(|proc_export| {
182            // When the export has a node id, use the forest node digest as the source of truth.
183            // This keeps procedure roots tied to the actual component MAST forest.
184            let digest = if let Some(node) = proc_export.node {
185                self.code
186                    .mast_forest()
187                    .get_node_by_id(node)
188                    .expect("export node not in the forest")
189                    .digest()
190            } else {
191                proc_export.digest
192            };
193            let is_auth = proc_export.attributes.has(AUTH_SCRIPT_ATTRIBUTE);
194            (AccountProcedureRoot::from_raw(digest), is_auth)
195        })
196    }
197
198    /// Returns the [`AccountProcedureRoot`] of the procedure with the specified path, or `None`
199    /// if it was not found in this component's library.
200    pub fn get_procedure_root_by_path(
201        &self,
202        proc_name: impl AsRef<Path>,
203    ) -> Option<AccountProcedureRoot> {
204        self.code.get_procedure_root_by_path(proc_name)
205    }
206
207    /// Returns `true` if `root` is the procedure root of any procedure exported by this
208    /// component.
209    pub fn has_procedure(&self, root: AccountProcedureRoot) -> bool {
210        self.procedures().any(|(proc_root, _)| proc_root == root)
211    }
212}
213
214impl From<AccountComponent> for AccountComponentCode {
215    fn from(component: AccountComponent) -> Self {
216        component.code
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use alloc::string::ToString;
223
224    use miden_mast_package::{Section, SectionId};
225    use semver::Version;
226
227    use super::*;
228    use crate::testing::account_code::CODE;
229    use crate::testing::assembler::assemble_test_library;
230    use crate::utils::serde::Serializable;
231
232    #[test]
233    fn test_extract_metadata_from_package() {
234        // Create a simple library for testing
235        let library =
236            assemble_test_library("test-extract-metadata", "test::extract_metadata", CODE);
237
238        // Test with metadata
239        let metadata = AccountComponentMetadata::new("test_component")
240            .with_description("A test component")
241            .with_version(Version::new(1, 0, 0));
242
243        let metadata_bytes = metadata.to_bytes();
244        let mut package_with_metadata = library.clone();
245        package_with_metadata
246            .sections
247            .push(Section::new(SectionId::ACCOUNT_COMPONENT_METADATA, metadata_bytes.clone()));
248
249        let extracted_metadata =
250            AccountComponentMetadata::try_from(&package_with_metadata).unwrap();
251        assert_eq!(extracted_metadata.name(), "test_component");
252
253        // Test without metadata - should fail
254        let package_without_metadata = library;
255
256        let result = AccountComponentMetadata::try_from(&package_without_metadata);
257        assert!(result.is_err());
258        let error_msg = result.unwrap_err().to_string();
259        assert!(error_msg.contains("package does not contain account component metadata"));
260    }
261
262    #[test]
263    fn test_from_library_with_init_data() {
264        // Create a simple library for testing
265        let library =
266            assemble_test_library("test-from-library-init-data", "test::from_library", CODE);
267        let component_code = AccountComponentCode::from(library.clone());
268
269        // Create metadata for the component
270        let metadata = AccountComponentMetadata::new("test_component")
271            .with_description("A test component")
272            .with_version(Version::new(1, 0, 0));
273
274        // Test with empty init data - this tests the complete workflow:
275        // Package + Metadata -> AccountComponent
276        let init_data = InitStorageData::default();
277        let component =
278            AccountComponent::from_library(&component_code, &metadata, &init_data).unwrap();
279
280        // Verify the component was created correctly
281        assert_eq!(component.storage_size(), 0);
282
283        // Test without metadata - should fail
284        let package_without_metadata = library;
285
286        let result = AccountComponent::from_package(&package_without_metadata, &init_data);
287        assert!(result.is_err());
288        let error_msg = result.unwrap_err().to_string();
289        assert!(error_msg.contains("package does not contain account component metadata"));
290    }
291}