-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
mod.rs
1821 lines (1604 loc) · 67.2 KB
/
mod.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
//! Foundry's main executor backend abstraction and implementation.
use crate::{
abi::CHEATCODE_ADDRESS,
executor::{
backend::snapshot::BackendSnapshot,
fork::{CreateFork, ForkId, MultiFork, SharedBackend},
inspector::{cheatcodes::Cheatcodes, DEFAULT_CREATE2_DEPLOYER},
snapshot::Snapshots,
},
utils::{b256_to_h256, h160_to_b160, h256_to_b256, ru256_to_u256, u256_to_ru256, u64_to_ru64},
CALLER, TEST_CONTRACT_ADDRESS,
};
use alloy_primitives::{U256, U64};
use ethers::{
prelude::Block,
types::{BlockNumber, Transaction},
utils::keccak256,
};
pub use in_memory_db::MemDb;
use revm::{
db::{CacheDB, DatabaseRef},
precompile::{Precompiles, SpecId},
primitives::{
Account, AccountInfo, Address, Bytecode, CreateScheme, Env, HashMap as Map, Log,
ResultAndState, TransactTo, B256, KECCAK_EMPTY,
},
Database, DatabaseCommit, Inspector, JournaledState, EVM,
};
use std::{
collections::{HashMap, HashSet},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
mod fuzz;
pub mod snapshot;
pub use fuzz::FuzzBackendWrapper;
mod diagnostic;
pub use diagnostic::RevertDiagnostic;
pub mod error;
use crate::executor::{
backend::{error::NoCheatcodeAccessError, in_memory_db::FoundryEvmInMemoryDB},
inspector::cheatcodes::util::configure_tx_env,
};
pub use error::{DatabaseError, DatabaseResult};
mod in_memory_db;
// A `revm::Database` that is used in forking mode
type ForkDB = CacheDB<SharedBackend>;
/// Represents a numeric `ForkId` valid only for the existence of the `Backend`.
/// The difference between `ForkId` and `LocalForkId` is that `ForkId` tracks pairs of `endpoint +
/// block` which can be reused by multiple tests, whereas the `LocalForkId` is unique within a test
pub type LocalForkId = U256;
/// Represents the index of a fork in the created forks vector
/// This is used for fast lookup
type ForkLookupIndex = usize;
/// All accounts that will have persistent storage across fork swaps. See also [`clone_data()`]
const DEFAULT_PERSISTENT_ACCOUNTS: [Address; 3] =
[CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, CALLER];
/// Slot corresponding to "failed" in bytes on the cheatcodes (HEVM) address.
/// Not prefixed with 0x.
const GLOBAL_FAILURE_SLOT: &str =
"6661696c65640000000000000000000000000000000000000000000000000000";
/// An extension trait that allows us to easily extend the `revm::Inspector` capabilities
#[auto_impl::auto_impl(&mut, Box)]
pub trait DatabaseExt: Database<Error = DatabaseError> {
/// Creates a new snapshot at the current point of execution.
///
/// A snapshot is associated with a new unique id that's created for the snapshot.
/// Snapshots can be reverted: [DatabaseExt::revert], however a snapshot can only be reverted
/// once. After a successful revert, the same snapshot id cannot be used again.
fn snapshot(&mut self, journaled_state: &JournaledState, env: &Env) -> U256;
/// Reverts the snapshot if it exists
///
/// Returns `true` if the snapshot was successfully reverted, `false` if no snapshot for that id
/// exists.
///
/// **N.B.** While this reverts the state of the evm to the snapshot, it keeps new logs made
/// since the snapshots was created. This way we can show logs that were emitted between
/// snapshot and its revert.
/// This will also revert any changes in the `Env` and replace it with the captured `Env` of
/// `Self::snapshot`
fn revert(
&mut self,
id: U256,
journaled_state: &JournaledState,
env: &mut Env,
) -> Option<JournaledState>;
/// Creates and also selects a new fork
///
/// This is basically `create_fork` + `select_fork`
fn create_select_fork(
&mut self,
fork: CreateFork,
env: &mut Env,
journaled_state: &mut JournaledState,
) -> eyre::Result<LocalForkId> {
let id = self.create_fork(fork)?;
self.select_fork(id, env, journaled_state)?;
Ok(id)
}
/// Creates and also selects a new fork
///
/// This is basically `create_fork` + `select_fork`
fn create_select_fork_at_transaction(
&mut self,
fork: CreateFork,
env: &mut Env,
journaled_state: &mut JournaledState,
transaction: B256,
) -> eyre::Result<LocalForkId> {
let id = self.create_fork_at_transaction(fork, transaction)?;
self.select_fork(id, env, journaled_state)?;
Ok(id)
}
/// Creates a new fork but does _not_ select it
fn create_fork(&mut self, fork: CreateFork) -> eyre::Result<LocalForkId>;
/// Creates a new fork but does _not_ select it
fn create_fork_at_transaction(
&mut self,
fork: CreateFork,
transaction: B256,
) -> eyre::Result<LocalForkId>;
/// Selects the fork's state
///
/// This will also modify the current `Env`.
///
/// **Note**: this does not change the local state, but swaps the remote state
///
/// # Errors
///
/// Returns an error if no fork with the given `id` exists
fn select_fork(
&mut self,
id: LocalForkId,
env: &mut Env,
journaled_state: &mut JournaledState,
) -> eyre::Result<()>;
/// Updates the fork to given block number.
///
/// This will essentially create a new fork at the given block height.
///
/// # Errors
///
/// Returns an error if not matching fork was found.
fn roll_fork(
&mut self,
id: Option<LocalForkId>,
block_number: U256,
env: &mut Env,
journaled_state: &mut JournaledState,
) -> eyre::Result<()>;
/// Updates the fork to given transaction hash
///
/// This will essentially create a new fork at the block this transaction was mined and replays
/// all transactions up until the given transaction.
///
/// # Errors
///
/// Returns an error if not matching fork was found.
fn roll_fork_to_transaction(
&mut self,
id: Option<LocalForkId>,
transaction: B256,
env: &mut Env,
journaled_state: &mut JournaledState,
) -> eyre::Result<()>;
/// Fetches the given transaction for the fork and executes it, committing the state in the DB
fn transact(
&mut self,
id: Option<LocalForkId>,
transaction: B256,
env: &mut Env,
journaled_state: &mut JournaledState,
cheatcodes_inspector: Option<&mut Cheatcodes>,
) -> eyre::Result<()>;
/// Returns the `ForkId` that's currently used in the database, if fork mode is on
fn active_fork_id(&self) -> Option<LocalForkId>;
/// Returns the Fork url that's currently used in the database, if fork mode is on
fn active_fork_url(&self) -> Option<String>;
/// Whether the database is currently in forked
fn is_forked_mode(&self) -> bool {
self.active_fork_id().is_some()
}
/// Ensures that an appropriate fork exits
///
/// If `id` contains a requested `Fork` this will ensure it exits.
/// Otherwise, this returns the currently active fork.
///
/// # Errors
///
/// Returns an error if the given `id` does not match any forks
///
/// Returns an error if no fork exits
fn ensure_fork(&self, id: Option<LocalForkId>) -> eyre::Result<LocalForkId>;
/// Ensures that a corresponding `ForkId` exists for the given local `id`
fn ensure_fork_id(&self, id: LocalForkId) -> eyre::Result<&ForkId>;
/// Handling multiple accounts/new contracts in a multifork environment can be challenging since
/// every fork has its own standalone storage section. So this can be a common error to run
/// into:
///
/// ```solidity
/// function testCanDeploy() public {
/// vm.selectFork(mainnetFork);
/// // contract created while on `mainnetFork`
/// DummyContract dummy = new DummyContract();
/// // this will succeed
/// dummy.hello();
///
/// vm.selectFork(optimismFork);
///
/// vm.expectRevert();
/// // this will revert since `dummy` contract only exists on `mainnetFork`
/// dummy.hello();
/// }
/// ```
///
/// If this happens (`dummy.hello()`), or more general, a call on an address that's not a
/// contract, revm will revert without useful context. This call will check in this context if
/// `address(dummy)` belongs to an existing contract and if not will check all other forks if
/// the contract is deployed there.
///
/// Returns a more useful error message if that's the case
fn diagnose_revert(
&self,
callee: Address,
journaled_state: &JournaledState,
) -> Option<RevertDiagnostic>;
/// Returns true if the given account is currently marked as persistent.
fn is_persistent(&self, acc: &Address) -> bool;
/// Revokes persistent status from the given account.
fn remove_persistent_account(&mut self, account: &Address) -> bool;
/// Marks the given account as persistent.
fn add_persistent_account(&mut self, account: Address) -> bool;
/// Removes persistent status from all given accounts
fn remove_persistent_accounts(&mut self, accounts: impl IntoIterator<Item = Address>) {
for acc in accounts {
self.remove_persistent_account(&acc);
}
}
/// Extends the persistent accounts with the accounts the iterator yields.
fn extend_persistent_accounts(&mut self, accounts: impl IntoIterator<Item = Address>) {
for acc in accounts {
self.add_persistent_account(acc);
}
}
/// Grants cheatcode access for the given `account`
///
/// Returns true if the `account` already has access
fn allow_cheatcode_access(&mut self, account: Address) -> bool;
/// Revokes cheatcode access for the given account
///
/// Returns true if the `account` was previously allowed cheatcode access
fn revoke_cheatcode_access(&mut self, account: Address) -> bool;
/// Returns `true` if the given account is allowed to execute cheatcodes
fn has_cheatcode_access(&self, account: Address) -> bool;
/// Ensures that `account` is allowed to execute cheatcodes
///
/// Returns an error if [`Self::has_cheatcode_access`] returns `false`
fn ensure_cheatcode_access(&self, account: Address) -> Result<(), NoCheatcodeAccessError> {
if !self.has_cheatcode_access(account) {
return Err(NoCheatcodeAccessError(account))
}
Ok(())
}
/// Same as [`Self::ensure_cheatcode_access()`] but only enforces it if the backend is currently
/// in forking mode
fn ensure_cheatcode_access_forking_mode(
&self,
account: Address,
) -> Result<(), NoCheatcodeAccessError> {
if self.is_forked_mode() {
return self.ensure_cheatcode_access(account)
}
Ok(())
}
}
/// Provides the underlying `revm::Database` implementation.
///
/// A `Backend` can be initialised in two forms:
///
/// # 1. Empty in-memory Database
/// This is the default variant: an empty `revm::Database`
///
/// # 2. Forked Database
/// A `revm::Database` that forks off a remote client
///
///
/// In addition to that we support forking manually on the fly.
/// Additional forks can be created. Each unique fork is identified by its unique `ForkId`. We treat
/// forks as unique if they have the same `(endpoint, block number)` pair.
///
/// When it comes to testing, it's intended that each contract will use its own `Backend`
/// (`Backend::clone`). This way each contract uses its own encapsulated evm state. For in-memory
/// testing, the database is just an owned `revm::InMemoryDB`.
///
/// Each `Fork`, identified by a unique id, uses completely separate storage, write operations are
/// performed only in the fork's own database, `ForkDB`.
///
/// A `ForkDB` consists of 2 halves:
/// - everything fetched from the remote is readonly
/// - all local changes (instructed by the contract) are written to the backend's `db` and don't
/// alter the state of the remote client.
///
/// # Fork swapping
///
/// Multiple "forks" can be created `Backend::create_fork()`, however only 1 can be used by the
/// `db`. However, their state can be hot-swapped by swapping the read half of `db` from one fork to
/// another.
/// When swapping forks (`Backend::select_fork()`) we also update the current `Env` of the `EVM`
/// accordingly, so that all `block.*` config values match
///
/// When another for is selected [`DatabaseExt::select_fork()`] the entire storage, including
/// `JournaledState` is swapped, but the storage of the caller's and the test contract account is
/// _always_ cloned. This way a fork has entirely separate storage but data can still be shared
/// across fork boundaries via stack and contract variables.
///
/// # Snapshotting
///
/// A snapshot of the current overall state can be taken at any point in time. A snapshot is
/// identified by a unique id that's returned when a snapshot is created. A snapshot can only be
/// reverted _once_. After a successful revert, the same snapshot id cannot be used again. Reverting
/// a snapshot replaces the current active state with the snapshot state, the snapshot is deleted
/// afterwards, as well as any snapshots taken after the reverted snapshot, (e.g.: reverting to id
/// 0x1 will delete snapshots with ids 0x1, 0x2, etc.)
///
/// **Note:** Snapshots work across fork-swaps, e.g. if fork `A` is currently active, then a
/// snapshot is created before fork `B` is selected, then fork `A` will be the active fork again
/// after reverting the snapshot.
#[derive(Debug, Clone)]
pub struct Backend {
/// The access point for managing forks
forks: MultiFork,
// The default in memory db
mem_db: FoundryEvmInMemoryDB,
/// The journaled_state to use to initialize new forks with
///
/// The way [`revm::JournaledState`] works is, that it holds the "hot" accounts loaded from the
/// underlying `Database` that feeds the Account and State data ([`revm::AccountInfo`])to the
/// journaled_state so it can apply changes to the state while the evm executes.
///
/// In a way the `JournaledState` is something like a cache that
/// 1. check if account is already loaded (hot)
/// 2. if not load from the `Database` (this will then retrieve the account via RPC in forking
/// mode)
///
/// To properly initialize we store the `JournaledState` before the first fork is selected
/// ([`DatabaseExt::select_fork`]).
///
/// This will be an empty `JournaledState`, which will be populated with persistent accounts,
/// See [`Self::update_fork_db()`] and [`clone_data()`].
fork_init_journaled_state: JournaledState,
/// The currently active fork database
///
/// If this is set, then the Backend is currently in forking mode
active_fork_ids: Option<(LocalForkId, ForkLookupIndex)>,
/// holds additional Backend data
inner: BackendInner,
}
// === impl Backend ===
impl Backend {
/// Creates a new Backend with a spawned multi fork thread.
pub async fn spawn(fork: Option<CreateFork>) -> Self {
Self::new(MultiFork::spawn().await, fork)
}
/// Creates a new instance of `Backend`
///
/// if `fork` is `Some` this will launch with a `fork` database, otherwise with an in-memory
/// database
pub fn new(forks: MultiFork, fork: Option<CreateFork>) -> Self {
trace!(target: "backend", forking_mode=?fork.is_some(), "creating executor backend");
// Note: this will take of registering the `fork`
let inner = BackendInner {
persistent_accounts: HashSet::from(DEFAULT_PERSISTENT_ACCOUNTS),
..Default::default()
};
let mut backend = Self {
forks,
mem_db: CacheDB::new(Default::default()),
fork_init_journaled_state: inner.new_journaled_state(),
active_fork_ids: None,
inner,
};
if let Some(fork) = fork {
let (fork_id, fork, _) =
backend.forks.create_fork(fork).expect("Unable to create fork");
let fork_db = ForkDB::new(fork);
let fork_ids = backend.inner.insert_new_fork(
fork_id.clone(),
fork_db,
backend.inner.new_journaled_state(),
);
backend.inner.launched_with_fork = Some((fork_id, fork_ids.0, fork_ids.1));
backend.active_fork_ids = Some(fork_ids);
}
trace!(target: "backend", forking_mode=? backend.active_fork_ids.is_some(), "created executor backend");
backend
}
/// Creates a new instance of `Backend` with fork added to the fork database and sets the fork
/// as active
pub(crate) async fn new_with_fork(
id: &ForkId,
fork: Fork,
journaled_state: JournaledState,
) -> Self {
let mut backend = Self::spawn(None).await;
let fork_ids = backend.inner.insert_new_fork(id.clone(), fork.db, journaled_state);
backend.inner.launched_with_fork = Some((id.clone(), fork_ids.0, fork_ids.1));
backend.active_fork_ids = Some(fork_ids);
backend
}
/// Creates a new instance with a `BackendDatabase::InMemory` cache layer for the `CacheDB`
pub fn clone_empty(&self) -> Self {
Self {
forks: self.forks.clone(),
mem_db: CacheDB::new(Default::default()),
fork_init_journaled_state: self.inner.new_journaled_state(),
active_fork_ids: None,
inner: Default::default(),
}
}
pub fn insert_account_info(&mut self, address: Address, account: AccountInfo) {
if let Some(db) = self.active_fork_db_mut() {
db.insert_account_info(address, account)
} else {
self.mem_db.insert_account_info(address, account)
}
}
/// Inserts a value on an account's storage without overriding account info
pub fn insert_account_storage(
&mut self,
address: Address,
slot: U256,
value: U256,
) -> Result<(), DatabaseError> {
let ret = if let Some(db) = self.active_fork_db_mut() {
db.insert_account_storage(address, slot, value)
} else {
self.mem_db.insert_account_storage(address, slot, value)
};
debug_assert!(self.storage(address, slot).unwrap() == value);
ret
}
/// Returns all snapshots created in this backend
pub fn snapshots(&self) -> &Snapshots<BackendSnapshot<BackendDatabaseSnapshot>> {
&self.inner.snapshots
}
/// Sets the address of the `DSTest` contract that is being executed
///
/// This will also mark the caller as persistent and remove the persistent status from the
/// previous test contract address
///
/// This will also grant cheatcode access to the test account
pub fn set_test_contract(&mut self, acc: Address) -> &mut Self {
trace!(?acc, "setting test account");
// toggle the previous sender
if let Some(current) = self.inner.test_contract_address.take() {
self.remove_persistent_account(¤t);
self.revoke_cheatcode_access(acc);
}
self.add_persistent_account(acc);
self.allow_cheatcode_access(acc);
self.inner.test_contract_address = Some(acc);
self
}
/// Sets the caller address
pub fn set_caller(&mut self, acc: Address) -> &mut Self {
trace!(?acc, "setting caller account");
self.inner.caller = Some(acc);
self.allow_cheatcode_access(acc);
self
}
/// Sets the current spec id
pub fn set_spec_id(&mut self, spec_id: SpecId) -> &mut Self {
trace!("setting precompile id");
self.inner.precompile_id = spec_id;
self
}
/// Returns the address of the set `DSTest` contract
pub fn test_contract_address(&self) -> Option<Address> {
self.inner.test_contract_address
}
/// Returns the set caller address
pub fn caller_address(&self) -> Option<Address> {
self.inner.caller
}
/// Failures occurred in snapshots are tracked when the snapshot is reverted
///
/// If an error occurs in a restored snapshot, the test is considered failed.
///
/// This returns whether there was a reverted snapshot that recorded an error
pub fn has_snapshot_failure(&self) -> bool {
self.inner.has_snapshot_failure.load(Ordering::Relaxed)
}
pub fn set_snapshot_failure(&self, has_snapshot_failure: bool) {
self.inner.has_snapshot_failure.store(has_snapshot_failure, Ordering::Relaxed);
}
/// Checks if the test contract associated with this backend failed, See
/// [Self::is_failed_test_contract]
pub fn is_failed(&self) -> bool {
self.has_snapshot_failure() ||
self.test_contract_address()
.map(|addr| self.is_failed_test_contract(addr))
.unwrap_or_default()
}
/// Checks if the given test function failed
///
/// DSTest will not revert inside its `assertEq`-like functions which allows
/// to test multiple assertions in 1 test function while also preserving logs.
/// Instead, it stores whether an `assert` failed in a boolean variable that we can read
pub fn is_failed_test_contract(&self, address: Address) -> bool {
/*
contract DSTest {
bool public IS_TEST = true;
// slot 0 offset 1 => second byte of slot0
bool private _failed;
}
*/
let value = self.storage(address, U256::ZERO).unwrap_or_default();
value.as_le_bytes()[1] != 0
}
/// Checks if the given test function failed by looking at the present value of the test
/// contract's `JournaledState`
///
/// See [`Self::is_failed_test_contract()]`
///
/// Note: we assume the test contract is either `forge-std/Test` or `DSTest`
pub fn is_failed_test_contract_state(
&self,
address: Address,
current_state: &JournaledState,
) -> bool {
if let Some(account) = current_state.state.get(&address) {
let value = account
.storage
.get(&revm::primitives::U256::ZERO)
.cloned()
.unwrap_or_default()
.present_value();
return value.as_le_bytes()[1] != 0
}
false
}
/// In addition to the `_failed` variable, `DSTest::fail()` stores a failure
/// in "failed"
/// See <https://github.com/dapphub/ds-test/blob/9310e879db8ba3ea6d5c6489a579118fd264a3f5/src/test.sol#L66-L72>
pub fn is_global_failure(&self, current_state: &JournaledState) -> bool {
let index: U256 = U256::from_str_radix(GLOBAL_FAILURE_SLOT, 16).expect("This is a bug.");
if let Some(account) = current_state.state.get(&CHEATCODE_ADDRESS) {
let value = account.storage.get(&index).cloned().unwrap_or_default().present_value();
return value == revm::primitives::U256::from(1)
}
false
}
/// When creating or switching forks, we update the AccountInfo of the contract
pub(crate) fn update_fork_db(
&self,
active_journaled_state: &mut JournaledState,
target_fork: &mut Fork,
) {
debug_assert!(
self.inner.test_contract_address.is_some(),
"Test contract address must be set"
);
self.update_fork_db_contracts(
self.inner.persistent_accounts.iter().copied(),
active_journaled_state,
target_fork,
)
}
/// Merges the state of all `accounts` from the currently active db into the given `fork`
pub(crate) fn update_fork_db_contracts(
&self,
accounts: impl IntoIterator<Item = Address>,
active_journaled_state: &mut JournaledState,
target_fork: &mut Fork,
) {
if let Some((_, fork_idx)) = self.active_fork_ids.as_ref() {
let active = self.inner.get_fork(*fork_idx);
merge_account_data(accounts, &active.db, active_journaled_state, target_fork)
} else {
merge_account_data(accounts, &self.mem_db, active_journaled_state, target_fork)
}
}
/// Returns the memory db used if not in forking mode
pub fn mem_db(&self) -> &FoundryEvmInMemoryDB {
&self.mem_db
}
/// Returns true if the `id` is currently active
pub fn is_active_fork(&self, id: LocalForkId) -> bool {
self.active_fork_ids.map(|(i, _)| i == id).unwrap_or_default()
}
/// Returns `true` if the `Backend` is currently in forking mode
pub fn is_in_forking_mode(&self) -> bool {
self.active_fork().is_some()
}
/// Returns the currently active `Fork`, if any
pub fn active_fork(&self) -> Option<&Fork> {
self.active_fork_ids.map(|(_, idx)| self.inner.get_fork(idx))
}
/// Returns the currently active `Fork`, if any
pub fn active_fork_mut(&mut self) -> Option<&mut Fork> {
self.active_fork_ids.map(|(_, idx)| self.inner.get_fork_mut(idx))
}
/// Returns the currently active `ForkDB`, if any
pub fn active_fork_db(&self) -> Option<&ForkDB> {
self.active_fork().map(|f| &f.db)
}
/// Returns the currently active `ForkDB`, if any
pub fn active_fork_db_mut(&mut self) -> Option<&mut ForkDB> {
self.active_fork_mut().map(|f| &mut f.db)
}
/// Creates a snapshot of the currently active database
pub(crate) fn create_db_snapshot(&self) -> BackendDatabaseSnapshot {
if let Some((id, idx)) = self.active_fork_ids {
let fork = self.inner.get_fork(idx).clone();
let fork_id = self.inner.ensure_fork_id(id).cloned().expect("Exists; qed");
BackendDatabaseSnapshot::Forked(id, fork_id, idx, Box::new(fork))
} else {
BackendDatabaseSnapshot::InMemory(self.mem_db.clone())
}
}
/// Since each `Fork` tracks logs separately, we need to merge them to get _all_ of them
pub fn merged_logs(&self, mut logs: Vec<Log>) -> Vec<Log> {
if let Some((_, active)) = self.active_fork_ids {
let mut all_logs = Vec::with_capacity(logs.len());
self.inner
.forks
.iter()
.enumerate()
.filter_map(|(idx, f)| f.as_ref().map(|f| (idx, f)))
.for_each(|(idx, f)| {
if idx == active {
all_logs.append(&mut logs);
} else {
all_logs.extend(f.journaled_state.logs.clone())
}
});
return all_logs
}
logs
}
/// Initializes settings we need to keep track of.
///
/// We need to track these mainly to prevent issues when switching between different evms
pub(crate) fn initialize(&mut self, env: &Env) {
self.set_caller(env.tx.caller);
self.set_spec_id(SpecId::from_spec_id(env.cfg.spec_id));
let test_contract = match env.tx.transact_to {
TransactTo::Call(to) => to,
TransactTo::Create(CreateScheme::Create) => {
revm::primitives::create_address(env.tx.caller, env.tx.nonce.unwrap_or_default())
}
TransactTo::Create(CreateScheme::Create2 { salt }) => {
let code_hash = B256::from_slice(keccak256(&env.tx.data).as_slice());
revm::primitives::create2_address(env.tx.caller, code_hash, salt)
}
};
self.set_test_contract(test_contract);
}
/// Executes the configured test call of the `env` without committing state changes
pub fn inspect_ref<INSP>(
&mut self,
env: &mut Env,
mut inspector: INSP,
) -> eyre::Result<ResultAndState>
where
INSP: Inspector<Self>,
{
self.initialize(env);
match revm::evm_inner::<Self, true>(env, self, &mut inspector).transact() {
Ok(res) => Ok(res),
Err(e) => eyre::bail!("backend: failed while inspecting: {:?}", e),
}
}
/// Returns true if the address is a precompile
pub fn is_existing_precompile(&self, addr: &Address) -> bool {
self.inner.precompiles().contains(addr)
}
/// Ths will clean up already loaded accounts that would be initialized without the correct data
/// from the fork
///
/// It can happen that an account is loaded before the first fork is selected, like
/// `getNonce(addr)`, which will load an empty account by default.
///
/// This account data then would not match the account data of a fork if it exists.
/// So when the first fork is initialized we replace these accounts with the actual account as
/// it exists on the fork.
fn prepare_init_journal_state(&mut self) -> Result<(), DatabaseError> {
let loaded_accounts = self
.fork_init_journaled_state
.state
.iter()
.filter(|(addr, _)| !self.is_existing_precompile(addr) && !self.is_persistent(addr))
.map(|(addr, _)| addr)
.copied()
.collect::<Vec<_>>();
for fork in self.inner.forks_iter_mut() {
let mut journaled_state = self.fork_init_journaled_state.clone();
for loaded_account in loaded_accounts.iter().copied() {
trace!(?loaded_account, "replacing account on init");
let fork_account = Database::basic(&mut fork.db, loaded_account)?
.ok_or(DatabaseError::MissingAccount(loaded_account))?;
let init_account =
journaled_state.state.get_mut(&loaded_account).expect("exists; qed");
init_account.info = fork_account;
}
fork.journaled_state = journaled_state;
}
Ok(())
}
/// Returns the block numbers required for replaying a transaction
fn get_block_number_and_block_for_transaction(
&self,
id: LocalForkId,
transaction: B256,
) -> eyre::Result<(U64, Block<Transaction>)> {
let fork = self.inner.get_fork_by_id(id)?;
let tx = fork.db.db.get_transaction(transaction)?;
// get the block number we need to fork
if let Some(tx_block) = tx.block_number {
let block = fork.db.db.get_full_block(BlockNumber::Number(tx_block))?;
// we need to subtract 1 here because we want the state before the transaction
// was mined
let fork_block = tx_block - 1;
Ok((U64::from(fork_block.as_u64()), block))
} else {
let block = fork.db.db.get_full_block(BlockNumber::Latest)?;
let number = block
.number
.ok_or_else(|| DatabaseError::BlockNotFound(BlockNumber::Latest.into()))?;
Ok((U64::from(number.as_u64()), block))
}
}
/// Replays all the transactions at the forks current block that were mined before the `tx`
///
/// Returns the _unmined_ transaction that corresponds to the given `tx_hash`
pub fn replay_until(
&mut self,
id: LocalForkId,
env: Env,
tx_hash: B256,
journaled_state: &mut JournaledState,
) -> eyre::Result<Option<Transaction>> {
trace!(?id, ?tx_hash, "replay until transaction");
let fork_id = self.ensure_fork_id(id)?.clone();
let fork = self.inner.get_fork_by_id_mut(id)?;
let full_block = fork
.db
.db
.get_full_block(BlockNumber::Number(ru256_to_u256(env.block.number).as_u64().into()))?;
for tx in full_block.transactions.into_iter() {
if tx.hash().eq(&b256_to_h256(tx_hash)) {
// found the target transaction
return Ok(Some(tx))
}
trace!(tx=?tx.hash, "committing transaction");
commit_transaction(tx, env.clone(), journaled_state, fork, &fork_id, None)?;
}
Ok(None)
}
}
// === impl a bunch of `revm::Database` adjacent implementations ===
impl DatabaseExt for Backend {
fn snapshot(&mut self, journaled_state: &JournaledState, env: &Env) -> U256 {
trace!("create snapshot");
let id = self.inner.snapshots.insert(BackendSnapshot::new(
self.create_db_snapshot(),
journaled_state.clone(),
env.clone(),
));
trace!(target: "backend", "Created new snapshot {}", id);
id
}
fn revert(
&mut self,
id: U256,
current_state: &JournaledState,
current: &mut Env,
) -> Option<JournaledState> {
trace!(?id, "revert snapshot");
if let Some(mut snapshot) = self.inner.snapshots.remove_at(id) {
// Re-insert snapshot to persist it
self.inner.snapshots.insert_at(snapshot.clone(), id);
// need to check whether there's a global failure which means an error occurred either
// during the snapshot or even before
if self.is_global_failure(current_state) {
self.inner.has_snapshot_failure.store(true, Ordering::Relaxed);
}
// merge additional logs
snapshot.merge(current_state);
let BackendSnapshot { db, mut journaled_state, env } = snapshot;
match db {
BackendDatabaseSnapshot::InMemory(mem_db) => {
self.mem_db = mem_db;
}
BackendDatabaseSnapshot::Forked(id, fork_id, idx, mut fork) => {
// there might be the case where the snapshot was created during `setUp` with
// another caller, so we need to ensure the caller account is present in the
// journaled state and database
let caller = current.tx.caller;
if !journaled_state.state.contains_key(&caller) {
let caller_account = current_state
.state
.get(&caller)
.map(|acc| acc.info.clone())
.unwrap_or_default();
if !fork.db.accounts.contains_key(&caller) {
// update the caller account which is required by the evm
fork.db.insert_account_info(caller, caller_account.clone());
}
journaled_state.state.insert(caller, caller_account.into());
}
self.inner.revert_snapshot(id, fork_id, idx, *fork);
self.active_fork_ids = Some((id, idx))
}
}
update_current_env_with_fork_env(current, env);
trace!(target: "backend", "Reverted snapshot {}", id);
Some(journaled_state)
} else {
warn!(target: "backend", "No snapshot to revert for {}", id);
None
}
}
fn create_fork(&mut self, fork: CreateFork) -> eyre::Result<LocalForkId> {
trace!("create fork");
let (fork_id, fork, _) = self.forks.create_fork(fork)?;
let fork_db = ForkDB::new(fork);
let (id, _) =
self.inner.insert_new_fork(fork_id, fork_db, self.fork_init_journaled_state.clone());
Ok(id)
}
fn create_fork_at_transaction(
&mut self,
fork: CreateFork,
transaction: B256,
) -> eyre::Result<LocalForkId> {
trace!(?transaction, "create fork at transaction");
let id = self.create_fork(fork)?;
let fork_id = self.ensure_fork_id(id).cloned()?;
let mut env = self
.forks
.get_env(fork_id)?
.ok_or_else(|| eyre::eyre!("Requested fork `{}` does not exit", id))?;
// we still need to roll to the transaction, but we only need an empty dummy state since we
// don't need to update the active journaled state yet
self.roll_fork_to_transaction(
Some(id),
transaction,
&mut env,
&mut self.inner.new_journaled_state(),
)?;
Ok(id)
}
/// Select an existing fork by id.
/// When switching forks we copy the shared state
fn select_fork(
&mut self,
id: LocalForkId,
env: &mut Env,
active_journaled_state: &mut JournaledState,
) -> eyre::Result<()> {
trace!(?id, "select fork");
if self.is_active_fork(id) {
// nothing to do
return Ok(())
}
let fork_id = self.ensure_fork_id(id).cloned()?;
let idx = self.inner.ensure_fork_index(&fork_id)?;
let fork_env = self
.forks
.get_env(fork_id)?
.ok_or_else(|| eyre::eyre!("Requested fork `{}` does not exit", id))?;
// If we're currently in forking mode we need to update the journaled_state to this point,
// this ensures the changes performed while the fork was active are recorded
if let Some(active) = self.active_fork_mut() {
active.journaled_state = active_journaled_state.clone();
let caller = env.tx.caller;
let caller_account = active.journaled_state.state.get(&env.tx.caller).cloned();
let target_fork = self.inner.get_fork_mut(idx);
// depth 0 will be the default value when the fork was created
if target_fork.journaled_state.depth == 0 {
// Initialize caller with its fork info
if let Some(mut acc) = caller_account {
let fork_account = Database::basic(&mut target_fork.db, caller)?
.ok_or(DatabaseError::MissingAccount(caller))?;