-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
inspector.rs
2153 lines (1923 loc) · 90.5 KB
/
inspector.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
//! Cheatcode EVM inspector.
use crate::{
evm::{
mapping::{self, MappingSlots},
mock::{MockCallDataContext, MockCallReturnData},
prank::Prank,
DealRecord, GasRecord, RecordAccess,
},
inspector::utils::CommonCreateInput,
script::{Broadcast, Wallets},
test::{
assume::AssumeNoRevert,
expect::{
self, ExpectedCallData, ExpectedCallTracker, ExpectedCallType, ExpectedEmit,
ExpectedRevert, ExpectedRevertKind,
},
},
utils::IgnoredTraces,
CheatsConfig, CheatsCtxt, DynCheatcode, Error, Result,
Vm::{self, AccountAccess},
};
use alloy_primitives::{
hex,
map::{AddressHashMap, HashMap},
Address, Bytes, Log, TxKind, B256, U256,
};
use alloy_rpc_types::request::{TransactionInput, TransactionRequest};
use alloy_sol_types::{SolCall, SolInterface, SolValue};
use foundry_common::{evm::Breakpoints, TransactionMaybeSigned, SELECTOR_LEN};
use foundry_evm_core::{
abi::Vm::stopExpectSafeMemoryCall,
backend::{DatabaseError, DatabaseExt, RevertDiagnostic},
constants::{CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS, MAGIC_ASSUME},
utils::new_evm_with_existing_context,
InspectorExt,
};
use foundry_evm_traces::{TracingInspector, TracingInspectorConfig};
use foundry_wallets::multi_wallet::MultiWallet;
use itertools::Itertools;
use proptest::test_runner::{RngAlgorithm, TestRng, TestRunner};
use rand::Rng;
use revm::{
interpreter::{
opcode as op, CallInputs, CallOutcome, CallScheme, CreateInputs, CreateOutcome,
EOFCreateInputs, EOFCreateKind, Gas, InstructionResult, Interpreter, InterpreterAction,
InterpreterResult,
},
primitives::{BlockEnv, CreateScheme, EVMError, EvmStorageSlot, SpecId, EOF_MAGIC_BYTES},
EvmContext, InnerEvmContext, Inspector,
};
use serde_json::Value;
use std::{
collections::{BTreeMap, VecDeque},
fs::File,
io::BufReader,
ops::Range,
path::PathBuf,
sync::Arc,
};
mod utils;
pub type Ecx<'a, 'b, 'c> = &'a mut EvmContext<&'b mut (dyn DatabaseExt + 'c)>;
pub type InnerEcx<'a, 'b, 'c> = &'a mut InnerEvmContext<&'b mut (dyn DatabaseExt + 'c)>;
/// Helper trait for obtaining complete [revm::Inspector] instance from mutable reference to
/// [Cheatcodes].
///
/// This is needed for cases when inspector itself needs mutable access to [Cheatcodes] state and
/// allows us to correctly execute arbitrary EVM frames from inside cheatcode implementations.
pub trait CheatcodesExecutor {
/// Core trait method accepting mutable reference to [Cheatcodes] and returning
/// [revm::Inspector].
fn get_inspector<'a>(&'a mut self, cheats: &'a mut Cheatcodes) -> Box<dyn InspectorExt + 'a>;
/// Obtains [revm::Evm] instance and executes the given CREATE frame.
fn exec_create(
&mut self,
inputs: CreateInputs,
ccx: &mut CheatsCtxt,
) -> Result<CreateOutcome, EVMError<DatabaseError>> {
with_evm(self, ccx, |evm| {
evm.context.evm.inner.journaled_state.depth += 1;
// Handle EOF bytecode
let first_frame_or_result = if evm.handler.cfg.spec_id.is_enabled_in(SpecId::OSAKA) &&
inputs.scheme == CreateScheme::Create &&
inputs.init_code.starts_with(&EOF_MAGIC_BYTES)
{
evm.handler.execution().eofcreate(
&mut evm.context,
Box::new(EOFCreateInputs::new(
inputs.caller,
inputs.value,
inputs.gas_limit,
EOFCreateKind::Tx { initdata: inputs.init_code },
)),
)?
} else {
evm.handler.execution().create(&mut evm.context, Box::new(inputs))?
};
let mut result = match first_frame_or_result {
revm::FrameOrResult::Frame(first_frame) => evm.run_the_loop(first_frame)?,
revm::FrameOrResult::Result(result) => result,
};
evm.handler.execution().last_frame_return(&mut evm.context, &mut result)?;
let outcome = match result {
revm::FrameResult::Call(_) => unreachable!(),
revm::FrameResult::Create(create) | revm::FrameResult::EOFCreate(create) => create,
};
evm.context.evm.inner.journaled_state.depth -= 1;
Ok(outcome)
})
}
fn console_log(&mut self, ccx: &mut CheatsCtxt, message: String) {
self.get_inspector(ccx.state).console_log(message);
}
/// Returns a mutable reference to the tracing inspector if it is available.
fn tracing_inspector(&mut self) -> Option<&mut Option<TracingInspector>> {
None
}
}
/// Constructs [revm::Evm] and runs a given closure with it.
fn with_evm<E, F, O>(
executor: &mut E,
ccx: &mut CheatsCtxt,
f: F,
) -> Result<O, EVMError<DatabaseError>>
where
E: CheatcodesExecutor + ?Sized,
F: for<'a, 'b> FnOnce(
&mut revm::Evm<'_, &'b mut dyn InspectorExt, &'a mut dyn DatabaseExt>,
) -> Result<O, EVMError<DatabaseError>>,
{
let mut inspector = executor.get_inspector(ccx.state);
let error = std::mem::replace(&mut ccx.ecx.error, Ok(()));
let l1_block_info = std::mem::take(&mut ccx.ecx.l1_block_info);
let inner = revm::InnerEvmContext {
env: ccx.ecx.env.clone(),
journaled_state: std::mem::replace(
&mut ccx.ecx.journaled_state,
revm::JournaledState::new(Default::default(), Default::default()),
),
db: &mut ccx.ecx.db as &mut dyn DatabaseExt,
error,
l1_block_info,
};
let mut evm = new_evm_with_existing_context(inner, &mut *inspector);
let res = f(&mut evm)?;
ccx.ecx.journaled_state = evm.context.evm.inner.journaled_state;
ccx.ecx.env = evm.context.evm.inner.env;
ccx.ecx.l1_block_info = evm.context.evm.inner.l1_block_info;
ccx.ecx.error = evm.context.evm.inner.error;
Ok(res)
}
/// Basic implementation of [CheatcodesExecutor] that simply returns the [Cheatcodes] instance as an
/// inspector.
#[derive(Debug, Default, Clone, Copy)]
struct TransparentCheatcodesExecutor;
impl CheatcodesExecutor for TransparentCheatcodesExecutor {
fn get_inspector<'a>(&'a mut self, cheats: &'a mut Cheatcodes) -> Box<dyn InspectorExt + 'a> {
Box::new(cheats)
}
}
macro_rules! try_or_return {
($e:expr) => {
match $e {
Ok(v) => v,
Err(_) => return,
}
};
}
/// Contains additional, test specific resources that should be kept for the duration of the test
#[derive(Debug, Default)]
pub struct Context {
/// Buffered readers for files opened for reading (path => BufReader mapping)
pub opened_read_files: HashMap<PathBuf, BufReader<File>>,
}
/// Every time we clone `Context`, we want it to be empty
impl Clone for Context {
fn clone(&self) -> Self {
Default::default()
}
}
impl Context {
/// Clears the context.
#[inline]
pub fn clear(&mut self) {
self.opened_read_files.clear();
}
}
/// Helps collecting transactions from different forks.
#[derive(Clone, Debug)]
pub struct BroadcastableTransaction {
/// The optional RPC URL.
pub rpc: Option<String>,
/// The transaction to broadcast.
pub transaction: TransactionMaybeSigned,
}
#[derive(Clone, Debug, Copy)]
pub struct RecordDebugStepInfo {
/// The debug trace node index when the recording starts.
pub start_node_idx: usize,
/// The original tracer config when the recording starts.
pub original_tracer_config: TracingInspectorConfig,
}
/// Holds gas metering state.
#[derive(Clone, Debug, Default)]
pub struct GasMetering {
/// True if gas metering is paused.
pub paused: bool,
/// True if gas metering was resumed or reset during the test.
/// Used to reconcile gas when frame ends (if spent less than refunded).
pub touched: bool,
/// True if gas metering should be reset to frame limit.
pub reset: bool,
/// Stores paused gas frames.
pub paused_frames: Vec<Gas>,
/// The group and name of the active snapshot.
pub active_gas_snapshot: Option<(String, String)>,
/// Cache of the amount of gas used in previous call.
/// This is used by the `lastCallGas` cheatcode.
pub last_call_gas: Option<crate::Vm::Gas>,
/// True if gas recording is enabled.
pub recording: bool,
/// The gas used in the last frame.
pub last_gas_used: u64,
/// Gas records for the active snapshots.
pub gas_records: Vec<GasRecord>,
}
impl GasMetering {
/// Start the gas recording.
pub fn start(&mut self) {
self.recording = true;
}
/// Stop the gas recording.
pub fn stop(&mut self) {
self.recording = false;
}
/// Resume paused gas metering.
pub fn resume(&mut self) {
if self.paused {
self.paused = false;
self.touched = true;
}
self.paused_frames.clear();
}
/// Reset gas to limit.
pub fn reset(&mut self) {
self.paused = false;
self.touched = true;
self.reset = true;
self.paused_frames.clear();
}
}
/// Holds data about arbitrary storage.
#[derive(Clone, Debug, Default)]
pub struct ArbitraryStorage {
/// Mapping of arbitrary storage addresses to generated values (slot, arbitrary value).
/// (SLOADs return random value if storage slot wasn't accessed).
/// Changed values are recorded and used to copy storage to different addresses.
pub values: HashMap<Address, HashMap<U256, U256>>,
/// Mapping of address with storage copied to arbitrary storage address source.
pub copies: HashMap<Address, Address>,
}
impl ArbitraryStorage {
/// Marks an address with arbitrary storage.
pub fn mark_arbitrary(&mut self, address: &Address) {
self.values.insert(*address, HashMap::default());
}
/// Maps an address that copies storage with the arbitrary storage address.
pub fn mark_copy(&mut self, from: &Address, to: &Address) {
if self.values.contains_key(from) {
self.copies.insert(*to, *from);
}
}
/// Saves arbitrary storage value for a given address:
/// - store value in changed values cache.
/// - update account's storage with given value.
pub fn save(&mut self, ecx: InnerEcx, address: Address, slot: U256, data: U256) {
self.values.get_mut(&address).expect("missing arbitrary address entry").insert(slot, data);
if let Ok(mut account) = ecx.load_account(address) {
account.storage.insert(slot, EvmStorageSlot::new(data));
}
}
/// Copies arbitrary storage value from source address to the given target address:
/// - if a value is present in arbitrary values cache, then update target storage and return
/// existing value.
/// - if no value was yet generated for given slot, then save new value in cache and update both
/// source and target storages.
pub fn copy(&mut self, ecx: InnerEcx, target: Address, slot: U256, new_value: U256) -> U256 {
let source = self.copies.get(&target).expect("missing arbitrary copy target entry");
let storage_cache = self.values.get_mut(source).expect("missing arbitrary source storage");
let value = match storage_cache.get(&slot) {
Some(value) => *value,
None => {
storage_cache.insert(slot, new_value);
// Update source storage with new value.
if let Ok(mut source_account) = ecx.load_account(*source) {
source_account.storage.insert(slot, EvmStorageSlot::new(new_value));
}
new_value
}
};
// Update target storage with new value.
if let Ok(mut target_account) = ecx.load_account(target) {
target_account.storage.insert(slot, EvmStorageSlot::new(value));
}
value
}
}
/// List of transactions that can be broadcasted.
pub type BroadcastableTransactions = VecDeque<BroadcastableTransaction>;
/// An EVM inspector that handles calls to various cheatcodes, each with their own behavior.
///
/// Cheatcodes can be called by contracts during execution to modify the VM environment, such as
/// mocking addresses, signatures and altering call reverts.
///
/// Executing cheatcodes can be very powerful. Most cheatcodes are limited to evm internals, but
/// there are also cheatcodes like `ffi` which can execute arbitrary commands or `writeFile` and
/// `readFile` which can manipulate files of the filesystem. Therefore, several restrictions are
/// implemented for these cheatcodes:
/// - `ffi`, and file cheatcodes are _always_ opt-in (via foundry config) and never enabled by
/// default: all respective cheatcode handlers implement the appropriate checks
/// - File cheatcodes require explicit permissions which paths are allowed for which operation, see
/// `Config.fs_permission`
/// - Only permitted accounts are allowed to execute cheatcodes in forking mode, this ensures no
/// contract deployed on the live network is able to execute cheatcodes by simply calling the
/// cheatcode address: by default, the caller, test contract and newly deployed contracts are
/// allowed to execute cheatcodes
#[derive(Clone, Debug)]
pub struct Cheatcodes {
/// The block environment
///
/// Used in the cheatcode handler to overwrite the block environment separately from the
/// execution block environment.
pub block: Option<BlockEnv>,
/// The gas price.
///
/// Used in the cheatcode handler to overwrite the gas price separately from the gas price
/// in the execution environment.
pub gas_price: Option<U256>,
/// Address labels
pub labels: AddressHashMap<String>,
/// Prank information
pub prank: Option<Prank>,
/// Expected revert information
pub expected_revert: Option<ExpectedRevert>,
/// Assume next call can revert and discard fuzz run if it does.
pub assume_no_revert: Option<AssumeNoRevert>,
/// Additional diagnostic for reverts
pub fork_revert_diagnostic: Option<RevertDiagnostic>,
/// Recorded storage reads and writes
pub accesses: Option<RecordAccess>,
/// Recorded account accesses (calls, creates) organized by relative call depth, where the
/// topmost vector corresponds to accesses at the depth at which account access recording
/// began. Each vector in the matrix represents a list of accesses at a specific call
/// depth. Once that call context has ended, the last vector is removed from the matrix and
/// merged into the previous vector.
pub recorded_account_diffs_stack: Option<Vec<Vec<AccountAccess>>>,
/// The information of the debug step recording.
pub record_debug_steps_info: Option<RecordDebugStepInfo>,
/// Recorded logs
pub recorded_logs: Option<Vec<crate::Vm::Log>>,
/// Mocked calls
// **Note**: inner must a BTreeMap because of special `Ord` impl for `MockCallDataContext`
pub mocked_calls: HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
/// Mocked functions. Maps target address to be mocked to pair of (calldata, mock address).
pub mocked_functions: HashMap<Address, HashMap<Bytes, Address>>,
/// Expected calls
pub expected_calls: ExpectedCallTracker,
/// Expected emits
pub expected_emits: VecDeque<ExpectedEmit>,
/// Map of context depths to memory offset ranges that may be written to within the call depth.
pub allowed_mem_writes: HashMap<u64, Vec<Range<u64>>>,
/// Current broadcasting information
pub broadcast: Option<Broadcast>,
/// Scripting based transactions
pub broadcastable_transactions: BroadcastableTransactions,
/// Additional, user configurable context this Inspector has access to when inspecting a call
pub config: Arc<CheatsConfig>,
/// Test-scoped context holding data that needs to be reset every test run
pub context: Context,
/// Whether to commit FS changes such as file creations, writes and deletes.
/// Used to prevent duplicate changes file executing non-committing calls.
pub fs_commit: bool,
/// Serialized JSON values.
// **Note**: both must a BTreeMap to ensure the order of the keys is deterministic.
pub serialized_jsons: BTreeMap<String, BTreeMap<String, Value>>,
/// All recorded ETH `deal`s.
pub eth_deals: Vec<DealRecord>,
/// Gas metering state.
pub gas_metering: GasMetering,
/// Contains gas snapshots made over the course of a test suite.
// **Note**: both must a BTreeMap to ensure the order of the keys is deterministic.
pub gas_snapshots: BTreeMap<String, BTreeMap<String, String>>,
/// Mapping slots.
pub mapping_slots: Option<AddressHashMap<MappingSlots>>,
/// The current program counter.
pub pc: usize,
/// Breakpoints supplied by the `breakpoint` cheatcode.
/// `char -> (address, pc)`
pub breakpoints: Breakpoints,
/// Optional cheatcodes `TestRunner`. Used for generating random values from uint and int
/// strategies.
test_runner: Option<TestRunner>,
/// Ignored traces.
pub ignored_traces: IgnoredTraces,
/// Addresses with arbitrary storage.
pub arbitrary_storage: Option<ArbitraryStorage>,
/// Deprecated cheatcodes mapped to the reason. Used to report warnings on test results.
pub deprecated: HashMap<&'static str, Option<&'static str>>,
/// Unlocked wallets used in scripts and testing of scripts.
pub wallets: Option<Wallets>,
}
// This is not derived because calling this in `fn new` with `..Default::default()` creates a second
// `CheatsConfig` which is unused, and inside it `ProjectPathsConfig` is relatively expensive to
// create.
impl Default for Cheatcodes {
fn default() -> Self {
Self::new(Arc::default())
}
}
impl Cheatcodes {
/// Creates a new `Cheatcodes` with the given settings.
pub fn new(config: Arc<CheatsConfig>) -> Self {
Self {
fs_commit: true,
labels: config.labels.clone(),
config,
block: Default::default(),
gas_price: Default::default(),
prank: Default::default(),
expected_revert: Default::default(),
assume_no_revert: Default::default(),
fork_revert_diagnostic: Default::default(),
accesses: Default::default(),
recorded_account_diffs_stack: Default::default(),
recorded_logs: Default::default(),
record_debug_steps_info: Default::default(),
mocked_calls: Default::default(),
mocked_functions: Default::default(),
expected_calls: Default::default(),
expected_emits: Default::default(),
allowed_mem_writes: Default::default(),
broadcast: Default::default(),
broadcastable_transactions: Default::default(),
context: Default::default(),
serialized_jsons: Default::default(),
eth_deals: Default::default(),
gas_metering: Default::default(),
gas_snapshots: Default::default(),
mapping_slots: Default::default(),
pc: Default::default(),
breakpoints: Default::default(),
test_runner: Default::default(),
ignored_traces: Default::default(),
arbitrary_storage: Default::default(),
deprecated: Default::default(),
wallets: Default::default(),
}
}
/// Returns the configured wallets if available, else creates a new instance.
pub fn wallets(&mut self) -> &Wallets {
self.wallets.get_or_insert(Wallets::new(MultiWallet::default(), None))
}
/// Sets the unlocked wallets.
pub fn set_wallets(&mut self, wallets: Wallets) {
self.wallets = Some(wallets);
}
/// Decodes the input data and applies the cheatcode.
fn apply_cheatcode(
&mut self,
ecx: Ecx,
call: &CallInputs,
executor: &mut dyn CheatcodesExecutor,
) -> Result {
// decode the cheatcode call
let decoded = Vm::VmCalls::abi_decode(&call.input, false).map_err(|e| {
if let alloy_sol_types::Error::UnknownSelector { name: _, selector } = e {
let msg = format!(
"unknown cheatcode with selector {selector}; \
you may have a mismatch between the `Vm` interface (likely in `forge-std`) \
and the `forge` version"
);
return alloy_sol_types::Error::Other(std::borrow::Cow::Owned(msg));
}
e
})?;
let caller = call.caller;
// ensure the caller is allowed to execute cheatcodes,
// but only if the backend is in forking mode
ecx.db.ensure_cheatcode_access_forking_mode(&caller)?;
apply_dispatch(
&decoded,
&mut CheatsCtxt {
state: self,
ecx: &mut ecx.inner,
precompiles: &mut ecx.precompiles,
gas_limit: call.gas_limit,
caller,
},
executor,
)
}
/// Grants cheat code access for new contracts if the caller also has
/// cheatcode access or the new contract is created in top most call.
///
/// There may be cheatcodes in the constructor of the new contract, in order to allow them
/// automatically we need to determine the new address.
fn allow_cheatcodes_on_create(&self, ecx: InnerEcx, caller: Address, created_address: Address) {
if ecx.journaled_state.depth <= 1 || ecx.db.has_cheatcode_access(&caller) {
ecx.db.allow_cheatcode_access(created_address);
}
}
/// Called when there was a revert.
///
/// Cleanup any previously applied cheatcodes that altered the state in such a way that revm's
/// revert would run into issues.
pub fn on_revert(&mut self, ecx: Ecx) {
trace!(deals=?self.eth_deals.len(), "rolling back deals");
// Delay revert clean up until expected revert is handled, if set.
if self.expected_revert.is_some() {
return;
}
// we only want to apply cleanup top level
if ecx.journaled_state.depth() > 0 {
return;
}
// Roll back all previously applied deals
// This will prevent overflow issues in revm's [`JournaledState::journal_revert`] routine
// which rolls back any transfers.
while let Some(record) = self.eth_deals.pop() {
if let Some(acc) = ecx.journaled_state.state.get_mut(&record.address) {
acc.info.balance = record.old_balance;
}
}
}
// common create functionality for both legacy and EOF.
fn create_common<Input>(&mut self, ecx: Ecx, mut input: Input) -> Option<CreateOutcome>
where
Input: CommonCreateInput,
{
let ecx = &mut ecx.inner;
let gas = Gas::new(input.gas_limit());
// Apply our prank
if let Some(prank) = &self.prank {
if ecx.journaled_state.depth() >= prank.depth && input.caller() == prank.prank_caller {
// At the target depth we set `msg.sender`
if ecx.journaled_state.depth() == prank.depth {
input.set_caller(prank.new_caller);
}
// At the target depth, or deeper, we set `tx.origin`
if let Some(new_origin) = prank.new_origin {
ecx.env.tx.caller = new_origin;
}
}
}
// Apply our broadcast
if let Some(broadcast) = &self.broadcast {
if ecx.journaled_state.depth() >= broadcast.depth &&
input.caller() == broadcast.original_caller
{
if let Err(err) =
ecx.journaled_state.load_account(broadcast.new_origin, &mut ecx.db)
{
return Some(CreateOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: Error::encode(err),
gas,
},
address: None,
});
}
ecx.env.tx.caller = broadcast.new_origin;
if ecx.journaled_state.depth() == broadcast.depth {
input.set_caller(broadcast.new_origin);
let is_fixed_gas_limit = check_if_fixed_gas_limit(ecx, input.gas_limit());
let account = &ecx.journaled_state.state()[&broadcast.new_origin];
self.broadcastable_transactions.push_back(BroadcastableTransaction {
rpc: ecx.db.active_fork_url(),
transaction: TransactionRequest {
from: Some(broadcast.new_origin),
to: None,
value: Some(input.value()),
input: TransactionInput::new(input.init_code()),
nonce: Some(account.info.nonce),
gas: if is_fixed_gas_limit { Some(input.gas_limit()) } else { None },
..Default::default()
}
.into(),
});
input.log_debug(self, &input.scheme().unwrap_or(CreateScheme::Create));
}
}
}
// Allow cheatcodes from the address of the new contract
let address = input.allow_cheatcodes(self, ecx);
// If `recordAccountAccesses` has been called, record the create
if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
recorded_account_diffs_stack.push(vec![AccountAccess {
chainInfo: crate::Vm::ChainInfo {
forkId: ecx.db.active_fork_id().unwrap_or_default(),
chainId: U256::from(ecx.env.cfg.chain_id),
},
accessor: input.caller(),
account: address,
kind: crate::Vm::AccountAccessKind::Create,
initialized: true,
oldBalance: U256::ZERO, // updated on (eof)create_end
newBalance: U256::ZERO, // updated on (eof)create_end
value: input.value(),
data: input.init_code(),
reverted: false,
deployedCode: Bytes::new(), // updated on (eof)create_end
storageAccesses: vec![], // updated on (eof)create_end
depth: ecx.journaled_state.depth(),
}]);
}
None
}
// common create_end functionality for both legacy and EOF.
fn create_end_common(&mut self, ecx: Ecx, mut outcome: CreateOutcome) -> CreateOutcome
where {
let ecx = &mut ecx.inner;
// Clean up pranks
if let Some(prank) = &self.prank {
if ecx.journaled_state.depth() == prank.depth {
ecx.env.tx.caller = prank.prank_origin;
// Clean single-call prank once we have returned to the original depth
if prank.single_call {
std::mem::take(&mut self.prank);
}
}
}
// Clean up broadcasts
if let Some(broadcast) = &self.broadcast {
if ecx.journaled_state.depth() == broadcast.depth {
ecx.env.tx.caller = broadcast.original_origin;
// Clean single-call broadcast once we have returned to the original depth
if broadcast.single_call {
std::mem::take(&mut self.broadcast);
}
}
}
// Handle expected reverts
if let Some(expected_revert) = &self.expected_revert {
if ecx.journaled_state.depth() <= expected_revert.depth &&
matches!(expected_revert.kind, ExpectedRevertKind::Default)
{
let expected_revert = std::mem::take(&mut self.expected_revert).unwrap();
return match expect::handle_expect_revert(
false,
true,
&expected_revert,
outcome.result.result,
outcome.result.output.clone(),
&self.config.available_artifacts,
) {
Ok((address, retdata)) => {
outcome.result.result = InstructionResult::Return;
outcome.result.output = retdata;
outcome.address = address;
outcome
}
Err(err) => {
outcome.result.result = InstructionResult::Revert;
outcome.result.output = err.abi_encode().into();
outcome
}
};
}
}
// If `startStateDiffRecording` has been called, update the `reverted` status of the
// previous call depth's recorded accesses, if any
if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
// The root call cannot be recorded.
if ecx.journaled_state.depth() > 0 {
let mut last_depth =
recorded_account_diffs_stack.pop().expect("missing CREATE account accesses");
// Update the reverted status of all deeper calls if this call reverted, in
// accordance with EVM behavior
if outcome.result.is_revert() {
last_depth.iter_mut().for_each(|element| {
element.reverted = true;
element
.storageAccesses
.iter_mut()
.for_each(|storage_access| storage_access.reverted = true);
})
}
let create_access = last_depth.first_mut().expect("empty AccountAccesses");
// Assert that we're at the correct depth before recording post-create state
// changes. Depending on what depth the cheat was called at, there
// may not be any pending calls to update if execution has
// percolated up to a higher depth.
if create_access.depth == ecx.journaled_state.depth() {
debug_assert_eq!(
create_access.kind as u8,
crate::Vm::AccountAccessKind::Create as u8
);
if let Some(address) = outcome.address {
if let Ok(created_acc) =
ecx.journaled_state.load_account(address, &mut ecx.db)
{
create_access.newBalance = created_acc.info.balance;
create_access.deployedCode =
created_acc.info.code.clone().unwrap_or_default().original_bytes();
}
}
}
// Merge the last depth's AccountAccesses into the AccountAccesses at the current
// depth, or push them back onto the pending vector if higher depths were not
// recorded. This preserves ordering of accesses.
if let Some(last) = recorded_account_diffs_stack.last_mut() {
last.append(&mut last_depth);
} else {
recorded_account_diffs_stack.push(last_depth);
}
}
}
outcome
}
pub fn call_with_executor(
&mut self,
ecx: Ecx,
call: &mut CallInputs,
executor: &mut impl CheatcodesExecutor,
) -> Option<CallOutcome> {
let gas = Gas::new(call.gas_limit);
// At the root call to test function or script `run()`/`setUp()` functions, we are
// decreasing sender nonce to ensure that it matches on-chain nonce once we start
// broadcasting.
if ecx.journaled_state.depth == 0 {
let sender = ecx.env.tx.caller;
let account = match super::evm::journaled_account(ecx, sender) {
Ok(account) => account,
Err(err) => {
return Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: err.abi_encode().into(),
gas,
},
memory_offset: call.return_memory_offset.clone(),
})
}
};
let prev = account.info.nonce;
account.info.nonce = prev.saturating_sub(1);
trace!(target: "cheatcodes", %sender, nonce=account.info.nonce, prev, "corrected nonce");
}
if call.target_address == CHEATCODE_ADDRESS {
return match self.apply_cheatcode(ecx, call, executor) {
Ok(retdata) => Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Return,
output: retdata.into(),
gas,
},
memory_offset: call.return_memory_offset.clone(),
}),
Err(err) => Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: err.abi_encode().into(),
gas,
},
memory_offset: call.return_memory_offset.clone(),
}),
};
}
let ecx = &mut ecx.inner;
if call.target_address == HARDHAT_CONSOLE_ADDRESS {
return None;
}
// Handle expected calls
// Grab the different calldatas expected.
if let Some(expected_calls_for_target) = self.expected_calls.get_mut(&call.bytecode_address)
{
// Match every partial/full calldata
for (calldata, (expected, actual_count)) in expected_calls_for_target {
// Increment actual times seen if...
// The calldata is at most, as big as this call's input, and
if calldata.len() <= call.input.len() &&
// Both calldata match, taking the length of the assumed smaller one (which will have at least the selector), and
*calldata == call.input[..calldata.len()] &&
// The value matches, if provided
expected
.value
.map_or(true, |value| Some(value) == call.transfer_value()) &&
// The gas matches, if provided
expected.gas.map_or(true, |gas| gas == call.gas_limit) &&
// The minimum gas matches, if provided
expected.min_gas.map_or(true, |min_gas| min_gas <= call.gas_limit)
{
*actual_count += 1;
}
}
}
// Handle mocked calls
if let Some(mocks) = self.mocked_calls.get_mut(&call.bytecode_address) {
let ctx =
MockCallDataContext { calldata: call.input.clone(), value: call.transfer_value() };
if let Some(return_data_queue) = match mocks.get_mut(&ctx) {
Some(queue) => Some(queue),
None => mocks
.iter_mut()
.find(|(mock, _)| {
call.input.get(..mock.calldata.len()) == Some(&mock.calldata[..]) &&
mock.value.map_or(true, |value| Some(value) == call.transfer_value())
})
.map(|(_, v)| v),
} {
if let Some(return_data) = if return_data_queue.len() == 1 {
// If the mocked calls stack has a single element in it, don't empty it
return_data_queue.front().map(|x| x.to_owned())
} else {
// Else, we pop the front element
return_data_queue.pop_front()
} {
return Some(CallOutcome {
result: InterpreterResult {
result: return_data.ret_type,
output: return_data.data,
gas,
},
memory_offset: call.return_memory_offset.clone(),
});
}
}
}
// Apply our prank
if let Some(prank) = &self.prank {
if ecx.journaled_state.depth() >= prank.depth && call.caller == prank.prank_caller {
let mut prank_applied = false;
// At the target depth we set `msg.sender`
if ecx.journaled_state.depth() == prank.depth {
call.caller = prank.new_caller;
prank_applied = true;
}
// At the target depth, or deeper, we set `tx.origin`
if let Some(new_origin) = prank.new_origin {
ecx.env.tx.caller = new_origin;
prank_applied = true;
}
// If prank applied for first time, then update
if prank_applied {
if let Some(applied_prank) = prank.first_time_applied() {
self.prank = Some(applied_prank);
}
}
}
}
// Apply our broadcast
if let Some(broadcast) = &self.broadcast {
// We only apply a broadcast *to a specific depth*.
//
// We do this because any subsequent contract calls *must* exist on chain and
// we only want to grab *this* call, not internal ones
if ecx.journaled_state.depth() == broadcast.depth &&
call.caller == broadcast.original_caller
{
// At the target depth we set `msg.sender` & tx.origin.
// We are simulating the caller as being an EOA, so *both* must be set to the
// broadcast.origin.
ecx.env.tx.caller = broadcast.new_origin;
call.caller = broadcast.new_origin;
// Add a `legacy` transaction to the VecDeque. We use a legacy transaction here
// because we only need the from, to, value, and data. We can later change this
// into 1559, in the cli package, relatively easily once we
// know the target chain supports EIP-1559.
if !call.is_static {
if let Err(err) = ecx.load_account(broadcast.new_origin) {
return Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: Error::encode(err),
gas,
},
memory_offset: call.return_memory_offset.clone(),
});
}
let is_fixed_gas_limit = check_if_fixed_gas_limit(ecx, call.gas_limit);