forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinspector.rs
1691 lines (1542 loc) · 76.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, 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_continue {
($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()
}
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, _: &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;
}
}
fn step(&mut self, interpreter: &mut Interpreter, ecx: &mut EvmContext<DB>) {
let ecx = &mut ecx.inner;
self.pc = interpreter.program_counter();
// reset gas if gas metering is turned off
match self.gas_metering {
Some(None) => {
// need to store gas metering
self.gas_metering = Some(Some(interpreter.gas));
}
Some(Some(gas)) => {
match interpreter.current_opcode() {
opcode::CREATE | opcode::CREATE2 => {
// set we're about to enter CREATE frame to meter its gas on first opcode
// inside it
self.gas_metering_create = Some(None)
}
opcode::STOP | opcode::RETURN | opcode::SELFDESTRUCT | opcode::REVERT => {
// If we are ending current execution frame, we want to just fully reset gas
// otherwise weird things with returning gas from a call happen
// ref: https://github.com/bluealloy/revm/blob/2cb991091d32330cfe085320891737186947ce5a/crates/revm/src/evm_impl.rs#L190
//
// It would be nice if we had access to the interpreter in `call_end`, as we
// could just do this there instead.
match self.gas_metering_create {
None | Some(None) => {
interpreter.gas = Gas::new(0);
}
Some(Some(gas)) => {
// If this was CREATE frame, set correct gas limit. This is needed
// because CREATE opcodes deduct additional gas for code storage,
// and deducted amount is compared to gas limit. If we set this to
// 0, the CREATE would fail with out of gas.
//
// If we however set gas limit to the limit of outer frame, it would
// cause a panic after erasing gas cost post-create. Reason for this
// is pre-create REVM records `gas_limit - (gas_limit / 64)` as gas
// used, and erases costs by `remaining` gas post-create.
// gas used ref: https://github.com/bluealloy/revm/blob/2cb991091d32330cfe085320891737186947ce5a/crates/revm/src/instructions/host.rs#L254-L258
// post-create erase ref: https://github.com/bluealloy/revm/blob/2cb991091d32330cfe085320891737186947ce5a/crates/revm/src/instructions/host.rs#L279
interpreter.gas = Gas::new(gas.limit());
// reset CREATE gas metering because we're about to exit its frame
self.gas_metering_create = None
}
}
}
_ => {
// if just starting with CREATE opcodes, record its inner frame gas
if let Some(None) = self.gas_metering_create {
self.gas_metering_create = Some(Some(interpreter.gas))
}
// dont monitor gas changes, keep it constant
interpreter.gas = gas;
}
}
}
_ => {}
}
// Record writes and reads if `record` has been called
if let Some(storage_accesses) = &mut self.accesses {
match interpreter.current_opcode() {
opcode::SLOAD => {
let key = try_or_continue!(interpreter.stack().peek(0));
storage_accesses
.reads
.entry(interpreter.contract().target_address)
.or_default()
.push(key);
}
opcode::SSTORE => {
let key = try_or_continue!(interpreter.stack().peek(0));
// An SSTORE does an SLOAD internally
storage_accesses
.reads
.entry(interpreter.contract().target_address)
.or_default()
.push(key);
storage_accesses
.writes
.entry(interpreter.contract().target_address)
.or_default()
.push(key);
}
_ => (),
}
}
// Record account access via SELFDESTRUCT if `recordAccountAccesses` has been called
if let Some(account_accesses) = &mut self.recorded_account_diffs_stack {
if interpreter.current_opcode() == opcode::SELFDESTRUCT {
let target = try_or_continue!(interpreter.stack().peek(0));
// load balance of this account
let value = ecx
.balance(interpreter.contract().target_address)
.map(|(b, _)| b)
.unwrap_or(U256::ZERO);
let account = Address::from_word(B256::from(target));
// get previous balance and initialized status of the target account
// TODO: use load_account_exists
let (initialized, old_balance) = if let Ok((account, _)) =
ecx.journaled_state.load_account(account, &mut ecx.db)
{
(account.info.exists(), account.info.balance)
} else {
(false, U256::ZERO)
};
// register access for the target account
let access = crate::Vm::AccountAccess {
chainInfo: crate::Vm::ChainInfo {
forkId: ecx.db.active_fork_id().unwrap_or_default(),
chainId: U256::from(ecx.env.cfg.chain_id),
},
accessor: interpreter.contract().target_address,
account,
kind: crate::Vm::AccountAccessKind::SelfDestruct,
initialized,
oldBalance: old_balance,
newBalance: old_balance + value,
value,
data: Bytes::new(),
reverted: false,
deployedCode: Bytes::new(),
storageAccesses: vec![],
depth: ecx.journaled_state.depth(),
};
// Ensure that we're not selfdestructing a context recording was initiated on
if let Some(last) = account_accesses.last_mut() {
last.push(access);
}
}
}
// Record granular ordered storage accesses if `startStateDiffRecording` has been called
if let Some(recorded_account_diffs_stack) = &mut self.recorded_account_diffs_stack {
match interpreter.current_opcode() {
opcode::SLOAD => {
let key = try_or_continue!(interpreter.stack().peek(0));
let address = interpreter.contract().target_address;
// Try to include present value for informational purposes, otherwise assume
// it's not set (zero value)
let mut present_value = U256::ZERO;
// Try to load the account and the slot's present value
if ecx.load_account(address).is_ok() {
if let Ok((previous, _)) = ecx.sload(address, key) {
present_value = previous;
}
}
let access = crate::Vm::StorageAccess {
account: interpreter.contract().target_address,
slot: key.into(),
isWrite: false,
previousValue: present_value.into(),
newValue: present_value.into(),
reverted: false,
};
append_storage_access(
recorded_account_diffs_stack,
access,
ecx.journaled_state.depth(),
);
}
opcode::SSTORE => {
let key = try_or_continue!(interpreter.stack().peek(0));
let value = try_or_continue!(interpreter.stack().peek(1));
let address = interpreter.contract().target_address;
// Try to load the account and the slot's previous value, otherwise, assume it's
// not set (zero value)
let mut previous_value = U256::ZERO;
if ecx.load_account(address).is_ok() {
if let Ok((previous, _)) = ecx.sload(address, key) {
previous_value = previous;
}
}
let access = crate::Vm::StorageAccess {
account: address,
slot: key.into(),
isWrite: true,
previousValue: previous_value.into(),
newValue: value.into(),
reverted: false,
};
append_storage_access(
recorded_account_diffs_stack,
access,
ecx.journaled_state.depth(),
);
}
// Record account accesses via the EXT family of opcodes
opcode::EXTCODECOPY |
opcode::EXTCODESIZE |
opcode::EXTCODEHASH |
opcode::BALANCE => {
let kind = match interpreter.current_opcode() {
opcode::EXTCODECOPY => crate::Vm::AccountAccessKind::Extcodecopy,
opcode::EXTCODESIZE => crate::Vm::AccountAccessKind::Extcodesize,
opcode::EXTCODEHASH => crate::Vm::AccountAccessKind::Extcodehash,
opcode::BALANCE => crate::Vm::AccountAccessKind::Balance,
_ => unreachable!(),
};
let address = Address::from_word(B256::from(try_or_continue!(interpreter
.stack()
.peek(0))));
let balance;
let initialized;
// TODO: use ecx.load_account
if let Ok((acc, _)) = ecx.journaled_state.load_account(address, &mut ecx.db) {
initialized = acc.info.exists();
balance = acc.info.balance;
} else {
initialized = false;
balance = U256::ZERO;
}
let account_access = crate::Vm::AccountAccess {
chainInfo: crate::Vm::ChainInfo {
forkId: ecx.db.active_fork_id().unwrap_or_default(),
chainId: U256::from(ecx.env.cfg.chain_id),
},
accessor: interpreter.contract().target_address,
account: address,
kind,
initialized,
oldBalance: balance,
newBalance: balance,
value: U256::ZERO,
data: Bytes::new(),
reverted: false,
deployedCode: Bytes::new(),
storageAccesses: vec![],
depth: ecx.journaled_state.depth(),
};
// Record the EXT* call as an account access at the current depth
// (future storage accesses will be recorded in a new "Resume" context)
if let Some(last) = recorded_account_diffs_stack.last_mut() {
last.push(account_access);
} else {
recorded_account_diffs_stack.push(vec![account_access]);
}
}
_ => (),
}
}
// If the allowed memory writes cheatcode is active at this context depth, check to see
// if the current opcode can either mutate directly or expand memory. If the opcode at
// the current program counter is a match, check if the modified memory lies within the
// allowed ranges. If not, revert and fail the test.
if let Some(ranges) = self.allowed_mem_writes.get(&ecx.journaled_state.depth()) {
// The `mem_opcode_match` macro is used to match the current opcode against a list of
// opcodes that can mutate memory (either directly or expansion via reading). If the
// opcode is a match, the memory offsets that are being written to are checked to be
// within the allowed ranges. If not, the test is failed and the transaction is
// reverted. For all opcodes that can mutate memory aside from MSTORE,
// MSTORE8, and MLOAD, the size and destination offset are on the stack, and
// the macro expands all of these cases. For MSTORE, MSTORE8, and MLOAD, the
// size of the memory write is implicit, so these cases are hard-coded.
macro_rules! mem_opcode_match {
($(($opcode:ident, $offset_depth:expr, $size_depth:expr, $writes:expr)),* $(,)?) => {
match interpreter.current_opcode() {
////////////////////////////////////////////////////////////////
// OPERATIONS THAT CAN EXPAND/MUTATE MEMORY BY WRITING //
////////////////////////////////////////////////////////////////
opcode::MSTORE => {
// The offset of the mstore operation is at the top of the stack.
let offset = try_or_continue!(interpreter.stack().peek(0)).saturating_to::<u64>();
// If none of the allowed ranges contain [offset, offset + 32), memory has been
// unexpectedly mutated.
if !ranges.iter().any(|range| {
range.contains(&offset) && range.contains(&(offset + 31))
}) {
// SPECIAL CASE: When the compiler attempts to store the selector for
// `stopExpectSafeMemory`, this is allowed. It will do so at the current free memory
// pointer, which could have been updated to the exclusive upper bound during
// execution.
let value = try_or_continue!(interpreter.stack().peek(1)).to_be_bytes::<32>();
let selector = stopExpectSafeMemoryCall {}.cheatcode().func.selector_bytes;
if value[0..SELECTOR_LEN] == selector {
return
}
disallowed_mem_write(offset, 32, interpreter, ranges);
return
}
}
opcode::MSTORE8 => {
// The offset of the mstore8 operation is at the top of the stack.
let offset = try_or_continue!(interpreter.stack().peek(0)).saturating_to::<u64>();
// If none of the allowed ranges contain the offset, memory has been
// unexpectedly mutated.
if !ranges.iter().any(|range| range.contains(&offset)) {
disallowed_mem_write(offset, 1, interpreter, ranges);
return
}
}
////////////////////////////////////////////////////////////////
// OPERATIONS THAT CAN EXPAND MEMORY BY READING //
////////////////////////////////////////////////////////////////
opcode::MLOAD => {
// The offset of the mload operation is at the top of the stack
let offset = try_or_continue!(interpreter.stack().peek(0)).saturating_to::<u64>();
// If the offset being loaded is >= than the memory size, the
// memory is being expanded. If none of the allowed ranges contain
// [offset, offset + 32), memory has been unexpectedly mutated.
if offset >= interpreter.shared_memory.len() as u64 && !ranges.iter().any(|range| {
range.contains(&offset) && range.contains(&(offset + 31))
}) {
disallowed_mem_write(offset, 32, interpreter, ranges);
return
}
}
////////////////////////////////////////////////////////////////
// OPERATIONS WITH OFFSET AND SIZE ON STACK //
////////////////////////////////////////////////////////////////
opcode::CALL => {
// The destination offset of the operation is the fifth element on the stack.
let dest_offset = try_or_continue!(interpreter.stack().peek(5)).saturating_to::<u64>();
// The size of the data that will be copied is the sixth element on the stack.
let size = try_or_continue!(interpreter.stack().peek(6)).saturating_to::<u64>();
// If none of the allowed ranges contain [dest_offset, dest_offset + size),
// memory outside of the expected ranges has been touched. If the opcode
// only reads from memory, this is okay as long as the memory is not expanded.
let fail_cond = !ranges.iter().any(|range| {
range.contains(&dest_offset) &&
range.contains(&(dest_offset + size.saturating_sub(1)))
});
// If the failure condition is met, set the output buffer to a revert string
// that gives information about the allowed ranges and revert.
if fail_cond {
// SPECIAL CASE: When a call to `stopExpectSafeMemory` is performed, this is allowed.
// It allocated calldata at the current free memory pointer, and will attempt to read
// from this memory region to perform the call.
let to = Address::from_word(try_or_continue!(interpreter.stack().peek(1)).to_be_bytes::<32>().into());
if to == CHEATCODE_ADDRESS {
let args_offset = try_or_continue!(interpreter.stack().peek(3)).saturating_to::<usize>();
let args_size = try_or_continue!(interpreter.stack().peek(4)).saturating_to::<usize>();
let selector = stopExpectSafeMemoryCall {}.cheatcode().func.selector_bytes;
let memory_word = interpreter.shared_memory.slice(args_offset, args_size);
if memory_word[0..SELECTOR_LEN] == selector {
return
}
}
disallowed_mem_write(dest_offset, size, interpreter, ranges);
return
}
}
$(opcode::$opcode => {
// The destination offset of the operation.
let dest_offset = try_or_continue!(interpreter.stack().peek($offset_depth)).saturating_to::<u64>();
// The size of the data that will be copied.
let size = try_or_continue!(interpreter.stack().peek($size_depth)).saturating_to::<u64>();
// If none of the allowed ranges contain [dest_offset, dest_offset + size),
// memory outside of the expected ranges has been touched. If the opcode
// only reads from memory, this is okay as long as the memory is not expanded.
let fail_cond = !ranges.iter().any(|range| {
range.contains(&dest_offset) &&
range.contains(&(dest_offset + size.saturating_sub(1)))
}) && ($writes ||
[dest_offset, (dest_offset + size).saturating_sub(1)].into_iter().any(|offset| {
offset >= interpreter.shared_memory.len() as u64
})
);
// If the failure condition is met, set the output buffer to a revert string
// that gives information about the allowed ranges and revert.
if fail_cond {
disallowed_mem_write(dest_offset, size, interpreter, ranges);
return
}
})*
_ => ()
}
}
}
// Check if the current opcode can write to memory, and if so, check if the memory
// being written to is registered as safe to modify.
mem_opcode_match!(
(CALLDATACOPY, 0, 2, true),
(CODECOPY, 0, 2, true),
(RETURNDATACOPY, 0, 2, true),
(EXTCODECOPY, 1, 3, true),
(CALLCODE, 5, 6, true),
(STATICCALL, 4, 5, true),
(DELEGATECALL, 4, 5, true),
(KECCAK256, 0, 1, false),
(LOG0, 0, 1, false),
(LOG1, 0, 1, false),
(LOG2, 0, 1, false),
(LOG3, 0, 1, false),
(LOG4, 0, 1, false),
(CREATE, 1, 2, false),
(CREATE2, 1, 2, false),
(RETURN, 0, 1, false),
(REVERT, 0, 1, false),
)
}
// Record writes with sstore (and sha3) if `StartMappingRecording` has been called
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);
}
// Stores this log if `recordLogs` has been called
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.target_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(),
})