-
Notifications
You must be signed in to change notification settings - Fork 588
/
cache.rs
287 lines (267 loc) · 10.6 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
//! Tests that `CompiledContractCache` is working correctly. Currently testing only wasmer code, so disabled outside of x86_64
#![cfg(target_arch = "x86_64")]
use super::{create_context, with_vm_variants, LATEST_PROTOCOL_VERSION};
use crate::internal::VMKind;
use crate::near_vm_runner::NearVM;
use crate::runner::VMResult;
use crate::wasmer2_runner::Wasmer2VM;
use crate::{prepare, MockCompiledContractCache};
use assert_matches::assert_matches;
use near_primitives::contract::ContractCode;
use near_primitives::hash::CryptoHash;
use near_primitives::runtime::fees::RuntimeFeesConfig;
use near_primitives::types::{CompiledContract, CompiledContractCache};
use near_stable_hasher::StableHasher;
use near_vm_compiler::{CpuFeature, Target};
use near_vm_engine::Executable;
use near_vm_errors::VMRunnerError;
use near_vm_logic::mocks::mock_external::MockedExternal;
use near_vm_logic::VMConfig;
use std::hash::{Hash, Hasher};
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn test_caches_compilation_error() {
let config = VMConfig::test();
with_vm_variants(&config, |vm_kind: VMKind| {
match vm_kind {
VMKind::Wasmer0 | VMKind::Wasmer2 | VMKind::NearVm => {}
VMKind::Wasmtime => return,
}
let cache = MockCompiledContractCache::default();
let code = [42; 1000];
let terragas = 1000000000000u64;
assert_eq!(cache.len(), 0);
let outcome1 =
make_cached_contract_call_vm(&config, &cache, &code, "method_name1", terragas, vm_kind)
.expect("bad failure");
println!("{:?}", cache);
assert_eq!(cache.len(), 1);
let outcome2 =
make_cached_contract_call_vm(&config, &cache, &code, "method_name2", terragas, vm_kind)
.expect("bad failure");
assert_eq!(outcome1.aborted.as_ref(), outcome2.aborted.as_ref());
})
}
#[test]
fn test_does_not_cache_io_error() {
let config = VMConfig::test();
with_vm_variants(&config, |vm_kind: VMKind| {
match vm_kind {
VMKind::Wasmer0 | VMKind::Wasmer2 | VMKind::NearVm => {}
VMKind::Wasmtime => return,
}
let code = near_test_contracts::trivial_contract();
let prepaid_gas = 10u64.pow(12);
let mut cache = FaultingCompiledContractCache::default();
cache.set_read_fault(true);
let result =
make_cached_contract_call_vm(&config, &cache, &code, "main", prepaid_gas, vm_kind);
assert_matches!(
result.err(),
Some(VMRunnerError::CacheError(near_vm_errors::CacheError::ReadError(_)))
);
cache.set_write_fault(true);
let result =
make_cached_contract_call_vm(&config, &cache, &code, "main", prepaid_gas, vm_kind);
assert_matches!(
result.err(),
Some(VMRunnerError::CacheError(near_vm_errors::CacheError::WriteError(_)))
);
})
}
fn make_cached_contract_call_vm(
config: &VMConfig,
cache: &dyn CompiledContractCache,
code: &[u8],
method_name: &str,
prepaid_gas: u64,
vm_kind: VMKind,
) -> VMResult {
let mut fake_external = MockedExternal::new();
let mut context = create_context(vec![]);
let fees = RuntimeFeesConfig::test();
let promise_results = vec![];
context.prepaid_gas = prepaid_gas;
let code = ContractCode::new(code.to_vec(), None);
let runtime = vm_kind.runtime(config.clone()).expect("runtime has not been compiled");
runtime.run(
&code,
method_name,
&mut fake_external,
context,
&fees,
&promise_results,
LATEST_PROTOCOL_VERSION,
Some(cache),
)
}
#[test]
fn test_wasmer2_artifact_output_stability() {
use wasmer_engine::Executable;
// If this test has failed, you want to adjust the necessary constants so that `cache::vm_hash`
// changes (and only then the hashes here).
//
// Note that this test is a best-effort fish net. Some changes that should modify the hash will
// fall through the cracks here, but hopefully it should catch most of the fish just fine.
let seeds = [2, 3, 5, 7, 11, 13, 17];
let prepared_hashes = [
11313378614122864359,
5865541421624917606,
11731917380556063495,
8000182875575317016,
3130574445877428311,
11574598916196339098,
10719493536745069553,
];
let mut got_prepared_hashes = Vec::with_capacity(seeds.len());
let compiled_hashes = [
16241863964906842660,
9891733092817574479,
10697830987582926315,
8841851979868162585,
10549554738494211661,
11197084127324548219,
6788687979647989853,
];
let mut got_compiled_hashes = Vec::with_capacity(seeds.len());
for seed in seeds {
let contract = ContractCode::new(near_test_contracts::arbitrary_contract(seed), None);
let config = VMConfig::test();
let prepared_code =
prepare::prepare_contract(contract.code(), &config, VMKind::Wasmer2).unwrap();
let mut hasher = StableHasher::new();
(&contract.code(), &prepared_code).hash(&mut hasher);
got_prepared_hashes.push(hasher.finish());
let mut features = wasmer_compiler::CpuFeature::set();
features.insert(wasmer_compiler::CpuFeature::AVX);
let triple = "x86_64-unknown-linux-gnu".parse().unwrap();
let target = wasmer_compiler::Target::new(triple, features);
let vm = Wasmer2VM::new_for_target(config, target);
let artifact = vm.compile_uncached(&contract).unwrap();
let serialized = artifact.serialize().unwrap();
let mut hasher = StableHasher::new();
serialized.hash(&mut hasher);
let this_hash = hasher.finish();
got_compiled_hashes.push(this_hash);
std::fs::write(format!("/tmp/artifact{}", this_hash), serialized).unwrap();
}
// These asserts have failed as a result of some change and the following text describes what
// the implications of the change.
//
// May need a protocol version change, and definitely wants a `WASMER2_CONFIG version update
// too, as below. Maybe something else too.
assert!(
got_prepared_hashes == prepared_hashes,
"contract preparation hashes have changed to {:#?}",
got_prepared_hashes
);
// In this case you will need to adjust the WASMER2_CONFIG version so that the cached contracts
// are evicted from the contract cache.
assert!(
got_compiled_hashes == compiled_hashes,
"VM output hashes have changed to {:#?}",
got_compiled_hashes
);
// Once it has been confirmed that these steps have been done, the expected hashes in this test
// can be adjusted.
}
#[test]
fn test_near_vm_artifact_output_stability() {
// If this test has failed, you want to adjust the necessary constants so that `cache::vm_hash`
// changes (and only then the hashes here).
//
// Note that this test is a best-effort fish net. Some changes that should modify the hash will
// fall through the cracks here, but hopefully it should catch most of the fish just fine.
let seeds = [2, 3, 5, 7, 11, 13, 17];
let prepared_hashes = [
15237011375120738807,
3750594434467176559,
2196541628148102482,
1576495094908614397,
6394387219699970793,
18132026143745992229,
4095228008100475322,
];
let mut got_prepared_hashes = Vec::with_capacity(seeds.len());
let compiled_hashes = [
13406898264102036990,
357008982248812492,
10171838574337806556,
8933666767302544249,
9580084654030896497,
6856335382562175488,
17700820009951734912,
];
let mut got_compiled_hashes = Vec::with_capacity(seeds.len());
for seed in seeds {
let contract = ContractCode::new(near_test_contracts::arbitrary_contract(seed), None);
let config = VMConfig::test();
let prepared_code =
prepare::prepare_contract(contract.code(), &config, VMKind::NearVm).unwrap();
let mut hasher = StableHasher::new();
(&contract.code(), &prepared_code).hash(&mut hasher);
got_prepared_hashes.push(hasher.finish());
let mut features = CpuFeature::set();
features.insert(CpuFeature::AVX);
let triple = "x86_64-unknown-linux-gnu".parse().unwrap();
let target = Target::new(triple, features);
let vm = NearVM::new_for_target(config, target);
let artifact = vm.compile_uncached(&contract).unwrap();
let serialized = artifact.serialize().unwrap();
let mut hasher = StableHasher::new();
serialized.hash(&mut hasher);
let this_hash = hasher.finish();
got_compiled_hashes.push(this_hash);
std::fs::write(format!("/tmp/artifact{}", this_hash), serialized).unwrap();
}
// These asserts have failed as a result of some change and the following text describes what
// the implications of the change.
//
// May need a protocol version change, and definitely wants a `WASMER2_CONFIG version update
// too, as below. Maybe something else too.
assert!(
got_prepared_hashes == prepared_hashes,
"contract preparation hashes have changed to {:#?}",
got_prepared_hashes
);
// In this case you will need to adjust the WASMER2_CONFIG version so that the cached contracts
// are evicted from the contract cache.
assert!(
got_compiled_hashes == compiled_hashes,
"VM output hashes have changed to {:#?}",
got_compiled_hashes
);
// Once it has been confirmed that these steps have been done, the expected hashes in this test
// can be adjusted.
}
/// [`CompiledContractCache`] which simulates failures in the underlying
/// database.
#[derive(Default)]
struct FaultingCompiledContractCache {
read_fault: AtomicBool,
write_fault: AtomicBool,
inner: MockCompiledContractCache,
}
impl FaultingCompiledContractCache {
fn set_read_fault(&mut self, yes: bool) {
*self.read_fault.get_mut() = yes;
}
fn set_write_fault(&mut self, yes: bool) {
*self.write_fault.get_mut() = yes;
}
}
impl CompiledContractCache for FaultingCompiledContractCache {
fn put(&self, key: &CryptoHash, value: CompiledContract) -> std::io::Result<()> {
if self.write_fault.swap(false, Ordering::Relaxed) {
return Err(io::ErrorKind::Other.into());
}
self.inner.put(key, value)
}
fn get(&self, key: &CryptoHash) -> std::io::Result<Option<CompiledContract>> {
if self.read_fault.swap(false, Ordering::Relaxed) {
return Err(io::ErrorKind::Other.into());
}
self.inner.get(key)
}
}