-
Notifications
You must be signed in to change notification settings - Fork 335
/
memory.rs
217 lines (188 loc) · 7.44 KB
/
memory.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
use std::time::SystemTime;
use tempfile::TempDir;
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use cosmwasm_std::{coins, Empty};
use cosmwasm_vm::testing::{mock_backend, mock_env, mock_info, MockApi, MockQuerier, MockStorage};
use cosmwasm_vm::{
call_execute, call_instantiate, capabilities_from_csv, Cache, CacheOptions, Checksum,
InstanceOptions, Size,
};
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
const END_AFTER: u64 = 2 * 60; // seconds
const ROUNDS: usize = 1024;
const ROUND_LEN: usize = 16;
// Instance
const DEFAULT_MEMORY_LIMIT: Size = Size::mebi(64);
const DEFAULT_GAS_LIMIT: u64 = u64::MAX;
const DEFAULT_INSTANCE_OPTIONS: InstanceOptions = InstanceOptions {
gas_limit: DEFAULT_GAS_LIMIT,
print_debug: false,
};
// Cache
const MEMORY_CACHE_SIZE: Size = Size::mebi(5);
struct Execute {
pub msg: &'static [u8],
pub expect_error: bool,
}
struct Contract {
pub wasm: &'static [u8],
pub instantiate_msg: Option<&'static [u8]>,
pub execute_msgs: Vec<Execute>,
}
fn contracts() -> Vec<Contract> {
vec![
Contract {
wasm: include_bytes!("../testdata/cyberpunk.wasm"),
instantiate_msg: Some(b"{}"),
execute_msgs: vec![
Execute {
msg: br#"{"unreachable":{}}"#,
expect_error: true,
},
Execute {
msg: br#"{"allocate_large_memory":{"pages":1000}}"#,
expect_error: false,
},
Execute {
// mem_cost in KiB
msg: br#"{"argon2":{"mem_cost":256,"time_cost":1}}"#,
expect_error: false,
},
Execute {
msg: br#"{"memory_loop":{}}"#,
expect_error: true,
},
],
},
Contract {
wasm: include_bytes!("../testdata/hackatom.wasm"),
instantiate_msg: Some(br#"{"verifier": "verifies", "beneficiary": "benefits"}"#),
execute_msgs: vec![Execute {
msg: br#"{"release":{}}"#,
expect_error: false,
}],
},
Contract {
wasm: include_bytes!("../testdata/hackatom_1.0.wasm"),
instantiate_msg: Some(br#"{"verifier": "verifies", "beneficiary": "benefits"}"#),
execute_msgs: vec![Execute {
msg: br#"{"release":{}}"#,
expect_error: false,
}],
},
Contract {
wasm: include_bytes!("../testdata/ibc_reflect.wasm"),
instantiate_msg: None,
execute_msgs: vec![],
},
]
}
fn app() -> () {
let start_time = SystemTime::now();
let options = CacheOptions::new(
TempDir::new().unwrap().into_path(),
capabilities_from_csv("iterator,staking,stargate"),
MEMORY_CACHE_SIZE,
DEFAULT_MEMORY_LIMIT,
);
let contracts = contracts();
let checksums = {
let cache: Cache<MockApi, MockStorage, MockQuerier> =
unsafe { Cache::new(options.clone()).unwrap() };
let mut checksums = Vec::<Checksum>::new();
for contract in &contracts {
checksums.push(cache.save_wasm(contract.wasm).unwrap());
}
checksums
};
let after = SystemTime::now().duration_since(start_time).unwrap();
eprintln!("Done compiling after {after:?}");
let cache: Cache<MockApi, MockStorage, MockQuerier> =
unsafe { Cache::new(options.clone()).unwrap() };
for round in 0..ROUNDS {
for _ in 0..ROUND_LEN {
if SystemTime::now()
.duration_since(start_time)
.unwrap()
.as_secs()
> END_AFTER
{
eprintln!("Round {round}. End time reached. Ending the process");
let metrics = cache.metrics();
eprintln!("Cache metrics: {metrics:?}");
return; // ends app()
}
for idx in 0..contracts.len() {
let mut instance = cache
.get_instance(&checksums[idx], mock_backend(&[]), DEFAULT_INSTANCE_OPTIONS)
.unwrap();
instance.set_debug_handler(|_msg, info| {
let _t = now_rfc3339();
let _gas = info.gas_remaining;
//eprintln!("[{t}]: {msg} (gas remaining: {gas})");
});
if let Some(msg) = contracts[idx].instantiate_msg {
let info = mock_info("creator", &coins(1000, "earth"));
let contract_result =
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg)
.unwrap();
assert!(contract_result.into_result().is_ok());
}
for (execution_idx, execute) in contracts[idx].execute_msgs.iter().enumerate() {
let info = mock_info("verifies", &coins(15, "earth"));
let msg = execute.msg;
let res =
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg);
if execute.expect_error {
if !res.is_err() {
panic!(
"Round {round}, Execution {execution_idx}, Contract {idx}. Expected error but got {res:?}"
);
}
} else {
if res.is_err() {
panic!("Round {round}, Execution {execution_idx}, Contract {idx}. Expected no error but got {res:?}");
}
}
}
}
/*
let mut instance = cache
.get_instance(&checksums[1], mock_backend(&[]), DEFAULT_INSTANCE_OPTIONS)
.unwrap();
// println!("Done instantiating contract {i}");
instance.set_debug_handler(|msg, info| {
let t = now_rfc3339();
let gas = info.gas_remaining;
eprintln!("[{t}]: {msg} (gas remaining: {gas})");
});
let info = mock_info("creator", &coins(1000, "earth"));
let msg = br#"{"verifier": "verifies", "beneficiary": "benefits"}"#;
let contract_result =
call_instantiate::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg).unwrap();
assert!(contract_result.into_result().is_ok());
let info = mock_info("verifies", &coins(15, "earth"));
let msg = br#"{"release":{}}"#;
let contract_result =
call_execute::<_, _, _, Empty>(&mut instance, &mock_env(), &info, msg).unwrap();
assert!(contract_result.into_result().is_ok());
*/
}
// let stats = cache.stats();
// // eprintln!("Stats: {stats:?}");
// assert_eq!(stats.misses, 0);
// assert_eq!(stats.hits_fs_cache, 2);
// assert_eq!(stats.hits_memory_cache as usize, 2 * (ROUND_LEN - 1));
}
}
fn now_rfc3339() -> String {
let dt = OffsetDateTime::from(SystemTime::now());
dt.format(&Rfc3339).unwrap_or_default()
}
pub fn main() {
#[cfg(feature = "dhat-heap")]
let _profiler = dhat::Profiler::new_heap();
app();
}