miden_objects/account/storage/
mod.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct AccountStorage {
44 slots: Vec<StorageSlot>,
45}
46
47impl AccountStorage {
48 pub const MAX_NUM_STORAGE_SLOTS: usize = 255;
50
51 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 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 pub fn commitment(&self) -> Word {
104 build_slots_commitment(&self.slots)
105 }
106
107 pub fn num_slots(&self) -> u8 {
109 self.slots.len() as u8
112 }
113
114 pub fn slots(&self) -> &Vec<StorageSlot> {
116 &self.slots
117 }
118
119 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 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 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 pub fn as_elements(&self) -> Vec<Felt> {
163 slots_as_elements(self.slots())
164 }
165
166 pub(super) fn apply_delta(&mut self, delta: &AccountStorageDelta) -> Result<(), AccountError> {
174 let len = self.slots.len() as u8;
175
176 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 for (&idx, &value) in delta.values().iter() {
193 self.set_item(idx, value)?;
194 }
195
196 Ok(())
197 }
198
199 pub fn set_item(&mut self, index: u8, value: Word) -> Result<Word, AccountError> {
208 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 Err(AccountError::StorageSlotNotValue(index)),
222 };
223
224 self.slots[index as usize] = StorageSlot::Value(value);
226
227 Ok(old_value)
228 }
229
230 pub fn set_map_item(
239 &mut self,
240 index: u8,
241 key: Word,
242 value: Word,
243 ) -> Result<(Word, Word), AccountError> {
244 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 let old_root = storage_map.root();
261
262 let old_value = storage_map.insert(key, value);
264
265 Ok((old_root, old_value))
266 }
267}
268
269impl 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
281fn slots_as_elements(slots: &[StorageSlot]) -> Vec<Felt> {
286 slots
287 .iter()
288 .flat_map(|slot| StorageSlotHeader::from(slot).as_elements())
289 .collect()
290}
291
292pub fn build_slots_commitment(slots: &[StorageSlot]) -> Word {
294 let elements = slots_as_elements(slots);
295 Hasher::hash_elements(&elements)
296}
297
298impl 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 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#[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 let storage = AccountStorage::new(vec![]).unwrap();
348 let bytes = storage.to_bytes();
349 assert_eq!(storage, AccountStorage::read_from_bytes(&bytes).unwrap());
350
351 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}