-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathmod.rs
More file actions
4044 lines (3529 loc) · 157 KB
/
mod.rs
File metadata and controls
4044 lines (3529 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! In-memory blockchain backend.
use self::state::trie_storage;
use super::executor::new_evm_with_inspector;
use crate::{
ForkChoice, NodeConfig, PrecompileFactory,
config::PruneStateHistoryConfig,
eth::{
backend::{
cheats::{CheatEcrecover, CheatsManager},
db::{Db, MaybeFullDatabase, SerializableState, StateDb},
env::Env,
executor::{ExecutedTransactions, TransactionExecutor},
fork::ClientFork,
genesis::GenesisConfig,
mem::{
state::{storage_root, trie_accounts},
storage::MinedTransactionReceipt,
},
notifications::{NewBlockNotification, NewBlockNotifications},
time::{TimeManager, utc_from_secs},
validate::TransactionValidator,
},
error::{BlockchainError, ErrDetail, InvalidTransactionError},
fees::{FeeDetails, FeeManager, MIN_SUGGESTED_PRIORITY_FEE},
macros::node_info,
pool::transactions::PoolTransaction,
sign::build_impersonated,
},
mem::{
inspector::AnvilInspector,
storage::{BlockchainStorage, InMemoryBlockStates, MinedBlockOutcome},
},
};
use alloy_chains::NamedChain;
use alloy_consensus::{
Blob, BlockHeader, EnvKzgSettings, Header, Signed, Transaction as TransactionTrait,
TrieAccount, TxEnvelope, TxReceipt, Typed2718,
proofs::{calculate_receipt_root, calculate_transaction_root},
transaction::Recovered,
};
use alloy_eips::{
BlockNumHash, Encodable2718, eip2935, eip4844::kzg_to_versioned_hash, eip7840::BlobParams,
eip7910::SystemContract,
};
use alloy_evm::{
Database, Evm, FromRecoveredTx,
eth::EthEvmContext,
overrides::{OverrideBlockHashes, apply_state_overrides},
precompiles::{DynPrecompile, Precompile, PrecompilesMap},
};
use alloy_network::{
AnyHeader, AnyRpcBlock, AnyRpcHeader, AnyRpcTransaction, AnyTxEnvelope, AnyTxType, Network,
ReceiptResponse, TransactionBuilder, UnknownTxEnvelope, UnknownTypedTransaction,
};
use alloy_primitives::{
Address, B256, Bytes, TxHash, TxKind, U64, U256, hex, keccak256, logs_bloom,
map::{AddressMap, HashMap, HashSet},
};
use alloy_rpc_types::{
AccessList, Block as AlloyBlock, BlockId, BlockNumberOrTag as BlockNumber, BlockTransactions,
EIP1186AccountProofResponse as AccountProof, EIP1186StorageProof as StorageProof, Filter,
Header as AlloyHeader, Index, Log, Transaction, TransactionReceipt,
anvil::Forking,
request::TransactionRequest,
serde_helpers::JsonStorageKey,
simulate::{SimBlock, SimCallResult, SimulatePayload, SimulatedBlock},
state::EvmOverrides,
trace::{
filter::TraceFilter,
geth::{
FourByteFrame, GethDebugBuiltInTracerType, GethDebugTracerType,
GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, NoopFrame,
},
parity::{LocalizedTransactionTrace, TraceResultsWithTransactionHash, TraceType},
},
};
use alloy_serde::{OtherFields, WithOtherFields};
use alloy_trie::{HashBuilder, Nibbles, proof::ProofRetainer};
use anvil_core::eth::{
block::{Block, BlockInfo},
transaction::{MaybeImpersonatedTransaction, PendingTransaction, TransactionInfo},
};
use anvil_rpc::error::RpcError;
use chrono::Datelike;
use eyre::{Context, Result};
use flate2::{Compression, read::GzDecoder, write::GzEncoder};
use foundry_evm::{
backend::{DatabaseError, DatabaseResult, RevertStateSnapshotAction},
constants::DEFAULT_CREATE2_DEPLOYER_RUNTIME_CODE,
core::{either_evm::EitherEvm, precompiles::EC_RECOVER},
decode::RevertDecoder,
inspectors::AccessListInspector,
traces::{
CallTraceDecoder, FourByteInspector, GethTraceBuilder, TracingInspector,
TracingInspectorConfig,
},
utils::{get_blob_base_fee_update_fraction, get_blob_base_fee_update_fraction_by_spec_id},
};
use foundry_primitives::{
FoundryNetwork, FoundryReceiptEnvelope, FoundryTransactionRequest, FoundryTxEnvelope,
FoundryTxReceipt, get_deposit_tx_parts,
};
use futures::channel::mpsc::{UnboundedSender, unbounded};
use op_alloy_consensus::DEPOSIT_TX_TYPE_ID;
use op_revm::{OpContext, OpHaltReason, OpTransaction};
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use revm::{
DatabaseCommit, Inspector,
context::{Block as RevmBlock, BlockEnv, Cfg, TxEnv},
context_interface::{
block::BlobExcessGasAndPrice,
result::{ExecutionResult, Output, ResultAndState},
},
database::{CacheDB, DbAccount, WrapDatabaseRef},
interpreter::InstructionResult,
precompile::{PrecompileSpecId, Precompiles},
primitives::{KECCAK_EMPTY, hardfork::SpecId},
state::AccountInfo,
};
use std::{
collections::BTreeMap,
fmt::{self, Debug},
io::{Read, Write},
ops::{Mul, Not},
path::PathBuf,
sync::Arc,
time::Duration,
};
use storage::{Blockchain, DEFAULT_HISTORY_LIMIT, MinedTransaction};
use tokio::sync::RwLock as AsyncRwLock;
pub mod cache;
pub mod fork_db;
pub mod in_memory_db;
pub mod inspector;
pub mod state;
pub mod storage;
/// Helper trait that combines revm::DatabaseRef with Debug.
/// This is needed because alloy-evm requires Debug on Database implementations.
/// With trait upcasting now stable, we can now upcast from this trait to revm::DatabaseRef.
pub trait DatabaseRef: revm::DatabaseRef<Error = DatabaseError> + Debug {}
impl<T> DatabaseRef for T where T: revm::DatabaseRef<Error = DatabaseError> + Debug {}
impl DatabaseRef for dyn crate::eth::backend::db::Db {}
// Gas per transaction not creating a contract.
pub const MIN_TRANSACTION_GAS: u128 = 21000;
// Gas per transaction creating a contract.
pub const MIN_CREATE_GAS: u128 = 53000;
pub type State = foundry_evm::utils::StateChangeset;
/// A block request, which includes the Pool Transactions if it's Pending
pub enum BlockRequest<T = FoundryTxEnvelope> {
Pending(Vec<Arc<PoolTransaction<T>>>),
Number(u64),
}
impl<T> fmt::Debug for BlockRequest<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pending(txs) => f.debug_tuple("Pending").field(&txs.len()).finish(),
Self::Number(n) => f.debug_tuple("Number").field(n).finish(),
}
}
}
impl<T> BlockRequest<T> {
pub fn block_number(&self) -> BlockNumber {
match *self {
Self::Pending(_) => BlockNumber::Pending,
Self::Number(n) => BlockNumber::Number(n),
}
}
}
/// Gives access to the [revm::Database]
pub struct Backend<N: Network> {
/// Access to [`revm::Database`] abstraction.
///
/// This will be used in combination with [`alloy_evm::Evm`] and is responsible for feeding
/// data to the evm during its execution.
///
/// At time of writing, there are two different types of `Db`:
/// - [`MemDb`](crate::mem::in_memory_db::MemDb): everything is stored in memory
/// - [`ForkDb`](crate::mem::fork_db::ForkedDatabase): forks off a remote client, missing
/// data is retrieved via RPC-calls
///
/// In order to commit changes to the [`revm::Database`], the [`alloy_evm::Evm`] requires
/// mutable access, which requires a write-lock from this `db`. In forking mode, the time
/// during which the write-lock is active depends on whether the `ForkDb` can provide all
/// requested data from memory or whether it has to retrieve it via RPC calls first. This
/// means that it potentially blocks for some time, even taking into account the rate
/// limits of RPC endpoints. Therefore the `Db` is guarded by a `tokio::sync::RwLock` here
/// so calls that need to read from it, while it's currently written to, don't block. E.g.
/// a new block is currently mined and a new [`Self::set_storage_at()`] request is being
/// executed.
db: Arc<AsyncRwLock<Box<dyn Db>>>,
/// stores all block related data in memory.
blockchain: Blockchain<N>,
/// Historic states of previous blocks.
states: Arc<RwLock<InMemoryBlockStates>>,
/// Env data of the chain
env: Arc<RwLock<Env>>,
/// This is set if this is currently forked off another client.
fork: Arc<RwLock<Option<ClientFork>>>,
/// Provides time related info, like timestamp.
time: TimeManager,
/// Contains state of custom overrides.
cheats: CheatsManager,
/// Contains fee data.
fees: FeeManager,
/// Initialised genesis.
genesis: GenesisConfig,
/// Listeners for new blocks that get notified when a new block was imported.
new_block_listeners: Arc<Mutex<Vec<UnboundedSender<NewBlockNotification>>>>,
/// Keeps track of active state snapshots at a specific block.
active_state_snapshots: Arc<Mutex<HashMap<U256, (u64, B256)>>>,
enable_steps_tracing: bool,
print_logs: bool,
print_traces: bool,
/// Recorder used for decoding traces, used together with print_traces
call_trace_decoder: Arc<CallTraceDecoder>,
/// How to keep history state
prune_state_history_config: PruneStateHistoryConfig,
/// max number of blocks with transactions in memory
transaction_block_keeper: Option<usize>,
node_config: Arc<AsyncRwLock<NodeConfig>>,
/// Slots in an epoch
slots_in_an_epoch: u64,
/// Precompiles to inject to the EVM.
precompile_factory: Option<Arc<dyn PrecompileFactory>>,
/// Prevent race conditions during mining
mining: Arc<tokio::sync::Mutex<()>>,
/// Disable pool balance checks
disable_pool_balance_checks: bool,
}
impl<N: Network> Clone for Backend<N> {
fn clone(&self) -> Self {
Self {
db: self.db.clone(),
blockchain: self.blockchain.clone(),
states: self.states.clone(),
env: self.env.clone(),
fork: self.fork.clone(),
time: self.time.clone(),
cheats: self.cheats.clone(),
fees: self.fees.clone(),
genesis: self.genesis.clone(),
new_block_listeners: self.new_block_listeners.clone(),
active_state_snapshots: self.active_state_snapshots.clone(),
enable_steps_tracing: self.enable_steps_tracing,
print_logs: self.print_logs,
print_traces: self.print_traces,
call_trace_decoder: self.call_trace_decoder.clone(),
prune_state_history_config: self.prune_state_history_config,
transaction_block_keeper: self.transaction_block_keeper,
node_config: self.node_config.clone(),
slots_in_an_epoch: self.slots_in_an_epoch,
precompile_factory: self.precompile_factory.clone(),
mining: self.mining.clone(),
disable_pool_balance_checks: self.disable_pool_balance_checks,
}
}
}
impl<N: Network> fmt::Debug for Backend<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Backend").finish_non_exhaustive()
}
}
// Methods that are generic over any Network.
impl<N: Network> Backend<N> {
/// Sets the account to impersonate
///
/// Returns `true` if the account is already impersonated
pub fn impersonate(&self, addr: Address) -> bool {
if self.cheats.impersonated_accounts().contains(&addr) {
return true;
}
// Ensure EIP-3607 is disabled
let mut env = self.env.write();
env.evm_env.cfg_env.disable_eip3607 = true;
self.cheats.impersonate(addr)
}
/// Removes the account that from the impersonated set
///
/// If the impersonated `addr` is a contract then we also reset the code here
pub fn stop_impersonating(&self, addr: Address) {
self.cheats.stop_impersonating(&addr);
}
/// If set to true will make every account impersonated
pub fn auto_impersonate_account(&self, enabled: bool) {
self.cheats.set_auto_impersonate_account(enabled);
}
/// Returns the configured fork, if any
pub fn get_fork(&self) -> Option<ClientFork> {
self.fork.read().clone()
}
/// Returns the database
pub fn get_db(&self) -> &Arc<AsyncRwLock<Box<dyn Db>>> {
&self.db
}
/// Returns the `AccountInfo` from the database
pub async fn get_account(&self, address: Address) -> DatabaseResult<AccountInfo> {
Ok(self.db.read().await.basic_ref(address)?.unwrap_or_default())
}
/// Whether we're forked off some remote client
pub fn is_fork(&self) -> bool {
self.fork.read().is_some()
}
/// Writes the CREATE2 deployer code directly to the database at the address provided.
pub async fn set_create2_deployer(&self, address: Address) -> DatabaseResult<()> {
self.set_code(address, Bytes::from_static(DEFAULT_CREATE2_DEPLOYER_RUNTIME_CODE)).await?;
Ok(())
}
/// Updates memory limits that should be more strict when auto-mine is enabled
pub(crate) fn update_interval_mine_block_time(&self, block_time: Duration) {
self.states.write().update_interval_mine_block_time(block_time)
}
/// Returns the `TimeManager` responsible for timestamps
pub fn time(&self) -> &TimeManager {
&self.time
}
/// Returns the `CheatsManager` responsible for executing cheatcodes
pub fn cheats(&self) -> &CheatsManager {
&self.cheats
}
/// Whether to skip blob validation
pub fn skip_blob_validation(&self, impersonator: Option<Address>) -> bool {
self.cheats().auto_impersonate_accounts()
|| impersonator
.is_some_and(|addr| self.cheats().impersonated_accounts().contains(&addr))
}
/// Returns the `FeeManager` that manages fee/pricings
pub fn fees(&self) -> &FeeManager {
&self.fees
}
/// The env data of the blockchain
pub fn env(&self) -> &Arc<RwLock<Env>> {
&self.env
}
/// Returns the current best hash of the chain
pub fn best_hash(&self) -> B256 {
self.blockchain.storage.read().best_hash
}
/// Returns the current best number of the chain
pub fn best_number(&self) -> u64 {
self.blockchain.storage.read().best_number
}
/// Sets the block number
pub fn set_block_number(&self, number: u64) {
let mut env = self.env.write();
env.evm_env.block_env.number = U256::from(number);
}
/// Returns the client coinbase address.
pub fn coinbase(&self) -> Address {
self.env.read().evm_env.block_env.beneficiary
}
/// Returns the client coinbase address.
pub fn chain_id(&self) -> U256 {
U256::from(self.env.read().evm_env.cfg_env.chain_id)
}
pub fn set_chain_id(&self, chain_id: u64) {
self.env.write().evm_env.cfg_env.chain_id = chain_id;
}
/// Returns the genesis data for the Beacon API.
pub fn genesis_time(&self) -> u64 {
self.genesis.timestamp
}
/// Returns balance of the given account.
pub async fn current_balance(&self, address: Address) -> DatabaseResult<U256> {
Ok(self.get_account(address).await?.balance)
}
/// Returns balance of the given account.
pub async fn current_nonce(&self, address: Address) -> DatabaseResult<u64> {
Ok(self.get_account(address).await?.nonce)
}
/// Sets the coinbase address
pub fn set_coinbase(&self, address: Address) {
self.env.write().evm_env.block_env.beneficiary = address;
}
/// Sets the nonce of the given address
pub async fn set_nonce(&self, address: Address, nonce: U256) -> DatabaseResult<()> {
self.db.write().await.set_nonce(address, nonce.try_into().unwrap_or(u64::MAX))
}
/// Sets the balance of the given address
pub async fn set_balance(&self, address: Address, balance: U256) -> DatabaseResult<()> {
self.db.write().await.set_balance(address, balance)
}
/// Sets the code of the given address
pub async fn set_code(&self, address: Address, code: Bytes) -> DatabaseResult<()> {
self.db.write().await.set_code(address, code)
}
/// Sets the value for the given slot of the given address
pub async fn set_storage_at(
&self,
address: Address,
slot: U256,
val: B256,
) -> DatabaseResult<()> {
self.db.write().await.set_storage_at(address, slot.into(), val)
}
/// Returns the configured specid
pub fn spec_id(&self) -> SpecId {
self.env.read().evm_env.cfg_env.spec
}
/// Returns true for post London
pub fn is_eip1559(&self) -> bool {
(self.spec_id() as u8) >= (SpecId::LONDON as u8)
}
/// Returns true for post Merge
pub fn is_eip3675(&self) -> bool {
(self.spec_id() as u8) >= (SpecId::MERGE as u8)
}
/// Returns true for post Berlin
pub fn is_eip2930(&self) -> bool {
(self.spec_id() as u8) >= (SpecId::BERLIN as u8)
}
/// Returns true for post Cancun
pub fn is_eip4844(&self) -> bool {
(self.spec_id() as u8) >= (SpecId::CANCUN as u8)
}
/// Returns true for post Prague
pub fn is_eip7702(&self) -> bool {
(self.spec_id() as u8) >= (SpecId::PRAGUE as u8)
}
/// Returns true if op-stack deposits are active
pub fn is_optimism(&self) -> bool {
self.env.read().networks.is_optimism()
}
/// Returns the precompiles for the current spec.
pub fn precompiles(&self) -> BTreeMap<String, Address> {
let spec_id = self.env.read().evm_env.cfg_env.spec;
let precompiles = Precompiles::new(PrecompileSpecId::from_spec_id(spec_id));
let mut precompiles_map = BTreeMap::<String, Address>::default();
for (address, precompile) in precompiles.inner() {
precompiles_map.insert(precompile.id().name().to_string(), *address);
}
// Extend with configured network precompiles.
precompiles_map.extend(self.env.read().networks.precompiles());
if let Some(factory) = &self.precompile_factory {
for (address, precompile) in factory.precompiles() {
precompiles_map.insert(precompile.precompile_id().to_string(), address);
}
}
precompiles_map
}
/// Returns the system contracts for the current spec.
pub fn system_contracts(&self) -> BTreeMap<SystemContract, Address> {
let mut system_contracts = BTreeMap::<SystemContract, Address>::default();
let spec_id = self.env.read().evm_env.cfg_env.spec;
if spec_id >= SpecId::CANCUN {
system_contracts.extend(SystemContract::cancun());
}
if spec_id >= SpecId::PRAGUE {
system_contracts.extend(SystemContract::prague(None));
}
system_contracts
}
/// Returns [`BlobParams`] corresponding to the current spec.
pub fn blob_params(&self) -> BlobParams {
let spec_id = self.env.read().evm_env.cfg_env.spec;
if spec_id >= SpecId::OSAKA {
return BlobParams::osaka();
}
if spec_id >= SpecId::PRAGUE {
return BlobParams::prague();
}
BlobParams::cancun()
}
/// Returns an error if EIP1559 is not active (pre Berlin)
pub fn ensure_eip1559_active(&self) -> Result<(), BlockchainError> {
if self.is_eip1559() {
return Ok(());
}
Err(BlockchainError::EIP1559TransactionUnsupportedAtHardfork)
}
/// Returns an error if EIP1559 is not active (pre muirGlacier)
pub fn ensure_eip2930_active(&self) -> Result<(), BlockchainError> {
if self.is_eip2930() {
return Ok(());
}
Err(BlockchainError::EIP2930TransactionUnsupportedAtHardfork)
}
pub fn ensure_eip4844_active(&self) -> Result<(), BlockchainError> {
if self.is_eip4844() {
return Ok(());
}
Err(BlockchainError::EIP4844TransactionUnsupportedAtHardfork)
}
pub fn ensure_eip7702_active(&self) -> Result<(), BlockchainError> {
if self.is_eip7702() {
return Ok(());
}
Err(BlockchainError::EIP7702TransactionUnsupportedAtHardfork)
}
/// Returns an error if op-stack deposits are not active
pub fn ensure_op_deposits_active(&self) -> Result<(), BlockchainError> {
if self.is_optimism() {
return Ok(());
}
Err(BlockchainError::DepositTransactionUnsupported)
}
/// Returns the block gas limit
pub fn gas_limit(&self) -> u64 {
self.env.read().evm_env.block_env.gas_limit
}
/// Sets the block gas limit
pub fn set_gas_limit(&self, gas_limit: u64) {
self.env.write().evm_env.block_env.gas_limit = gas_limit;
}
/// Returns the current base fee
pub fn base_fee(&self) -> u64 {
self.fees.base_fee()
}
/// Returns whether the minimum suggested priority fee is enforced
pub fn is_min_priority_fee_enforced(&self) -> bool {
self.fees.is_min_priority_fee_enforced()
}
pub fn excess_blob_gas_and_price(&self) -> Option<BlobExcessGasAndPrice> {
self.fees.excess_blob_gas_and_price()
}
/// Sets the current basefee
pub fn set_base_fee(&self, basefee: u64) {
self.fees.set_base_fee(basefee)
}
/// Sets the gas price
pub fn set_gas_price(&self, price: u128) {
self.fees.set_gas_price(price)
}
pub fn elasticity(&self) -> f64 {
self.fees.elasticity()
}
/// Returns the total difficulty of the chain until this block
///
/// Note: this will always be `0` in memory mode
/// In forking mode this will always be the total difficulty of the forked block
pub fn total_difficulty(&self) -> U256 {
self.blockchain.storage.read().total_difficulty
}
/// Creates a new `evm_snapshot` at the current height.
///
/// Returns the id of the snapshot created.
pub async fn create_state_snapshot(&self) -> U256 {
let num = self.best_number();
let hash = self.best_hash();
let id = self.db.write().await.snapshot_state();
trace!(target: "backend", "creating snapshot {} at {}", id, num);
self.active_state_snapshots.lock().insert(id, (num, hash));
id
}
pub fn list_state_snapshots(&self) -> BTreeMap<U256, (u64, B256)> {
self.active_state_snapshots.lock().clone().into_iter().collect()
}
/// Returns the environment for the next block
fn next_env(&self) -> Env {
let mut env = self.env.read().clone();
// increase block number for this block
env.evm_env.block_env.number = env.evm_env.block_env.number.saturating_add(U256::from(1));
env.evm_env.block_env.basefee = self.base_fee();
env.evm_env.block_env.blob_excess_gas_and_price = self.excess_blob_gas_and_price();
env.evm_env.block_env.timestamp = U256::from(self.time.current_call_timestamp());
env
}
/// Builds [`Inspector`] with the configured options.
fn build_inspector(&self) -> AnvilInspector {
let mut inspector = AnvilInspector::default();
if self.print_logs {
inspector = inspector.with_log_collector();
}
if self.print_traces {
inspector = inspector.with_trace_printer();
}
inspector
}
/// Returns a new block event stream that yields Notifications when a new block was added
pub fn new_block_notifications(&self) -> NewBlockNotifications {
let (tx, rx) = unbounded();
self.new_block_listeners.lock().push(tx);
trace!(target: "backed", "added new block listener");
rx
}
/// Notifies all `new_block_listeners` about the new block
fn notify_on_new_block(&self, header: Header, hash: B256) {
// cleanup closed notification streams first, if the channel is closed we can remove the
// sender half for the set
self.new_block_listeners.lock().retain(|tx| !tx.is_closed());
let notification = NewBlockNotification { hash, header: Arc::new(header) };
self.new_block_listeners
.lock()
.retain(|tx| tx.unbounded_send(notification.clone()).is_ok());
}
/// Returns the block number for the given block id
pub fn convert_block_number(&self, block: Option<BlockNumber>) -> u64 {
let current = self.best_number();
match block.unwrap_or(BlockNumber::Latest) {
BlockNumber::Latest | BlockNumber::Pending => current,
BlockNumber::Earliest => 0,
BlockNumber::Number(num) => num,
BlockNumber::Safe => current.saturating_sub(self.slots_in_an_epoch),
BlockNumber::Finalized => current.saturating_sub(self.slots_in_an_epoch * 2),
}
}
/// Returns the block and its hash for the given id
fn get_block_with_hash(&self, id: impl Into<BlockId>) -> Option<(Block, B256)> {
let hash = match id.into() {
BlockId::Hash(hash) => hash.block_hash,
BlockId::Number(number) => {
let storage = self.blockchain.storage.read();
let slots_in_an_epoch = self.slots_in_an_epoch;
match number {
BlockNumber::Latest => storage.best_hash,
BlockNumber::Earliest => storage.genesis_hash,
BlockNumber::Pending => return None,
BlockNumber::Number(num) => *storage.hashes.get(&num)?,
BlockNumber::Safe => {
if storage.best_number > (slots_in_an_epoch) {
*storage.hashes.get(&(storage.best_number - (slots_in_an_epoch)))?
} else {
storage.genesis_hash // treat the genesis block as safe "by definition"
}
}
BlockNumber::Finalized => {
if storage.best_number > (slots_in_an_epoch * 2) {
*storage.hashes.get(&(storage.best_number - (slots_in_an_epoch * 2)))?
} else {
storage.genesis_hash
}
}
}
}
};
let block = self.get_block_by_hash(hash)?;
Some((block, hash))
}
pub fn get_block(&self, id: impl Into<BlockId>) -> Option<Block> {
self.get_block_with_hash(id).map(|(block, _)| block)
}
pub fn get_block_by_hash(&self, hash: B256) -> Option<Block> {
self.blockchain.get_block_by_hash(&hash)
}
/// Returns the traces for the given transaction
pub(crate) fn mined_parity_trace_transaction(
&self,
hash: B256,
) -> Option<Vec<LocalizedTransactionTrace>> {
self.blockchain.storage.read().transactions.get(&hash).map(|tx| tx.parity_traces())
}
/// Returns the traces for the given block
pub(crate) fn mined_parity_trace_block(
&self,
block: u64,
) -> Option<Vec<LocalizedTransactionTrace>> {
let block = self.get_block(block)?;
let mut traces = vec![];
let storage = self.blockchain.storage.read();
for tx in block.body.transactions {
traces.extend(storage.transactions.get(&tx.hash())?.parity_traces());
}
Some(traces)
}
/// Returns the mined transaction for the given hash
pub(crate) fn mined_transaction(&self, hash: B256) -> Option<MinedTransaction<N>> {
self.blockchain.storage.read().transactions.get(&hash).cloned()
}
/// Overrides the given signature to impersonate the specified address during ecrecover.
pub async fn impersonate_signature(
&self,
signature: Bytes,
address: Address,
) -> Result<(), BlockchainError> {
self.cheats.add_recover_override(signature, address);
Ok(())
}
/// Returns code by its hash
pub async fn debug_code_by_hash(
&self,
code_hash: B256,
block_id: Option<BlockId>,
) -> Result<Option<Bytes>, BlockchainError> {
if let Ok(code) = self.db.read().await.code_by_hash_ref(code_hash) {
return Ok(Some(code.original_bytes()));
}
if let Some(fork) = self.get_fork() {
return Ok(fork.debug_code_by_hash(code_hash, block_id).await?);
}
Ok(None)
}
/// Returns the value associated with a key from the database
/// Currently only supports bytecode lookups.
///
/// Based on Reth implementation: <https://github.com/paradigmxyz/reth/blob/66cfa9ed1a8c4bc2424aacf6fb2c1e67a78ee9a2/crates/rpc/rpc/src/debug.rs#L1146-L1178>
///
/// Key should be: 0x63 (1-byte prefix) + 32 bytes (code_hash)
/// Total key length must be 33 bytes.
pub async fn debug_db_get(&self, key: String) -> Result<Option<Bytes>, BlockchainError> {
let key_bytes = if key.starts_with("0x") {
hex::decode(&key)
.map_err(|_| BlockchainError::Message("Invalid hex key".to_string()))?
} else {
key.into_bytes()
};
// Validate key length: must be 33 bytes (1 byte prefix + 32 bytes code hash)
if key_bytes.len() != 33 {
return Err(BlockchainError::Message(format!(
"Invalid key length: expected 33 bytes, got {}",
key_bytes.len()
)));
}
// Check for bytecode prefix (0x63 = 'c' in ASCII)
if key_bytes[0] != 0x63 {
return Err(BlockchainError::Message(
"Key prefix must be 0x63 for code hash lookups".to_string(),
));
}
let code_hash = B256::from_slice(&key_bytes[1..33]);
// Use the existing debug_code_by_hash method to retrieve the bytecode
self.debug_code_by_hash(code_hash, None).await
}
fn mined_block_by_hash(&self, hash: B256) -> Option<AnyRpcBlock> {
let block = self.blockchain.get_block_by_hash(&hash)?;
Some(self.convert_block_with_hash(block, Some(hash)))
}
pub(crate) async fn mined_transactions_by_block_number(
&self,
number: BlockNumber,
) -> Option<Vec<AnyRpcTransaction>> {
if let Some(block) = self.get_block(number) {
return self.mined_transactions_in_block(&block);
}
None
}
/// Returns all transactions given a block
pub(crate) fn mined_transactions_in_block(
&self,
block: &Block,
) -> Option<Vec<AnyRpcTransaction>> {
let mut transactions = Vec::with_capacity(block.body.transactions.len());
let base_fee = block.header.base_fee_per_gas();
let storage = self.blockchain.storage.read();
for hash in block.body.transactions.iter().map(|tx| tx.hash()) {
let info = storage.transactions.get(&hash)?.info.clone();
let tx = block.body.transactions.get(info.transaction_index as usize)?.clone();
let tx = transaction_build(Some(hash), tx, Some(block), Some(info), base_fee);
transactions.push(tx);
}
Some(transactions)
}
pub fn mined_block_by_number(&self, number: BlockNumber) -> Option<AnyRpcBlock> {
let (block, hash) = self.get_block_with_hash(number)?;
let mut block = self.convert_block_with_hash(block, Some(hash));
block.transactions.convert_to_hashes();
Some(block)
}
pub fn get_full_block(&self, id: impl Into<BlockId>) -> Option<AnyRpcBlock> {
let (block, hash) = self.get_block_with_hash(id)?;
let transactions = self.mined_transactions_in_block(&block)?;
let mut block = self.convert_block_with_hash(block, Some(hash));
block.inner.transactions = BlockTransactions::Full(transactions);
Some(block)
}
/// Takes a block as it's stored internally and returns the eth api conform block format.
pub fn convert_block(&self, block: Block) -> AnyRpcBlock {
self.convert_block_with_hash(block, None)
}
/// Takes a block as it's stored internally and returns the eth api conform block format.
/// If `known_hash` is provided, it will be used instead of computing `hash_slow()`.
pub fn convert_block_with_hash(&self, block: Block, known_hash: Option<B256>) -> AnyRpcBlock {
let size = U256::from(alloy_rlp::encode(&block).len() as u32);
let header = block.header.clone();
let transactions = block.body.transactions;
let hash = known_hash.unwrap_or_else(|| header.hash_slow());
let Header { number, withdrawals_root, .. } = header;
let block = AlloyBlock {
header: AlloyHeader {
inner: AnyHeader::from(header),
hash,
total_difficulty: Some(self.total_difficulty()),
size: Some(size),
},
transactions: alloy_rpc_types::BlockTransactions::Hashes(
transactions.into_iter().map(|tx| tx.hash()).collect(),
),
uncles: vec![],
withdrawals: withdrawals_root.map(|_| Default::default()),
};
let mut block = WithOtherFields::new(block);
// If Arbitrum, apply chain specifics to converted block.
if is_arbitrum(self.env.read().evm_env.cfg_env.chain_id) {
// Set `l1BlockNumber` field.
block.other.insert("l1BlockNumber".to_string(), number.into());
}
AnyRpcBlock::from(block)
}
pub async fn block_by_hash(&self, hash: B256) -> Result<Option<AnyRpcBlock>, BlockchainError> {
trace!(target: "backend", "get block by hash {:?}", hash);
if let tx @ Some(_) = self.mined_block_by_hash(hash) {
return Ok(tx);
}
if let Some(fork) = self.get_fork() {
return Ok(fork.block_by_hash(hash).await?);
}
Ok(None)
}
pub async fn block_by_hash_full(
&self,
hash: B256,
) -> Result<Option<AnyRpcBlock>, BlockchainError> {
trace!(target: "backend", "get block by hash {:?}", hash);
if let tx @ Some(_) = self.get_full_block(hash) {
return Ok(tx);
}
if let Some(fork) = self.get_fork() {
return Ok(fork.block_by_hash_full(hash).await?);
}
Ok(None)
}
pub async fn block_by_number(
&self,
number: BlockNumber,
) -> Result<Option<AnyRpcBlock>, BlockchainError> {
trace!(target: "backend", "get block by number {:?}", number);
if let tx @ Some(_) = self.mined_block_by_number(number) {
return Ok(tx);
}
if let Some(fork) = self.get_fork() {
let number = self.convert_block_number(Some(number));
if fork.predates_fork_inclusive(number) {
return Ok(fork.block_by_number(number).await?);
}
}
Ok(None)
}
pub async fn block_by_number_full(
&self,
number: BlockNumber,
) -> Result<Option<AnyRpcBlock>, BlockchainError> {
trace!(target: "backend", "get block by number {:?}", number);
if let tx @ Some(_) = self.get_full_block(number) {
return Ok(tx);
}
if let Some(fork) = self.get_fork() {
let number = self.convert_block_number(Some(number));
if fork.predates_fork_inclusive(number) {
return Ok(fork.block_by_number_full(number).await?);
}
}
Ok(None)
}
/// Converts the `BlockNumber` into a numeric value
///
/// # Errors
///
/// returns an error if the requested number is larger than the current height
pub async fn ensure_block_number<T: Into<BlockId>>(
&self,
block_id: Option<T>,
) -> Result<u64, BlockchainError> {
let current = self.best_number();
let requested =
match block_id.map(Into::into).unwrap_or(BlockId::Number(BlockNumber::Latest)) {
BlockId::Hash(hash) => {
self.block_by_hash(hash.block_hash)
.await?
.ok_or(BlockchainError::BlockNotFound)?
.header
.number
}
BlockId::Number(num) => match num {
BlockNumber::Latest | BlockNumber::Pending => current,
BlockNumber::Earliest => U64::ZERO.to::<u64>(),
BlockNumber::Number(num) => num,
BlockNumber::Safe => current.saturating_sub(self.slots_in_an_epoch),
BlockNumber::Finalized => current.saturating_sub(self.slots_in_an_epoch * 2),
},
};
if requested > current {
Err(BlockchainError::BlockOutOfRange(current, requested))
} else {
Ok(requested)
}
}