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
use crate::database::{
    Column,
    Database,
};
use fuel_core_storage::{
    Error as StorageError,
    Mappable,
    Result as StorageResult,
    StorageInspect,
    StorageMutate,
};
use fuel_core_types::{
    blockchain::primitives::{
        BlockHeight,
        BlockId,
    },
    fuel_merkle::binary,
    fuel_tx::TxId,
    fuel_types::{
        Bytes32,
        ContractId,
        MessageId,
    },
};
use serde::{
    de::DeserializeOwned,
    Serialize,
};
use std::borrow::Cow;

/// 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: Bytes32,
    /// 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().into(),
            version: 0,
        }
    }
}

/// 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 MMR data for the 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`] table.
pub struct FuelBlockMerkleMetadata;

impl Mappable for FuelBlockMerkleMetadata {
    type Key = BlockHeight;
    type OwnedKey = Self::Key;
    type Value = DenseMerkleMetadata;
    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<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 ContractId {
    type Type<'a> = &'a [u8];

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

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

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

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];

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

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

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