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
use std::{fs::File, io::Write, iter::FromIterator, path::PathBuf, sync::Arc};

use byteorder::{BigEndian, WriteBytesExt};
use dashmap::DashMap;
use locutus_stdlib::prelude::{ContractCode, Parameters, WrappedContract};
use semver::Version;
use serde::{Deserialize, Serialize};
use stretto::Cache;

use crate::store::{StoreEntriesContainer, StoreFsManagement};
use crate::{error::RuntimeInnerError, ContractContainer, RuntimeResult, WasmAPIVersion};

use super::ContractKey;

type ContractCodeKey = [u8; 32];

#[derive(Serialize, Deserialize, Default)]
struct KeyToCodeMap(Vec<(ContractKey, ContractCodeKey)>);

impl StoreEntriesContainer for KeyToCodeMap {
    type MemContainer = Arc<DashMap<ContractKey, ContractCodeKey>>;
    type Key = ContractKey;
    type Value = ContractCodeKey;

    fn update(self, container: &mut Self::MemContainer) {
        for (k, v) in self.0 {
            container.insert(k, v);
        }
    }

    fn replace(container: &Self::MemContainer) -> Self {
        KeyToCodeMap::from(&**container)
    }

    fn insert(container: &mut Self::MemContainer, key: Self::Key, value: Self::Value) {
        container.insert(key, value);
    }
}

impl From<&DashMap<ContractKey, ContractCodeKey>> for KeyToCodeMap {
    fn from(vals: &DashMap<ContractKey, ContractCodeKey>) -> Self {
        let mut map = vec![];
        for r in vals.iter() {
            map.push((r.key().clone(), *r.value()));
        }
        Self(map)
    }
}

/// Handle contract blob storage on the file system.
pub struct ContractStore {
    contracts_dir: PathBuf,
    contract_cache: Cache<ContractCodeKey, Arc<ContractCode<'static>>>,
    key_to_code_part: Arc<DashMap<ContractKey, ContractCodeKey>>,
}
// TODO: add functionality to delete old contracts which have not been used for a while
//       to keep the total speed used under a configured threshold

static LOCK_FILE_PATH: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
static KEY_FILE_PATH: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();

impl StoreFsManagement<KeyToCodeMap> for ContractStore {}

impl ContractStore {
    /// # Arguments
    /// - max_size: max size in bytes of the contracts being cached
    pub fn new(contracts_dir: PathBuf, max_size: i64) -> RuntimeResult<Self> {
        const ERR: &str = "failed to build mem cache";
        let key_to_code_part;
        let _ = LOCK_FILE_PATH.try_insert(contracts_dir.join("__LOCK"));
        // if the lock file exists is from a previous execution so is safe to delete it
        let _ = std::fs::remove_file(LOCK_FILE_PATH.get().unwrap().as_path());
        let key_file = match KEY_FILE_PATH
            .try_insert(contracts_dir.join("KEY_DATA"))
            .map_err(|(e, _)| e)
        {
            Ok(f) => f,
            Err(f) => f,
        };
        if !key_file.exists() {
            std::fs::create_dir_all(&contracts_dir).map_err(|err| {
                tracing::error!("error creating contract dir: {err}");
                err
            })?;
            key_to_code_part = Arc::new(DashMap::new());
            File::create(contracts_dir.join("KEY_DATA"))?;
        } else {
            let map = Self::load_from_file(
                KEY_FILE_PATH.get().unwrap().as_path(),
                LOCK_FILE_PATH.get().unwrap().as_path(),
            )?;
            key_to_code_part = Arc::new(DashMap::from_iter(map.0));
        }
        Self::watch_changes(
            key_to_code_part.clone(),
            KEY_FILE_PATH.get().unwrap().as_path(),
            LOCK_FILE_PATH.get().unwrap().as_path(),
        )?;
        Ok(Self {
            contract_cache: Cache::new(100, max_size).expect(ERR),
            contracts_dir,
            key_to_code_part,
        })
    }

    /// Returns a copy of the contract bytes if available, none otherwise.
    pub fn fetch_contract(
        &self,
        key: &ContractKey,
        params: &Parameters<'_>,
    ) -> Option<ContractContainer> {
        let result = key
            .code_hash()
            .and_then(|code_hash| {
                self.contract_cache.get(code_hash).map(|data| {
                    Some(ContractContainer::Wasm(WasmAPIVersion::V1(
                        WrappedContract::new(data.value().clone(), params.clone().into_owned()),
                    )))
                })
            })
            .flatten();
        if result.is_some() {
            return result;
        }

        self.key_to_code_part.get(key).and_then(|key| {
            let code_hash = key.value();
            let path = bs58::encode(code_hash.as_slice())
                .with_alphabet(bs58::Alphabet::BITCOIN)
                .into_string()
                .to_lowercase();
            let key_path = self.contracts_dir.join(path).with_extension("wasm");
            let ContractContainer::Wasm(WasmAPIVersion::V1(WrappedContract {
                data, params, ..
            })) = ContractContainer::try_from((&*key_path, params.clone().into_owned()))
                .map_err(|err| {
                    tracing::debug!("contract not found: {err}");
                    err
                })
                .ok()?;
            // add back the contract part to the mem store
            let size = data.data().len() as i64;
            self.contract_cache.insert(*code_hash, data.clone(), size);
            Some(ContractContainer::Wasm(WasmAPIVersion::V1(
                WrappedContract::new(data, params),
            )))
        })
    }

    /// Store a copy of the contract in the local store, in case it hasn't been stored previously.
    pub fn store_contract(&mut self, contract: ContractContainer) -> RuntimeResult<()> {
        let (key, code) = match contract.clone() {
            ContractContainer::Wasm(WasmAPIVersion::V1(contract_v1)) => {
                (contract_v1.key().clone(), contract_v1.code().clone())
            }
        };
        let contract_hash = key.code_hash().ok_or_else(|| {
            tracing::warn!("trying to store partially unspecified contract `{}`", key);
            RuntimeInnerError::UnwrapContract
        })?;
        if self.contract_cache.get(contract_hash).is_some() {
            return Ok(());
        }

        Self::update(
            &mut self.key_to_code_part,
            key.clone(),
            *contract_hash,
            KEY_FILE_PATH.get().unwrap(),
            LOCK_FILE_PATH.get().unwrap().as_path(),
        )?;

        let key_path = bs58::encode(contract_hash)
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .into_string()
            .to_lowercase();
        let key_path = self.contracts_dir.join(key_path).with_extension("wasm");
        if let Ok(code) = WrappedContract::get_data_from_fs(&key_path) {
            let size = code.data().len() as i64;
            self.contract_cache
                .insert(*contract_hash, Arc::new(code), size);
            return Ok(());
        }

        // insert in the memory cache
        let size = code.data().len() as i64;
        let data = code.data().to_vec();
        self.contract_cache
            .insert(*contract_hash, Arc::new(ContractCode::from(data)), size);

        let version: Version = Version::from(contract);
        let mut serialized_version =
            serde_json::to_vec(&version).map_err(|e| RuntimeInnerError::Any(Box::new(e)))?;

        let mut output: Vec<u8> = Vec::with_capacity(
            std::mem::size_of::<u32>() + serialized_version.len() + code.data().len(),
        );
        output.write_u32::<BigEndian>(serialized_version.len() as u32)?;
        output.append(&mut serialized_version);
        output.append(&mut code.data().to_vec());

        let mut file = File::create(key_path)?;
        file.write_all(output.as_slice())?;

        Ok(())
    }

    pub fn get_contract_path(&mut self, key: &ContractKey) -> RuntimeResult<PathBuf> {
        let contract_hash = match key.code_hash() {
            Some(k) => *k,
            None => self.code_hash_from_key(key).ok_or_else(|| {
                tracing::warn!("trying to store partially unspecified contract `{key}`");
                RuntimeInnerError::UnwrapContract
            })?,
        };

        let key_path = bs58::encode(contract_hash)
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .into_string()
            .to_lowercase();
        Ok(self.contracts_dir.join(key_path).with_extension("wasm"))
    }

    pub fn code_hash_from_key(&self, key: &ContractKey) -> Option<ContractCodeKey> {
        self.key_to_code_part.get(key).map(|r| *r.value())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn store_and_load() -> Result<(), Box<dyn std::error::Error>> {
        let contract_dir = std::env::temp_dir()
            .join("locutus-test")
            .join("contract-store-test");
        std::fs::create_dir_all(&contract_dir)?;
        let mut store = ContractStore::new(contract_dir, 10_000)?;
        let contract = WrappedContract::new(
            Arc::new(ContractCode::from(vec![0, 1, 2])),
            [0, 1].as_ref().into(),
        );
        let container = ContractContainer::Wasm(WasmAPIVersion::V1(contract.clone()));
        store.store_contract(container)?;
        let f = store.fetch_contract(contract.key(), &[0, 1].as_ref().into());
        assert!(f.is_some());
        Ok(())
    }
}