forked from Jon-Becker/heimdall-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm.rs
2186 lines (1821 loc) · 97.2 KB
/
vm.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
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use hashbrown::HashSet;
use std::{
ops::{Div, Rem, Shl, Shr},
time::{SystemTime, UNIX_EPOCH},
};
use alloy::primitives::{keccak256, Address, I256, U256};
use eyre::{OptionExt, Result};
use heimdall_common::utils::strings::sign_uint;
#[cfg(feature = "step-tracing")]
use std::time::Instant;
#[cfg(feature = "step-tracing")]
use tracing::trace;
use crate::core::opcodes::OpCodeInfo;
use super::{
constants::{COINBASE_ADDRESS, CREATE2_ADDRESS, CREATE_ADDRESS},
log::Log,
memory::Memory,
opcodes::{WrappedInput, WrappedOpcode},
stack::Stack,
storage::Storage,
};
/// The [`VM`] struct represents an EVM instance. \
/// It contains the EVM's [`Stack`], [`Memory`], [`Storage`], and other state variables needed to
/// emulate EVM execution.
#[derive(Clone, Debug)]
pub struct VM {
pub stack: Stack,
pub memory: Memory,
pub storage: Storage,
pub instruction: u128,
pub bytecode: Vec<u8>,
pub calldata: Vec<u8>,
pub address: Address,
pub origin: Address,
pub caller: Address,
pub value: u128,
pub gas_remaining: u128,
pub gas_used: u128,
pub events: Vec<Log>,
pub returndata: Vec<u8>,
pub exitcode: u128,
pub address_access_set: HashSet<U256>,
#[cfg(feature = "step-tracing")]
pub operation_count: u128,
#[cfg(feature = "step-tracing")]
pub start_time: Instant,
}
/// [`ExecutionResult`] is the result of a single contract execution.
#[derive(Clone, Debug)]
pub struct ExecutionResult {
pub gas_used: u128,
pub gas_remaining: u128,
pub returndata: Vec<u8>,
pub exitcode: u128,
pub events: Vec<Log>,
pub instruction: u128,
}
/// [`State`] is the state of the EVM after executing a single instruction. It is returned by the
/// [`VM::step`] function, and is used by heimdall for tracing contract execution.
#[derive(Clone, Debug)]
pub struct State {
pub last_instruction: Instruction,
pub gas_used: u128,
pub gas_remaining: u128,
pub stack: Stack,
pub memory: Memory,
pub storage: Storage,
pub events: Vec<Log>,
}
/// [`Instruction`] is a single EVM instruction. It is returned by the [`VM::step`] function, and
/// contains necessary tracing information, such as the opcode executed, it's inputs and outputs, as
/// well as their parent operations.
#[derive(Clone, Debug)]
pub struct Instruction {
pub instruction: u128,
pub opcode: u8,
pub inputs: Vec<U256>,
pub outputs: Vec<U256>,
pub input_operations: Vec<WrappedOpcode>,
pub output_operations: Vec<WrappedOpcode>,
}
impl VM {
/// Creates a new [`VM`] instance with the given bytecode, calldata, address, origin, caller,
/// value, and gas limit.
///
/// ```
/// use heimdall_vm::core::vm::VM;
/// use alloy::primitives::Address;
///
/// let vm = VM::new(
/// &vec![0x00],
/// &vec![],
/// "0x0000000000000000000000000000000000000000".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000001".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000002".parse::<Address>().expect("failed to parse Address"),
/// 0,
/// 1000000000000000000,
/// );
/// ```
pub fn new(
bytecode: &[u8],
calldata: &[u8],
address: Address,
origin: Address,
caller: Address,
value: u128,
gas_limit: u128,
) -> VM {
VM {
stack: Stack::new(),
memory: Memory::new(),
storage: Storage::new(),
instruction: 1,
bytecode: bytecode.to_vec(),
calldata: calldata.to_vec(),
address,
origin,
caller,
value,
gas_remaining: gas_limit.max(21000) - 21000,
gas_used: 21000,
events: Vec::new(),
returndata: Vec::new(),
exitcode: 255,
address_access_set: HashSet::new(),
#[cfg(feature = "step-tracing")]
operation_count: 0,
#[cfg(feature = "step-tracing")]
start_time: Instant::now(),
}
}
/// Exits current execution with the given code and returndata.
///
/// ```
/// use heimdall_vm::core::vm::VM;
/// use alloy::primitives::Address;
///
/// let mut vm = VM::new(
/// &vec![0x00],
/// &vec![],
/// "0x0000000000000000000000000000000000000000".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000001".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000002".parse::<Address>().expect("failed to parse Address"),
/// 0,
/// 1000000000000000000,
/// );
///
/// vm.exit(0xff, Vec::new());
/// assert_eq!(vm.exitcode, 0xff);
/// ```
pub fn exit(&mut self, code: u128, returndata: Vec<u8>) {
self.exitcode = code;
self.returndata = returndata;
}
/// Consume gas units, halting execution if out of gas
///
/// ```
/// use heimdall_vm::core::vm::VM;
/// use alloy::primitives::Address;
///
/// let mut vm = VM::new(
/// &vec![0x00],
/// &vec![],
/// "0x0000000000000000000000000000000000000000".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000001".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000002".parse::<Address>().expect("failed to parse Address"),
/// 0,
/// 1000000000000000000,
/// );
///
/// vm.consume_gas(100);
/// assert_eq!(vm.gas_remaining, 999999999999978900);
///
/// vm.consume_gas(1000000000000000000);
/// assert_eq!(vm.gas_remaining, 0);
/// assert_eq!(vm.exitcode, 9);
/// ```
pub fn consume_gas(&mut self, amount: u128) -> bool {
// REVERT if out of gas
if amount > self.gas_remaining {
self.gas_used += self.gas_remaining;
self.gas_remaining = 0;
self.exit(9, Vec::new());
return false;
}
self.gas_remaining = self.gas_remaining.saturating_sub(amount);
self.gas_used = self.gas_used.saturating_add(amount);
true
}
/// Executes the next instruction in the bytecode. Returns information about the instruction
/// executed.
///
/// ```no_run
/// use heimdall_vm::core::vm::VM;
/// use alloy::primitives::Address;
///
/// let mut vm = VM::new(
/// &vec![0x00],
/// &vec![],
/// "0x0000000000000000000000000000000000000000".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000001".parse::<Address>().expect("failed to parse Address"),
/// "0x0000000000000000000000000000000000000002".parse::<Address>().expect("failed to parse Address"),
/// 0,
/// 1000000000000000000,
/// );
///
/// // vm._step(); // 0x00 EXIT
/// // assert_eq!(vm.exitcode, 10);
/// ```
fn _step(&mut self) -> Result<Instruction> {
// sanity check
if self.bytecode.len() < self.instruction as usize {
self.exit(2, Vec::new());
return Ok(Instruction {
instruction: self.instruction,
opcode: 0xff,
inputs: Vec::new(),
outputs: Vec::new(),
input_operations: Vec::new(),
output_operations: Vec::new(),
});
}
// get the opcode at the current instruction
let opcode = self
.bytecode
.get((self.instruction - 1) as usize)
.ok_or_eyre(format!("invalid jumpdest: {}", self.instruction - 1))?
.to_owned();
let last_instruction = self.instruction;
self.instruction += 1;
#[cfg(feature = "step-tracing")]
{
self.operation_count += 1;
}
#[cfg(feature = "step-tracing")]
let start_time = Instant::now();
// add the opcode to the trace
let opcode_info = OpCodeInfo::from(opcode);
let input_frames = self.stack.peek_n(opcode_info.inputs() as usize);
let input_operations =
input_frames.iter().map(|x| x.operation.clone()).collect::<Vec<WrappedOpcode>>();
let inputs = input_frames.iter().map(|x| x.value).collect::<Vec<U256>>();
// Consume the minimum gas for the opcode
let gas_cost = opcode_info.min_gas();
self.consume_gas(gas_cost.into());
// convert inputs to WrappedInputs
let wrapped_inputs = input_operations
.iter()
.map(|x| WrappedInput::Opcode(x.to_owned()))
.collect::<Vec<WrappedInput>>();
let mut operation = WrappedOpcode::new(opcode, wrapped_inputs);
// if step-tracing feature is enabled, print the current operation
#[cfg(feature = "step-tracing")]
trace!(
pc = self.instruction - 1,
opcode = opcode_info.name(),
inputs = ?inputs
.iter()
.map(|x| format!("{:#x}", x))
.collect::<Vec<String>>(),
"executing opcode"
);
// execute the operation
match opcode {
// STOP
0x00 => {
self.exit(10, Vec::new());
return Ok(Instruction {
instruction: last_instruction,
opcode,
inputs,
outputs: Vec::new(),
input_operations,
output_operations: Vec::new(),
});
}
// ADD
0x01 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value.overflowing_add(b.value).0;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// MUL
0x02 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value.overflowing_mul(b.value).0;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// SUB
0x03 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value.overflowing_sub(b.value).0;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// DIV
0x04 => {
let numerator = self.stack.pop()?;
let denominator = self.stack.pop()?;
let mut result = U256::ZERO;
if !denominator.value.is_zero() {
result = numerator.value.div(denominator.value);
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&numerator.operation.opcode) &&
(0x5f..=0x7f).contains(&denominator.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// SDIV
0x05 => {
let numerator = self.stack.pop()?;
let denominator = self.stack.pop()?;
let mut result = I256::ZERO;
if !denominator.value.is_zero() {
result = sign_uint(numerator.value).div(sign_uint(denominator.value));
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&numerator.operation.opcode) &&
(0x5f..=0x7f).contains(&denominator.operation.opcode)
{
simplified_operation =
WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result.into_raw())])
}
self.stack.push(result.into_raw(), simplified_operation);
}
// MOD
0x06 => {
let a = self.stack.pop()?;
let modulus = self.stack.pop()?;
let mut result = U256::ZERO;
if !modulus.value.is_zero() {
result = a.value.rem(modulus.value);
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&modulus.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// SMOD
0x07 => {
let a = self.stack.pop()?;
let modulus = self.stack.pop()?;
let mut result = I256::ZERO;
if !modulus.value.is_zero() {
result = sign_uint(a.value).rem(sign_uint(modulus.value));
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&modulus.operation.opcode)
{
simplified_operation =
WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result.into_raw())])
}
self.stack.push(result.into_raw(), simplified_operation);
}
// ADDMOD
0x08 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let modulus = self.stack.pop()?;
let mut result = U256::ZERO;
if !modulus.value.is_zero() {
result = a.value.overflowing_add(b.value).0.rem(modulus.value);
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// MULMOD
0x09 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let modulus = self.stack.pop()?;
let mut result = U256::ZERO;
if !modulus.value.is_zero() {
result = a.value.overflowing_mul(b.value).0.rem(modulus.value);
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// EXP
0x0A => {
let a = self.stack.pop()?;
let exponent = self.stack.pop()?;
let result = a.value.overflowing_pow(exponent.value).0;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&exponent.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
// consume dynamic gas
let exponent_byte_size = exponent.value.bit_len() / 8;
let gas_cost = 50 * exponent_byte_size;
self.consume_gas(gas_cost as u128);
self.stack.push(result, simplified_operation);
}
// SIGNEXTEND
0x0B => {
let x = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
let t = x * U256::from(8u32) + U256::from(7u32);
let sign_bit = U256::from(1u32) << t;
// (b & sign_bit - 1) - (b & sign_bit)
let result = (b & (sign_bit.overflowing_sub(U256::from(1u32)).0))
.overflowing_sub(b & sign_bit)
.0;
self.stack.push(result, operation)
}
// LT
0x10 => {
let a = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
match a.lt(&b) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// GT
0x11 => {
let a = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
match a.gt(&b) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// SLT
0x12 => {
let a = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
match sign_uint(a).lt(&sign_uint(b)) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// SGT
0x13 => {
let a = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
match sign_uint(a).gt(&sign_uint(b)) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// EQ
0x14 => {
let a = self.stack.pop()?.value;
let b = self.stack.pop()?.value;
match a.eq(&b) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// ISZERO
0x15 => {
let a = self.stack.pop()?.value;
match a.eq(&U256::from(0u8)) {
true => self.stack.push(U256::from(1u8), operation),
false => self.stack.push(U256::ZERO, operation),
}
}
// AND
0x16 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value & b.value;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// OR
0x17 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value | b.value;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// XOR
0x18 => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let result = a.value ^ b.value;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// NOT
0x19 => {
let a = self.stack.pop()?;
let result = !a.value;
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) {
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// BYTE
0x1A => {
let b = self.stack.pop()?.value;
let a = self.stack.pop()?.value;
if b >= U256::from(32u32) {
self.stack.push(U256::ZERO, operation)
} else {
let result =
a / (U256::from(256u32).pow(U256::from(31u32) - b)) % U256::from(256u32);
self.stack.push(result, operation);
}
}
// SHL
0x1B => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
// if shift is greater than 255, result is 0
let result =
if a.value > U256::from(255u8) { U256::ZERO } else { b.value.shl(a.value) };
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// SHR
0x1C => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
// if shift is greater than 255, result is 0
let result =
if a.value > U256::from(255u8) { U256::ZERO } else { b.value.shr(a.value) };
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation = WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result)])
}
self.stack.push(result, simplified_operation);
}
// SAR
0x1D => {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
// convert a to usize
let usize_a: usize = a.value.try_into().unwrap_or(usize::MAX);
let mut result = I256::ZERO;
if !b.value.is_zero() {
result = sign_uint(b.value).shr(usize_a);
}
// if both inputs are PUSH instructions, simplify the operation
let mut simplified_operation = operation;
if (0x5f..=0x7f).contains(&a.operation.opcode) &&
(0x5f..=0x7f).contains(&b.operation.opcode)
{
simplified_operation =
WrappedOpcode::new(0x7f, vec![WrappedInput::Raw(result.into_raw())])
}
self.stack.push(result.into_raw(), simplified_operation);
}
// SHA3
0x20 => {
let offset = self.stack.pop()?.value;
let size = self.stack.pop()?.value;
// Safely convert U256 to usize
let offset: usize = offset.try_into().unwrap_or(usize::MAX);
let size: usize = size.try_into().unwrap_or(usize::MAX);
let data = self.memory.read(offset, size);
let result = keccak256(data);
// consume dynamic gas
let minimum_word_size = size.div_ceil(32) as u128;
let gas_cost = 6 * minimum_word_size + self.memory.expansion_cost(offset, size);
self.consume_gas(gas_cost);
self.stack.push(U256::from_be_bytes(result.0), operation);
}
// ADDRESS
0x30 => {
let mut result = [0u8; 32];
result[12..].copy_from_slice(self.address.as_ref());
self.stack.push(U256::from_be_bytes(result), operation);
}
// BALANCE
0x31 => {
let address = self.stack.pop()?.value;
// consume dynamic gas
if !self.address_access_set.contains(&address) {
self.consume_gas(2600);
self.address_access_set.insert(address);
} else {
self.consume_gas(100);
}
// balance is set to 1 wei because we won't run into div by 0 errors
self.stack.push(U256::from(1), operation);
}
// ORIGIN
0x32 => {
// convert self.origin to U256
let mut result = [0u8; 32];
result[12..].copy_from_slice(self.origin.as_ref());
self.stack.push(U256::from_be_bytes(result), operation);
}
// CALLER
0x33 => {
let mut result = [0u8; 32];
result[12..].copy_from_slice(self.caller.as_ref());
self.stack.push(U256::from_be_bytes(result), operation);
}
// CALLVALUE
0x34 => {
self.stack.push(U256::from(self.value), operation);
}
// CALLDATALOAD
0x35 => {
let i = self.stack.pop()?.value;
// Safely convert U256 to usize
let i: usize = i.try_into().unwrap_or(usize::MAX);
let result = if i.saturating_add(32) > self.calldata.len() {
let mut value = [0u8; 32];
if i <= self.calldata.len() {
value[..self.calldata.len() - i].copy_from_slice(&self.calldata[i..]);
}
U256::from_be_bytes(value)
} else {
U256::from_be_slice(&self.calldata[i..i + 32])
};
self.stack.push(result, operation);
}
// CALLDATASIZE
0x36 => {
let result = U256::from(self.calldata.len());
self.stack.push(result, operation);
}
// CALLDATACOPY
0x37 => {
let dest_offset = self.stack.pop()?.value;
let offset = self.stack.pop()?.value;
let size = self.stack.pop()?.value;
// Safely convert U256 to usize, clamping to calldata length
let dest_offset: usize = dest_offset.try_into().unwrap_or(usize::MAX);
let offset: usize = offset.try_into().unwrap_or(usize::MAX);
let size: usize = size.try_into().unwrap_or(usize::MAX);
// clamp values to calldata length
let end_offset_clamped = offset.saturating_add(size).min(self.calldata.len());
let size = size.min(self.calldata.len());
let mut value =
self.calldata.get(offset..end_offset_clamped).unwrap_or(&[]).to_owned();
// pad value with 0x00
if value.len() < size {
value.resize(size, 0u8);
}
// consume dynamic gas
let minimum_word_size = size.div_ceil(32) as u128;
let gas_cost = 3 * minimum_word_size + self.memory.expansion_cost(offset, size);
self.consume_gas(gas_cost);
self.memory.store_with_opcode(
dest_offset,
size,
&value,
#[cfg(feature = "experimental")]
operation,
);
}
// CODESIZE
0x38 => {
let result = U256::from(self.bytecode.len() as u128);
self.stack.push(result, operation);
}
// CODECOPY
0x39 => {
let dest_offset = self.stack.pop()?.value;
let offset = self.stack.pop()?.value;
let size = self.stack.pop()?.value;
// Safely convert U256 to usize, clamping to bytecode length
let dest_offset: usize = dest_offset.try_into().unwrap_or(usize::MAX);
let offset: usize = offset.try_into().unwrap_or(usize::MAX);
let size: usize = size.try_into().unwrap_or(usize::MAX);
// clamp values to bytecode length
let value_offset_safe = offset.saturating_add(size).min(self.bytecode.len());
let mut value =
self.bytecode.get(offset..value_offset_safe).unwrap_or(&[]).to_owned();
// pad value with 0x00
if value.len() < size {
value.resize(size, 0u8);
}
// consume dynamic gas
let minimum_word_size = size.div_ceil(32) as u128;
let gas_cost = 3 * minimum_word_size + self.memory.expansion_cost(offset, size);
self.consume_gas(gas_cost);
self.memory.store_with_opcode(
dest_offset,
size,
&value,
#[cfg(feature = "experimental")]
operation,
);
}
// GASPRICE
0x3A => {
self.stack.push(U256::from(1), operation);
}
// EXTCODESIZE
0x3B => {
let address = self.stack.pop()?.value;
// consume dynamic gas
if !self.address_access_set.contains(&address) {
self.consume_gas(2600);
self.address_access_set.insert(address);
} else {
self.consume_gas(100);
}
self.stack.push(U256::from(1), operation);
}
// EXTCODECOPY
0x3C => {
let address = self.stack.pop()?.value;
let dest_offset = self.stack.pop()?.value;
self.stack.pop()?;
let size = self.stack.pop()?.value;
// Safely convert U256 to usize
let dest_offset: usize = dest_offset.try_into().unwrap_or(0);
let size: usize = size.try_into().unwrap_or(256);
let mut value = Vec::with_capacity(size);
value.fill(0xff);
// consume dynamic gas
let minimum_word_size = size.div_ceil(32) as u128;
let gas_cost =
3 * minimum_word_size + self.memory.expansion_cost(dest_offset, size);
self.consume_gas(gas_cost);
if !self.address_access_set.contains(&address) {
self.consume_gas(2600);
self.address_access_set.insert(address);
} else {
self.consume_gas(100);
}
self.memory.store_with_opcode(
dest_offset,
size,
&value,
#[cfg(feature = "experimental")]
operation,
);
}
// RETURNDATASIZE
0x3D => {
self.stack.push(U256::from(1u8), operation);
}
// RETURNDATACOPY
0x3E => {
let dest_offset = self.stack.pop()?.value;
self.stack.pop()?;
let size = self.stack.pop()?.value;
// Safely convert U256 to usize
let dest_offset: usize = dest_offset.try_into().unwrap_or(0);
let size: usize = size.try_into().unwrap_or(256);
let mut value = Vec::with_capacity(size);
value.fill(0xff);
// consume dynamic gas
let minimum_word_size = size.div_ceil(32) as u128;
let gas_cost =
3 * minimum_word_size + self.memory.expansion_cost(dest_offset, size);
self.consume_gas(gas_cost);
self.memory.store_with_opcode(
dest_offset,
size,
&value,
#[cfg(feature = "experimental")]
operation,
);
}
// EXTCODEHASH and BLOCKHASH
0x3F | 0x40 => {
let address = self.stack.pop()?.value;
// consume dynamic gas