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
use crate::error::{Error, WasmError};
use log::{trace, warn};
use codec::Decode;
use sp_core::{storage::well_known_keys, traits::Externalities};
use sp_version::RuntimeVersion;
use std::{collections::hash_map::{Entry, HashMap}, panic::AssertUnwindSafe};
use sc_executor_common::wasm_runtime::WasmRuntime;
use sp_wasm_interface::Function;
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum WasmExecutionMethod {
Interpreted,
#[cfg(feature = "wasmtime")]
Compiled,
}
struct VersionedRuntime {
runtime: Box<dyn WasmRuntime>,
heap_pages: u64,
version: RuntimeVersion,
}
pub struct RuntimesCache {
instances: HashMap<(WasmExecutionMethod, Vec<u8>), Result<VersionedRuntime, WasmError>>,
}
impl RuntimesCache {
pub fn new() -> RuntimesCache {
RuntimesCache {
instances: HashMap::new(),
}
}
pub fn fetch_runtime<E: Externalities>(
&mut self,
ext: &mut E,
wasm_method: WasmExecutionMethod,
default_heap_pages: u64,
host_functions: &[&'static dyn Function],
) -> Result<(&mut (dyn WasmRuntime + 'static), &RuntimeVersion, Vec<u8>), Error> {
let code_hash = ext
.original_storage_hash(well_known_keys::CODE)
.ok_or(Error::InvalidCode("`CODE` not found in storage.".into()))?;
let heap_pages = ext
.storage(well_known_keys::HEAP_PAGES)
.and_then(|pages| u64::decode(&mut &pages[..]).ok())
.unwrap_or(default_heap_pages);
let result = match self.instances.entry((wasm_method, code_hash.clone())) {
Entry::Occupied(o) => {
let result = o.into_mut();
if let Ok(ref mut cached_runtime) = result {
let heap_pages_changed = cached_runtime.heap_pages != heap_pages;
let host_functions_changed = cached_runtime.runtime.host_functions()
!= host_functions;
if heap_pages_changed || host_functions_changed {
let changed = if heap_pages_changed {
"heap_pages"
} else {
"host functions"
};
trace!(
target: "runtimes_cache",
"{} were changed. Reinstantiating the instance",
changed,
);
*result = create_versioned_wasm_runtime(
ext,
wasm_method,
heap_pages,
host_functions.into(),
);
if let Err(ref err) = result {
warn!(target: "runtimes_cache", "cannot create a runtime: {:?}", err);
}
}
}
result
},
Entry::Vacant(v) => {
trace!(target: "runtimes_cache", "no instance found in cache, creating now.");
let result = create_versioned_wasm_runtime(
ext,
wasm_method,
heap_pages,
host_functions.into(),
);
if let Err(ref err) = result {
warn!(target: "runtimes_cache", "cannot create a runtime: {:?}", err);
}
v.insert(result)
}
};
result.as_mut()
.map(|entry| (entry.runtime.as_mut(), &entry.version, code_hash))
.map_err(|ref e| Error::InvalidCode(format!("{:?}", e)))
}
pub fn invalidate_runtime(
&mut self,
wasm_method: WasmExecutionMethod,
code_hash: Vec<u8>,
) {
self.instances.remove(&(wasm_method, code_hash));
}
}
pub fn create_wasm_runtime_with_code(
wasm_method: WasmExecutionMethod,
heap_pages: u64,
code: &[u8],
host_functions: Vec<&'static dyn Function>,
allow_missing_func_imports: bool,
) -> Result<Box<dyn WasmRuntime>, WasmError> {
match wasm_method {
WasmExecutionMethod::Interpreted =>
sc_executor_wasmi::create_instance(code, heap_pages, host_functions, allow_missing_func_imports)
.map(|runtime| -> Box<dyn WasmRuntime> { Box::new(runtime) }),
#[cfg(feature = "wasmtime")]
WasmExecutionMethod::Compiled =>
sc_executor_wasmtime::create_instance(code, heap_pages, host_functions, allow_missing_func_imports)
.map(|runtime| -> Box<dyn WasmRuntime> { Box::new(runtime) }),
}
}
fn create_versioned_wasm_runtime<E: Externalities>(
ext: &mut E,
wasm_method: WasmExecutionMethod,
heap_pages: u64,
host_functions: Vec<&'static dyn Function>,
) -> Result<VersionedRuntime, WasmError> {
let code = ext
.original_storage(well_known_keys::CODE)
.ok_or(WasmError::CodeNotFound)?;
let mut runtime = create_wasm_runtime_with_code(wasm_method, heap_pages, &code, host_functions, false)?;
let version_result = {
let mut ext = AssertUnwindSafe(ext);
let mut runtime = AssertUnwindSafe(runtime.as_mut());
crate::native_executor::with_externalities_safe(
&mut **ext,
move || runtime.call("Core_version", &[])
).map_err(|_| WasmError::Instantiation("panic in call to get runtime version".into()))?
};
let encoded_version = version_result
.map_err(|e| WasmError::Instantiation(format!("failed to call \"Core_version\": {}", e)))?;
let version = RuntimeVersion::decode(&mut encoded_version.as_slice())
.map_err(|_| WasmError::Instantiation("failed to decode \"Core_version\" result".into()))?;
Ok(VersionedRuntime {
runtime,
version,
heap_pages,
})
}
#[cfg(test)]
mod tests {
use sp_wasm_interface::HostFunctions;
#[test]
fn host_functions_are_equal() {
let host_functions = sp_io::SubstrateHostFunctions::host_functions();
let equal = &host_functions[..] == &host_functions[..];
assert!(equal, "Host functions are not equal");
}
}