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
314
315
316
use crate::types::{
    ModuleInfo, ModuleMetadata, ModuleMetadataDeserializer, ModuleMetadataSerializer,
};
use massa_hash::Hash;
use massa_sc_runtime::{GasCosts, RuntimeModule};
use massa_serialization::{DeserializeError, Deserializer, Serializer};
use rand::RngCore;
use rocksdb::{Direction, IteratorMode, WriteBatch, DB};
use std::path::PathBuf;
use tracing::debug;

const OPEN_ERROR: &str = "critical: rocksdb open operation failed";
const CRUD_ERROR: &str = "critical: rocksdb crud operation failed";
const DATA_SER_ERROR: &str = "critical: metadata serialization failed";
const DATA_DESER_ERROR: &str = "critical: metadata deserialization failed";
const MOD_SER_ERROR: &str = "critical: module serialization failed";
const MOD_DESER_ERROR: &str = "critical: module deserialization failed";
const MODULE_IDENT: u8 = 0u8;
const DATA_IDENT: u8 = 1u8;

/// Module key formatting macro
#[macro_export]
macro_rules! module_key {
    ($bc_hash:expr) => {
        [&$bc_hash.to_bytes()[..], &[MODULE_IDENT]].concat()
    };
}

/// Delta key formatting macro
#[macro_export]
macro_rules! metadata_key {
    ($bc_hash:expr) => {
        [&$bc_hash.to_bytes()[..], &[DATA_IDENT]].concat()
    };
}

pub(crate) struct HDCache {
    /// RocksDB database
    db: DB,
    /// How many entries are in the db. Count is initialized at creation time by iterating
    /// over all the entries in the db then it is maintained in memory
    entry_count: usize,
    /// Maximum number of entries we want to keep in the db.
    /// When this maximum is reached `snip_amount` entries are removed
    max_entry_count: usize,
    /// How many entries are removed when `entry_count` reaches `max_entry_count`
    snip_amount: usize,
    /// Module metadata serializer
    meta_ser: ModuleMetadataSerializer,
    /// Module metadata deserializer
    meta_deser: ModuleMetadataDeserializer,
}

impl HDCache {
    /// Create a new HDCache
    ///
    /// # Arguments
    /// * path: where to store the db
    /// * max_entry_count: maximum number of entries we want to keep in the db
    /// * amount_to_remove: how many entries are removed when `entry_count` reaches `max_entry_count`
    pub fn new(path: PathBuf, max_entry_count: usize, snip_amount: usize) -> Self {
        let db = DB::open_default(path).expect(OPEN_ERROR);
        let entry_count = db.iterator(IteratorMode::Start).count();

        Self {
            db,
            entry_count,
            max_entry_count,
            snip_amount,
            meta_ser: ModuleMetadataSerializer::new(),
            meta_deser: ModuleMetadataDeserializer::new(),
        }
    }

    /// Insert a new module in the cache
    pub fn insert(&mut self, hash: Hash, module_info: ModuleInfo) {
        if self.entry_count >= self.max_entry_count {
            self.snip();
        }

        let mut ser_metadata = Vec::new();
        let ser_module = match module_info {
            ModuleInfo::Invalid(err_msg) => {
                self.meta_ser
                    .serialize(&ModuleMetadata::Invalid(err_msg), &mut ser_metadata)
                    .expect(DATA_SER_ERROR);
                Vec::new()
            }
            ModuleInfo::Module(module) => {
                self.meta_ser
                    .serialize(&ModuleMetadata::NotExecuted, &mut ser_metadata)
                    .expect(DATA_SER_ERROR);
                module.serialize().expect(MOD_SER_ERROR)
            }
            ModuleInfo::ModuleAndDelta((module, delta)) => {
                self.meta_ser
                    .serialize(&ModuleMetadata::Delta(delta), &mut ser_metadata)
                    .expect(DATA_SER_ERROR);
                module.serialize().expect(MOD_SER_ERROR)
            }
        };

        let mut batch = WriteBatch::default();
        batch.put(module_key!(hash), ser_module);
        batch.put(metadata_key!(hash), ser_metadata);
        self.db.write(batch).expect(CRUD_ERROR);

        self.entry_count = self.entry_count.saturating_add(1);

        debug!("(HD insert) entry_count is: {}", self.entry_count);
    }

    /// Sets the initialization cost of a given module separately
    ///
    /// # Arguments
    /// * `hash`: hash associated to the module for which we want to set the cost
    /// * `init_cost`: the new cost associated to the module
    pub fn set_init_cost(&self, hash: Hash, init_cost: u64) {
        let mut ser_metadata = Vec::new();
        self.meta_ser
            .serialize(&ModuleMetadata::Delta(init_cost), &mut ser_metadata)
            .expect(DATA_SER_ERROR);
        self.db
            .put(metadata_key!(hash), ser_metadata)
            .expect(CRUD_ERROR);
    }

    /// Sets a given module as invalid
    pub fn set_invalid(&self, hash: Hash, err_msg: String) {
        let mut ser_metadata = Vec::new();
        self.meta_ser
            .serialize(&ModuleMetadata::Invalid(err_msg), &mut ser_metadata)
            .expect(DATA_SER_ERROR);
        self.db
            .put(metadata_key!(hash), ser_metadata)
            .expect(CRUD_ERROR);
    }

    /// Retrieve a module
    pub fn get(&self, hash: Hash, gas_costs: GasCosts) -> Option<ModuleInfo> {
        let mut iterator = self
            .db
            .iterator(IteratorMode::From(&module_key!(hash), Direction::Forward));

        if let (Some(Ok((key_1, ser_module))), Some(Ok((key_2, ser_metadata)))) =
            (iterator.next(), iterator.next())
        {
            if *key_1 == module_key!(hash) && *key_2 == metadata_key!(hash) {
                let (_, metadata) = self
                    .meta_deser
                    .deserialize::<DeserializeError>(&ser_metadata)
                    .expect(DATA_DESER_ERROR);
                if let ModuleMetadata::Invalid(err_msg) = metadata {
                    return Some(ModuleInfo::Invalid(err_msg));
                }
                let module =
                    RuntimeModule::deserialize(&ser_module, gas_costs.max_instance_cost, gas_costs)
                        .expect(MOD_DESER_ERROR);
                let result = match metadata {
                    ModuleMetadata::Invalid(err_msg) => ModuleInfo::Invalid(err_msg),
                    ModuleMetadata::NotExecuted => ModuleInfo::Module(module),
                    ModuleMetadata::Delta(delta) => ModuleInfo::ModuleAndDelta((module, delta)),
                };
                Some(result)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Try to remove as much as `self.amount_to_snip` entries from the db
    fn snip(&mut self) {
        let mut iter = self.db.raw_iterator();
        let mut batch = WriteBatch::default();
        let mut snipped_count: usize = 0;

        while snipped_count < self.snip_amount {
            // generate a random key
            let mut rbytes = [0u8; 16];
            rand::thread_rng().fill_bytes(&mut rbytes);
            let key = *Hash::compute_from(&rbytes).to_bytes();

            // take the upper existing key
            iter.seek_for_prev(key);

            // check iterator validity
            if !iter.valid() {
                continue;
            }

            // unwrap justified by above conditional statement.
            // seeking the previous key of a randombly generated one
            // will always end up on a metadata key.
            let metadata_key = iter.key().unwrap();
            batch.delete(metadata_key);
            iter.prev();
            let module_key = iter.key().unwrap();
            batch.delete(module_key);

            // increase snipped_count
            snipped_count += 1;
        }

        // safety check
        if batch.len() / 2 != snipped_count {
            panic!("snipped_count incoherence");
        }

        // delete the key and reduce entry_count
        self.db.write(batch).expect(CRUD_ERROR);
        self.entry_count -= snipped_count;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use massa_hash::Hash;
    use massa_sc_runtime::{Compiler, GasCosts, RuntimeModule};
    use rand::thread_rng;
    use serial_test::serial;
    use tempfile::TempDir;

    fn make_default_module_info() -> ModuleInfo {
        let bytecode: Vec<u8> = vec![
            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f,
            0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x0b, 0x01, 0x07, 0x61, 0x64, 0x64, 0x5f,
            0x6f, 0x6e, 0x65, 0x00, 0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x41, 0x01,
            0x6a, 0x0b, 0x00, 0x1a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x01, 0x0a, 0x01, 0x00, 0x07,
            0x61, 0x64, 0x64, 0x5f, 0x6f, 0x6e, 0x65, 0x02, 0x07, 0x01, 0x00, 0x01, 0x00, 0x02,
            0x70, 0x30,
        ];
        ModuleInfo::Module(
            RuntimeModule::new(&bytecode, GasCosts::default(), Compiler::CL).unwrap(),
        )
    }

    fn setup() -> HDCache {
        let tmp_path = TempDir::new().unwrap().path().to_path_buf();
        HDCache::new(tmp_path, 1000, 10)
    }

    #[test]
    #[serial]
    fn test_basic_crud() {
        let mut cache = setup();
        let hash = Hash::compute_from(b"test_hash");
        let module = make_default_module_info();

        let init_cost = 100;
        let gas_costs = GasCosts::default();

        cache.insert(hash, module);
        let cached_module_v1 = cache.get(hash, gas_costs.clone()).unwrap();
        assert!(matches!(cached_module_v1, ModuleInfo::Module(_)));

        cache.set_init_cost(hash, init_cost);
        let cached_module_v2 = cache.get(hash, gas_costs.clone()).unwrap();
        assert!(matches!(cached_module_v2, ModuleInfo::ModuleAndDelta(_)));

        let err_msg = "test_error".to_string();
        cache.set_invalid(hash, err_msg.clone());
        let cached_module_v3 = cache.get(hash, gas_costs).unwrap();
        let ModuleInfo::Invalid(res_err) = cached_module_v3 else {
            panic!("expected ModuleInfo::Invalid");
        };
        assert_eq!(res_err, err_msg);
    }

    #[test]
    #[serial]
    fn test_insert_more_than_max_entry() {
        let mut cache = setup();
        let module = make_default_module_info();

        // fill the db: add cache.max_entry_count entries
        for count in 0..cache.max_entry_count {
            let key = Hash::compute_from(count.to_string().as_bytes());
            cache.insert(key, module.clone());
        }
        assert_eq!(cache.entry_count, cache.max_entry_count);

        // insert one more entry
        let key = Hash::compute_from(cache.max_entry_count.to_string().as_bytes());
        cache.insert(key, module);
        assert_eq!(
            cache.entry_count,
            cache.max_entry_count - cache.snip_amount + 1
        );
        dbg!(cache.entry_count);
    }

    #[test]
    #[serial]
    fn test_missing_module() {
        let mut cache = setup();
        let module = make_default_module_info();

        let gas_costs = GasCosts::default();

        for count in 0..cache.max_entry_count {
            let key = Hash::compute_from(count.to_string().as_bytes());
            cache.insert(key, module.clone());
        }

        for _ in 0..cache.max_entry_count {
            let mut rbytes = [0u8; 16];
            thread_rng().fill_bytes(&mut rbytes);
            let get_key = Hash::compute_from(&rbytes);
            let cached_module = cache.get(get_key, gas_costs.clone());
            assert!(cached_module.is_none());
        }
    }
}