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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use crate::Config;
use frame_support::traits::Get;
use pwasm_utils::{
parity_wasm::{
builder,
elements::{
self, BlockType, CustomSection, FuncBody, Instruction, Instructions, Section, ValueType,
},
},
stack_height::inject_limiter,
};
use sp_core::crypto::UncheckedFrom;
use sp_runtime::traits::Hash;
use sp_sandbox::{EnvironmentDefinitionBuilder, Memory};
use sp_std::{borrow::ToOwned, convert::TryFrom, prelude::*};
#[derive(Default)]
pub struct ModuleDefinition {
pub memory: Option<ImportedMemory>,
pub data_segments: Vec<DataSegment>,
pub num_globals: u32,
pub imported_functions: Vec<ImportedFunction>,
pub deploy_body: Option<FuncBody>,
pub call_body: Option<FuncBody>,
pub aux_body: Option<FuncBody>,
pub aux_arg_num: u32,
pub inject_stack_metering: bool,
pub table: Option<TableSegment>,
pub dummy_section: u32,
}
pub struct TableSegment {
pub num_elements: u32,
pub function_index: u32,
}
pub struct DataSegment {
pub offset: u32,
pub value: Vec<u8>,
}
#[derive(Clone)]
pub struct ImportedMemory {
pub min_pages: u32,
pub max_pages: u32,
}
impl ImportedMemory {
pub fn max<T: Config>() -> Self
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
{
let pages = max_pages::<T>();
Self { min_pages: pages, max_pages: pages }
}
}
pub struct ImportedFunction {
pub module: &'static str,
pub name: &'static str,
pub params: Vec<ValueType>,
pub return_type: Option<ValueType>,
}
#[derive(Clone)]
pub struct WasmModule<T: Config> {
pub code: Vec<u8>,
pub hash: <T::Hashing as Hash>::Output,
memory: Option<ImportedMemory>,
}
impl<T: Config> From<ModuleDefinition> for WasmModule<T>
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
{
fn from(def: ModuleDefinition) -> Self {
let func_offset = u32::try_from(def.imported_functions.len()).unwrap();
let mut contract = builder::module()
.function()
.signature()
.build()
.with_body(
def.deploy_body
.unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())),
)
.build()
.function()
.signature()
.build()
.with_body(
def.call_body
.unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())),
)
.build()
.export()
.field("deploy")
.internal()
.func(func_offset)
.build()
.export()
.field("call")
.internal()
.func(func_offset + 1)
.build();
if let Some(body) = def.aux_body {
let mut signature = contract.function().signature();
for _ in 0..def.aux_arg_num {
signature = signature.with_param(ValueType::I64);
}
contract = signature.build().with_body(body).build();
}
if let Some(memory) = &def.memory {
contract = contract
.import()
.module("env")
.field("memory")
.external()
.memory(memory.min_pages, Some(memory.max_pages))
.build();
}
for func in def.imported_functions {
let sig = builder::signature()
.with_params(func.params)
.with_results(func.return_type.into_iter().collect())
.build_sig();
let sig = contract.push_signature(sig);
contract = contract
.import()
.module(func.module)
.field(func.name)
.with_external(elements::External::Function(sig))
.build();
}
for data in def.data_segments {
contract = contract
.data()
.offset(Instruction::I32Const(data.offset as i32))
.value(data.value)
.build()
}
if def.num_globals > 0 {
use rand::{distributions::Standard, prelude::*};
let rng = rand_pcg::Pcg32::seed_from_u64(3112244599778833558);
for val in rng.sample_iter(Standard).take(def.num_globals as usize) {
contract = contract
.global()
.value_type()
.i64()
.mutable()
.init_expr(Instruction::I64Const(val))
.build()
}
}
if let Some(table) = def.table {
contract = contract
.table()
.with_min(table.num_elements)
.with_max(Some(table.num_elements))
.with_element(0, vec![table.function_index; table.num_elements as usize])
.build();
}
if def.dummy_section > 0 {
contract = contract.with_section(Section::Custom(CustomSection::new(
"dummy".to_owned(),
vec![42; def.dummy_section as usize],
)));
}
let mut code = contract.build();
if def.inject_stack_metering {
code = inject_limiter(code, T::Schedule::get().limits.stack_height).unwrap();
}
let code = code.to_bytes().unwrap();
let hash = T::Hashing::hash(&code);
Self { code, hash, memory: def.memory }
}
}
impl<T: Config> WasmModule<T>
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
{
pub fn dummy() -> Self {
ModuleDefinition::default().into()
}
pub fn dummy_with_bytes(dummy_bytes: u32) -> Self {
let module_overhead = 65;
ModuleDefinition {
memory: Some(ImportedMemory::max::<T>()),
dummy_section: dummy_bytes.saturating_sub(module_overhead),
..Default::default()
}
.into()
}
pub fn sized(target_bytes: u32) -> Self {
use self::elements::Instruction::{End, I32Const, If, Return};
let expansions = (target_bytes.saturating_sub(63) / 6).saturating_sub(1);
const EXPANSION: [Instruction; 4] = [I32Const(0), If(BlockType::NoResult), Return, End];
ModuleDefinition {
call_body: Some(body::repeated(expansions, &EXPANSION)),
memory: Some(ImportedMemory::max::<T>()),
..Default::default()
}
.into()
}
pub fn getter(getter_name: &'static str, repeat: u32) -> Self {
let pages = max_pages::<T>();
ModuleDefinition {
memory: Some(ImportedMemory::max::<T>()),
imported_functions: vec![ImportedFunction {
module: "seal0",
name: getter_name,
params: vec![ValueType::I32, ValueType::I32],
return_type: None,
}],
data_segments: vec![DataSegment {
offset: 0,
value: (pages * 64 * 1024 - 4).to_le_bytes().to_vec(),
}],
call_body: Some(body::repeated(
repeat,
&[
Instruction::I32Const(4),
Instruction::I32Const(0),
Instruction::Call(0),
],
)),
..Default::default()
}
.into()
}
pub fn hasher(name: &'static str, repeat: u32, data_size: u32) -> Self {
ModuleDefinition {
memory: Some(ImportedMemory::max::<T>()),
imported_functions: vec![ImportedFunction {
module: "seal0",
name,
params: vec![ValueType::I32, ValueType::I32, ValueType::I32],
return_type: None,
}],
call_body: Some(body::repeated(
repeat,
&[
Instruction::I32Const(0),
Instruction::I32Const(data_size as i32),
Instruction::I32Const(0),
Instruction::Call(0),
],
)),
..Default::default()
}
.into()
}
pub fn add_memory<S>(&self, env: &mut EnvironmentDefinitionBuilder<S>) -> Option<Memory> {
let memory = if let Some(memory) = &self.memory { memory } else { return None };
let memory = Memory::new(memory.min_pages, Some(memory.max_pages)).unwrap();
env.add_memory("env", "memory", memory.clone());
Some(memory)
}
pub fn unary_instr(instr: Instruction, repeat: u32) -> Self {
use body::DynInstr::{RandomI64Repeated, Regular};
ModuleDefinition {
call_body: Some(body::repeated_dyn(
repeat,
vec![RandomI64Repeated(1), Regular(instr), Regular(Instruction::Drop)],
)),
..Default::default()
}
.into()
}
pub fn binary_instr(instr: Instruction, repeat: u32) -> Self {
use body::DynInstr::{RandomI64Repeated, Regular};
ModuleDefinition {
call_body: Some(body::repeated_dyn(
repeat,
vec![RandomI64Repeated(2), Regular(instr), Regular(Instruction::Drop)],
)),
..Default::default()
}
.into()
}
}
pub mod body {
use super::*;
pub enum DynInstr {
Regular(Instruction),
Counter(u32, u32),
RandomUnaligned(u32, u32),
RandomI32(i32, i32),
RandomI32Repeated(usize),
RandomI64Repeated(usize),
RandomGetLocal(u32, u32),
RandomSetLocal(u32, u32),
RandomTeeLocal(u32, u32),
RandomGetGlobal(u32, u32),
RandomSetGlobal(u32, u32),
}
pub fn plain(instructions: Vec<Instruction>) -> FuncBody {
FuncBody::new(Vec::new(), Instructions::new(instructions))
}
pub fn repeated(repetitions: u32, instructions: &[Instruction]) -> FuncBody {
let instructions = Instructions::new(
instructions
.iter()
.cycle()
.take(instructions.len() * usize::try_from(repetitions).unwrap())
.cloned()
.chain(sp_std::iter::once(Instruction::End))
.collect(),
);
FuncBody::new(Vec::new(), instructions)
}
pub fn repeated_dyn(repetitions: u32, mut instructions: Vec<DynInstr>) -> FuncBody {
use rand::{distributions::Standard, prelude::*};
let mut rng = rand_pcg::Pcg32::seed_from_u64(8446744073709551615);
let body = (0..instructions.len())
.cycle()
.take(instructions.len() * usize::try_from(repetitions).unwrap())
.flat_map(|idx| match &mut instructions[idx] {
DynInstr::Regular(instruction) => vec![instruction.clone()],
DynInstr::Counter(offset, increment_by) => {
let current = *offset;
*offset += *increment_by;
vec![Instruction::I32Const(current as i32)]
},
DynInstr::RandomUnaligned(low, high) => {
let unaligned = rng.gen_range(*low..*high) | 1;
vec![Instruction::I32Const(unaligned as i32)]
},
DynInstr::RandomI32(low, high) => {
vec![Instruction::I32Const(rng.gen_range(*low..*high))]
},
DynInstr::RandomI32Repeated(num) => (&mut rng)
.sample_iter(Standard)
.take(*num)
.map(|val| Instruction::I32Const(val))
.collect(),
DynInstr::RandomI64Repeated(num) => (&mut rng)
.sample_iter(Standard)
.take(*num)
.map(|val| Instruction::I64Const(val))
.collect(),
DynInstr::RandomGetLocal(low, high) => {
vec![Instruction::GetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetLocal(low, high) => {
vec![Instruction::SetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomTeeLocal(low, high) => {
vec![Instruction::TeeLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomGetGlobal(low, high) => {
vec![Instruction::GetGlobal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetGlobal(low, high) => {
vec![Instruction::SetGlobal(rng.gen_range(*low..*high))]
},
})
.chain(sp_std::iter::once(Instruction::End))
.collect();
FuncBody::new(Vec::new(), Instructions::new(body))
}
pub fn inject_locals(body: &mut FuncBody, num: u32) {
use self::elements::Local;
*body.locals_mut() = vec![Local::new(num, ValueType::I64)];
}
}
pub fn max_pages<T: Config>() -> u32
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
{
T::Schedule::get().limits.memory_pages
}