miden_objects/account/storage/header.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
use alloc::vec::Vec;
use vm_core::{
utils::{ByteReader, ByteWriter, Deserializable, Serializable},
ZERO,
};
use vm_processor::DeserializationError;
use super::{AccountStorage, Felt, StorageSlot, StorageSlotType, Word};
use crate::AccountError;
// ACCOUNT STORAGE HEADER
// ================================================================================================
/// Storage slot header is a lighter version of the [StorageSlot] storing only the type and the
/// top-level value for the slot, and being, in fact, just a thin wrapper around a tuple.
///
/// That is, for complex storage slot (e.g., storage map), the header contains only the commitment
/// to the underlying data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StorageSlotHeader(StorageSlotType, Word);
impl StorageSlotHeader {
/// Returns a new instance of storage slot header from the provided storage slot type and value.
pub fn new(value: &(StorageSlotType, Word)) -> Self {
Self(value.0, value.1)
}
/// Returns this storage slot header as field elements.
///
/// This is done by converting this storage slot into 8 field elements as follows:
/// ```text
/// [SLOT_VALUE, slot_type, 0, 0, 0]
/// ```
pub fn as_elements(&self) -> [Felt; StorageSlot::NUM_ELEMENTS_PER_STORAGE_SLOT] {
let mut elements = [ZERO; StorageSlot::NUM_ELEMENTS_PER_STORAGE_SLOT];
elements[0..4].copy_from_slice(&self.1);
elements[4..8].copy_from_slice(&self.0.as_word());
elements
}
}
impl From<&StorageSlot> for StorageSlotHeader {
fn from(value: &StorageSlot) -> Self {
Self(value.slot_type(), value.value())
}
}
/// Account storage header is a lighter version of the [AccountStorage] storing only the type and
/// the top-level value for each storage slot.
///
/// That is, for complex storage slots (e.g., storage maps), the header contains only the commitment
/// to the underlying data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountStorageHeader {
slots: Vec<(StorageSlotType, Word)>,
}
impl AccountStorageHeader {
// CONSTRUCTOR
// --------------------------------------------------------------------------------------------
/// Returns a new instance of account storage header initialized with the provided slots.
///
/// # Panics
/// - If the number of provided slots is greater than [AccountStorage::MAX_NUM_STORAGE_SLOTS].
pub fn new(slots: Vec<(StorageSlotType, Word)>) -> Self {
assert!(slots.len() <= AccountStorage::MAX_NUM_STORAGE_SLOTS);
Self { slots }
}
// PUBLIC ACCESSORS
// --------------------------------------------------------------------------------------------
/// Returns an iterator over the storage header slots.
pub fn slots(&self) -> impl Iterator<Item = &(StorageSlotType, Word)> {
self.slots.iter()
}
/// Returns the number of slots contained in the storage header.
pub fn num_slots(&self) -> usize {
self.slots.len()
}
/// Returns a slot contained in the storage header at a given index.
///
/// # Errors
/// - If the index is out of bounds.
pub fn slot(&self, index: usize) -> Result<&(StorageSlotType, Word), AccountError> {
self.slots.get(index).ok_or(AccountError::StorageIndexOutOfBounds {
slots_len: self.slots.len() as u8,
index: index as u8,
})
}
/// Converts storage slots of this account storage header into a vector of field elements.
///
/// This is done by first converting each storage slot into exactly 8 elements as follows:
/// ```text
/// [STORAGE_SLOT_VALUE, storage_slot_type, 0, 0, 0]
/// ```
/// And then concatenating the resulting elements into a single vector.
pub fn as_elements(&self) -> Vec<Felt> {
self.slots
.iter()
.flat_map(|slot| StorageSlotHeader::new(slot).as_elements())
.collect()
}
}
impl From<AccountStorage> for AccountStorageHeader {
fn from(value: AccountStorage) -> Self {
value.get_header()
}
}
// SERIALIZATION
// ================================================================================================
impl Serializable for AccountStorageHeader {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let len = self.slots.len() as u8;
target.write_u8(len);
target.write_many(self.slots())
}
}
impl Deserializable for AccountStorageHeader {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let len = source.read_u8()?;
let slots = source.read_many(len as usize)?;
// number of storage slots is guaranteed to be smaller than or equal to 255
Ok(Self::new(slots))
}
}
// TESTS
// ================================================================================================
#[cfg(test)]
mod tests {
use vm_core::{
utils::{Deserializable, Serializable},
Felt,
};
use super::AccountStorageHeader;
use crate::account::{AccountStorage, StorageSlotType};
#[test]
fn test_from_account_storage() {
// create new storage header from AccountStorage
let slots = vec![
(StorageSlotType::Value, [Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)]),
(StorageSlotType::Value, [Felt::new(5), Felt::new(6), Felt::new(7), Felt::new(8)]),
(
StorageSlotType::Map,
[
Felt::new(12405212884040084310),
Felt::new(17614307840949763446),
Felt::new(6101527485586301500),
Felt::new(14442045877206841081),
],
),
];
let expected_header = AccountStorageHeader { slots };
let account_storage = AccountStorage::mock();
assert_eq!(expected_header, AccountStorageHeader::from(account_storage))
}
#[test]
fn test_serde_account_storage_header() {
// create new storage header
let storage = AccountStorage::mock();
let storage_header = AccountStorageHeader::from(storage);
// serde storage header
let bytes = storage_header.to_bytes();
let deserialized = AccountStorageHeader::read_from_bytes(&bytes).unwrap();
// assert deserialized == storage header
assert_eq!(storage_header, deserialized);
}
}