forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspector.rs
1693 lines (1532 loc) · 74.8 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, RecordAccess,
},
script::{Broadcast, ScriptWallets},
test::expect::{
self, ExpectedCallData, ExpectedCallTracker, ExpectedCallType, ExpectedEmit,
ExpectedRevert, ExpectedRevertKind,
},
CheatsConfig, CheatsCtxt, DynCheatcode, Error, Result, Vm,
Vm::AccountAccess,
};
use alloy_primitives::{Address, Bytes, Log, TxKind, B256, U256};
use alloy_rpc_types::request::{TransactionInput, TransactionRequest};
use alloy_sol_types::{SolInterface, SolValue};
use foundry_common::{evm::Breakpoints, SELECTOR_LEN};
use foundry_config::Config;
use foundry_evm_core::{
abi::Vm::stopExpectSafeMemoryCall,
backend::{DatabaseExt, RevertDiagnostic},
constants::{CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS},
InspectorExt,
};
use itertools::Itertools;
use revm::{
interpreter::{
opcode, CallInputs, CallOutcome, CallScheme, CreateInputs, CreateOutcome, Gas,
InstructionResult, Interpreter, InterpreterAction, InterpreterResult,
},
primitives::{BlockEnv, CreateScheme, TransactTo},
EvmContext, InnerEvmContext, Inspector,
};
use rustc_hash::FxHashMap;
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap, VecDeque},
fs::File,
io::BufReader,
ops::Range,
path::PathBuf,
sync::Arc,
};
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, Default)]
pub struct BroadcastableTransaction {
/// The optional RPC URL.
pub rpc: Option<String>,
/// The transaction to broadcast.
pub transaction: TransactionRequest,
}
/// 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: HashMap<Address, String>,
/// Prank information
pub prank: Option<Prank>,
/// Expected revert information
pub expected_revert: Option<ExpectedRevert>,
/// 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>>>,
/// Recorded logs
pub recorded_logs: Option<Vec<crate::Vm::Log>>,
/// 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>,
/// Mocked calls
// **Note**: inner must a BTreeMap because of special `Ord` impl for `MockCallDataContext`
pub mocked_calls: HashMap<Address, BTreeMap<MockCallDataContext, MockCallReturnData>>,
/// 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: FxHashMap<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>,
/// Holds the stored gas info for when we pause gas metering. It is an `Option<Option<..>>`
/// because the `call` callback in an `Inspector` doesn't get access to
/// the `revm::Interpreter` which holds the `revm::Gas` struct that
/// we need to copy. So we convert it to a `Some(None)` in `apply_cheatcode`, and once we have
/// the interpreter, we copy the gas struct. Then each time there is an execution of an
/// operation, we reset the gas.
pub gas_metering: Option<Option<Gas>>,
/// Holds stored gas info for when we pause gas metering, and we're entering/inside
/// CREATE / CREATE2 frames. This is needed to make gas meter pausing work correctly when
/// paused and creating new contracts.
pub gas_metering_create: Option<Option<Gas>>,
/// Mapping slots.
pub mapping_slots: Option<HashMap<Address, MappingSlots>>,
/// The current program counter.
pub pc: usize,
/// Breakpoints supplied by the `breakpoint` cheatcode.
/// `char -> (address, pc)`
pub breakpoints: Breakpoints,
}
// 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(),
fork_revert_diagnostic: Default::default(),
accesses: Default::default(),
recorded_account_diffs_stack: Default::default(),
recorded_logs: Default::default(),
last_call_gas: Default::default(),
mocked_calls: 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_metering_create: Default::default(),
mapping_slots: Default::default(),
pc: Default::default(),
breakpoints: Default::default(),
}
}
/// Returns the configured script wallets.
pub fn script_wallets(&self) -> Option<&ScriptWallets> {
self.config.script_wallets.as_ref()
}
/// Decodes the input data and applies the cheatcode.
fn apply_cheatcode<DB: DatabaseExt>(
&mut self,
ecx: &mut EvmContext<DB>,
call: &CallInputs,
) -> 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,
caller,
},
)
}
/// Determines the address of the contract and marks it as allowed.
///
/// Returns the address of the contract created.
///
/// 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<DB: DatabaseExt>(
&self,
ecx: &mut InnerEvmContext<DB>,
inputs: &CreateInputs,
) -> Address {
let old_nonce = ecx
.journaled_state
.state
.get(&inputs.caller)
.map(|acc| acc.info.nonce)
.unwrap_or_default();
let created_address = inputs.created_address(old_nonce);
if ecx.journaled_state.depth > 1 && !ecx.db.has_cheatcode_access(&inputs.caller) {
// we only grant cheat code access for new contracts if the caller also has
// cheatcode access and the new contract is created in top most call
return created_address;
}
ecx.db.allow_cheatcode_access(created_address);
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<DB: DatabaseExt>(&mut self, ecx: &mut EvmContext<DB>) {
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;
}
}
}
}
impl<DB: DatabaseExt> Inspector<DB> for Cheatcodes {
#[inline]
fn initialize_interp(&mut self, _interpreter: &mut Interpreter, ecx: &mut EvmContext<DB>) {
// When the first interpreter is initialized we've circumvented the balance and gas checks,
// so we apply our actual block data with the correct fees and all.
if let Some(block) = self.block.take() {
ecx.env.block = block;
}
if let Some(gas_price) = self.gas_price.take() {
ecx.env.tx.gas_price = gas_price;
}
}
#[inline]
fn step(&mut self, interpreter: &mut Interpreter, ecx: &mut EvmContext<DB>) {
self.pc = interpreter.program_counter();
// `pauseGasMetering`: reset interpreter gas.
if self.gas_metering.is_some() {
self.meter_gas(interpreter);
}
// `record`: record storage reads and writes.
if self.accesses.is_some() {
self.record_accesses(interpreter);
}
// `startStateDiffRecording`: record granular ordered storage accesses.
if self.recorded_account_diffs_stack.is_some() {
self.record_state_diffs(interpreter, ecx);
}
// `expectSafeMemory`: check if the current opcode is allowed to interact with memory.
if !self.allowed_mem_writes.is_empty() {
self.check_mem_opcodes(interpreter, ecx.journaled_state.depth());
}
// `startMappingRecording`: record SSTORE and KECCAK256.
if let Some(mapping_slots) = &mut self.mapping_slots {
mapping::step(mapping_slots, interpreter);
}
}
fn log(&mut self, _context: &mut EvmContext<DB>, log: &Log) {
if !self.expected_emits.is_empty() {
expect::handle_expect_emit(self, log);
}
// `recordLogs`
if let Some(storage_recorded_logs) = &mut self.recorded_logs {
storage_recorded_logs.push(Vm::Log {
topics: log.data.topics().to_vec(),
data: log.data.data.clone(),
emitter: log.address,
});
}
}
fn call(&mut self, ecx: &mut EvmContext<DB>, call: &mut CallInputs) -> 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;
if sender != Config::DEFAULT_SENDER {
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);
debug!(target: "cheatcodes", %sender, nonce=account.info.nonce, prev, "corrected nonce");
}
}
if call.target_address == CHEATCODE_ADDRESS {
return match self.apply_cheatcode(ecx, call) {
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(&call.bytecode_address) {
let ctx =
MockCallDataContext { calldata: call.input.clone(), value: call.transfer_value() };
if let Some(return_data) = mocks.get(&ctx).or_else(|| {
mocks
.iter()
.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)
}) {
return Some(CallOutcome {
result: InterpreterResult {
result: return_data.ret_type,
output: return_data.data.clone(),
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);
let account =
ecx.journaled_state.state().get_mut(&broadcast.new_origin).unwrap();
self.broadcastable_transactions.push_back(BroadcastableTransaction {
rpc: ecx.db.active_fork_url(),
transaction: TransactionRequest {
from: Some(broadcast.new_origin),
to: Some(TxKind::from(Some(call.target_address))),
value: call.transfer_value(),
input: TransactionInput::new(call.input.clone()),
nonce: Some(account.info.nonce),
gas: if is_fixed_gas_limit {
Some(call.gas_limit as u128)
} else {
None
},
..Default::default()
},
});
debug!(target: "cheatcodes", tx=?self.broadcastable_transactions.back().unwrap(), "broadcastable call");
let prev = account.info.nonce;
// Touch account to ensure that incremented nonce is committed
account.mark_touch();
account.info.nonce += 1;
debug!(target: "cheatcodes", address=%broadcast.new_origin, nonce=prev+1, prev, "incremented nonce");
} else if broadcast.single_call {
let msg = "`staticcall`s are not allowed after `broadcast`; use `startBroadcast` instead";
return Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: Error::encode(msg),
gas,
},
memory_offset: call.return_memory_offset.clone(),
})
}
}
}
// Record called accounts if `startStateDiffRecording` has been called
if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
// Determine if account is "initialized," ie, it has a non-zero balance, a non-zero
// nonce, a non-zero KECCAK_EMPTY codehash, or non-empty code
let initialized;
let old_balance;
if let Ok((acc, _)) = ecx.load_account(call.target_address) {
initialized = acc.info.exists();
old_balance = acc.info.balance;
} else {
initialized = false;
old_balance = U256::ZERO;
}
let kind = match call.scheme {
CallScheme::Call => crate::Vm::AccountAccessKind::Call,
CallScheme::CallCode => crate::Vm::AccountAccessKind::CallCode,
CallScheme::DelegateCall => crate::Vm::AccountAccessKind::DelegateCall,
CallScheme::StaticCall => crate::Vm::AccountAccessKind::StaticCall,
};
// Record this call by pushing it to a new pending vector; all subsequent calls at
// that depth will be pushed to the same vector. When the call ends, the
// RecordedAccountAccess (and all subsequent RecordedAccountAccesses) will be
// updated with the revert status of this call, since the EVM does not mark accounts
// as "warm" if the call from which they were accessed is reverted
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: call.caller,
account: call.bytecode_address,
kind,
initialized,
oldBalance: old_balance,
newBalance: U256::ZERO, // updated on call_end
value: call.call_value(),
data: call.input.clone(),
reverted: false,
deployedCode: Bytes::new(),
storageAccesses: vec![], // updated on step
depth: ecx.journaled_state.depth(),
}]);
}
None
}
fn call_end(
&mut self,
ecx: &mut EvmContext<DB>,
call: &CallInputs,
mut outcome: CallOutcome,
) -> CallOutcome {
let ecx = &mut ecx.inner;
let cheatcode_call = call.target_address == CHEATCODE_ADDRESS ||
call.target_address == HARDHAT_CONSOLE_ADDRESS;
// Clean up pranks/broadcasts if it's not a cheatcode call end. We shouldn't do
// it for cheatcode calls because they are not appplied for cheatcodes in the `call` hook.
// This should be placed before the revert handling, because we might exit early there
if !cheatcode_call {
// 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 {
let _ = self.prank.take();
}
}
}
// Clean up broadcast
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 {
let _ = self.broadcast.take();
}
}
}
}
// Handle expected reverts
if let Some(expected_revert) = &self.expected_revert {
if ecx.journaled_state.depth() <= expected_revert.depth {
let needs_processing: bool = match expected_revert.kind {
ExpectedRevertKind::Default => !cheatcode_call,
// `pending_processing` == true means that we're in the `call_end` hook for
// `vm.expectCheatcodeRevert` and shouldn't expect revert here
ExpectedRevertKind::Cheatcode { pending_processing } => {
cheatcode_call && !pending_processing
}
};
if needs_processing {
let expected_revert = std::mem::take(&mut self.expected_revert).unwrap();
return match expect::handle_expect_revert(
false,
expected_revert.reason.as_deref(),
outcome.result.result,
outcome.result.output.clone(),
) {
Err(error) => {
trace!(expected=?expected_revert, ?error, status=?outcome.result.result, "Expected revert mismatch");
outcome.result.result = InstructionResult::Revert;
outcome.result.output = error.abi_encode().into();
outcome
}
Ok((_, retdata)) => {
outcome.result.result = InstructionResult::Return;
outcome.result.output = retdata;
outcome
}
};
}
// Flip `pending_processing` flag for cheatcode revert expectations, marking that
// we've exited the `expectCheatcodeRevert` call scope
if let ExpectedRevertKind::Cheatcode { pending_processing } =
&mut self.expected_revert.as_mut().unwrap().kind
{
if *pending_processing {
*pending_processing = false;
}
}
}
}
// Exit early for calls to cheatcodes as other logic is not relevant for cheatcode
// invocations
if cheatcode_call {
return outcome
}
// Record the gas usage of the call, this allows the `lastCallGas` cheatcode to
// retrieve the gas usage of the last call.
let gas = outcome.result.gas;
self.last_call_gas = Some(crate::Vm::Gas {
gasLimit: gas.limit(),
gasTotalUsed: gas.spent(),
gasMemoryUsed: 0,
gasRefunded: gas.refunded(),
gasRemaining: gas.remaining(),
});
// 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_recorded_depth =
recorded_account_diffs_stack.pop().expect("missing CALL 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_recorded_depth.iter_mut().for_each(|element| {
element.reverted = true;
element
.storageAccesses
.iter_mut()
.for_each(|storage_access| storage_access.reverted = true);
})
}
let call_access = last_recorded_depth.first_mut().expect("empty AccountAccesses");
// Assert that we're at the correct depth before recording post-call state changes.
// Depending on the 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 call_access.depth == ecx.journaled_state.depth() {
if let Ok((acc, _)) = ecx.load_account(call.target_address) {
debug_assert!(access_is_call(call_access.kind));
call_access.newBalance = acc.info.balance;
}
}
// 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_recorded_depth);
} else {
recorded_account_diffs_stack.push(last_recorded_depth);
}
}
}
// At the end of the call,
// we need to check if we've found all the emits.
// We know we've found all the expected emits in the right order
// if the queue is fully matched.
// If it's not fully matched, then either:
// 1. Not enough events were emitted (we'll know this because the amount of times we
// inspected events will be less than the size of the queue) 2. The wrong events
// were emitted (The inspected events should match the size of the queue, but still some
// events will not be matched)
// First, check that we're at the call depth where the emits were declared from.
let should_check_emits = self
.expected_emits
.iter()
.any(|expected| expected.depth == ecx.journaled_state.depth()) &&
// Ignore staticcalls
!call.is_static;
if should_check_emits {
// Not all emits were matched.
if self.expected_emits.iter().any(|expected| !expected.found) {
outcome.result.result = InstructionResult::Revert;
outcome.result.output = "log != expected log".abi_encode().into();
return outcome
} else {
// All emits were found, we're good.
// Clear the queue, as we expect the user to declare more events for the next call
// if they wanna match further events.
self.expected_emits.clear()
}
}
// this will ensure we don't have false positives when trying to diagnose reverts in fork
// mode
let diag = self.fork_revert_diagnostic.take();
// if there's a revert and a previous call was diagnosed as fork related revert then we can
// return a better error here
if outcome.result.is_revert() {
if let Some(err) = diag {
outcome.result.output = Error::encode(err.to_error_msg(&self.labels));
return outcome
}
}
// try to diagnose reverts in multi-fork mode where a call is made to an address that does
// not exist
if let TransactTo::Call(test_contract) = ecx.env.tx.transact_to {
// if a call to a different contract than the original test contract returned with
// `Stop` we check if the contract actually exists on the active fork
if ecx.db.is_forked_mode() &&
outcome.result.result == InstructionResult::Stop &&
call.target_address != test_contract
{
self.fork_revert_diagnostic =
ecx.db.diagnose_revert(call.target_address, &ecx.journaled_state);
}
}
// If the depth is 0, then this is the root call terminating
if ecx.journaled_state.depth() == 0 {
// If we already have a revert, we shouldn't run the below logic as it can obfuscate an
// earlier error that happened first with unrelated information about
// another error when using cheatcodes.
if outcome.result.is_revert() {
return outcome;
}
// If there's not a revert, we can continue on to run the last logic for expect*
// cheatcodes. Match expected calls
for (address, calldatas) in &self.expected_calls {
// Loop over each address, and for each address, loop over each calldata it expects.
for (calldata, (expected, actual_count)) in calldatas {
// Grab the values we expect to see
let ExpectedCallData { gas, min_gas, value, count, call_type } = expected;
let failed = match call_type {
// If the cheatcode was called with a `count` argument,
// we must check that the EVM performed a CALL with this calldata exactly
// `count` times.
ExpectedCallType::Count => *count != *actual_count,
// If the cheatcode was called without a `count` argument,
// we must check that the EVM performed a CALL with this calldata at least
// `count` times. The amount of times to check was
// the amount of time the cheatcode was called.
ExpectedCallType::NonCount => *count > *actual_count,
};
if failed {
let expected_values = [
Some(format!("data {}", hex::encode_prefixed(calldata))),
value.as_ref().map(|v| format!("value {v}")),
gas.map(|g| format!("gas {g}")),
min_gas.map(|g| format!("minimum gas {g}")),
]
.into_iter()
.flatten()
.join(", ");
let but = if outcome.result.is_ok() {
let s = if *actual_count == 1 { "" } else { "s" };
format!("was called {actual_count} time{s}")
} else {
"the call reverted instead; \
ensure you're testing the happy path when using `expectCall`"
.to_string()
};
let s = if *count == 1 { "" } else { "s" };
let msg = format!(
"expected call to {address} with {expected_values} \
to be called {count} time{s}, but {but}"
);
outcome.result.result = InstructionResult::Revert;
outcome.result.output = Error::encode(msg);
return outcome;
}
}
}
// Check if we have any leftover expected emits
// First, if any emits were found at the root call, then we its ok and we remove them.
self.expected_emits.retain(|expected| !expected.found);
// If not empty, we got mismatched emits
if !self.expected_emits.is_empty() {
let msg = if outcome.result.is_ok() {
"expected an emit, but no logs were emitted afterwards. \
you might have mismatched events or not enough events were emitted"
} else {
"expected an emit, but the call reverted instead. \
ensure you're testing the happy path when using `expectEmit`"
};
outcome.result.result = InstructionResult::Revert;
outcome.result.output = Error::encode(msg);
return outcome;
}
}
outcome
}
fn create(
&mut self,
ecx: &mut EvmContext<DB>,
call: &mut CreateInputs,
) -> Option<CreateOutcome> {
let ecx = &mut ecx.inner;
let gas = Gas::new(call.gas_limit);
// Apply our prank
if let Some(prank) = &self.prank {
if ecx.journaled_state.depth() >= prank.depth && call.caller == prank.prank_caller {
// At the target depth we set `msg.sender`
if ecx.journaled_state.depth() == prank.depth {
call.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 &&
call.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 {
call.caller = broadcast.new_origin;
let is_fixed_gas_limit = check_if_fixed_gas_limit(ecx, call.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(call.value),
input: TransactionInput::new(call.init_code.clone()),
nonce: Some(account.info.nonce),
gas: if is_fixed_gas_limit {
Some(call.gas_limit as u128)
} else {