-
Notifications
You must be signed in to change notification settings - Fork 582
/
cache.rs
378 lines (342 loc) · 13.3 KB
/
cache.rs
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use crate::errors::{ContractPrecompilatonError, ContractPrecompilatonResult, IntoVMError};
use crate::prepare;
use crate::wasmer1_runner::{default_wasmer1_store, wasmer1_vm_hash};
use crate::wasmer_runner::wasmer0_vm_hash;
use crate::wasmtime_runner::wasmtime_vm_hash;
use crate::VMKind;
use borsh::{BorshDeserialize, BorshSerialize};
#[cfg(not(feature = "no_cache"))]
use cached::{cached_key, SizedCache};
use near_primitives::contract::ContractCode;
use near_primitives::hash::CryptoHash;
use near_primitives::types::CompiledContractCache;
use near_vm_errors::CacheError::{DeserializationError, ReadError, SerializationError, WriteError};
use near_vm_errors::{CacheError, VMError};
use near_vm_logic::VMConfig;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, BorshDeserialize, BorshSerialize)]
enum ContractCacheKey {
Version1 {
code_hash: CryptoHash,
vm_config_non_crypto_hash: u64,
vm_kind: VMKind,
},
// unused
_Version2,
// bump to depreciate bincode/serde-bench based wasmer 0.x cache
Version3 {
code_hash: CryptoHash,
vm_config_non_crypto_hash: u64,
vm_kind: VMKind,
vm_hash: u64,
},
}
#[derive(Debug, Clone, BorshDeserialize, BorshSerialize)]
enum CacheRecord {
Error(VMError),
Code(Vec<u8>),
}
fn vm_hash(vm_kind: VMKind) -> u64 {
match vm_kind {
VMKind::Wasmer0 => wasmer0_vm_hash(),
VMKind::Wasmer1 => wasmer1_vm_hash(),
VMKind::Wasmtime => wasmtime_vm_hash(),
}
}
pub fn get_contract_cache_key(
code: &ContractCode,
vm_kind: VMKind,
config: &VMConfig,
) -> CryptoHash {
let _span = tracing::debug_span!(target: "vm", "get_key").entered();
let key = ContractCacheKey::Version3 {
code_hash: *code.hash(),
vm_config_non_crypto_hash: config.non_crypto_hash(),
vm_kind,
vm_hash: vm_hash(vm_kind),
};
near_primitives::hash::hash(&key.try_to_vec().unwrap())
}
fn cache_error(error: VMError, key: &CryptoHash, cache: &dyn CompiledContractCache) -> VMError {
let record = CacheRecord::Error(error.clone());
if cache.put(&key.0, &record.try_to_vec().unwrap()).is_err() {
VMError::CacheError(WriteError)
} else {
error
}
}
#[derive(Default)]
pub struct MockCompiledContractCache {
store: Arc<Mutex<HashMap<Vec<u8>, Vec<u8>>>>,
}
impl MockCompiledContractCache {
pub fn len(&self) -> usize {
self.store.lock().unwrap().len()
}
}
impl CompiledContractCache for MockCompiledContractCache {
fn put(&self, key: &[u8], value: &[u8]) -> Result<(), std::io::Error> {
self.store.lock().unwrap().insert(key.to_vec(), value.to_vec());
Ok(())
}
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, std::io::Error> {
let res = self.store.lock().unwrap().get(key).cloned();
Ok(res)
}
}
impl fmt::Debug for MockCompiledContractCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let guard = self.store.lock().unwrap();
let hm: &HashMap<_, _> = &*guard;
fmt::Debug::fmt(hm, f)
}
}
#[cfg(not(feature = "no_cache"))]
const CACHE_SIZE: usize = 128;
#[cfg(feature = "wasmer0_vm")]
pub mod wasmer0_cache {
use super::*;
use wasmer_runtime::{compiler_for_backend, Backend};
use wasmer_runtime_core::cache::Artifact;
use wasmer_runtime_core::load_cache_with;
pub(crate) fn compile_module(
code: &[u8],
config: &VMConfig,
) -> Result<wasmer_runtime::Module, VMError> {
let prepared_code = prepare::prepare_contract(code, config)?;
wasmer_runtime::compile(&prepared_code).map_err(|err| err.into_vm_error())
}
pub(crate) fn compile_and_serialize_wasmer(
wasm_code: &[u8],
config: &VMConfig,
key: &CryptoHash,
cache: &dyn CompiledContractCache,
) -> Result<wasmer_runtime::Module, VMError> {
let _span = tracing::debug_span!(target: "vm", "compile_and_serialize_wasmer").entered();
let module = compile_module(wasm_code, config).map_err(|e| cache_error(e, &key, cache))?;
let artifact =
module.cache().map_err(|_e| VMError::CacheError(SerializationError { hash: key.0 }))?;
let code = artifact
.serialize()
.map_err(|_e| VMError::CacheError(SerializationError { hash: key.0 }))?;
let serialized = CacheRecord::Code(code).try_to_vec().unwrap();
cache.put(key.as_ref(), &serialized).map_err(|_e| VMError::CacheError(WriteError))?;
Ok(module)
}
/// Deserializes contract or error from the binary data. Signature means that we could either
/// return module or cached error, which both considered to be `Ok()`, or encounter an error during
/// the deserialization process.
fn deserialize_wasmer(
serialized: &[u8],
) -> Result<Result<wasmer_runtime::Module, VMError>, CacheError> {
let _span = tracing::debug_span!(target: "vm", "deserialize_wasmer").entered();
let record = CacheRecord::try_from_slice(serialized).map_err(|_e| DeserializationError)?;
let serialized_artifact = match record {
CacheRecord::Error(err) => return Ok(Err(err)),
CacheRecord::Code(code) => code,
};
let artifact = Artifact::deserialize(serialized_artifact.as_slice())
.map_err(|_e| CacheError::DeserializationError)?;
unsafe {
let compiler = compiler_for_backend(Backend::Singlepass).unwrap();
match load_cache_with(artifact, compiler.as_ref()) {
Ok(module) => Ok(Ok(module)),
Err(_) => Err(CacheError::DeserializationError),
}
}
}
fn compile_module_cached_wasmer_impl(
key: CryptoHash,
wasm_code: &[u8],
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
) -> Result<wasmer_runtime::Module, VMError> {
if cache.is_none() {
return compile_module(wasm_code, config);
}
let cache = cache.unwrap();
match cache.get(&key.0) {
Ok(serialized) => match serialized {
Some(serialized) => {
deserialize_wasmer(serialized.as_slice()).map_err(VMError::CacheError)?
}
None => compile_and_serialize_wasmer(wasm_code, config, &key, cache),
},
Err(_) => Err(VMError::CacheError(ReadError)),
}
}
#[cfg(not(feature = "no_cache"))]
cached_key! {
MODULES: SizedCache<CryptoHash, Result<wasmer_runtime::Module, VMError>>
= SizedCache::with_size(CACHE_SIZE);
Key = {
key
};
fn memcache_compile_module_cached_wasmer(
key: CryptoHash,
wasm_code: &[u8],
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>) -> Result<wasmer_runtime::Module, VMError> = {
compile_module_cached_wasmer_impl(key, wasm_code, config, cache)
}
}
pub(crate) fn compile_module_cached_wasmer0(
code: &ContractCode,
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
) -> Result<wasmer_runtime::Module, VMError> {
let key = get_contract_cache_key(code, VMKind::Wasmer0, config);
#[cfg(not(feature = "no_cache"))]
return memcache_compile_module_cached_wasmer(key, code.code(), config, cache);
#[cfg(feature = "no_cache")]
return compile_module_cached_wasmer_impl(key, code.code(), config, cache);
}
}
#[cfg(feature = "wasmer1_vm")]
pub mod wasmer1_cache {
use near_primitives::contract::ContractCode;
use super::*;
fn compile_module_wasmer1(
code: &[u8],
config: &VMConfig,
store: &wasmer::Store,
) -> Result<wasmer::Module, VMError> {
let prepared_code = prepare::prepare_contract(code, config)?;
wasmer::Module::new(&store, prepared_code).map_err(|err| err.into_vm_error())
}
pub(crate) fn compile_and_serialize_wasmer1(
wasm_code: &[u8],
key: &CryptoHash,
config: &VMConfig,
cache: &dyn CompiledContractCache,
store: &wasmer::Store,
) -> Result<wasmer::Module, VMError> {
let _span = tracing::debug_span!(target: "vm", "compile_and_serialize_wasmer1").entered();
let module = compile_module_wasmer1(wasm_code, config, store)
.map_err(|e| cache_error(e, &key, cache))?;
let code = module
.serialize()
.map_err(|_e| VMError::CacheError(SerializationError { hash: key.0 }))?;
let serialized = CacheRecord::Code(code).try_to_vec().unwrap();
cache.put(key.as_ref(), &serialized).map_err(|_e| VMError::CacheError(WriteError))?;
Ok(module)
}
fn deserialize_wasmer1(
serialized: &[u8],
store: &wasmer::Store,
) -> Result<Result<wasmer::Module, VMError>, CacheError> {
let _span = tracing::debug_span!(target: "vm", "deserialize_wasmer1").entered();
let record = CacheRecord::try_from_slice(serialized).map_err(|_e| DeserializationError)?;
let serialized_module = match record {
CacheRecord::Error(err) => return Ok(Err(err)),
CacheRecord::Code(code) => code,
};
unsafe {
Ok(Ok(wasmer::Module::deserialize(store, serialized_module.as_slice())
.map_err(|_e| CacheError::DeserializationError)?))
}
}
fn compile_module_cached_wasmer1_impl(
key: CryptoHash,
wasm_code: &[u8],
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
store: &wasmer::Store,
) -> Result<wasmer::Module, VMError> {
if cache.is_none() {
return compile_module_wasmer1(wasm_code, config, store);
}
let cache = cache.unwrap();
match cache.get(&key.0) {
Ok(serialized) => match serialized {
Some(serialized) => deserialize_wasmer1(serialized.as_slice(), store)
.map_err(VMError::CacheError)?,
None => compile_and_serialize_wasmer1(wasm_code, &key, config, cache, store),
},
Err(_) => Err(VMError::CacheError(ReadError)),
}
}
#[cfg(not(feature = "no_cache"))]
cached_key! {
MODULES: SizedCache<CryptoHash, Result<wasmer::Module, VMError>>
= SizedCache::with_size(CACHE_SIZE);
Key = {
key
};
fn memcache_compile_module_cached_wasmer1(
key: CryptoHash,
wasm_code: &[u8],
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
store: &wasmer::Store) -> Result<wasmer::Module, VMError> = {
compile_module_cached_wasmer1_impl(key, wasm_code, config, cache, store)
}
}
pub(crate) fn compile_module_cached_wasmer1(
code: &ContractCode,
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
store: &wasmer::Store,
) -> Result<wasmer::Module, VMError> {
let key = get_contract_cache_key(code, VMKind::Wasmer1, config);
#[cfg(not(feature = "no_cache"))]
return memcache_compile_module_cached_wasmer1(key, code.code(), config, cache, store);
#[cfg(feature = "no_cache")]
return compile_module_cached_wasmer1_impl(key, code.code(), config, cache, store);
}
}
pub fn precompile_contract_vm(
vm_kind: VMKind,
wasm_code: &ContractCode,
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
) -> Result<ContractPrecompilatonResult, ContractPrecompilatonError> {
let cache = match cache {
None => return Ok(ContractPrecompilatonResult::CacheNotAvailable),
Some(it) => it,
};
let key = get_contract_cache_key(wasm_code, vm_kind, config);
// Check if we already cached with such a key.
match cache.get(&key.0) {
// If so - do not override.
Ok(Some(_)) => return Ok(ContractPrecompilatonResult::ContractAlreadyInCache),
Ok(None) | Err(_) => {}
};
match vm_kind {
VMKind::Wasmer0 => {
match wasmer0_cache::compile_and_serialize_wasmer(wasm_code.code(), config, &key, cache)
{
Ok(_) => Ok(ContractPrecompilatonResult::ContractCompiled),
Err(err) => Err(ContractPrecompilatonError::new(err)),
}
}
VMKind::Wasmer1 => {
let store = default_wasmer1_store();
match wasmer1_cache::compile_and_serialize_wasmer1(
wasm_code.code(),
&key,
config,
cache,
&store,
) {
Ok(_) => Ok(ContractPrecompilatonResult::ContractCompiled),
Err(err) => Err(ContractPrecompilatonError::new(err)),
}
}
VMKind::Wasmtime => {
panic!("Not yet supported")
}
}
}
/// Precompiles contract for the current default VM, and stores result to the cache.
/// Returns `Ok(true)` if compiled code was added to the cache, and `Ok(false)` if element
/// is already in the cache, or if cache is `None`.
pub fn precompile_contract(
wasm_code: &ContractCode,
config: &VMConfig,
cache: Option<&dyn CompiledContractCache>,
) -> Result<ContractPrecompilatonResult, ContractPrecompilatonError> {
precompile_contract_vm(VMKind::default(), wasm_code, config, cache)
}