-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathexecutor.rs
More file actions
1951 lines (1757 loc) · 65.4 KB
/
executor.rs
File metadata and controls
1951 lines (1757 loc) · 65.4 KB
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 crate::backend::Backend;
use crate::core::utils::{U256_ZERO, U64_MAX};
use crate::core::{ExitFatal, InterpreterHandler, Machine};
use crate::executor::stack::precompile::{
PrecompileFailure, PrecompileHandle, PrecompileOutput, PrecompileSet,
};
use crate::executor::stack::tagged_runtime::{RuntimeKind, TaggedRuntime};
use crate::gasometer::{self, Gasometer, StorageTarget};
use crate::maybe_borrowed::MaybeBorrowed;
use crate::prelude::*;
use crate::runtime::Resolve;
use crate::{
Capture, Config, Context, CreateScheme, ExitError, ExitReason, Handler, Opcode, Runtime,
Transfer,
};
use core::{cmp::min, convert::Infallible};
use primitive_types::{H160, H256, U256};
use sha3::{Digest, Keccak256};
use smallvec::{smallvec, SmallVec};
macro_rules! emit_exit {
($reason:expr) => {{
let reason = $reason;
event!(Exit {
reason: &reason,
return_value: &Vec::new(),
});
reason
}};
($reason:expr, $return_value:expr) => {{
let reason = $reason;
let return_value = $return_value;
event!(Exit {
reason: &reason,
return_value: &return_value,
});
(reason, return_value)
}};
}
macro_rules! try_or_fail {
( $e:expr ) => {
match $e {
Ok(v) => v,
Err(e) => return Capture::Exit((e.into(), Vec::new())),
}
};
}
const DEFAULT_CALL_STACK_CAPACITY: usize = 4;
const fn l64(gas: u64) -> u64 {
gas - gas / 64
}
pub enum StackExitKind {
Succeeded,
Reverted,
Failed,
}
/// `Authorization` contains already prepared data for EIP-7702.
/// - `authority`is `ecrecovered` authority address.
/// - `address` is delegation destination address.
/// - `nonce` is the `nonce` value which `authority.nonce` should be equal.
/// - `is_valid` is the flag that indicates the validity of the authorization. It is used to
/// charge gas for each authorization item, but if it's invalid exclude from EVM `authority_list` flow.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Authorization {
pub authority: H160,
pub address: H160,
pub nonce: u64,
pub is_valid: bool,
}
impl Authorization {
/// Create a new `Authorization` with given `authority`, `address`, and `nonce`.
#[must_use]
pub const fn new(authority: H160, address: H160, nonce: u64, is_valid: bool) -> Self {
Self {
authority,
address,
nonce,
is_valid,
}
}
/// Returns `true` if `authority` is delegated to `address`.
/// `0xef0100 ++ address`, and it is always 23 bytes.
#[must_use]
pub fn is_delegated(code: &[u8]) -> bool {
code.len() == 23 && code.starts_with(&[0xEF, 0x01, 0x00])
}
/// Get `authority` delegated `address`.
/// It checks, is it delegation designation (EIP-7702).
#[must_use]
pub fn get_delegated_address(code: &[u8]) -> Option<H160> {
if Self::is_delegated(code) {
// `code` size is always 23 bytes.
Some(H160::from_slice(&code[3..]))
} else {
None
}
}
/// Returns the delegation code as composing: `0xef0100 ++ address`.
/// Result code is always 23 bytes.
#[must_use]
pub fn delegation_code(&self) -> Vec<u8> {
let mut code = Vec::with_capacity(23);
code.extend(&[0xEF, 0x01, 0x00]);
code.extend(self.address.as_bytes());
code
}
}
#[derive(Default, Clone, Debug)]
pub struct Accessed {
pub accessed_addresses: BTreeSet<H160>,
pub accessed_storage: BTreeSet<(H160, H256)>,
pub authority: BTreeMap<H160, H160>,
}
impl Accessed {
pub fn access_address(&mut self, address: H160) {
self.accessed_addresses.insert(address);
}
pub fn access_addresses<I>(&mut self, addresses: I)
where
I: Iterator<Item = H160>,
{
self.accessed_addresses.extend(addresses);
}
pub fn access_storages<I>(&mut self, storages: I)
where
I: Iterator<Item = (H160, H256)>,
{
for storage in storages {
self.accessed_storage.insert((storage.0, storage.1));
}
}
/// Add authority to the accessed authority list (EIP-7702).
pub fn add_authority(&mut self, authority: H160, address: H160) {
self.authority.insert(authority, address);
}
/// Remove authority from the accessed authority list (EIP-7702).
pub fn remove_authority(&mut self, authority: H160) {
self.authority.remove(&authority);
}
/// Get authority from the accessed authority list (EIP-7702).
#[must_use]
pub fn get_authority_target(&self, authority: H160) -> Option<H160> {
self.authority.get(&authority).copied()
}
/// Check if authority is in the accessed authority list (EIP-7702).
#[must_use]
pub fn is_authority(&self, authority: H160) -> bool {
self.authority.contains_key(&authority)
}
}
#[derive(Clone, Debug)]
pub struct StackSubstateMetadata<'config> {
gasometer: Gasometer<'config>,
is_static: bool,
depth: Option<usize>,
accessed: Option<Accessed>,
}
impl<'config> StackSubstateMetadata<'config> {
#[must_use]
pub fn new(gas_limit: u64, config: &'config Config) -> Self {
let accessed = if config.increase_state_access_gas {
Some(Accessed::default())
} else {
None
};
Self {
gasometer: Gasometer::new(gas_limit, config),
is_static: false,
depth: None,
accessed,
}
}
/// Swallow commit implements part of logic for `exit_commit`:
/// - Record opcode stipend.
/// - Record an explicit refund.
/// - Merge warmed accounts and storages
///
/// # Errors
/// Return `ExitError` that is thrown by gasometer gas calculation errors.
pub fn swallow_commit(&mut self, other: Self) -> Result<(), ExitError> {
self.gasometer.record_stipend(other.gasometer.gas())?;
self.gasometer
.record_refund(other.gasometer.refunded_gas())?;
// Merge warmed accounts and storages
if let (Some(mut other_accessed), Some(self_accessed)) =
(other.accessed, self.accessed.as_mut())
{
self_accessed
.accessed_addresses
.append(&mut other_accessed.accessed_addresses);
self_accessed
.accessed_storage
.append(&mut other_accessed.accessed_storage);
self_accessed
.authority
.append(&mut other_accessed.authority);
}
Ok(())
}
/// Swallow revert implements part of logic for `exit_commit`:
/// - Record opcode stipend.
///
/// # Errors
/// Return `ExitError` that is thrown by gasometer gas calculation errors.
pub fn swallow_revert(&mut self, other: &Self) -> Result<(), ExitError> {
self.gasometer.record_stipend(other.gasometer.gas())
}
/// Swallow revert implements part of logic for `exit_commit`:
/// At the moment, it does nothing.
pub const fn swallow_discard(&self, _other: &Self) {}
#[must_use]
pub fn spit_child(&self, gas_limit: u64, is_static: bool) -> Self {
Self {
gasometer: Gasometer::new(gas_limit, self.gasometer.config()),
is_static: is_static || self.is_static,
depth: self.depth.map_or(Some(0), |n| Some(n + 1)),
accessed: self.accessed.as_ref().map(|_| Accessed::default()),
}
}
#[must_use]
pub const fn gasometer(&self) -> &Gasometer<'config> {
&self.gasometer
}
pub fn gasometer_mut(&mut self) -> &mut Gasometer<'config> {
&mut self.gasometer
}
#[must_use]
pub const fn is_static(&self) -> bool {
self.is_static
}
#[must_use]
pub const fn depth(&self) -> Option<usize> {
self.depth
}
pub fn access_address(&mut self, address: H160) {
if let Some(accessed) = &mut self.accessed {
accessed.access_address(address);
}
}
pub fn access_addresses<I>(&mut self, addresses: I)
where
I: Iterator<Item = H160>,
{
if let Some(accessed) = &mut self.accessed {
accessed.access_addresses(addresses);
}
}
pub fn access_storage(&mut self, address: H160, key: H256) {
if let Some(accessed) = &mut self.accessed {
accessed.accessed_storage.insert((address, key));
}
}
pub fn access_storages<I>(&mut self, storages: I)
where
I: Iterator<Item = (H160, H256)>,
{
if let Some(accessed) = &mut self.accessed {
accessed.access_storages(storages);
}
}
/// Used for gas calculation logic.
/// It's most significant for `cold/warm` gas calculation as warmed addresses spent less gas.
#[must_use]
pub const fn accessed(&self) -> &Option<Accessed> {
&self.accessed
}
/// Add authority to accessed list (related to EIP-7702)
pub fn add_authority(&mut self, authority: H160, address: H160) {
if let Some(accessed) = &mut self.accessed {
accessed.add_authority(authority, address);
}
}
/// Remove authority from accessed list (related to EIP-7702)
pub fn remove_authority(&mut self, authority: H160) {
if let Some(accessed) = &mut self.accessed {
accessed.remove_authority(authority);
}
}
}
#[auto_impl::auto_impl(& mut, Box)]
pub trait StackState<'config>: Backend {
fn metadata(&self) -> &StackSubstateMetadata<'config>;
fn metadata_mut(&mut self) -> &mut StackSubstateMetadata<'config>;
fn enter(&mut self, gas_limit: u64, is_static: bool);
/// # Errors
/// Return `ExitError`
fn exit_commit(&mut self) -> Result<(), ExitError>;
/// # Errors
/// Return `ExitError`
fn exit_revert(&mut self) -> Result<(), ExitError>;
/// # Errors
/// Return `ExitError`
fn exit_discard(&mut self) -> Result<(), ExitError>;
fn is_empty(&self, address: H160) -> bool;
fn deleted(&self, address: H160) -> bool;
fn is_created(&self, address: H160) -> bool;
fn is_cold(&self, address: H160) -> bool;
fn is_storage_cold(&self, address: H160, key: H256) -> bool;
/// # Errors
/// Return `ExitError`
fn inc_nonce(&mut self, address: H160) -> Result<(), ExitError>;
fn set_storage(&mut self, address: H160, key: H256, value: H256);
fn reset_storage(&mut self, address: H160);
fn log(&mut self, address: H160, topics: Vec<H256>, data: Vec<u8>);
fn set_deleted(&mut self, address: H160);
fn set_created(&mut self, address: H160);
fn set_code(&mut self, address: H160, code: Vec<u8>);
/// # Errors
/// Return `ExitError`
fn transfer(&mut self, transfer: Transfer) -> Result<(), ExitError>;
fn reset_balance(&mut self, address: H160);
fn touch(&mut self, address: H160);
/// # Errors
/// Return `ExitError`
fn record_external_operation(
&mut self,
#[allow(clippy::used_underscore_binding)] _op: crate::ExternalOperation,
) -> Result<(), ExitError> {
Ok(())
}
/// # Errors
/// Return `ExitError`
fn record_external_dynamic_opcode_cost(
&mut self,
#[allow(clippy::used_underscore_binding)] _opcode: Opcode,
#[allow(clippy::used_underscore_binding)] _gas_cost: gasometer::GasCost,
#[allow(clippy::used_underscore_binding)] _target: StorageTarget,
) -> Result<(), ExitError> {
Ok(())
}
/// # Errors
/// Return `ExitError`
fn record_external_cost(
&mut self,
#[allow(clippy::used_underscore_binding)] _ref_time: Option<u64>,
#[allow(clippy::used_underscore_binding)] _proof_size: Option<u64>,
#[allow(clippy::used_underscore_binding)] _storage_growth: Option<u64>,
) -> Result<(), ExitError> {
Ok(())
}
fn refund_external_cost(
&mut self,
#[allow(clippy::used_underscore_binding)] _ref_time: Option<u64>,
#[allow(clippy::used_underscore_binding)] _proof_size: Option<u64>,
) {
}
/// Set tstorage value of address at index.
/// EIP-1153: Transient storage
///
/// # Errors
/// Return `ExitError`
fn tstore(&mut self, address: H160, index: H256, value: U256) -> Result<(), ExitError>;
/// Get tstorage value of address at index.
/// EIP-1153: Transient storage
///
/// # Errors
/// Return `ExitError`
fn tload(&mut self, address: H160, index: H256) -> Result<U256, ExitError>;
/// EIP-7702 - check is authority cold.
fn is_authority_cold(&mut self, address: H160) -> Option<bool>;
/// EIP-7702 - get authority target address.
fn get_authority_target(&mut self, address: H160) -> Option<H160>;
}
/// Stack-based executor.
pub struct StackExecutor<'config, 'precompiles, S, P> {
config: &'config Config,
state: S,
precompile_set: &'precompiles P,
}
impl<'config, 'precompiles, S: StackState<'config>, P: PrecompileSet>
StackExecutor<'config, 'precompiles, S, P>
{
/// Return a reference of the Config.
pub const fn config(&self) -> &'config Config {
self.config
}
/// Return a reference to the precompile set.
pub const fn precompiles(&self) -> &'precompiles P {
self.precompile_set
}
/// Create a new stack-based executor with given precompiles.
pub const fn new_with_precompiles(
state: S,
config: &'config Config,
precompile_set: &'precompiles P,
) -> Self {
Self {
config,
state,
precompile_set,
}
}
pub const fn state(&self) -> &S {
&self.state
}
pub fn state_mut(&mut self) -> &mut S {
&mut self.state
}
#[allow(clippy::missing_const_for_fn)]
pub fn into_state(self) -> S {
self.state
}
/// Create a substate executor from the current executor.
pub fn enter_substate(&mut self, gas_limit: u64, is_static: bool) {
self.state.enter(gas_limit, is_static);
}
/// Exit a substate.
///
/// # Panics
/// Panic occurs if a result is an empty `substate` stack.
///
/// # Errors
/// Return `ExitError`
pub fn exit_substate(&mut self, kind: &StackExitKind) -> Result<(), ExitError> {
match kind {
StackExitKind::Succeeded => self.state.exit_commit(),
StackExitKind::Reverted => self.state.exit_revert(),
StackExitKind::Failed => self.state.exit_discard(),
}
}
/// Execute the runtime until it returns.
pub fn execute(&mut self, runtime: &mut Runtime) -> ExitReason {
let mut call_stack: SmallVec<[TaggedRuntime; DEFAULT_CALL_STACK_CAPACITY]> =
smallvec!(TaggedRuntime {
kind: RuntimeKind::Execute,
inner: MaybeBorrowed::Borrowed(runtime),
});
let (reason, _, _) = self.execute_with_call_stack(&mut call_stack);
reason
}
/// Execute using Runtimes on the `call_stack` until it returns.
fn execute_with_call_stack(
&mut self,
call_stack: &mut SmallVec<[TaggedRuntime<'_>; DEFAULT_CALL_STACK_CAPACITY]>,
) -> (ExitReason, Option<H160>, Vec<u8>) {
// This `interrupt_runtime` is used to pass the runtime obtained from the
// `Capture::Trap` branch in the match below back to the top of the call stack.
// The reason we can't simply `push` the runtime directly onto the stack in the
// `Capture::Trap` branch is because the borrow-checker complains that the stack
// is already borrowed as long as we hold a pointer on the last element
// (i.e. the currently executing runtime).
let mut interrupt_runtime = None;
loop {
if let Some(rt) = interrupt_runtime.take() {
call_stack.push(rt);
}
let Some(runtime) = call_stack.last_mut() else {
return (
ExitReason::Fatal(ExitFatal::UnhandledInterrupt),
None,
Vec::new(),
);
};
let reason = {
let inner_runtime = &mut runtime.inner;
match inner_runtime.run(self) {
Capture::Exit(reason) => reason,
Capture::Trap(Resolve::Call(rt, _)) => {
interrupt_runtime = Some(rt.0);
continue;
}
Capture::Trap(Resolve::Create(rt, _)) => {
interrupt_runtime = Some(rt.0);
continue;
}
}
};
let runtime_kind = runtime.kind;
let (reason, maybe_address, return_data) = match runtime_kind {
RuntimeKind::Create(created_address) => {
let (reason, maybe_address, return_data) = self.exit_substate_for_create(
created_address,
reason,
runtime.inner.machine().return_value(),
);
(reason, maybe_address, return_data)
}
RuntimeKind::Call(code_address) => {
let return_data = self.exit_substate_for_call(
code_address,
&reason,
runtime.inner.machine().return_value(),
);
(reason, None, return_data)
}
RuntimeKind::Execute => (reason, None, runtime.inner.machine().return_value()),
};
// We're done with that runtime now, so can pop it off the call stack
call_stack.pop();
// Now pass the results from that runtime on to the next one in the stack
let Some(runtime) = call_stack.last_mut() else {
return (reason, None, return_data);
};
emit_exit!(&reason, &return_data);
let inner_runtime = &mut runtime.inner;
let maybe_error = match runtime_kind {
RuntimeKind::Create(_) => {
inner_runtime.finish_create(reason, maybe_address, return_data)
}
RuntimeKind::Call(_) | RuntimeKind::Execute => {
inner_runtime.finish_call(reason, return_data)
}
};
// Early exit if passing on the result caused an error
if let Err(e) = maybe_error {
return (e, None, Vec::new());
}
}
}
/// Get remaining gas.
pub fn gas(&self) -> u64 {
self.state.metadata().gasometer.gas()
}
fn record_create_transaction_cost(
&mut self,
init_code: &[u8],
access_list: &[(H160, Vec<H256>)],
) -> Result<(), ExitError> {
let transaction_cost = gasometer::create_transaction_cost(init_code, access_list);
let gasometer = &mut self.state.metadata_mut().gasometer;
gasometer.record_transaction(transaction_cost)
}
fn maybe_record_init_code_cost(&mut self, init_code: &[u8]) -> Result<(), ExitError> {
if let Some(limit) = self.config.max_initcode_size {
// EIP-3860
if init_code.len() > limit {
self.state.metadata_mut().gasometer.fail();
return Err(ExitError::CreateContractLimit);
}
return self
.state
.metadata_mut()
.gasometer
.record_cost(gasometer::init_code_cost(init_code));
}
Ok(())
}
/// Execute a `CREATE` transaction.
pub fn transact_create(
&mut self,
caller: H160,
value: U256,
init_code: Vec<u8>,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>, // See EIP-2930
) -> (ExitReason, Vec<u8>) {
if self.nonce(caller) >= U64_MAX {
return (ExitError::MaxNonce.into(), Vec::new());
}
let address = self.create_address(CreateScheme::Legacy { caller });
event!(TransactCreate {
caller,
value,
init_code: &init_code,
gas_limit,
address,
});
if let Some(limit) = self.config.max_initcode_size {
if init_code.len() > limit {
self.state.metadata_mut().gasometer.fail();
return emit_exit!(ExitError::CreateContractLimit.into(), Vec::new());
}
}
if let Err(e) = self.record_create_transaction_cost(&init_code, &access_list) {
return emit_exit!(e.into(), Vec::new());
}
self.warm_addresses_and_storage(caller, address, access_list);
match self.create_inner(
caller,
CreateScheme::Legacy { caller },
value,
init_code,
Some(gas_limit),
false,
) {
Capture::Exit((s, v)) => emit_exit!(s, v),
Capture::Trap(rt) => {
let mut cs: SmallVec<[TaggedRuntime<'_>; DEFAULT_CALL_STACK_CAPACITY]> =
smallvec!(rt.0);
let (s, _, v) = self.execute_with_call_stack(&mut cs);
emit_exit!(s, v)
}
}
}
/// Same as `CREATE` but uses a specified address for created smart contract.
#[cfg(feature = "create-fixed")]
pub fn transact_create_fixed(
&mut self,
caller: H160,
address: H160,
value: U256,
init_code: Vec<u8>,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>, // See EIP-2930
) -> (ExitReason, Vec<u8>) {
let address = self.create_address(CreateScheme::Fixed(address));
event!(TransactCreate {
caller,
value,
init_code: &init_code,
gas_limit,
address
});
if let Err(e) = self.record_create_transaction_cost(&init_code, &access_list) {
return emit_exit!(e.into(), Vec::new());
}
self.warm_addresses_and_storage(caller, address, access_list);
match self.create_inner(
caller,
CreateScheme::Fixed(address),
value,
init_code,
Some(gas_limit),
false,
) {
Capture::Exit((s, v)) => emit_exit!(s, v),
Capture::Trap(rt) => {
let mut cs: SmallVec<[TaggedRuntime<'_>; DEFAULT_CALL_STACK_CAPACITY]> =
smallvec!(rt.0);
let (s, _, v) = self.execute_with_call_stack(&mut cs);
emit_exit!(s, v)
}
}
}
/// Execute a `CREATE2` transaction.
#[allow(clippy::too_many_arguments)]
pub fn transact_create2(
&mut self,
caller: H160,
value: U256,
init_code: Vec<u8>,
salt: H256,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>, // See EIP-2930
) -> (ExitReason, Vec<u8>) {
if let Some(limit) = self.config.max_initcode_size {
if init_code.len() > limit {
self.state.metadata_mut().gasometer.fail();
return emit_exit!(ExitError::CreateContractLimit.into(), Vec::new());
}
}
let code_hash =
H256::from_slice(<[u8; 32]>::from(Keccak256::digest(&init_code)).as_slice());
let address = self.create_address(CreateScheme::Create2 {
caller,
code_hash,
salt,
});
event!(TransactCreate2 {
caller,
value,
init_code: &init_code,
salt,
gas_limit,
address,
});
if let Err(e) = self.record_create_transaction_cost(&init_code, &access_list) {
return emit_exit!(e.into(), Vec::new());
}
self.warm_addresses_and_storage(caller, address, access_list);
match self.create_inner(
caller,
CreateScheme::Create2 {
caller,
code_hash,
salt,
},
value,
init_code,
Some(gas_limit),
false,
) {
Capture::Exit((s, v)) => emit_exit!(s, v),
Capture::Trap(rt) => {
let mut cs: SmallVec<[TaggedRuntime<'_>; DEFAULT_CALL_STACK_CAPACITY]> =
smallvec!(rt.0);
let (s, _, v) = self.execute_with_call_stack(&mut cs);
emit_exit!(s, v)
}
}
}
/// Execute a `CALL` transaction with a given parameters
///
/// ## Notes
/// - `access_list` associated to [EIP-2930: Optional access lists](https://eips.ethereum.org/EIPS/eip-2930)
/// - `authorization_list` associated to [EIP-7702: Authorized accounts](https://eips.ethereum.org/EIPS/eip-7702)
#[allow(clippy::too_many_arguments)]
pub fn transact_call(
&mut self,
caller: H160,
address: H160,
value: U256,
data: Vec<u8>,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>,
authorization_list: Vec<Authorization>,
) -> (ExitReason, Vec<u8>) {
event!(TransactCall {
caller,
address,
value,
data: &data,
gas_limit,
});
if self.nonce(caller) >= U64_MAX {
return (ExitError::MaxNonce.into(), Vec::new());
}
let transaction_cost =
gasometer::call_transaction_cost(&data, &access_list, authorization_list.len());
let gasometer = &mut self.state.metadata_mut().gasometer;
match gasometer.record_transaction(transaction_cost) {
Ok(()) => (),
Err(e) => return emit_exit!(e.into(), Vec::new()),
}
if let Err(e) = self.state.inc_nonce(caller) {
return (e.into(), Vec::new());
}
self.warm_addresses_and_storage(caller, address, access_list);
// EIP-7702. authorized accounts
// NOTE: it must be after `inc_nonce`
if let Err(e) = self.authorized_accounts(authorization_list) {
return (e.into(), Vec::new());
}
let context = Context {
caller,
address,
apparent_value: value,
};
match self.call_inner(
address,
Some(Transfer {
source: caller,
target: address,
value,
}),
data,
Some(gas_limit),
false,
false,
false,
context,
) {
Capture::Exit((s, v)) => emit_exit!(s, v),
Capture::Trap(rt) => {
let mut cs: SmallVec<[TaggedRuntime<'_>; DEFAULT_CALL_STACK_CAPACITY]> =
smallvec!(rt.0);
let (s, _, v) = self.execute_with_call_stack(&mut cs);
emit_exit!(s, v)
}
}
}
/// Get used gas for the current executor, given the price.
pub fn used_gas(&self) -> u64 {
// Avoid uncontrolled `u64` casting
let refunded_gas =
u64::try_from(self.state.metadata().gasometer.refunded_gas()).unwrap_or_default();
let total_used_gas = self.state.metadata().gasometer.total_used_gas();
let total_used_gas_refunded = self.state.metadata().gasometer.total_used_gas()
- min(
total_used_gas / self.config.max_refund_quotient,
refunded_gas,
);
// EIP-7623: max(total_used_gas, floor_gas)
if self.config.has_floor_gas
&& total_used_gas_refunded < self.state.metadata().gasometer.floor_gas()
{
self.state.metadata().gasometer.floor_gas()
} else {
total_used_gas_refunded
}
}
/// Get fee needed for the current executor, given the price.
pub fn fee(&self, price: U256) -> U256 {
let used_gas = self.used_gas();
U256::from(used_gas).saturating_mul(price)
}
/// Get account nonce.
/// NOTE: we don't need to cache it as by default it's `MemoryStackState` with cache flow
pub fn nonce(&self, address: H160) -> U256 {
self.state.basic(address).nonce
}
/// Check if the existing account is "create collision".
/// [EIP-7610](https://eips.ethereum.org/EIPS/eip-7610)
pub fn is_create_collision(&self, address: H160) -> bool {
!self.code(address).is_empty()
|| self.nonce(address) > U256_ZERO
|| !self.state.is_empty_storage(address)
}
/// Get the created address from given scheme.
pub fn create_address(&self, scheme: CreateScheme) -> H160 {
match scheme {
CreateScheme::Create2 {
caller,
code_hash,
salt,
} => {
let mut hasher = Keccak256::new();
hasher.update([0xff]);
hasher.update(&caller[..]);
hasher.update(&salt[..]);
hasher.update(&code_hash[..]);
H256::from_slice(<[u8; 32]>::from(hasher.finalize()).as_slice()).into()
}
CreateScheme::Legacy { caller } => {
let nonce = self.nonce(caller);
let mut stream = rlp::RlpStream::new_list(2);
stream.append(&caller);
stream.append(&nonce);
H256::from_slice(<[u8; 32]>::from(Keccak256::digest(stream.out())).as_slice())
.into()
}
CreateScheme::Fixed(address) => address,
}
}
/// According to `EIP-2930` - `access_list` should be warmed.
/// This function warms addresses and storage keys.
///
/// [EIP-2930: Optional access lists](https://eips.ethereum.org/EIPS/eip-2930)
pub fn warm_access_list(&mut self, access_list: Vec<(H160, Vec<H256>)>) {
let addresses = access_list.iter().map(|a| a.0);
self.state.metadata_mut().access_addresses(addresses);
let storage_keys = access_list
.into_iter()
.flat_map(|(address, keys)| keys.into_iter().map(move |key| (address, key)));
self.state.metadata_mut().access_storages(storage_keys);
}
/// Warm addresses and storage keys.
/// - According to `EIP-2929` the addresses should be warmed:
/// 1. caller (tx.sender)
/// 2. address (tx.to or the address being created if it is a contract creation transaction)
/// - Warm coinbase according to `EIP-3651`
/// - Warm `access_list` according to `EIP-2931`
///
/// ## References
/// - [EIP-2929: Gas cost increases for state access opcodes](https://eips.ethereum.org/EIPS/eip-2929)
/// - [EIP-2930: Optional access lists](https://eips.ethereum.org/EIPS/eip-2930)
/// - [EIP-3651: Warm COINBASE](https://eips.ethereum.org/EIPS/eip-3651)
fn warm_addresses_and_storage(
&mut self,
caller: H160,
address: H160,
access_list: Vec<(H160, Vec<H256>)>,
) {
if self.config.increase_state_access_gas {
if self.config.warm_coinbase_address {
// Warm coinbase address for EIP-3651
let coinbase = self.block_coinbase();
self.state
.metadata_mut()
.access_addresses([caller, address, coinbase].iter().copied());
} else {
self.state
.metadata_mut()
.access_addresses([caller, address].iter().copied());
}
self.warm_access_list(access_list);
}
}
/// Authorized accounts behavior.
///
/// According to `EIP-7702` behavior section should be several steps of verifications.
/// Current function includes steps 2.4-9 from the spec:
/// 2. Verify the `nonce` is less than `2**64 - 1`.
/// 4. Add `authority` to `accessed_addresses`
/// 5. Verify the code of `authority` is either empty or already delegated.
/// 6. Verify the `nonce` of `authority` is equal to `nonce` (of address).
/// 7. Add `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` gas to the global refund counter if authority exists in the trie.
/// 8. Set the code of `authority` to be `0xef0100 || address`. This is a delegation designation.
/// 9. Increase the `nonce` of `authority` by one.
///
/// It means, that steps 1,3 of spec must be passed before calling this function:
/// 1. Verify the chain id is either 0 or the chain’s current ID.
/// 3. `authority = ecrecover(...)`
///
/// See: [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702#behavior)
///
/// ## Errors
/// Return error if nonce increment return error.
fn authorized_accounts(
&mut self,
authorization_list: Vec<Authorization>,
) -> Result<(), ExitError> {
if !self.config.has_authorization_list {
return Ok(());
}
let mut refunded_accounts = 0;
let state = self.state_mut();
let mut warm_authority: Vec<H160> = Vec::with_capacity(authorization_list.len());
for authority in authorization_list {
// If EIP-7702 Spec validation steps 1, 3 return false.
if !authority.is_valid {
continue;
}
// 2. Verify the `nonce` is less than `2**64 - 1`.
if U256::from(authority.nonce) >= U64_MAX {
continue;
}
// 4. Add authority to accessed_addresses (as defined in EIP-2929)
warm_authority.push(authority.authority);
// 5. Verify the code of authority is either empty or already delegated.
let authority_code = state.code(authority.authority);
if !authority_code.is_empty() && !Authorization::is_delegated(&authority_code) {
continue;