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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use crate::database::{
    Column,
    Database,
};
use fuel_core_storage::{
    Error as StorageError,
    Mappable,
    MerkleRoot,
    Result as StorageResult,
    StorageInspect,
    StorageMutate,
};
use fuel_core_types::{
    blockchain::primitives::BlockId,
    fuel_merkle::{
        binary,
        sparse,
    },
    fuel_tx::TxId,
    fuel_types::{
        BlockHeight,
        ContractId,
        Nonce,
    },
};
use serde::{
    de::DeserializeOwned,
    Serialize,
};
use std::{
    borrow::Cow,
    ops::Deref,
};

/// Metadata for dense Merkle trees
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct DenseMerkleMetadata {
    /// The root hash of the dense Merkle tree structure
    pub root: MerkleRoot,
    /// The version of the dense Merkle tree structure is equal to the number of
    /// leaves. Every time we append a new leaf to the Merkle tree data set, we
    /// increment the version number.
    pub version: u64,
}

impl Default for DenseMerkleMetadata {
    fn default() -> Self {
        let empty_merkle_tree = binary::in_memory::MerkleTree::new();
        Self {
            root: empty_merkle_tree.root(),
            version: 0,
        }
    }
}

/// Metadata for sparse Merkle trees
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct SparseMerkleMetadata {
    /// The root hash of the sparse Merkle tree structure
    pub root: MerkleRoot,
}

impl Default for SparseMerkleMetadata {
    fn default() -> Self {
        let empty_merkle_tree = sparse::in_memory::MerkleTree::new();
        Self {
            root: empty_merkle_tree.root(),
        }
    }
}

/// The table of fuel block's secondary key - `BlockHeight`.
/// It links the `BlockHeight` to corresponding `BlockId`.
pub struct FuelBlockSecondaryKeyBlockHeights;

impl Mappable for FuelBlockSecondaryKeyBlockHeights {
    /// Secondary key - `BlockHeight`.
    type Key = BlockHeight;
    type OwnedKey = Self::Key;
    /// Primary key - `BlockId`.
    type Value = BlockId;
    type OwnedValue = Self::Value;
}

/// The table of BMT data for Fuel blocks.
pub struct FuelBlockMerkleData;

impl Mappable for FuelBlockMerkleData {
    type Key = u64;
    type OwnedKey = Self::Key;
    type Value = binary::Primitive;
    type OwnedValue = Self::Value;
}

/// The metadata table for [`FuelBlockMerkleData`](FuelBlockMerkleData) table.
pub struct FuelBlockMerkleMetadata;

impl Mappable for FuelBlockMerkleMetadata {
    type Key = BlockHeight;
    type OwnedKey = Self::Key;
    type Value = DenseMerkleMetadata;
    type OwnedValue = Self::Value;
}

/// The table of SMT data for Contract assets.
pub struct ContractsAssetsMerkleData;

impl Mappable for ContractsAssetsMerkleData {
    type Key = [u8; 32];
    type OwnedKey = Self::Key;
    type Value = sparse::Primitive;
    type OwnedValue = Self::Value;
}

/// The metadata table for [`ContractsAssetsMerkleData`](ContractsAssetsMerkleData) table
pub struct ContractsAssetsMerkleMetadata;

impl Mappable for ContractsAssetsMerkleMetadata {
    type Key = ContractId;
    type OwnedKey = Self::Key;
    type Value = SparseMerkleMetadata;
    type OwnedValue = Self::Value;
}

/// The table of SMT data for Contract state.
pub struct ContractsStateMerkleData;

impl Mappable for ContractsStateMerkleData {
    type Key = [u8; 32];
    type OwnedKey = Self::Key;
    type Value = sparse::Primitive;
    type OwnedValue = Self::Value;
}

/// The metadata table for [`ContractsStateMerkleData`](ContractsStateMerkleData) table
pub struct ContractsStateMerkleMetadata;

impl Mappable for ContractsStateMerkleMetadata {
    type Key = ContractId;
    type OwnedKey = Self::Key;
    type Value = SparseMerkleMetadata;
    type OwnedValue = Self::Value;
}

/// The table has a corresponding column in the database.
///
/// Using this trait allows the configured mappable type to have its'
/// database integration auto-implemented for single column interactions.
///
/// If the mappable type requires access to multiple columns or custom logic during setting/getting
/// then its' storage interfaces should be manually implemented and this trait should be avoided.
pub trait DatabaseColumn {
    /// The column of the table.
    fn column() -> Column;
}

impl DatabaseColumn for FuelBlockSecondaryKeyBlockHeights {
    fn column() -> Column {
        Column::FuelBlockSecondaryKeyBlockHeights
    }
}

impl DatabaseColumn for FuelBlockMerkleData {
    fn column() -> Column {
        Column::FuelBlockMerkleData
    }
}

impl DatabaseColumn for FuelBlockMerkleMetadata {
    fn column() -> Column {
        Column::FuelBlockMerkleMetadata
    }
}

impl DatabaseColumn for ContractsAssetsMerkleData {
    fn column() -> Column {
        Column::ContractsAssetsMerkleData
    }
}

impl DatabaseColumn for ContractsAssetsMerkleMetadata {
    fn column() -> Column {
        Column::ContractsAssetsMerkleMetadata
    }
}

impl DatabaseColumn for ContractsStateMerkleData {
    fn column() -> Column {
        Column::ContractsStateMerkleData
    }
}

impl DatabaseColumn for ContractsStateMerkleMetadata {
    fn column() -> Column {
        Column::ContractsStateMerkleMetadata
    }
}

impl<T> StorageInspect<T> for Database
where
    T: Mappable + DatabaseColumn,
    T::Key: ToDatabaseKey,
    T::OwnedValue: DeserializeOwned,
{
    type Error = StorageError;

    fn get(&self, key: &T::Key) -> StorageResult<Option<Cow<T::OwnedValue>>> {
        self.get(key.database_key().as_ref(), T::column())
            .map_err(Into::into)
    }

    fn contains_key(&self, key: &T::Key) -> StorageResult<bool> {
        self.contains_key(key.database_key().as_ref(), T::column())
            .map_err(Into::into)
    }
}

impl<T> StorageMutate<T> for Database
where
    T: Mappable + DatabaseColumn,
    T::Key: ToDatabaseKey,
    T::Value: Serialize,
    T::OwnedValue: DeserializeOwned,
{
    fn insert(
        &mut self,
        key: &T::Key,
        value: &T::Value,
    ) -> StorageResult<Option<T::OwnedValue>> {
        Database::insert(self, key.database_key().as_ref(), T::column(), &value)
            .map_err(Into::into)
    }

    fn remove(&mut self, key: &T::Key) -> StorageResult<Option<T::OwnedValue>> {
        Database::remove(self, key.database_key().as_ref(), T::column())
            .map_err(Into::into)
    }
}

/// Some keys requires pre-processing that could change their type.
pub trait ToDatabaseKey {
    /// A new type of prepared database key that can be converted into bytes.
    type Type<'a>: AsRef<[u8]>
    where
        Self: 'a;

    /// Coverts the key into database key that supports byte presentation.
    fn database_key(&self) -> Self::Type<'_>;
}

impl ToDatabaseKey for BlockHeight {
    type Type<'a> = [u8; 4];

    fn database_key(&self) -> Self::Type<'_> {
        self.to_bytes()
    }
}

impl ToDatabaseKey for u64 {
    type Type<'a> = [u8; 8];

    fn database_key(&self) -> Self::Type<'_> {
        self.to_be_bytes()
    }
}

impl ToDatabaseKey for Nonce {
    type Type<'a> = &'a [u8; 32];

    fn database_key(&self) -> Self::Type<'_> {
        self.deref()
    }
}

impl ToDatabaseKey for ContractId {
    type Type<'a> = &'a [u8; 32];

    fn database_key(&self) -> Self::Type<'_> {
        self.deref()
    }
}

impl ToDatabaseKey for BlockId {
    type Type<'a> = &'a [u8];

    fn database_key(&self) -> Self::Type<'_> {
        self.as_slice()
    }
}

impl ToDatabaseKey for TxId {
    type Type<'a> = &'a [u8; 32];

    fn database_key(&self) -> Self::Type<'_> {
        self.deref()
    }
}

impl ToDatabaseKey for () {
    type Type<'a> = &'a [u8];

    fn database_key(&self) -> Self::Type<'_> {
        &[]
    }
}

impl<const N: usize> ToDatabaseKey for [u8; N] {
    type Type<'a> = &'a [u8];

    fn database_key(&self) -> Self::Type<'_> {
        self.as_slice()
    }
}