-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
mod.rs
2504 lines (2202 loc) · 93.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
//! In memory blockchain backend
use crate::{
config::PruneStateHistoryConfig,
eth::{
backend::{
cheats::CheatsManager,
db::{AsHashDB, Db, MaybeHashDatabase, SerializableState},
executor::{ExecutedTransactions, TransactionExecutor},
fork::ClientFork,
genesis::GenesisConfig,
mem::storage::MinedTransactionReceipt,
notifications::{NewBlockNotification, NewBlockNotifications},
time::{utc_from_secs, TimeManager},
validate::TransactionValidator,
},
error::{BlockchainError, ErrDetail, InvalidTransactionError},
fees::{FeeDetails, FeeManager},
macros::node_info,
pool::transactions::PoolTransaction,
util::get_precompiles_for,
},
mem::{
inspector::Inspector,
storage::{BlockchainStorage, InMemoryBlockStates, MinedBlockOutcome},
},
revm::{
db::DatabaseRef,
primitives::{AccountInfo, U256 as rU256},
},
NodeConfig,
};
use alloy_consensus::{Header, Receipt, ReceiptWithBloom};
use alloy_network::Sealable;
use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, B64, U128, U256, U64, U8};
use alloy_rlp::Decodable;
use alloy_rpc_trace_types::{
geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace},
parity::LocalizedTransactionTrace,
};
use alloy_rpc_types::{
request::TransactionRequest, state::StateOverride, AccessList, Block as AlloyBlock, BlockId,
BlockNumberOrTag as BlockNumber, EIP1186AccountProofResponse as AccountProof,
EIP1186StorageProof as StorageProof, Filter, FilteredParams, Header as AlloyHeader, Log,
Transaction, TransactionReceipt,
};
use anvil_core::{
eth::{
block::{Block, BlockInfo},
proof::BasicAccount,
transaction::{
MaybeImpersonatedTransaction, PendingTransaction, TransactionInfo, TypedReceipt,
TypedTransaction,
},
trie::RefTrieDB,
utils::{alloy_to_revm_access_list, meets_eip155},
},
types::{Forking, Index},
};
use anvil_rpc::error::RpcError;
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use foundry_common::types::ToAlloy;
use foundry_evm::{
backend::{DatabaseError, DatabaseResult, RevertSnapshotAction},
constants::DEFAULT_CREATE2_DEPLOYER_RUNTIME_CODE,
decode::RevertDecoder,
inspectors::AccessListTracer,
revm::{
self,
db::CacheDB,
interpreter::InstructionResult,
primitives::{
BlockEnv, CreateScheme, EVMError, Env, ExecutionResult, InvalidHeader, Output, SpecId,
TransactTo, TxEnv, KECCAK_EMPTY,
},
},
traces::{TracingInspector, TracingInspectorConfig},
utils::{eval_to_instruction_result, halt_to_instruction_result},
};
use futures::channel::mpsc::{unbounded, UnboundedSender};
use hash_db::HashDB;
use parking_lot::{Mutex, RwLock};
use std::{
collections::{BTreeMap, HashMap},
io::{Read, Write},
ops::Deref,
sync::Arc,
time::Duration,
};
use storage::{Blockchain, MinedTransaction};
use tokio::sync::RwLock as AsyncRwLock;
use trie_db::{Recorder, Trie};
pub mod cache;
pub mod fork_db;
pub mod in_memory_db;
pub mod inspector;
pub mod state;
pub mod storage;
// Gas per transaction not creating a contract.
pub const MIN_TRANSACTION_GAS: U256 = U256::from_limbs([21_000, 0, 0, 0]);
// Gas per transaction creating a contract.
pub const MIN_CREATE_GAS: U256 = U256::from_limbs([53_000, 0, 0, 0]);
pub type State = foundry_evm::utils::StateChangeset;
/// A block request, which includes the Pool Transactions if it's Pending
#[derive(Debug)]
pub enum BlockRequest {
Pending(Vec<Arc<PoolTransaction>>),
Number(u64),
}
impl BlockRequest {
pub fn block_number(&self) -> BlockNumber {
match *self {
BlockRequest::Pending(_) => BlockNumber::Pending,
BlockRequest::Number(n) => BlockNumber::Number(n),
}
}
}
/// Gives access to the [revm::Database]
#[derive(Clone)]
pub struct Backend {
/// Access to [`revm::Database`] abstraction.
///
/// This will be used in combination with [`revm::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::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 [`revm::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. Therefor 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()`] request is being executed.
db: Arc<AsyncRwLock<Box<dyn Db>>>,
/// stores all block related data in memory
blockchain: Blockchain,
/// 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 snapshots at a specific block
active_snapshots: Arc<Mutex<HashMap<U256, (u64, B256)>>>,
enable_steps_tracing: bool,
/// 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>>,
}
impl Backend {
/// Initialises the balance of the given accounts
#[allow(clippy::too_many_arguments)]
pub async fn with_genesis(
db: Arc<AsyncRwLock<Box<dyn Db>>>,
env: Arc<RwLock<Env>>,
genesis: GenesisConfig,
fees: FeeManager,
fork: Arc<RwLock<Option<ClientFork>>>,
enable_steps_tracing: bool,
prune_state_history_config: PruneStateHistoryConfig,
transaction_block_keeper: Option<usize>,
automine_block_time: Option<Duration>,
node_config: Arc<AsyncRwLock<NodeConfig>>,
) -> Self {
// if this is a fork then adjust the blockchain storage
let blockchain = if let Some(fork) = fork.read().as_ref() {
trace!(target: "backend", "using forked blockchain at {}", fork.block_number());
Blockchain::forked(fork.block_number(), fork.block_hash(), fork.total_difficulty())
} else {
Blockchain::new(
&env.read(),
fees.is_eip1559().then(|| fees.base_fee()),
genesis.timestamp,
)
};
let start_timestamp = if let Some(fork) = fork.read().as_ref() {
fork.timestamp()
} else {
genesis.timestamp
};
let states = if prune_state_history_config.is_config_enabled() {
// if prune state history is enabled, configure the state cache only for memory
prune_state_history_config
.max_memory_history
.map(InMemoryBlockStates::new)
.unwrap_or_default()
.memory_only()
} else {
Default::default()
};
let backend = Self {
db,
blockchain,
states: Arc::new(RwLock::new(states)),
env,
fork,
time: TimeManager::new(start_timestamp),
cheats: Default::default(),
new_block_listeners: Default::default(),
fees,
genesis,
active_snapshots: Arc::new(Mutex::new(Default::default())),
enable_steps_tracing,
prune_state_history_config,
transaction_block_keeper,
node_config,
};
if let Some(interval_block_time) = automine_block_time {
backend.update_interval_mine_block_time(interval_block_time);
}
// Note: this can only fail in forking mode, in which case we can't recover
backend.apply_genesis().await.expect("Failed to create genesis");
backend
}
/// 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)
}
/// Applies the configured genesis settings
///
/// This will fund, create the genesis accounts
async fn apply_genesis(&self) -> DatabaseResult<()> {
trace!(target: "backend", "setting genesis balances");
if self.fork.read().is_some() {
// fetch all account first
let mut genesis_accounts_futures = Vec::with_capacity(self.genesis.accounts.len());
for address in self.genesis.accounts.iter().copied() {
let db = Arc::clone(&self.db);
// The forking Database backend can handle concurrent requests, we can fetch all dev
// accounts concurrently by spawning the job to a new task
genesis_accounts_futures.push(tokio::task::spawn(async move {
let db = db.read().await;
let info = db.basic_ref(address)?.unwrap_or_default();
Ok::<_, DatabaseError>((address, info))
}));
}
let genesis_accounts = futures::future::join_all(genesis_accounts_futures).await;
let mut db = self.db.write().await;
// in fork mode we only set the balance, this way the accountinfo is fetched from the
// remote client, preserving code and nonce. The reason for that is private keys for dev
// accounts are commonly known and are used on testnets
let mut fork_genesis_infos = self.genesis.fork_genesis_account_infos.lock();
fork_genesis_infos.clear();
for res in genesis_accounts {
let (address, mut info) = res.map_err(DatabaseError::display)??;
info.balance = self.genesis.balance;
db.insert_account(address, info.clone());
// store the fetched AccountInfo, so we can cheaply reset in [Self::reset_fork()]
fork_genesis_infos.push(info);
}
} else {
let mut db = self.db.write().await;
for (account, info) in self.genesis.account_infos() {
db.insert_account(account, info);
}
}
let db = self.db.write().await;
// apply the genesis.json alloc
self.genesis.apply_genesis_json_alloc(db)?;
Ok(())
}
/// Sets the account to impersonate
///
/// Returns `true` if the account is already impersonated
pub async fn impersonate(&self, addr: Address) -> DatabaseResult<bool> {
if self.cheats.impersonated_accounts().contains(&addr) {
return Ok(true);
}
// Ensure EIP-3607 is disabled
let mut env = self.env.write();
env.cfg.disable_eip3607 = true;
Ok(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 async fn stop_impersonating(&self, addr: Address) -> DatabaseResult<()> {
self.cheats.stop_impersonating(&addr);
Ok(())
}
/// If set to true will make every account impersonated
pub async 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()
}
pub fn precompiles(&self) -> Vec<Address> {
get_precompiles_for(self.env.read().cfg.spec_id)
}
/// Resets the fork to a fresh state
pub async fn reset_fork(&self, forking: Forking) -> Result<(), BlockchainError> {
if !self.is_fork() {
if let Some(eth_rpc_url) = forking.clone().json_rpc_url {
let mut env = self.env.read().clone();
let (db, config) = {
let mut node_config = self.node_config.write().await;
// we want to force the correct base fee for the next block during
// `setup_fork_db_config`
node_config.base_fee.take();
node_config.setup_fork_db_config(eth_rpc_url, &mut env, &self.fees).await
};
*self.db.write().await = Box::new(db);
let fork = ClientFork::new(config, Arc::clone(&self.db));
*self.env.write() = env;
*self.fork.write() = Some(fork);
} else {
return Err(RpcError::invalid_params(
"Forking not enabled and RPC URL not provided to start forking",
)
.into());
}
}
if let Some(fork) = self.get_fork() {
let block_number =
forking.block_number.map(BlockNumber::from).unwrap_or(BlockNumber::Latest);
// reset the fork entirely and reapply the genesis config
fork.reset(forking.json_rpc_url.clone(), block_number).await?;
let fork_block_number = fork.block_number();
let fork_block = fork
.block_by_number(fork_block_number)
.await?
.ok_or(BlockchainError::BlockNotFound)?;
// update all settings related to the forked block
{
let mut env = self.env.write();
env.cfg.chain_id = fork.chain_id();
env.block = BlockEnv {
number: rU256::from(fork_block_number),
timestamp: fork_block.header.timestamp,
gas_limit: fork_block.header.gas_limit,
difficulty: fork_block.header.difficulty,
prevrandao: Some(fork_block.header.mix_hash.unwrap_or_default()),
// Keep previous `coinbase` and `basefee` value
coinbase: env.block.coinbase,
basefee: env.block.basefee,
..env.block.clone()
};
self.time.reset(env.block.timestamp.to::<u64>());
// this is the base fee of the current block, but we need the base fee of
// the next block
let next_block_base_fee = self.fees.get_next_block_base_fee_per_gas(
fork_block.header.gas_used,
fork_block.header.gas_limit,
fork_block.header.base_fee_per_gas.unwrap_or_default(),
);
self.fees.set_base_fee(U256::from(next_block_base_fee));
// also reset the total difficulty
self.blockchain.storage.write().total_difficulty = fork.total_difficulty();
}
// reset storage
*self.blockchain.storage.write() = BlockchainStorage::forked(
fork.block_number(),
fork.block_hash(),
fork.total_difficulty(),
);
self.states.write().clear();
// insert back all genesis accounts, by reusing cached `AccountInfo`s we don't need to
// fetch the data via RPC again
let mut db = self.db.write().await;
// clear database
db.clear();
let fork_genesis_infos = self.genesis.fork_genesis_account_infos.lock();
for (address, info) in
self.genesis.accounts.iter().copied().zip(fork_genesis_infos.iter().cloned())
{
db.insert_account(address, info);
}
// reset the genesis.json alloc
self.genesis.apply_genesis_json_alloc(db)?;
Ok(())
} else {
Err(RpcError::invalid_params("Forking not enabled").into())
}
}
/// 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
}
/// 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.env.read().block.number.try_into().unwrap_or(u64::MAX)
}
/// Sets the block number
pub fn set_block_number(&self, number: U256) {
let mut env = self.env.write();
env.block.number = number;
}
/// Returns the client coinbase address.
pub fn coinbase(&self) -> Address {
self.env.read().block.coinbase
}
/// Returns the client coinbase address.
pub fn chain_id(&self) -> U256 {
U256::from(self.env.read().cfg.chain_id)
}
pub fn set_chain_id(&self, chain_id: u64) {
self.env.write().cfg.chain_id = chain_id;
}
/// 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<U256> {
Ok(U256::from(self.get_account(address).await?.nonce))
}
/// Sets the coinbase address
pub fn set_coinbase(&self, address: Address) {
self.env.write().block.coinbase = 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.0.into())
}
/// 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, U256::from_be_bytes(val.0))
}
/// Returns the configured specid
pub fn spec_id(&self) -> SpecId {
self.env.read().cfg.spec_id
}
/// 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 if op-stack deposits are active
pub fn is_optimism(&self) -> bool {
self.env.read().cfg.optimism
}
/// 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)
}
/// 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) -> U256 {
self.env.read().block.gas_limit
}
/// Sets the block gas limit
pub fn set_gas_limit(&self, gas_limit: U256) {
self.env.write().block.gas_limit = gas_limit;
}
/// Returns the current base fee
pub fn base_fee(&self) -> U256 {
self.fees.base_fee()
}
/// Sets the current basefee
pub fn set_base_fee(&self, basefee: U256) {
self.fees.set_base_fee(basefee)
}
/// Returns the current gas price
pub fn gas_price(&self) -> U256 {
self.fees.gas_price()
}
/// Returns the suggested fee cap
pub fn max_priority_fee_per_gas(&self) -> U256 {
self.fees.max_priority_fee_per_gas()
}
/// Sets the gas price
pub fn set_gas_price(&self, price: U256) {
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_snapshot(&self) -> U256 {
let num = self.best_number();
let hash = self.best_hash();
let id = self.db.write().await.snapshot();
trace!(target: "backend", "creating snapshot {} at {}", id, num);
self.active_snapshots.lock().insert(id, (num, hash));
id
}
/// Reverts the state to the snapshot identified by the given `id`.
pub async fn revert_snapshot(&self, id: U256) -> Result<bool, BlockchainError> {
let block = { self.active_snapshots.lock().remove(&id) };
if let Some((num, hash)) = block {
let best_block_hash = {
// revert the storage that's newer than the snapshot
let current_height = self.best_number();
let mut storage = self.blockchain.storage.write();
for n in ((num + 1)..=current_height).rev() {
trace!(target: "backend", "reverting block {}", n);
let n = U64::from(n);
if let Some(hash) = storage.hashes.remove(&n) {
if let Some(block) = storage.blocks.remove(&hash) {
for tx in block.transactions {
let _ = storage.transactions.remove(&tx.hash());
}
}
}
}
storage.best_number = U64::from(num);
storage.best_hash = hash;
hash
};
let block =
self.block_by_hash(best_block_hash).await?.ok_or(BlockchainError::BlockNotFound)?;
let reset_time = block.header.timestamp.to::<u64>();
self.time.reset(reset_time);
let mut env = self.env.write();
env.block = BlockEnv {
number: rU256::from(num),
timestamp: block.header.timestamp,
difficulty: block.header.difficulty,
// ensures prevrandao is set
prevrandao: Some(block.header.mix_hash.unwrap_or_default()),
gas_limit: block.header.gas_limit,
// Keep previous `coinbase` and `basefee` value
coinbase: env.block.coinbase,
basefee: env.block.basefee,
..Default::default()
};
}
Ok(self.db.write().await.revert(id, RevertSnapshotAction::RevertRemove))
}
pub fn list_snapshots(&self) -> BTreeMap<U256, (u64, B256)> {
self.active_snapshots.lock().clone().into_iter().collect()
}
/// Get the current state.
pub async fn serialized_state(&self) -> Result<SerializableState, BlockchainError> {
let at = self.env.read().block.clone();
let state = self.db.read().await.dump_state(at)?;
state.ok_or_else(|| {
RpcError::invalid_params("Dumping state not supported with the current configuration")
.into()
})
}
/// Write all chain data to serialized bytes buffer
pub async fn dump_state(&self) -> Result<Bytes, BlockchainError> {
let state = self.serialized_state().await?;
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder
.write_all(&serde_json::to_vec(&state).unwrap_or_default())
.map_err(|_| BlockchainError::DataUnavailable)?;
Ok(encoder.finish().unwrap_or_default().into())
}
/// Apply [SerializableState] data to the backend storage.
pub async fn load_state(&self, state: SerializableState) -> Result<bool, BlockchainError> {
// reset the block env
if let Some(block) = state.block.clone() {
self.env.write().block = block;
}
if !self.db.write().await.load_state(state)? {
Err(RpcError::invalid_params(
"Loading state not supported with the current configuration",
)
.into())
} else {
Ok(true)
}
}
/// Deserialize and add all chain data to the backend storage
pub async fn load_state_bytes(&self, buf: Bytes) -> Result<bool, BlockchainError> {
let orig_buf = &buf.0[..];
let mut decoder = GzDecoder::new(orig_buf);
let mut decoded_data = Vec::new();
let state: SerializableState = serde_json::from_slice(if decoder.header().is_some() {
decoder
.read_to_end(decoded_data.as_mut())
.map_err(|_| BlockchainError::FailedToDecodeStateDump)?;
&decoded_data
} else {
&buf.0
})
.map_err(|_| BlockchainError::FailedToDecodeStateDump)?;
self.load_state(state).await
}
/// 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.block.number = env.block.number.saturating_add(rU256::from(1));
env.block.basefee = self.base_fee();
env.block.timestamp = rU256::from(self.time.current_call_timestamp());
env
}
/// executes the transactions without writing to the underlying database
pub async fn inspect_tx(
&self,
tx: Arc<PoolTransaction>,
) -> Result<
(InstructionResult, Option<Output>, u64, State, Vec<revm::primitives::Log>),
BlockchainError,
> {
let mut env = self.next_env();
env.tx = tx.pending_transaction.to_revm_tx_env();
let db = self.db.read().await;
let mut inspector = Inspector::default();
let mut evm = revm::EVM::new();
evm.env = env;
evm.database(&*db);
let result_and_state = match evm.inspect_ref(&mut inspector) {
Ok(res) => res,
Err(e) => return Err(e.into()),
};
let state = result_and_state.state;
let (exit_reason, gas_used, out, logs) = match result_and_state.result {
ExecutionResult::Success { reason, gas_used, logs, output, .. } => {
(eval_to_instruction_result(reason), gas_used, Some(output), Some(logs))
}
ExecutionResult::Revert { gas_used, output } => {
(InstructionResult::Revert, gas_used, Some(Output::Call(output)), None)
}
ExecutionResult::Halt { reason, gas_used } => {
(halt_to_instruction_result(reason), gas_used, None, None)
}
};
inspector.print_logs();
Ok((exit_reason, out, gas_used, state, logs.unwrap_or_default()))
}
/// Creates the pending block
///
/// This will execute all transaction in the order they come but will not mine the block
pub async fn pending_block(&self, pool_transactions: Vec<Arc<PoolTransaction>>) -> BlockInfo {
self.with_pending_block(pool_transactions, |_, block| block).await
}
/// Creates the pending block
///
/// This will execute all transaction in the order they come but will not mine the block
pub async fn with_pending_block<F, T>(
&self,
pool_transactions: Vec<Arc<PoolTransaction>>,
f: F,
) -> T
where
F: FnOnce(Box<dyn MaybeHashDatabase + '_>, BlockInfo) -> T,
{
let db = self.db.read().await;
let env = self.next_env();
let mut cache_db = CacheDB::new(&*db);
let storage = self.blockchain.storage.read();
let executor = TransactionExecutor {
db: &mut cache_db,
validator: self,
pending: pool_transactions.into_iter(),
block_env: env.block.clone(),
cfg_env: env.cfg,
parent_hash: storage.best_hash,
gas_used: U256::ZERO,
enable_steps_tracing: self.enable_steps_tracing,
};
// create a new pending block
let executed = executor.execute();
f(Box::new(cache_db), executed.block)
}
/// Mines a new block and stores it.
///
/// this will execute all transaction in the order they come in and return all the markers they
/// provide.
pub async fn mine_block(
&self,
pool_transactions: Vec<Arc<PoolTransaction>>,
) -> MinedBlockOutcome {
self.do_mine_block(pool_transactions).await
}
async fn do_mine_block(
&self,
pool_transactions: Vec<Arc<PoolTransaction>>,
) -> MinedBlockOutcome {
trace!(target: "backend", "creating new block with {} transactions", pool_transactions.len());
let (outcome, header, block_hash) = {
let current_base_fee = self.base_fee();
let mut env = self.env.read().clone();
if env.block.basefee.is_zero() {
// this is an edge case because the evm fails if `tx.effective_gas_price < base_fee`
// 0 is only possible if it's manually set
env.cfg.disable_base_fee = true;
}
// increase block number for this block
env.block.number = env.block.number.saturating_add(rU256::from(1));
env.block.basefee = current_base_fee;
env.block.timestamp = rU256::from(self.time.next_timestamp());
let best_hash = self.blockchain.storage.read().best_hash;
if self.prune_state_history_config.is_state_history_supported() {
let db = self.db.read().await.current_state();
// store current state before executing all transactions
self.states.write().insert(best_hash, db);
}
let (executed_tx, block_hash) = {
let mut db = self.db.write().await;
let executor = TransactionExecutor {
db: &mut *db,
validator: self,
pending: pool_transactions.into_iter(),
block_env: env.block.clone(),
cfg_env: env.cfg.clone(),
parent_hash: best_hash,
gas_used: U256::ZERO,
enable_steps_tracing: self.enable_steps_tracing,
};
let executed_tx = executor.execute();
// we also need to update the new blockhash in the db itself
let block_hash = executed_tx.block.block.header.hash();
db.insert_block_hash(U256::from(executed_tx.block.block.header.number), block_hash);
(executed_tx, block_hash)
};
// create the new block with the current timestamp
let ExecutedTransactions { block, included, invalid } = executed_tx;
let BlockInfo { block, transactions, receipts } = block;
let header = block.header.clone();
let block_number: U64 = env.block.number.to::<U64>();
trace!(
target: "backend",
"Mined block {} with {} tx {:?}",
block_number,
transactions.len(),
transactions.iter().map(|tx| tx.transaction_hash).collect::<Vec<_>>()
);
let mut storage = self.blockchain.storage.write();
// update block metadata
storage.best_number = block_number;
storage.best_hash = block_hash;
// Difficulty is removed and not used after Paris (aka TheMerge). Value is replaced with
// prevrandao. https://github.com/bluealloy/revm/blob/1839b3fce8eaeebb85025576f2519b80615aca1e/crates/interpreter/src/instructions/host_env.rs#L27
if !self.is_eip3675() {
storage.total_difficulty =
storage.total_difficulty.saturating_add(header.difficulty);
}
storage.blocks.insert(block_hash, block);
storage.hashes.insert(block_number, block_hash);
node_info!("");
// insert all transactions
for (info, receipt) in transactions.into_iter().zip(receipts) {
// log some tx info
node_info!(" Transaction: {:?}", info.transaction_hash);
if let Some(contract) = &info.contract_address {
node_info!(" Contract created: {contract:?}");
}
node_info!(" Gas used: {}", receipt.gas_used());
if !info.exit.is_ok() {
let r = RevertDecoder::new().decode(
info.out.as_ref().map(|b| &b[..]).unwrap_or_default(),
Some(info.exit),
);
node_info!(" Error: reverted with: {r}");
}
node_info!("");
let mined_tx = MinedTransaction {
info,
receipt,
block_hash,
block_number: block_number.to::<u64>(),
};
storage.transactions.insert(mined_tx.info.transaction_hash, mined_tx);
}
// remove old transactions that exceed the transaction block keeper
if let Some(transaction_block_keeper) = self.transaction_block_keeper {
if storage.blocks.len() > transaction_block_keeper {
let to_clear = block_number
.to::<u64>()
.saturating_sub(transaction_block_keeper.try_into().unwrap());
storage.remove_block_transactions_by_number(to_clear)
}
}
// we intentionally set the difficulty to `0` for newer blocks
env.block.difficulty = rU256::from(0);
// update env with new values
*self.env.write() = env;
let timestamp = utc_from_secs(header.timestamp);
node_info!(" Block Number: {}", block_number);
node_info!(" Block Hash: {:?}", block_hash);
node_info!(" Block Time: {:?}\n", timestamp.to_rfc2822());
let outcome = MinedBlockOutcome { block_number, included, invalid };
(outcome, header, block_hash)
};