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
use crate::{
database::Database,
exec_context::ExecContext,
test_api::{
DebugInfo,
EmittedEvent,
},
types::{
AccountId,
Key,
},
};
use std::panic::panic_any;
type Result = core::result::Result<(), Error>;
macro_rules! define_error_codes {
(
$(
$( #[$attr:meta] )*
$name:ident = $discr:literal,
)*
) => {
#[cfg_attr(test, derive(PartialEq, Eq))]
#[derive(Debug)]
#[repr(u32)]
pub enum Error {
$(
$( #[$attr] )*
$name = $discr,
)*
Unknown,
}
impl From<ReturnCode> for Result {
#[inline]
fn from(return_code: ReturnCode) -> Self {
match return_code.0 {
0 => Ok(()),
$(
$discr => Err(Error::$name),
)*
_ => Err(Error::Unknown),
}
}
}
};
}
define_error_codes! {
CalleeTrapped = 1,
CalleeReverted = 2,
KeyNotFound = 3,
BelowSubsistenceThreshold = 4,
TransferFailed = 5,
NewContractNotFunded = 6,
CodeNotFound = 7,
NotCallable = 8,
LoggingDisabled = 9,
EcdsaRecoverFailed = 11,
}
#[repr(transparent)]
pub struct ReturnCode(u32);
impl ReturnCode {
pub fn into_u32(self) -> u32 {
self.0
}
}
pub struct Engine {
pub database: Database,
pub exec_context: ExecContext,
pub(crate) debug_info: DebugInfo,
}
impl Engine {
pub fn new() -> Self {
Self {
database: Database::new(),
exec_context: ExecContext::new(),
debug_info: DebugInfo::new(),
}
}
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
impl Engine {
pub fn transfer(&mut self, account_id: &[u8], mut value: &[u8]) -> Result {
let increment = <u128 as scale::Decode>::decode(&mut value)
.map_err(|_| Error::TransferFailed)?;
let dest = account_id.to_vec();
let dest_old_balance = self.get_balance(dest.clone()).unwrap_or_default();
let contract = self.get_callee();
let contract_old_balance = self
.get_balance(contract.clone())
.map_err(|_| Error::TransferFailed)?;
self.database
.set_balance(&contract, contract_old_balance - increment);
self.database
.set_balance(&dest, dest_old_balance + increment);
Ok(())
}
pub fn deposit_event(&mut self, topics: &[u8], data: &[u8]) {
let topics_count: scale::Compact<u32> = scale::Decode::decode(&mut &topics[0..1])
.expect("decoding number of topics failed");
let topics_count = topics_count.0 as usize;
let topics_vec = if topics_count > 0 {
let topics = &topics[1..];
let bytes_per_topic = topics.len() / topics_count;
let topics_vec: Vec<Vec<u8>> = topics
.chunks(bytes_per_topic)
.map(|chunk| chunk.to_vec())
.collect();
assert_eq!(topics_count, topics_vec.len());
topics_vec
} else {
Vec::new()
};
self.debug_info.record_event(EmittedEvent {
topics: topics_vec,
data: data.to_vec(),
});
}
pub fn set_storage(&mut self, key: &[u8; 32], encoded_value: &[u8]) {
let callee = self.get_callee();
let account_id = AccountId::from_bytes(&callee[..]);
self.debug_info.inc_writes(account_id.clone());
self.debug_info
.record_cell_for_account(account_id, key.to_vec());
let _ = self.database.insert_into_contract_storage(
&callee,
key,
encoded_value.to_vec(),
);
}
pub fn get_storage(&mut self, key: &[u8; 32], output: &mut &mut [u8]) -> Result {
let callee = self.get_callee();
let account_id = AccountId::from_bytes(&callee[..]);
self.debug_info.inc_reads(account_id);
match self.database.get_from_contract_storage(&callee, key) {
Some(val) => {
set_output(output, val);
Ok(())
}
None => Err(Error::KeyNotFound),
}
}
pub fn clear_storage(&mut self, key: &[u8; 32]) {
let callee = self.get_callee();
let account_id = AccountId::from_bytes(&callee[..]);
self.debug_info.inc_writes(account_id.clone());
let _ = self
.debug_info
.remove_cell_for_account(account_id, key.to_vec());
let _ = self.database.remove_contract_storage(&callee, key);
}
pub fn terminate(&mut self, beneficiary: &[u8]) -> ! {
let contract = self.get_callee();
let all = self.get_balance(contract).expect("could not get balance");
let value = &scale::Encode::encode(&all)[..];
self.transfer(beneficiary, value)
.expect("transfer did not work");
let res = (all, beneficiary.to_vec());
panic_any(scale::Encode::encode(&res));
}
pub fn caller(&self, output: &mut &mut [u8]) {
let caller = self
.exec_context
.caller
.as_ref()
.expect("no caller has been set")
.as_bytes();
set_output(output, caller);
}
pub fn balance(&self, output: &mut &mut [u8]) {
let contract = self
.exec_context
.callee
.as_ref()
.expect("no callee has been set");
let balance_in_storage = self
.database
.get_balance(&contract.as_bytes().to_vec())
.expect("currently executing contract must exist");
let balance = scale::Encode::encode(&balance_in_storage);
set_output(output, &balance[..])
}
pub fn value_transferred(&self, output: &mut &mut [u8]) {
let value_transferred: Vec<u8> =
scale::Encode::encode(&self.exec_context.value_transferred);
set_output(output, &value_transferred[..])
}
pub fn address(&self, output: &mut &mut [u8]) {
let callee = self
.exec_context
.callee
.as_ref()
.expect("no callee has been set")
.as_bytes();
set_output(output, callee)
}
pub fn restore_to(
&mut self,
_account_id: &[u8],
_code_hash: &[u8],
_rent_allowance: &[u8],
filtered_keys: &[&[u8]],
) {
let _filtered_keys: Vec<crate::Key> =
filtered_keys.iter().map(|k| Key::from_bytes(k)).collect();
unimplemented!("off-chain environment does not yet support `restore_to`");
}
pub fn debug_message(&mut self, message: &str) {
self.debug_info.record_debug_message(String::from(message));
print!("{}", message);
}
pub fn hash_blake2_256(input: &[u8], output: &mut [u8; 32]) {
super::hashing::blake2b_256(input, output);
}
pub fn hash_blake2_128(input: &[u8], output: &mut [u8; 16]) {
super::hashing::blake2b_128(input, output);
}
pub fn hash_sha2_256(input: &[u8], output: &mut [u8; 32]) {
super::hashing::sha2_256(input, output);
}
pub fn hash_keccak_256(input: &[u8], output: &mut [u8; 32]) {
super::hashing::keccak_256(input, output);
}
pub fn block_number(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `block_number`");
}
pub fn block_timestamp(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `block_timestamp`");
}
pub fn gas_left(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `gas_left`");
}
pub fn rent_allowance(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `rent_allowance`");
}
pub fn minimum_balance(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `minimum_balance`");
}
pub fn tombstone_deposit(&self, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `tombstone_deposit`");
}
#[allow(clippy::too_many_arguments)]
pub fn instantiate(
&mut self,
_code_hash: &[u8],
_gas_limit: u64,
_endowment: &[u8],
_input: &[u8],
_out_address: &mut &mut [u8],
_out_return_value: &mut &mut [u8],
_salt: &[u8],
) -> Result {
unimplemented!("off-chain environment does not yet support `instantiate`");
}
pub fn call(
&mut self,
_callee: &[u8],
_gas_limit: u64,
_value: &[u8],
_input: &[u8],
_output: &mut &mut [u8],
) -> Result {
unimplemented!("off-chain environment does not yet support `call`");
}
pub fn weight_to_fee(&self, _gas: u64, _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `weight_to_fee`");
}
pub fn set_rent_allowance(&mut self, _value: &[u8]) {
unimplemented!("off-chain environment does not yet support `set_rent_allowance`");
}
pub fn random(&self, _subject: &[u8], _output: &mut &mut [u8]) {
unimplemented!("off-chain environment does not yet support `random`");
}
pub fn call_chain_extension(
&mut self,
_func_id: u32,
_input: &[u8],
_output: &mut &mut [u8],
) -> u32 {
unimplemented!(
"off-chain environment does not yet support `call_chain_extension`"
);
}
pub fn ecdsa_recover(
&mut self,
signature: &[u8; 65],
message_hash: &[u8; 32],
output: &mut [u8; 33],
) -> Result {
use secp256k1::{
recover,
Message,
RecoveryId,
Signature,
};
let recovery_byte = if signature[64] > 26 {
signature[64] - 27
} else {
signature[64]
};
let message = Message::parse(message_hash);
let signature = Signature::parse_slice(&signature[0..64])
.unwrap_or_else(|error| panic!("Unable to parse the signature: {}", error));
let recovery_id = RecoveryId::parse(recovery_byte)
.unwrap_or_else(|error| panic!("Unable to parse the recovery id: {}", error));
let pub_key = recover(&message, &signature, &recovery_id);
match pub_key {
Ok(pub_key) => {
*output = pub_key.serialize_compressed();
Ok(())
}
Err(_) => Err(Error::EcdsaRecoverFailed),
}
}
}
fn set_output(output: &mut &mut [u8], slice: &[u8]) {
assert!(
slice.len() <= output.len(),
"the output buffer is too small! the decoded storage is of size {} bytes, \
but the output buffer has only room for {}.",
slice.len(),
output.len(),
);
output[..slice.len()].copy_from_slice(slice);
}