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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
use super::panic_payload;
use ethereum_types::{Address, BigEndianHash, H256, U256};
use std::cmp;
use vm::{self, CallType};
use wasmi::{
self, Error as InterpreterError, MemoryRef, RuntimeArgs, RuntimeValue, Trap, TrapKind,
};
pub struct RuntimeContext {
pub address: Address,
pub sender: Address,
pub origin: Address,
pub code_address: Address,
pub value: U256,
}
pub struct Runtime<'a> {
gas_counter: u64,
gas_limit: u64,
ext: &'a mut dyn vm::Ext,
context: RuntimeContext,
memory: MemoryRef,
args: Vec<u8>,
result: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
StorageReadError,
StorageUpdateError,
MemoryAccessViolation,
Suicide,
Return,
SuicideAbort,
InvalidGasState,
BalanceQueryError,
AllocationFailed,
GasLimit,
Unknown,
BadUtf8,
Log,
Other,
InvalidSyscall,
Unreachable,
InvalidVirtualCall,
DivisionByZero,
InvalidConversionToInt,
StackOverflow,
Panic(String),
}
impl wasmi::HostError for Error {}
impl From<Trap> for Error {
fn from(trap: Trap) -> Self {
match *trap.kind() {
TrapKind::Unreachable => Error::Unreachable,
TrapKind::MemoryAccessOutOfBounds => Error::MemoryAccessViolation,
TrapKind::TableAccessOutOfBounds | TrapKind::ElemUninitialized => {
Error::InvalidVirtualCall
}
TrapKind::DivisionByZero => Error::DivisionByZero,
TrapKind::InvalidConversionToInt => Error::InvalidConversionToInt,
TrapKind::UnexpectedSignature => Error::InvalidVirtualCall,
TrapKind::StackOverflow => Error::StackOverflow,
TrapKind::Host(_) => Error::Other,
}
}
}
impl From<InterpreterError> for Error {
fn from(err: InterpreterError) -> Self {
match err {
InterpreterError::Value(_) => Error::InvalidSyscall,
InterpreterError::Memory(_) => Error::MemoryAccessViolation,
_ => Error::Other,
}
}
}
impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
match *self {
Error::StorageReadError => write!(f, "Storage read error"),
Error::StorageUpdateError => write!(f, "Storage update error"),
Error::MemoryAccessViolation => write!(f, "Memory access violation"),
Error::SuicideAbort => write!(f, "Attempt to suicide resulted in an error"),
Error::InvalidGasState => write!(f, "Invalid gas state"),
Error::BalanceQueryError => write!(f, "Balance query resulted in an error"),
Error::Suicide => write!(f, "Suicide result"),
Error::Return => write!(f, "Return result"),
Error::Unknown => write!(f, "Unknown runtime function invoked"),
Error::AllocationFailed => write!(f, "Memory allocation failed (OOM)"),
Error::BadUtf8 => write!(f, "String encoding is bad utf-8 sequence"),
Error::GasLimit => write!(f, "Invocation resulted in gas limit violated"),
Error::Log => write!(f, "Error occured while logging an event"),
Error::InvalidSyscall => write!(f, "Invalid syscall signature encountered at runtime"),
Error::Other => write!(f, "Other unspecified error"),
Error::Unreachable => write!(f, "Unreachable instruction encountered"),
Error::InvalidVirtualCall => write!(f, "Invalid virtual call"),
Error::DivisionByZero => write!(f, "Division by zero"),
Error::StackOverflow => write!(f, "Stack overflow"),
Error::InvalidConversionToInt => write!(f, "Invalid conversion to integer"),
Error::Panic(ref msg) => write!(f, "Panic: {}", msg),
}
}
}
type Result<T> = ::std::result::Result<T, Error>;
impl<'a> Runtime<'a> {
pub fn with_params(
ext: &mut dyn vm::Ext,
memory: MemoryRef,
gas_limit: u64,
args: Vec<u8>,
context: RuntimeContext,
) -> Runtime {
Runtime {
gas_counter: 0,
gas_limit: gas_limit,
memory: memory,
ext: ext,
context: context,
args: args,
result: Vec::new(),
}
}
fn h256_at(&self, ptr: u32) -> Result<H256> {
let mut buf = [0u8; 32];
self.memory.get_into(ptr, &mut buf[..])?;
Ok(H256::from_slice(&buf[..]))
}
fn address_at(&self, ptr: u32) -> Result<Address> {
let mut buf = [0u8; 20];
self.memory.get_into(ptr, &mut buf[..])?;
Ok(Address::from_slice(&buf[..]))
}
fn u256_at(&self, ptr: u32) -> Result<U256> {
let mut buf = [0u8; 32];
self.memory.get_into(ptr, &mut buf[..])?;
Ok(U256::from_big_endian(&buf[..]))
}
fn charge_gas(&mut self, amount: u64) -> bool {
let prev = self.gas_counter;
match prev.checked_add(amount) {
None => false,
Some(val) if val > self.gas_limit => false,
Some(_) => {
self.gas_counter = prev + amount;
true
}
}
}
pub fn charge<F>(&mut self, f: F) -> Result<()>
where
F: FnOnce(&vm::Schedule) -> u64,
{
let amount = f(self.ext.schedule());
if !self.charge_gas(amount as u64) {
Err(Error::GasLimit)
} else {
Ok(())
}
}
pub fn adjusted_charge<F>(&mut self, f: F) -> Result<()>
where
F: FnOnce(&vm::Schedule) -> u64,
{
self.charge(|schedule| {
f(schedule) * schedule.wasm().opcodes_div as u64 / schedule.wasm().opcodes_mul as u64
})
}
pub fn overflow_charge<F>(&mut self, f: F) -> Result<()>
where
F: FnOnce(&vm::Schedule) -> Option<u64>,
{
let amount = match f(self.ext.schedule()) {
Some(amount) => amount,
None => {
return Err(Error::GasLimit.into());
}
};
if !self.charge_gas(amount as u64) {
Err(Error::GasLimit.into())
} else {
Ok(())
}
}
pub fn adjusted_overflow_charge<F>(&mut self, f: F) -> Result<()>
where
F: FnOnce(&vm::Schedule) -> Option<u64>,
{
self.overflow_charge(|schedule| {
f(schedule)
.and_then(|x| x.checked_mul(schedule.wasm().opcodes_div as u64))
.map(|x| x / schedule.wasm().opcodes_mul as u64)
})
}
pub fn storage_read(&mut self, args: RuntimeArgs) -> Result<()> {
let key = self.h256_at(args.nth_checked(0)?)?;
let val_ptr: u32 = args.nth_checked(1)?;
let val = self
.ext
.storage_at(&key)
.map_err(|_| Error::StorageReadError)?;
self.adjusted_charge(|schedule| schedule.sload_gas as u64)?;
self.memory.set(val_ptr as u32, val.as_bytes())?;
Ok(())
}
pub fn storage_write(&mut self, args: RuntimeArgs) -> Result<()> {
let key = self.h256_at(args.nth_checked(0)?)?;
let val_ptr: u32 = args.nth_checked(1)?;
let val = self.h256_at(val_ptr)?;
let former_val = self
.ext
.storage_at(&key)
.map_err(|_| Error::StorageUpdateError)?;
if former_val == H256::zero() && val != H256::zero() {
self.adjusted_charge(|schedule| schedule.sstore_set_gas as u64)?;
} else {
self.adjusted_charge(|schedule| schedule.sstore_reset_gas as u64)?;
}
self.ext
.set_storage(key, val)
.map_err(|_| Error::StorageUpdateError)?;
if former_val != H256::zero() && val == H256::zero() {
let sstore_clears_schedule = self.schedule().sstore_refund_gas;
self.ext.add_sstore_refund(sstore_clears_schedule);
}
Ok(())
}
pub fn schedule(&self) -> &vm::Schedule {
self.ext.schedule()
}
pub fn ret(&mut self, args: RuntimeArgs) -> Result<()> {
let ptr: u32 = args.nth_checked(0)?;
let len: u32 = args.nth_checked(1)?;
trace!(target: "wasm", "Contract ret: {} bytes @ {}", len, ptr);
self.result = self.memory.get(ptr, len as usize)?;
Err(Error::Return)
}
pub fn into_result(self) -> Vec<u8> {
self.result
}
pub fn gas_left(&self) -> Result<u64> {
if self.gas_counter > self.gas_limit {
return Err(Error::InvalidGasState);
}
Ok(self.gas_limit - self.gas_counter)
}
fn gas(&mut self, args: RuntimeArgs) -> Result<()> {
let amount: u32 = args.nth_checked(0)?;
if self.charge_gas(amount as u64) {
Ok(())
} else {
Err(Error::GasLimit.into())
}
}
fn input_legnth(&mut self) -> RuntimeValue {
RuntimeValue::I32(self.args.len() as i32)
}
fn fetch_input(&mut self, args: RuntimeArgs) -> Result<()> {
let ptr: u32 = args.nth_checked(0)?;
let args_len = self.args.len() as u64;
self.charge(|s| args_len * s.wasm().memcpy as u64)?;
self.memory.set(ptr, &self.args[..])?;
Ok(())
}
fn panic(&mut self, args: RuntimeArgs) -> Result<()> {
let payload_ptr: u32 = args.nth_checked(0)?;
let payload_len: u32 = args.nth_checked(1)?;
let raw_payload = self.memory.get(payload_ptr, payload_len as usize)?;
let payload = panic_payload::decode(&raw_payload);
let msg = format!(
"{msg}, {file}:{line}:{col}",
msg = payload
.msg
.as_ref()
.map(String::as_ref)
.unwrap_or("<msg was stripped>"),
file = payload
.file
.as_ref()
.map(String::as_ref)
.unwrap_or("<unknown>"),
line = payload.line.unwrap_or(0),
col = payload.col.unwrap_or(0)
);
trace!(target: "wasm", "Contract custom panic message: {}", msg);
Err(Error::Panic(msg).into())
}
fn do_call(
&mut self,
use_val: bool,
call_type: CallType,
args: RuntimeArgs,
) -> Result<RuntimeValue> {
trace!(target: "wasm", "runtime: CALL({:?})", call_type);
let gas: u64 = args.nth_checked(0)?;
trace!(target: "wasm", " gas: {:?}", gas);
let address = self.address_at(args.nth_checked(1)?)?;
trace!(target: "wasm", " address: {:?}", address);
let vofs = if use_val { 1 } else { 0 };
let val = if use_val {
Some(self.u256_at(args.nth_checked(2)?)?)
} else {
None
};
trace!(target: "wasm", " val: {:?}", val);
let input_ptr: u32 = args.nth_checked(2 + vofs)?;
trace!(target: "wasm", " input_ptr: {:?}", input_ptr);
let input_len: u32 = args.nth_checked(3 + vofs)?;
trace!(target: "wasm", " input_len: {:?}", input_len);
let result_ptr: u32 = args.nth_checked(4 + vofs)?;
trace!(target: "wasm", " result_ptr: {:?}", result_ptr);
let result_alloc_len: u32 = args.nth_checked(5 + vofs)?;
trace!(target: "wasm", " result_len: {:?}", result_alloc_len);
if let Some(ref val) = val {
let address_balance = self
.ext
.balance(&self.context.address)
.map_err(|_| Error::BalanceQueryError)?;
if &address_balance < val {
trace!(target: "wasm", "runtime: call failed due to balance check");
return Ok((-1i32).into());
}
}
self.adjusted_charge(|schedule| schedule.call_gas as u64)?;
let mut result = Vec::with_capacity(result_alloc_len as usize);
result.resize(result_alloc_len as usize, 0);
let payload = self.memory.get(input_ptr, input_len as usize)?;
let adjusted_gas = match gas
.checked_mul(self.ext.schedule().wasm().opcodes_div as u64)
.map(|x| x / self.ext.schedule().wasm().opcodes_mul as u64)
{
Some(x) => x,
None => {
trace!("CALL overflowed gas, call aborted with error returned");
return Ok(RuntimeValue::I32(-1));
}
};
self.charge(|_| adjusted_gas)?;
let call_result = self
.ext
.call(
&gas.into(),
match call_type {
CallType::DelegateCall => &self.context.sender,
_ => &self.context.address,
},
match call_type {
CallType::Call | CallType::StaticCall => &address,
_ => &self.context.address,
},
val,
&payload,
&address,
call_type,
false,
)
.ok()
.expect("Trap is false; trap error will not happen; qed");
match call_result {
vm::MessageCallResult::Success(gas_left, data) => {
let len = cmp::min(result.len(), data.len());
(&mut result[..len]).copy_from_slice(&data[..len]);
self.gas_counter = self.gas_counter
- gas_left.low_u64() * self.ext.schedule().wasm().opcodes_div as u64
/ self.ext.schedule().wasm().opcodes_mul as u64;
self.memory.set(result_ptr, &result)?;
Ok(0i32.into())
}
vm::MessageCallResult::Reverted(gas_left, data) => {
let len = cmp::min(result.len(), data.len());
(&mut result[..len]).copy_from_slice(&data[..len]);
self.gas_counter = self.gas_counter
- gas_left.low_u64() * self.ext.schedule().wasm().opcodes_div as u64
/ self.ext.schedule().wasm().opcodes_mul as u64;
self.memory.set(result_ptr, &result)?;
Ok((-1i32).into())
}
vm::MessageCallResult::Failed => Ok((-1i32).into()),
}
}
fn ccall(&mut self, args: RuntimeArgs) -> Result<RuntimeValue> {
self.do_call(true, CallType::Call, args)
}
fn dcall(&mut self, args: RuntimeArgs) -> Result<RuntimeValue> {
self.do_call(false, CallType::DelegateCall, args)
}
fn scall(&mut self, args: RuntimeArgs) -> Result<RuntimeValue> {
self.do_call(false, CallType::StaticCall, args)
}
fn return_address_ptr(&mut self, ptr: u32, val: Address) -> Result<()> {
self.charge(|schedule| schedule.wasm().static_address as u64)?;
self.memory.set(ptr, val.as_bytes())?;
Ok(())
}
fn return_u256_ptr(&mut self, ptr: u32, val: U256) -> Result<()> {
let value: H256 = BigEndianHash::from_uint(&val);
self.charge(|schedule| schedule.wasm().static_u256 as u64)?;
self.memory.set(ptr, value.as_bytes())?;
Ok(())
}
pub fn value(&mut self, args: RuntimeArgs) -> Result<()> {
let val = self.context.value;
self.return_u256_ptr(args.nth_checked(0)?, val)
}
fn do_create(
&mut self,
endowment: U256,
code_ptr: u32,
code_len: u32,
result_ptr: u32,
scheme: vm::CreateContractAddress,
) -> Result<RuntimeValue> {
let code = self.memory.get(code_ptr, code_len as usize)?;
self.adjusted_charge(|schedule| schedule.create_gas as u64)?;
self.adjusted_charge(|schedule| schedule.create_data_gas as u64 * code.len() as u64)?;
let gas_left: U256 = U256::from(self.gas_left()?)
* U256::from(self.ext.schedule().wasm().opcodes_mul)
/ U256::from(self.ext.schedule().wasm().opcodes_div);
match self
.ext
.create(&gas_left, &endowment, &code, scheme, false)
.ok()
.expect("Trap is false; trap error will not happen; qed")
{
vm::ContractCreateResult::Created(address, gas_left) => {
self.memory.set(result_ptr, address.as_bytes())?;
self.gas_counter = self.gas_limit -
gas_left.low_u64() * self.ext.schedule().wasm().opcodes_div as u64
/ self.ext.schedule().wasm().opcodes_mul as u64;
trace!(target: "wasm", "runtime: create contract success (@{:?})", address);
Ok(0i32.into())
}
vm::ContractCreateResult::Failed => {
trace!(target: "wasm", "runtime: create contract fail");
Ok((-1i32).into())
}
vm::ContractCreateResult::Reverted(gas_left, _) => {
trace!(target: "wasm", "runtime: create contract reverted");
self.gas_counter = self.gas_limit -
gas_left.low_u64() * self.ext.schedule().wasm().opcodes_div as u64
/ self.ext.schedule().wasm().opcodes_mul as u64;
Ok((-1i32).into())
}
}
}
pub fn create(&mut self, args: RuntimeArgs) -> Result<RuntimeValue> {
trace!(target: "wasm", "runtime: CREATE");
let endowment = self.u256_at(args.nth_checked(0)?)?;
trace!(target: "wasm", " val: {:?}", endowment);
let code_ptr: u32 = args.nth_checked(1)?;
trace!(target: "wasm", " code_ptr: {:?}", code_ptr);
let code_len: u32 = args.nth_checked(2)?;
trace!(target: "wasm", " code_len: {:?}", code_len);
let result_ptr: u32 = args.nth_checked(3)?;
trace!(target: "wasm", "result_ptr: {:?}", result_ptr);
self.do_create(
endowment,
code_ptr,
code_len,
result_ptr,
vm::CreateContractAddress::FromSenderAndCodeHash,
)
}
pub fn create2(&mut self, args: RuntimeArgs) -> Result<RuntimeValue> {
trace!(target: "wasm", "runtime: CREATE2");
let endowment = self.u256_at(args.nth_checked(0)?)?;
trace!(target: "wasm", " val: {:?}", endowment);
let salt: H256 = BigEndianHash::from_uint(&self.u256_at(args.nth_checked(1)?)?);
trace!(target: "wasm", " salt: {:?}", salt);
let code_ptr: u32 = args.nth_checked(2)?;
trace!(target: "wasm", " code_ptr: {:?}", code_ptr);
let code_len: u32 = args.nth_checked(3)?;
trace!(target: "wasm", " code_len: {:?}", code_len);
let result_ptr: u32 = args.nth_checked(4)?;
trace!(target: "wasm", "result_ptr: {:?}", result_ptr);
self.do_create(
endowment,
code_ptr,
code_len,
result_ptr,
vm::CreateContractAddress::FromSenderSaltAndCodeHash(salt),
)
}
fn debug(&mut self, args: RuntimeArgs) -> Result<()> {
trace!(target: "wasm", "Contract debug message: {}", {
let msg_ptr: u32 = args.nth_checked(0)?;
let msg_len: u32 = args.nth_checked(1)?;
String::from_utf8(self.memory.get(msg_ptr, msg_len as usize)?)
.map_err(|_| Error::BadUtf8)?
});
Ok(())
}
pub fn suicide(&mut self, args: RuntimeArgs) -> Result<()> {
let refund_address = self.address_at(args.nth_checked(0)?)?;
if self
.ext
.exists(&refund_address)
.map_err(|_| Error::SuicideAbort)?
{
trace!(target: "wasm", "Suicide: refund to existing address {}", refund_address);
self.adjusted_charge(|schedule| schedule.suicide_gas as u64)?;
} else {
trace!(target: "wasm", "Suicide: refund to new address {}", refund_address);
self.adjusted_charge(|schedule| schedule.suicide_to_new_account_cost as u64)?;
}
self.ext
.suicide(&refund_address)
.map_err(|_| Error::SuicideAbort)?;
Err(Error::Suicide.into())
}
pub fn blockhash(&mut self, args: RuntimeArgs) -> Result<()> {
self.adjusted_charge(|schedule| schedule.blockhash_gas as u64)?;
let hash = self.ext.blockhash(&U256::from(args.nth_checked::<u64>(0)?));
self.memory.set(args.nth_checked(1)?, hash.as_bytes())?;
Ok(())
}
pub fn blocknumber(&mut self) -> Result<RuntimeValue> {
Ok(RuntimeValue::from(self.ext.env_info().number))
}
pub fn coinbase(&mut self, args: RuntimeArgs) -> Result<()> {
let coinbase = self.ext.env_info().author;
self.return_address_ptr(args.nth_checked(0)?, coinbase)
}
pub fn difficulty(&mut self, args: RuntimeArgs) -> Result<()> {
let difficulty = self.ext.env_info().difficulty;
self.return_u256_ptr(args.nth_checked(0)?, difficulty)
}
pub fn gasleft(&mut self) -> Result<RuntimeValue> {
Ok(RuntimeValue::from(
self.gas_left()? * self.ext.schedule().wasm().opcodes_mul as u64
/ self.ext.schedule().wasm().opcodes_div as u64,
))
}
pub fn gaslimit(&mut self, args: RuntimeArgs) -> Result<()> {
let gas_limit = self.ext.env_info().gas_limit;
self.return_u256_ptr(args.nth_checked(0)?, gas_limit)
}
pub fn address(&mut self, args: RuntimeArgs) -> Result<()> {
let address = self.context.address;
self.return_address_ptr(args.nth_checked(0)?, address)
}
pub fn sender(&mut self, args: RuntimeArgs) -> Result<()> {
let sender = self.context.sender;
self.return_address_ptr(args.nth_checked(0)?, sender)
}
pub fn origin(&mut self, args: RuntimeArgs) -> Result<()> {
let origin = self.context.origin;
self.return_address_ptr(args.nth_checked(0)?, origin)
}
pub fn timestamp(&mut self) -> Result<RuntimeValue> {
let timestamp = self.ext.env_info().timestamp;
Ok(RuntimeValue::from(timestamp))
}
pub fn elog(&mut self, args: RuntimeArgs) -> Result<()> {
let topic_ptr: u32 = args.nth_checked(0)?;
let topic_count: u32 = args.nth_checked(1)?;
let data_ptr: u32 = args.nth_checked(2)?;
let data_len: u32 = args.nth_checked(3)?;
if topic_count > 4 {
return Err(Error::Log.into());
}
self.adjusted_overflow_charge(|schedule| {
let topics_gas =
schedule.log_gas as u64 + schedule.log_topic_gas as u64 * topic_count as u64;
(schedule.log_data_gas as u64)
.checked_mul(schedule.log_data_gas as u64)
.and_then(|data_gas| data_gas.checked_add(topics_gas))
})?;
let mut topics: Vec<H256> = Vec::with_capacity(topic_count as usize);
topics.resize(topic_count as usize, H256::zero());
for i in 0..topic_count {
let offset = i
.checked_mul(32)
.ok_or(Error::MemoryAccessViolation)?
.checked_add(topic_ptr)
.ok_or(Error::MemoryAccessViolation)?;
*topics.get_mut(i as usize)
.expect("topics is resized to `topic_count`, i is in 0..topic count iterator, get_mut uses i as an indexer, get_mut cannot fail; qed")
= H256::from_slice(&self.memory.get(offset, 32)?[..]);
}
self.ext
.log(topics, &self.memory.get(data_ptr, data_len as usize)?)
.map_err(|_| Error::Log)?;
Ok(())
}
}
mod ext_impl {
use env::ids::*;
use wasmi::{Externals, RuntimeArgs, RuntimeValue, Trap};
macro_rules! void {
{ $e: expr } => { { $e?; Ok(None) } }
}
macro_rules! some {
{ $e: expr } => { { Ok(Some($e?)) } }
}
macro_rules! cast {
{ $e: expr } => { { Ok(Some($e)) } }
}
impl<'a> Externals for super::Runtime<'a> {
fn invoke_index(
&mut self,
index: usize,
args: RuntimeArgs,
) -> Result<Option<RuntimeValue>, Trap> {
match index {
STORAGE_WRITE_FUNC => void!(self.storage_write(args)),
STORAGE_READ_FUNC => void!(self.storage_read(args)),
RET_FUNC => void!(self.ret(args)),
GAS_FUNC => void!(self.gas(args)),
INPUT_LENGTH_FUNC => cast!(self.input_legnth()),
FETCH_INPUT_FUNC => void!(self.fetch_input(args)),
PANIC_FUNC => void!(self.panic(args)),
DEBUG_FUNC => void!(self.debug(args)),
CCALL_FUNC => some!(self.ccall(args)),
DCALL_FUNC => some!(self.dcall(args)),
SCALL_FUNC => some!(self.scall(args)),
VALUE_FUNC => void!(self.value(args)),
CREATE_FUNC => some!(self.create(args)),
SUICIDE_FUNC => void!(self.suicide(args)),
BLOCKHASH_FUNC => void!(self.blockhash(args)),
BLOCKNUMBER_FUNC => some!(self.blocknumber()),
COINBASE_FUNC => void!(self.coinbase(args)),
DIFFICULTY_FUNC => void!(self.difficulty(args)),
GASLIMIT_FUNC => void!(self.gaslimit(args)),
TIMESTAMP_FUNC => some!(self.timestamp()),
ADDRESS_FUNC => void!(self.address(args)),
SENDER_FUNC => void!(self.sender(args)),
ORIGIN_FUNC => void!(self.origin(args)),
ELOG_FUNC => void!(self.elog(args)),
CREATE2_FUNC => some!(self.create2(args)),
GASLEFT_FUNC => some!(self.gasleft()),
_ => panic!("env module doesn't provide function at index {}", index),
}
}
}
}