Skip to main content

fuel_vm/
storage.rs

1//! Storage backend implementations.
2
3use fuel_storage::Mappable;
4use fuel_tx::Contract;
5use fuel_types::{
6    Bytes32,
7    ContractId,
8};
9
10mod blob_data;
11mod contracts_assets;
12mod contracts_state;
13mod interpreter;
14#[cfg(feature = "test-helpers")]
15mod memory;
16pub mod predicate;
17
18pub use blob_data::{
19    BlobBytes,
20    BlobData,
21};
22pub use contracts_assets::{
23    ContractsAssetKey,
24    ContractsAssets,
25};
26pub use contracts_state::{
27    ContractsState,
28    ContractsStateData,
29    ContractsStateKey,
30};
31pub use interpreter::{
32    ContractsAssetsStorage,
33    InterpreterStorage,
34};
35#[cfg(feature = "test-helpers")]
36pub use memory::MemoryStorage;
37
38#[cfg(feature = "alloc")]
39use alloc::vec::Vec;
40
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43/// The uploaded bytecode can be in two states: fully uploaded or partially uploaded.
44pub enum UploadedBytecode {
45    /// The bytecode is partially uploaded.
46    Uncompleted {
47        /// The cumulative bytecode of `uploaded_subsections_number` parts.
48        bytecode: Vec<u8>,
49        /// The number of already included subsections of the bytecode.
50        uploaded_subsections_number: u16,
51    },
52    /// The bytecode is fully uploaded and ready to be used.
53    Completed(Vec<u8>),
54}
55
56/// The storage table for uploaded bytecode.
57pub struct UploadedBytecodes;
58
59impl Mappable for UploadedBytecodes {
60    /// The key is a Merkle root of the bytecode.
61    type Key = Self::OwnedKey;
62    type OwnedKey = Bytes32;
63    type OwnedValue = UploadedBytecode;
64    type Value = Self::OwnedValue;
65}
66
67/// The storage table for contract's raw byte code.
68pub struct ContractsRawCode;
69
70impl Mappable for ContractsRawCode {
71    type Key = Self::OwnedKey;
72    type OwnedKey = ContractId;
73    type OwnedValue = Contract;
74    type Value = [u8];
75}
76
77/// The macro defines a new type of double storage key. It is a merge of the two
78/// types into one general type that represents the storage key of some entity.
79///
80/// Both types are represented by one big array. It is done from the performance
81/// perspective to minimize the number of copies. The current code doesn't use
82/// consumed values and uses it in most cases as on big key(except tests, which
83/// require access to sub-keys). But in the future, we may change the layout of the
84/// fields based on the performance measurements/new business logic.
85#[macro_export]
86macro_rules! double_key {
87    (
88        $i:ident, $first:ident, $first_getter:ident, $second:ident, $second_getter:ident
89    ) => {
90        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
91        /// The FuelVM storage double key.
92        pub struct $i([u8; { $first::LEN + $second::LEN }]);
93
94        impl Default for $i {
95            fn default() -> Self {
96                Self([0; { Self::second_end() }])
97            }
98        }
99
100        impl $i {
101            /// The length of the underlying array.
102            pub const LEN: usize = $first::LEN + $second::LEN;
103
104            /// Create a new instance of the double storage key from references.
105            pub fn new(first: &$first, second: &$second) -> Self {
106                let mut default = Self::default();
107                default.0[0..Self::first_end()].copy_from_slice(first.as_ref());
108                default.0[Self::first_end()..Self::second_end()]
109                    .copy_from_slice(second.as_ref());
110                default
111            }
112
113            /// Creates a new instance of double storage key from the array.
114            pub fn from_array(array: [u8; { $first::LEN + $second::LEN }]) -> Self {
115                Self(array)
116            }
117
118            /// Creates a new instance of double storage key from the slice.
119            pub fn from_slice(
120                slice: &[u8],
121            ) -> Result<Self, core::array::TryFromSliceError> {
122                Ok(Self(slice.try_into()?))
123            }
124
125            /// Returns the reference to the first sub-key.
126            pub fn $first_getter(&self) -> &$first {
127                $first::from_bytes_ref(
128                    (&self.0[0..Self::first_end()])
129                        .try_into()
130                        .expect("0..first_end() < first_end() + second_end()"),
131                )
132            }
133
134            /// Returns the reference to the second sub-key.
135            pub fn $second_getter(&self) -> &$second {
136                $second::from_bytes_ref(
137                    (&self.0[Self::first_end()..Self::second_end()])
138                        .try_into()
139                        .expect("first_end()..second_end() < first_end() + second_end()"),
140                )
141            }
142
143            const fn first_end() -> usize {
144                $first::LEN
145            }
146
147            const fn second_end() -> usize {
148                $first::LEN + $second::LEN
149            }
150        }
151
152        impl From<(&$first, &$second)> for $i {
153            fn from(pair: (&$first, &$second)) -> Self {
154                Self::new(pair.0, pair.1)
155            }
156        }
157
158        impl AsRef<[u8]> for $i {
159            fn as_ref(&self) -> &[u8] {
160                self.0.as_ref()
161            }
162        }
163
164        impl From<$i> for ($first, $second) {
165            fn from(key: $i) -> ($first, $second) {
166                let first = &key.0[0..$i::first_end()];
167                let second = &key.0[$i::first_end()..$i::second_end()];
168                let first = first.try_into().unwrap();
169                let second = second.try_into().unwrap();
170                (first, second)
171            }
172        }
173
174        impl From<$i> for [u8; { $first::LEN + $second::LEN }] {
175            fn from(key: $i) -> [u8; { $first::LEN + $second::LEN }] {
176                key.0
177            }
178        }
179
180        impl TryFrom<&[u8]> for $i {
181            type Error = core::array::TryFromSliceError;
182
183            fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
184                $i::from_slice(slice)
185            }
186        }
187
188        #[cfg(feature = "serde")]
189        impl serde::Serialize for $i {
190            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
191            where
192                S: serde::Serializer,
193            {
194                use serde_with::SerializeAs;
195                serde_with::Bytes::serialize_as(&self.0, serializer)
196            }
197        }
198
199        #[cfg(feature = "serde")]
200        impl<'a> serde::Deserialize<'a> for $i {
201            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
202            where
203                D: serde::Deserializer<'a>,
204            {
205                use serde_with::DeserializeAs;
206                let bytes: [u8; $i::LEN] =
207                    serde_with::Bytes::deserialize_as(deserializer)?;
208                Ok(Self(bytes))
209            }
210        }
211    };
212}