miden_objects/account/storage/
mod.rs

1use alloc::string::ToString;
2use alloc::vec::Vec;
3
4use super::{
5    AccountError,
6    AccountStorageDelta,
7    ByteReader,
8    ByteWriter,
9    Deserializable,
10    DeserializationError,
11    Felt,
12    Hasher,
13    Serializable,
14    Word,
15};
16use crate::account::{AccountComponent, AccountType};
17
18mod slot;
19pub use slot::{StorageSlot, StorageSlotType};
20
21mod map;
22pub use map::{PartialStorageMap, StorageMap};
23
24mod header;
25pub use header::{AccountStorageHeader, StorageSlotHeader};
26
27mod partial;
28pub use partial::PartialStorage;
29
30// ACCOUNT STORAGE
31// ================================================================================================
32
33/// Account storage is composed of a variable number of index-addressable [StorageSlot]s up to
34/// 255 slots in total.
35///
36/// Each slot has a type which defines its size and structure. Currently, the following types are
37/// supported:
38/// - [StorageSlot::Value]: contains a single [Word] of data (i.e., 32 bytes).
39/// - [StorageSlot::Map]: contains a [StorageMap] which is a key-value map where both keys and
40///   values are [Word]s. The value of a storage slot containing a map is the commitment to the
41///   underlying map.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct AccountStorage {
44    slots: Vec<StorageSlot>,
45}
46
47impl AccountStorage {
48    /// The maximum number of storage slots allowed in an account storage.
49    pub const MAX_NUM_STORAGE_SLOTS: usize = 255;
50
51    // CONSTRUCTOR
52    // --------------------------------------------------------------------------------------------
53
54    /// Returns a new instance of account storage initialized with the provided items.
55    ///
56    /// # Errors
57    ///
58    /// Returns an error if:
59    /// - The number of [`StorageSlot`]s exceeds 255.
60    pub fn new(slots: Vec<StorageSlot>) -> Result<AccountStorage, AccountError> {
61        let num_slots = slots.len();
62
63        if num_slots > Self::MAX_NUM_STORAGE_SLOTS {
64            return Err(AccountError::StorageTooManySlots(num_slots as u64));
65        }
66
67        Ok(Self { slots })
68    }
69
70    /// Creates an [`AccountStorage`] from the provided components' storage slots.
71    ///
72    /// If the account type is faucet the reserved slot (slot 0) will be initialized.
73    /// - For Fungible Faucets the value is [`StorageSlot::empty_value`].
74    /// - For Non-Fungible Faucets the value is [`StorageSlot::empty_map`].
75    ///
76    /// If the storage needs to be initialized with certain values in that slot, those can be added
77    /// after construction with the standard set methods for items and maps.
78    ///
79    /// # Errors
80    ///
81    /// Returns an error if:
82    /// - The number of [`StorageSlot`]s of all components exceeds 255.
83    pub(super) fn from_components(
84        components: &[AccountComponent],
85        account_type: AccountType,
86    ) -> Result<AccountStorage, AccountError> {
87        let mut storage_slots = match account_type {
88            AccountType::FungibleFaucet => vec![StorageSlot::empty_value()],
89            AccountType::NonFungibleFaucet => vec![StorageSlot::empty_map()],
90            _ => vec![],
91        };
92
93        storage_slots
94            .extend(components.iter().flat_map(|component| component.storage_slots()).cloned());
95
96        Self::new(storage_slots)
97    }
98
99    // PUBLIC ACCESSORS
100    // --------------------------------------------------------------------------------------------
101
102    /// Returns a commitment to this storage.
103    pub fn commitment(&self) -> Word {
104        build_slots_commitment(&self.slots)
105    }
106
107    /// Returns the number of slots in the account's storage.
108    pub fn num_slots(&self) -> u8 {
109        // SAFETY: The constructors of account storage ensure that the number of slots fits into a
110        // u8.
111        self.slots.len() as u8
112    }
113
114    /// Returns a reference to the storage slots.
115    pub fn slots(&self) -> &Vec<StorageSlot> {
116        &self.slots
117    }
118
119    /// Returns an [AccountStorageHeader] for this account storage.
120    pub fn to_header(&self) -> AccountStorageHeader {
121        AccountStorageHeader::new(
122            self.slots.iter().map(|slot| (slot.slot_type(), slot.value())).collect(),
123        )
124    }
125
126    /// Returns an item from the storage at the specified index.
127    ///
128    /// # Errors:
129    /// - If the index is out of bounds
130    pub fn get_item(&self, index: u8) -> Result<Word, AccountError> {
131        self.slots
132            .get(index as usize)
133            .ok_or(AccountError::StorageIndexOutOfBounds {
134                slots_len: self.slots.len() as u8,
135                index,
136            })
137            .map(|slot| slot.value())
138    }
139
140    /// Returns a map item from a map located in storage at the specified index.
141    ///
142    /// # Errors:
143    /// - If the index is out of bounds
144    /// - If the [StorageSlot] is not [StorageSlotType::Map]
145    pub fn get_map_item(&self, index: u8, key: Word) -> Result<Word, AccountError> {
146        match self.slots.get(index as usize).ok_or(AccountError::StorageIndexOutOfBounds {
147            slots_len: self.slots.len() as u8,
148            index,
149        })? {
150            StorageSlot::Map(map) => Ok(map.get(&key)),
151            _ => Err(AccountError::StorageSlotNotMap(index)),
152        }
153    }
154
155    /// Converts storage slots of this account storage into a vector of field elements.
156    ///
157    /// This is done by first converting each storage slot into exactly 8 elements as follows:
158    /// ```text
159    /// [STORAGE_SLOT_VALUE, storage_slot_type, 0, 0, 0]
160    /// ```
161    /// And then concatenating the resulting elements into a single vector.
162    pub fn as_elements(&self) -> Vec<Felt> {
163        slots_as_elements(self.slots())
164    }
165
166    // STATE MUTATORS
167    // --------------------------------------------------------------------------------------------
168
169    /// Applies the provided delta to this account storage.
170    ///
171    /// # Errors:
172    /// - If the updates violate storage constraints.
173    pub(super) fn apply_delta(&mut self, delta: &AccountStorageDelta) -> Result<(), AccountError> {
174        let len = self.slots.len() as u8;
175
176        // update storage maps
177        for (&idx, map) in delta.maps().iter() {
178            let storage_slot = self
179                .slots
180                .get_mut(idx as usize)
181                .ok_or(AccountError::StorageIndexOutOfBounds { slots_len: len, index: idx })?;
182
183            let storage_map = match storage_slot {
184                StorageSlot::Map(map) => map,
185                _ => return Err(AccountError::StorageSlotNotMap(idx)),
186            };
187
188            storage_map.apply_delta(map);
189        }
190
191        // update storage values
192        for (&idx, &value) in delta.values().iter() {
193            self.set_item(idx, value)?;
194        }
195
196        Ok(())
197    }
198
199    /// Updates the value of the storage slot at the specified index.
200    ///
201    /// This method should be used only to update value slots. For updating values
202    /// in storage maps, please see [AccountStorage::set_map_item()].
203    ///
204    /// # Errors:
205    /// - If the index is out of bounds
206    /// - If the [StorageSlot] is not [StorageSlotType::Value]
207    pub fn set_item(&mut self, index: u8, value: Word) -> Result<Word, AccountError> {
208        // check if index is in bounds
209        let num_slots = self.slots.len();
210
211        if index as usize >= num_slots {
212            return Err(AccountError::StorageIndexOutOfBounds {
213                slots_len: self.slots.len() as u8,
214                index,
215            });
216        }
217
218        let old_value = match self.slots[index as usize] {
219            StorageSlot::Value(value) => value,
220            // return an error if the type != Value
221            _ => return Err(AccountError::StorageSlotNotValue(index)),
222        };
223
224        // update the value of the storage slot
225        self.slots[index as usize] = StorageSlot::Value(value);
226
227        Ok(old_value)
228    }
229
230    /// Updates the value of a key-value pair of a storage map at the specified index.
231    ///
232    /// This method should be used only to update storage maps. For updating values
233    /// in storage slots, please see [AccountStorage::set_item()].
234    ///
235    /// # Errors:
236    /// - If the index is out of bounds
237    /// - If the [StorageSlot] is not [StorageSlotType::Map]
238    pub fn set_map_item(
239        &mut self,
240        index: u8,
241        key: Word,
242        value: Word,
243    ) -> Result<(Word, Word), AccountError> {
244        // check if index is in bounds
245        let num_slots = self.slots.len();
246
247        if index as usize >= num_slots {
248            return Err(AccountError::StorageIndexOutOfBounds {
249                slots_len: self.slots.len() as u8,
250                index,
251            });
252        }
253
254        let storage_map = match self.slots[index as usize] {
255            StorageSlot::Map(ref mut map) => map,
256            _ => return Err(AccountError::StorageSlotNotMap(index)),
257        };
258
259        // get old map root to return
260        let old_root = storage_map.root();
261
262        // update the key-value pair in the map
263        let old_value = storage_map.insert(key, value);
264
265        Ok((old_root, old_value))
266    }
267}
268
269// ITERATORS
270// ================================================================================================
271
272impl IntoIterator for AccountStorage {
273    type Item = StorageSlot;
274    type IntoIter = alloc::vec::IntoIter<StorageSlot>;
275
276    fn into_iter(self) -> Self::IntoIter {
277        self.slots.into_iter()
278    }
279}
280
281// HELPER FUNCTIONS
282// ------------------------------------------------------------------------------------------------
283
284/// Converts given slots into field elements
285fn slots_as_elements(slots: &[StorageSlot]) -> Vec<Felt> {
286    slots
287        .iter()
288        .flat_map(|slot| StorageSlotHeader::from(slot).as_elements())
289        .collect()
290}
291
292/// Computes the commitment to the given slots
293pub fn build_slots_commitment(slots: &[StorageSlot]) -> Word {
294    let elements = slots_as_elements(slots);
295    Hasher::hash_elements(&elements)
296}
297
298// SERIALIZATION
299// ================================================================================================
300
301impl Serializable for AccountStorage {
302    fn write_into<W: ByteWriter>(&self, target: &mut W) {
303        target.write_u8(self.slots().len() as u8);
304        target.write_many(self.slots());
305    }
306
307    fn get_size_hint(&self) -> usize {
308        // Size of the serialized slot length.
309        let u8_size = 0u8.get_size_hint();
310        let mut size = u8_size;
311
312        for slot in self.slots() {
313            size += slot.get_size_hint();
314        }
315
316        size
317    }
318}
319
320impl Deserializable for AccountStorage {
321    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
322        let num_slots = source.read_u8()? as usize;
323        let slots = source.read_many::<StorageSlot>(num_slots)?;
324
325        Self::new(slots).map_err(|err| DeserializationError::InvalidValue(err.to_string()))
326    }
327}
328
329// TESTS
330// ================================================================================================
331
332#[cfg(test)]
333mod tests {
334    use super::{
335        AccountStorage,
336        Deserializable,
337        Serializable,
338        StorageMap,
339        Word,
340        build_slots_commitment,
341    };
342    use crate::account::StorageSlot;
343
344    #[test]
345    fn test_serde_account_storage() {
346        // empty storage
347        let storage = AccountStorage::new(vec![]).unwrap();
348        let bytes = storage.to_bytes();
349        assert_eq!(storage, AccountStorage::read_from_bytes(&bytes).unwrap());
350
351        // storage with values for default types
352        let storage = AccountStorage::new(vec![
353            StorageSlot::Value(Word::empty()),
354            StorageSlot::Map(StorageMap::default()),
355        ])
356        .unwrap();
357        let bytes = storage.to_bytes();
358        assert_eq!(storage, AccountStorage::read_from_bytes(&bytes).unwrap());
359    }
360
361    #[test]
362    fn test_account_storage_slots_commitment() {
363        let storage = AccountStorage::mock();
364        let storage_slots_commitment = build_slots_commitment(storage.slots());
365        assert_eq!(storage_slots_commitment, storage.commitment())
366    }
367}