-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathapi.rs
2598 lines (2348 loc) · 102 KB
/
api.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
use super::{backend::mem::BlockRequest, sign::build_typed_transaction};
use crate::{
eth::{
backend,
backend::{
db::SerializableState,
mem::{MIN_CREATE_GAS, MIN_TRANSACTION_GAS},
notifications::NewBlockNotifications,
validate::TransactionValidator,
},
error::{
decode_revert_reason, BlockchainError, FeeHistoryError, InvalidTransactionError,
Result, ToRpcResponseResult,
},
fees::{FeeDetails, FeeHistoryCache},
macros::node_info,
miner::FixedBlockTimeMiner,
pool::{
transactions::{
to_marker, PoolTransaction, TransactionOrder, TransactionPriority, TxMarker,
},
Pool,
},
sign,
sign::Signer,
},
filter::{EthFilter, Filters, LogsFilter},
mem::transaction_build,
revm::primitives::Output,
ClientFork, LoggingManager, Miner, MiningMode, StorageInfo,
};
use anvil_core::{
eth::{
block::BlockInfo,
proof::AccountProof,
state::StateOverride,
transaction::{
EthTransactionRequest, LegacyTransaction, PendingTransaction, TransactionKind,
TypedTransaction, TypedTransactionRequest,
},
EthRequest,
},
types::{
AnvilMetadata, EvmMineOptions, ForkedNetwork, Forking, Index, NodeEnvironment,
NodeForkConfig, NodeInfo, Work,
},
};
use anvil_rpc::{error::RpcError, response::ResponseResult};
use ethers::{
abi::ethereum_types::H64,
prelude::{DefaultFrame, TxpoolInspect},
providers::ProviderError,
types::{
transaction::{
eip2930::{AccessList, AccessListWithGasUsed},
eip712::TypedData,
},
Address, Block, BlockId, BlockNumber, Bytes, FeeHistory, Filter, FilteredParams,
GethDebugTracingOptions, GethTrace, Log, Trace, Transaction, TransactionReceipt, TxHash,
TxpoolContent, TxpoolInspectSummary, TxpoolStatus, H256, U256, U64,
},
utils::rlp,
};
use foundry_common::ProviderBuilder;
use foundry_evm::{
backend::DatabaseError,
revm::{
db::DatabaseRef,
interpreter::{return_ok, return_revert, InstructionResult},
primitives::BlockEnv,
},
};
use foundry_utils::types::ToEthers;
use futures::channel::{mpsc::Receiver, oneshot};
use parking_lot::RwLock;
use std::{collections::HashSet, future::Future, sync::Arc, time::Duration};
/// The client version: `anvil/v{major}.{minor}.{patch}`
pub const CLIENT_VERSION: &str = concat!("anvil/v", env!("CARGO_PKG_VERSION"));
/// The entry point for executing eth api RPC call - The Eth RPC interface.
///
/// This type is cheap to clone and can be used concurrently
#[derive(Clone)]
pub struct EthApi {
/// The transaction pool
pool: Arc<Pool>,
/// Holds all blockchain related data
/// In-Memory only for now
pub(super) backend: Arc<backend::mem::Backend>,
/// Whether this node is mining
is_mining: bool,
/// available signers
signers: Arc<Vec<Box<dyn Signer>>>,
/// data required for `eth_feeHistory`
fee_history_cache: FeeHistoryCache,
/// max number of items kept in fee cache
fee_history_limit: u64,
/// access to the actual miner
///
/// This access is required in order to adjust miner settings based on requests received from
/// custom RPC endpoints
miner: Miner,
/// allows to enabled/disable logging
logger: LoggingManager,
/// Tracks all active filters
filters: Filters,
/// How transactions are ordered in the pool
transaction_order: Arc<RwLock<TransactionOrder>>,
/// Whether we're listening for RPC calls
net_listening: bool,
/// The instance ID. Changes on every reset.
instance_id: Arc<RwLock<H256>>,
}
// === impl Eth RPC API ===
impl EthApi {
/// Creates a new instance
#[allow(clippy::too_many_arguments)]
pub fn new(
pool: Arc<Pool>,
backend: Arc<backend::mem::Backend>,
signers: Arc<Vec<Box<dyn Signer>>>,
fee_history_cache: FeeHistoryCache,
fee_history_limit: u64,
miner: Miner,
logger: LoggingManager,
filters: Filters,
transactions_order: TransactionOrder,
) -> Self {
Self {
pool,
backend,
is_mining: true,
signers,
fee_history_cache,
fee_history_limit,
miner,
logger,
filters,
net_listening: true,
transaction_order: Arc::new(RwLock::new(transactions_order)),
instance_id: Arc::new(RwLock::new(H256::random())),
}
}
/// Executes the [EthRequest] and returns an RPC [RpcResponse]
pub async fn execute(&self, request: EthRequest) -> ResponseResult {
trace!(target: "rpc::api", "executing eth request");
match request {
EthRequest::Web3ClientVersion(()) => self.client_version().to_rpc_result(),
EthRequest::Web3Sha3(content) => self.sha3(content).to_rpc_result(),
EthRequest::EthGetBalance(addr, block) => {
self.balance(addr, block).await.to_rpc_result()
}
EthRequest::EthGetTransactionByHash(hash) => {
self.transaction_by_hash(hash).await.to_rpc_result()
}
EthRequest::EthSendTransaction(request) => {
self.send_transaction(*request).await.to_rpc_result()
}
EthRequest::EthChainId(_) => self.eth_chain_id().to_rpc_result(),
EthRequest::EthNetworkId(_) => self.network_id().to_rpc_result(),
EthRequest::NetListening(_) => self.net_listening().to_rpc_result(),
EthRequest::EthGasPrice(_) => self.eth_gas_price().to_rpc_result(),
EthRequest::EthMaxPriorityFeePerGas(_) => {
self.gas_max_priority_fee_per_gas().to_rpc_result()
}
EthRequest::EthAccounts(_) => self.accounts().to_rpc_result(),
EthRequest::EthBlockNumber(_) => self.block_number().to_rpc_result(),
EthRequest::EthGetStorageAt(addr, slot, block) => {
self.storage_at(addr, slot, block).await.to_rpc_result()
}
EthRequest::EthGetBlockByHash(hash, full) => {
if full {
self.block_by_hash_full(hash).await.to_rpc_result()
} else {
self.block_by_hash(hash).await.to_rpc_result()
}
}
EthRequest::EthGetBlockByNumber(num, full) => {
if full {
self.block_by_number_full(num).await.to_rpc_result()
} else {
self.block_by_number(num).await.to_rpc_result()
}
}
EthRequest::EthGetTransactionCount(addr, block) => {
self.transaction_count(addr, block).await.to_rpc_result()
}
EthRequest::EthGetTransactionCountByHash(hash) => {
self.block_transaction_count_by_hash(hash).await.to_rpc_result()
}
EthRequest::EthGetTransactionCountByNumber(num) => {
self.block_transaction_count_by_number(num).await.to_rpc_result()
}
EthRequest::EthGetUnclesCountByHash(hash) => {
self.block_uncles_count_by_hash(hash).await.to_rpc_result()
}
EthRequest::EthGetUnclesCountByNumber(num) => {
self.block_uncles_count_by_number(num).await.to_rpc_result()
}
EthRequest::EthGetCodeAt(addr, block) => {
self.get_code(addr, block).await.to_rpc_result()
}
EthRequest::EthGetProof(addr, keys, block) => {
self.get_proof(addr, keys, block).await.to_rpc_result()
}
EthRequest::EthSign(addr, content) => self.sign(addr, content).await.to_rpc_result(),
EthRequest::EthSignTransaction(request) => {
self.sign_transaction(*request).await.to_rpc_result()
}
EthRequest::EthSignTypedData(addr, data) => {
self.sign_typed_data(addr, data).await.to_rpc_result()
}
EthRequest::EthSignTypedDataV3(addr, data) => {
self.sign_typed_data_v3(addr, data).await.to_rpc_result()
}
EthRequest::EthSignTypedDataV4(addr, data) => {
self.sign_typed_data_v4(addr, &data).await.to_rpc_result()
}
EthRequest::EthSendRawTransaction(tx) => {
self.send_raw_transaction(tx).await.to_rpc_result()
}
EthRequest::EthCall(call, block, overrides) => {
self.call(call, block, overrides).await.to_rpc_result()
}
EthRequest::EthCreateAccessList(call, block) => {
self.create_access_list(call, block).await.to_rpc_result()
}
EthRequest::EthEstimateGas(call, block) => {
self.estimate_gas(call, block).await.to_rpc_result()
}
EthRequest::EthGetTransactionByBlockHashAndIndex(hash, index) => {
self.transaction_by_block_hash_and_index(hash, index).await.to_rpc_result()
}
EthRequest::EthGetTransactionByBlockNumberAndIndex(num, index) => {
self.transaction_by_block_number_and_index(num, index).await.to_rpc_result()
}
EthRequest::EthGetTransactionReceipt(tx) => {
self.transaction_receipt(tx).await.to_rpc_result()
}
EthRequest::EthGetUncleByBlockHashAndIndex(hash, index) => {
self.uncle_by_block_hash_and_index(hash, index).await.to_rpc_result()
}
EthRequest::EthGetUncleByBlockNumberAndIndex(num, index) => {
self.uncle_by_block_number_and_index(num, index).await.to_rpc_result()
}
EthRequest::EthGetLogs(filter) => self.logs(filter).await.to_rpc_result(),
EthRequest::EthGetWork(_) => self.work().to_rpc_result(),
EthRequest::EthSyncing(_) => self.syncing().to_rpc_result(),
EthRequest::EthSubmitWork(nonce, pow, digest) => {
self.submit_work(nonce, pow, digest).to_rpc_result()
}
EthRequest::EthSubmitHashRate(rate, id) => {
self.submit_hashrate(rate, id).to_rpc_result()
}
EthRequest::EthFeeHistory(count, newest, reward_percentiles) => {
self.fee_history(count, newest, reward_percentiles).await.to_rpc_result()
}
// non eth-standard rpc calls
EthRequest::DebugTraceTransaction(tx, opts) => {
self.debug_trace_transaction(tx, opts).await.to_rpc_result()
}
// non eth-standard rpc calls
EthRequest::DebugTraceCall(tx, block, opts) => {
self.debug_trace_call(tx, block, opts).await.to_rpc_result()
}
EthRequest::TraceTransaction(tx) => self.trace_transaction(tx).await.to_rpc_result(),
EthRequest::TraceBlock(block) => self.trace_block(block).await.to_rpc_result(),
EthRequest::ImpersonateAccount(addr) => {
self.anvil_impersonate_account(addr).await.to_rpc_result()
}
EthRequest::StopImpersonatingAccount(addr) => {
self.anvil_stop_impersonating_account(addr).await.to_rpc_result()
}
EthRequest::AutoImpersonateAccount(enable) => {
self.anvil_auto_impersonate_account(enable).await.to_rpc_result()
}
EthRequest::GetAutoMine(()) => self.anvil_get_auto_mine().to_rpc_result(),
EthRequest::Mine(blocks, interval) => {
self.anvil_mine(blocks, interval).await.to_rpc_result()
}
EthRequest::SetAutomine(enabled) => {
self.anvil_set_auto_mine(enabled).await.to_rpc_result()
}
EthRequest::SetIntervalMining(interval) => {
self.anvil_set_interval_mining(interval).to_rpc_result()
}
EthRequest::DropTransaction(tx) => {
self.anvil_drop_transaction(tx).await.to_rpc_result()
}
EthRequest::Reset(fork) => {
self.anvil_reset(fork.and_then(|p| p.params)).await.to_rpc_result()
}
EthRequest::SetBalance(addr, val) => {
self.anvil_set_balance(addr, val).await.to_rpc_result()
}
EthRequest::SetCode(addr, code) => {
self.anvil_set_code(addr, code).await.to_rpc_result()
}
EthRequest::SetNonce(addr, nonce) => {
self.anvil_set_nonce(addr, nonce).await.to_rpc_result()
}
EthRequest::SetStorageAt(addr, slot, val) => {
self.anvil_set_storage_at(addr, slot, val).await.to_rpc_result()
}
EthRequest::SetCoinbase(addr) => self.anvil_set_coinbase(addr).await.to_rpc_result(),
EthRequest::SetChainId(id) => self.anvil_set_chain_id(id).await.to_rpc_result(),
EthRequest::SetLogging(log) => self.anvil_set_logging(log).await.to_rpc_result(),
EthRequest::SetMinGasPrice(gas) => {
self.anvil_set_min_gas_price(gas).await.to_rpc_result()
}
EthRequest::SetNextBlockBaseFeePerGas(gas) => {
self.anvil_set_next_block_base_fee_per_gas(gas).await.to_rpc_result()
}
EthRequest::DumpState(_) => self.anvil_dump_state().await.to_rpc_result(),
EthRequest::LoadState(buf) => self.anvil_load_state(buf).await.to_rpc_result(),
EthRequest::NodeInfo(_) => self.anvil_node_info().await.to_rpc_result(),
EthRequest::AnvilMetadata(_) => self.anvil_metadata().await.to_rpc_result(),
EthRequest::EvmSnapshot(_) => self.evm_snapshot().await.to_rpc_result(),
EthRequest::EvmRevert(id) => self.evm_revert(id).await.to_rpc_result(),
EthRequest::EvmIncreaseTime(time) => self.evm_increase_time(time).await.to_rpc_result(),
EthRequest::EvmSetNextBlockTimeStamp(time) => {
match u64::try_from(time).map_err(BlockchainError::UintConversion) {
Ok(time) => self.evm_set_next_block_timestamp(time).to_rpc_result(),
err @ Err(_) => err.to_rpc_result(),
}
}
EthRequest::EvmSetTime(timestamp) => {
match u64::try_from(timestamp).map_err(BlockchainError::UintConversion) {
Ok(timestamp) => self.evm_set_time(timestamp).to_rpc_result(),
err @ Err(_) => err.to_rpc_result(),
}
}
EthRequest::EvmSetBlockGasLimit(gas_limit) => {
self.evm_set_block_gas_limit(gas_limit).to_rpc_result()
}
EthRequest::EvmSetBlockTimeStampInterval(time) => {
self.evm_set_block_timestamp_interval(time).to_rpc_result()
}
EthRequest::EvmRemoveBlockTimeStampInterval(()) => {
self.evm_remove_block_timestamp_interval().to_rpc_result()
}
EthRequest::EvmMine(mine) => {
self.evm_mine(mine.and_then(|p| p.params)).await.to_rpc_result()
}
EthRequest::EvmMineDetailed(mine) => {
self.evm_mine_detailed(mine.and_then(|p| p.params)).await.to_rpc_result()
}
EthRequest::SetRpcUrl(url) => self.anvil_set_rpc_url(url).to_rpc_result(),
EthRequest::EthSendUnsignedTransaction(tx) => {
self.eth_send_unsigned_transaction(*tx).await.to_rpc_result()
}
EthRequest::EnableTraces(_) => self.anvil_enable_traces().await.to_rpc_result(),
EthRequest::EthNewFilter(filter) => self.new_filter(filter).await.to_rpc_result(),
EthRequest::EthGetFilterChanges(id) => self.get_filter_changes(&id).await,
EthRequest::EthNewBlockFilter(_) => self.new_block_filter().await.to_rpc_result(),
EthRequest::EthNewPendingTransactionFilter(_) => {
self.new_pending_transaction_filter().await.to_rpc_result()
}
EthRequest::EthGetFilterLogs(id) => self.get_filter_logs(&id).await.to_rpc_result(),
EthRequest::EthUninstallFilter(id) => self.uninstall_filter(&id).await.to_rpc_result(),
EthRequest::TxPoolStatus(_) => self.txpool_status().await.to_rpc_result(),
EthRequest::TxPoolInspect(_) => self.txpool_inspect().await.to_rpc_result(),
EthRequest::TxPoolContent(_) => self.txpool_content().await.to_rpc_result(),
EthRequest::ErigonGetHeaderByNumber(num) => {
self.erigon_get_header_by_number(num).await.to_rpc_result()
}
EthRequest::OtsGetApiLevel(_) => self.ots_get_api_level().await.to_rpc_result(),
EthRequest::OtsGetInternalOperations(hash) => {
self.ots_get_internal_operations(hash).await.to_rpc_result()
}
EthRequest::OtsHasCode(addr, num) => self.ots_has_code(addr, num).await.to_rpc_result(),
EthRequest::OtsTraceTransaction(hash) => {
self.ots_trace_transaction(hash).await.to_rpc_result()
}
EthRequest::OtsGetTransactionError(hash) => {
self.ots_get_transaction_error(hash).await.to_rpc_result()
}
EthRequest::OtsGetBlockDetails(num) => {
self.ots_get_block_details(num).await.to_rpc_result()
}
EthRequest::OtsGetBlockDetailsByHash(hash) => {
self.ots_get_block_details_by_hash(hash).await.to_rpc_result()
}
EthRequest::OtsGetBlockTransactions(num, page, page_size) => {
self.ots_get_block_transactions(num, page, page_size).await.to_rpc_result()
}
EthRequest::OtsSearchTransactionsBefore(address, num, page_size) => {
self.ots_search_transactions_before(address, num, page_size).await.to_rpc_result()
}
EthRequest::OtsSearchTransactionsAfter(address, num, page_size) => {
self.ots_search_transactions_after(address, num, page_size).await.to_rpc_result()
}
EthRequest::OtsGetTransactionBySenderAndNonce(address, nonce) => {
self.ots_get_transaction_by_sender_and_nonce(address, nonce).await.to_rpc_result()
}
EthRequest::OtsGetContractCreator(address) => {
self.ots_get_contract_creator(address).await.to_rpc_result()
}
}
}
fn sign_request(
&self,
from: &Address,
request: TypedTransactionRequest,
) -> Result<TypedTransaction> {
for signer in self.signers.iter() {
if signer.accounts().contains(from) {
let signature = signer.sign_transaction(request.clone(), from)?;
return build_typed_transaction(request, signature)
}
}
Err(BlockchainError::NoSignerAvailable)
}
/// Queries the current gas limit
fn current_gas_limit(&self) -> Result<U256> {
Ok(self.backend.gas_limit())
}
async fn block_request(&self, block_number: Option<BlockId>) -> Result<BlockRequest> {
let block_request = match block_number {
Some(BlockId::Number(BlockNumber::Pending)) => {
let pending_txs = self.pool.ready_transactions().collect();
BlockRequest::Pending(pending_txs)
}
_ => {
let number = self.backend.ensure_block_number(block_number).await?;
BlockRequest::Number(number.into())
}
};
Ok(block_request)
}
/// Returns the current client version.
///
/// Handler for ETH RPC call: `web3_clientVersion`
pub fn client_version(&self) -> Result<String> {
node_info!("web3_clientVersion");
Ok(CLIENT_VERSION.to_string())
}
/// Returns Keccak-256 (not the standardized SHA3-256) of the given data.
///
/// Handler for ETH RPC call: `web3_sha3`
pub fn sha3(&self, bytes: Bytes) -> Result<String> {
node_info!("web3_sha3");
let hash = ethers::utils::keccak256(bytes.as_ref());
Ok(ethers::utils::hex::encode(&hash[..]))
}
/// Returns protocol version encoded as a string (quotes are necessary).
///
/// Handler for ETH RPC call: `eth_protocolVersion`
pub fn protocol_version(&self) -> Result<u64> {
node_info!("eth_protocolVersion");
Ok(1)
}
/// Returns the number of hashes per second that the node is mining with.
///
/// Handler for ETH RPC call: `eth_hashrate`
pub fn hashrate(&self) -> Result<U256> {
node_info!("eth_hashrate");
Ok(U256::zero())
}
/// Returns the client coinbase address.
///
/// Handler for ETH RPC call: `eth_coinbase`
pub fn author(&self) -> Result<Address> {
node_info!("eth_coinbase");
Ok(self.backend.coinbase())
}
/// Returns true if client is actively mining new blocks.
///
/// Handler for ETH RPC call: `eth_mining`
pub fn is_mining(&self) -> Result<bool> {
node_info!("eth_mining");
Ok(self.is_mining)
}
/// Returns the chain ID used for transaction signing at the
/// current best block. None is returned if not
/// available.
///
/// Handler for ETH RPC call: `eth_chainId`
pub fn eth_chain_id(&self) -> Result<Option<U64>> {
node_info!("eth_chainId");
Ok(Some(self.backend.chain_id().as_u64().into()))
}
/// Returns the same as `chain_id`
///
/// Handler for ETH RPC call: `eth_networkId`
pub fn network_id(&self) -> Result<Option<String>> {
node_info!("eth_networkId");
let chain_id = self.backend.chain_id().as_u64();
Ok(Some(format!("{chain_id}")))
}
/// Returns true if client is actively listening for network connections.
///
/// Handler for ETH RPC call: `net_listening`
pub fn net_listening(&self) -> Result<bool> {
node_info!("net_listening");
Ok(self.net_listening)
}
/// Returns the current gas price
fn eth_gas_price(&self) -> Result<U256> {
node_info!("eth_gasPrice");
self.gas_price()
}
/// Returns the current gas price
pub fn gas_price(&self) -> Result<U256> {
Ok(self.backend.gas_price())
}
/// Returns a fee per gas that is an estimate of how much you can pay as a priority fee, or
/// 'tip', to get a transaction included in the current block.
///
/// Handler for ETH RPC call: `eth_maxPriorityFeePerGas`
pub fn gas_max_priority_fee_per_gas(&self) -> Result<U256> {
Ok(self.backend.max_priority_fee_per_gas())
}
/// Returns the block gas limit
pub fn gas_limit(&self) -> U256 {
self.backend.gas_limit()
}
/// Returns the accounts list
///
/// Handler for ETH RPC call: `eth_accounts`
pub fn accounts(&self) -> Result<Vec<Address>> {
node_info!("eth_accounts");
let mut unique = HashSet::new();
let mut accounts = Vec::new();
for signer in self.signers.iter() {
accounts.extend(signer.accounts().into_iter().filter(|acc| unique.insert(*acc)));
}
accounts.extend(
self.backend
.cheats()
.impersonated_accounts()
.into_iter()
.filter(|acc| unique.insert(*acc)),
);
Ok(accounts)
}
/// Returns the number of most recent block.
///
/// Handler for ETH RPC call: `eth_blockNumber`
pub fn block_number(&self) -> Result<U256> {
node_info!("eth_blockNumber");
Ok(self.backend.best_number().as_u64().into())
}
/// Returns balance of the given account.
///
/// Handler for ETH RPC call: `eth_getBalance`
pub async fn balance(&self, address: Address, block_number: Option<BlockId>) -> Result<U256> {
node_info!("eth_getBalance");
let block_request = self.block_request(block_number).await?;
// check if the number predates the fork, if in fork mode
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
if fork.predates_fork(number.as_u64()) {
return Ok(fork.get_balance(address, number.as_u64()).await?)
}
}
}
self.backend.get_balance(address, Some(block_request)).await
}
/// Returns content of the storage at given address.
///
/// Handler for ETH RPC call: `eth_getStorageAt`
pub async fn storage_at(
&self,
address: Address,
index: U256,
block_number: Option<BlockId>,
) -> Result<H256> {
node_info!("eth_getStorageAt");
let block_request = self.block_request(block_number).await?;
// check if the number predates the fork, if in fork mode
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
if fork.predates_fork(number.as_u64()) {
return Ok(fork
.storage_at(address, index, Some(BlockNumber::Number(*number)))
.await?)
}
}
}
self.backend.storage_at(address, index, Some(block_request)).await
}
/// Returns block with given hash.
///
/// Handler for ETH RPC call: `eth_getBlockByHash`
pub async fn block_by_hash(&self, hash: H256) -> Result<Option<Block<TxHash>>> {
node_info!("eth_getBlockByHash");
self.backend.block_by_hash(hash).await
}
/// Returns a _full_ block with given hash.
///
/// Handler for ETH RPC call: `eth_getBlockByHash`
pub async fn block_by_hash_full(&self, hash: H256) -> Result<Option<Block<Transaction>>> {
node_info!("eth_getBlockByHash");
self.backend.block_by_hash_full(hash).await
}
/// Returns block with given number.
///
/// Handler for ETH RPC call: `eth_getBlockByNumber`
pub async fn block_by_number(&self, number: BlockNumber) -> Result<Option<Block<TxHash>>> {
node_info!("eth_getBlockByNumber");
if number == BlockNumber::Pending {
return Ok(Some(self.pending_block().await))
}
self.backend.block_by_number(number).await
}
/// Returns a _full_ block with given number
///
/// Handler for ETH RPC call: `eth_getBlockByNumber`
pub async fn block_by_number_full(
&self,
number: BlockNumber,
) -> Result<Option<Block<Transaction>>> {
node_info!("eth_getBlockByNumber");
if number == BlockNumber::Pending {
return Ok(self.pending_block_full().await)
}
self.backend.block_by_number_full(number).await
}
/// Returns the number of transactions sent from given address at given time (block number).
///
/// Also checks the pending transactions if `block_number` is
/// `BlockId::Number(BlockNumber::Pending)`
///
/// Handler for ETH RPC call: `eth_getTransactionCount`
pub async fn transaction_count(
&self,
address: Address,
block_number: Option<BlockId>,
) -> Result<U256> {
node_info!("eth_getTransactionCount");
self.get_transaction_count(address, block_number).await
}
/// Returns the number of transactions in a block with given hash.
///
/// Handler for ETH RPC call: `eth_getBlockTransactionCountByHash`
pub async fn block_transaction_count_by_hash(&self, hash: H256) -> Result<Option<U256>> {
node_info!("eth_getBlockTransactionCountByHash");
let block = self.backend.block_by_hash(hash).await?;
Ok(block.map(|b| b.transactions.len().into()))
}
/// Returns the number of transactions in a block with given block number.
///
/// Handler for ETH RPC call: `eth_getBlockTransactionCountByNumber`
pub async fn block_transaction_count_by_number(
&self,
block_number: BlockNumber,
) -> Result<Option<U256>> {
node_info!("eth_getBlockTransactionCountByNumber");
let block_request = self.block_request(Some(block_number.into())).await?;
if let BlockRequest::Pending(txs) = block_request {
let block = self.backend.pending_block(txs).await;
return Ok(Some(block.transactions.len().into()))
}
let block = self.backend.block_by_number(block_number).await?;
Ok(block.map(|b| b.transactions.len().into()))
}
/// Returns the number of uncles in a block with given hash.
///
/// Handler for ETH RPC call: `eth_getUncleCountByBlockHash`
pub async fn block_uncles_count_by_hash(&self, hash: H256) -> Result<U256> {
node_info!("eth_getUncleCountByBlockHash");
let block =
self.backend.block_by_hash(hash).await?.ok_or(BlockchainError::BlockNotFound)?;
Ok(block.uncles.len().into())
}
/// Returns the number of uncles in a block with given block number.
///
/// Handler for ETH RPC call: `eth_getUncleCountByBlockNumber`
pub async fn block_uncles_count_by_number(&self, block_number: BlockNumber) -> Result<U256> {
node_info!("eth_getUncleCountByBlockNumber");
let block = self
.backend
.block_by_number(block_number)
.await?
.ok_or(BlockchainError::BlockNotFound)?;
Ok(block.uncles.len().into())
}
/// Returns the code at given address at given time (block number).
///
/// Handler for ETH RPC call: `eth_getCode`
pub async fn get_code(&self, address: Address, block_number: Option<BlockId>) -> Result<Bytes> {
node_info!("eth_getCode");
let block_request = self.block_request(block_number).await?;
// check if the number predates the fork, if in fork mode
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
if fork.predates_fork(number.as_u64()) {
return Ok(fork.get_code(address, number.as_u64()).await?)
}
}
}
self.backend.get_code(address, Some(block_request)).await
}
/// Returns the account and storage values of the specified account including the Merkle-proof.
/// This call can be used to verify that the data you are pulling from is not tampered with.
///
/// Handler for ETH RPC call: `eth_getProof`
pub async fn get_proof(
&self,
address: Address,
keys: Vec<H256>,
block_number: Option<BlockId>,
) -> Result<AccountProof> {
node_info!("eth_getProof");
let block_request = self.block_request(block_number).await?;
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
// if we're in forking mode, or still on the forked block (no blocks mined yet) then
// we can delegate the call
if fork.predates_fork_inclusive(number.as_u64()) {
return Ok(fork.get_proof(address, keys, Some((*number).into())).await?)
}
}
}
let proof = self.backend.prove_account_at(address, keys, Some(block_request)).await?;
Ok(proof)
}
/// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md).
///
/// Handler for ETH RPC call: `eth_signTypedData`
pub async fn sign_typed_data(
&self,
_address: Address,
_data: serde_json::Value,
) -> Result<String> {
node_info!("eth_signTypedData");
Err(BlockchainError::RpcUnimplemented)
}
/// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md).
///
/// Handler for ETH RPC call: `eth_signTypedData_v3`
pub async fn sign_typed_data_v3(
&self,
_address: Address,
_data: serde_json::Value,
) -> Result<String> {
node_info!("eth_signTypedData_v3");
Err(BlockchainError::RpcUnimplemented)
}
/// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md), and includes full support of arrays and recursive data structures.
///
/// Handler for ETH RPC call: `eth_signTypedData_v4`
pub async fn sign_typed_data_v4(&self, address: Address, data: &TypedData) -> Result<String> {
node_info!("eth_signTypedData_v4");
let signer = self.get_signer(address).ok_or(BlockchainError::NoSignerAvailable)?;
let signature = signer.sign_typed_data(address, data).await?;
Ok(format!("0x{signature}"))
}
/// The sign method calculates an Ethereum specific signature
///
/// Handler for ETH RPC call: `eth_sign`
pub async fn sign(&self, address: Address, content: impl AsRef<[u8]>) -> Result<String> {
node_info!("eth_sign");
let signer = self.get_signer(address).ok_or(BlockchainError::NoSignerAvailable)?;
let signature = signer.sign(address, content.as_ref()).await?;
Ok(format!("0x{signature}"))
}
/// Signs a transaction
///
/// Handler for ETH RPC call: `eth_signTransaction`
pub async fn sign_transaction(&self, request: EthTransactionRequest) -> Result<String> {
node_info!("eth_signTransaction");
let from = request.from.map(Ok).unwrap_or_else(|| {
self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable)
})?;
let (nonce, _) = self.request_nonce(&request, from).await?;
let request = self.build_typed_tx_request(request, nonce)?;
let signer = self.get_signer(from).ok_or(BlockchainError::NoSignerAvailable)?;
let signature = signer.sign_transaction(request, &from)?;
Ok(format!("0x{signature}"))
}
/// Sends a transaction
///
/// Handler for ETH RPC call: `eth_sendTransaction`
pub async fn send_transaction(&self, request: EthTransactionRequest) -> Result<TxHash> {
node_info!("eth_sendTransaction");
let from = request.from.map(Ok).unwrap_or_else(|| {
self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable)
})?;
let (nonce, on_chain_nonce) = self.request_nonce(&request, from).await?;
let request = self.build_typed_tx_request(request, nonce)?;
// if the sender is currently impersonated we need to "bypass" signing
let pending_transaction = if self.is_impersonated(from) {
let bypass_signature = self.backend.cheats().bypass_signature();
let transaction = sign::build_typed_transaction(request, bypass_signature)?;
self.ensure_typed_transaction_supported(&transaction)?;
trace!(target : "node", ?from, "eth_sendTransaction: impersonating");
PendingTransaction::with_impersonated(transaction, from)
} else {
let transaction = self.sign_request(&from, request)?;
self.ensure_typed_transaction_supported(&transaction)?;
PendingTransaction::new(transaction)?
};
// pre-validate
self.backend.validate_pool_transaction(&pending_transaction).await?;
let requires = required_marker(nonce, on_chain_nonce, from);
let provides = vec![to_marker(nonce.as_u64(), from)];
debug_assert!(requires != provides);
self.add_pending_transaction(pending_transaction, requires, provides)
}
/// Sends signed transaction, returning its hash.
///
/// Handler for ETH RPC call: `eth_sendRawTransaction`
pub async fn send_raw_transaction(&self, tx: Bytes) -> Result<TxHash> {
node_info!("eth_sendRawTransaction");
let data = tx.as_ref();
if data.is_empty() {
return Err(BlockchainError::EmptyRawTransactionData)
}
let transaction = if data[0] > 0x7f {
// legacy transaction
match rlp::decode::<LegacyTransaction>(data) {
Ok(transaction) => TypedTransaction::Legacy(transaction),
Err(_) => return Err(BlockchainError::FailedToDecodeSignedTransaction),
}
} else {
// the [TypedTransaction] requires a valid rlp input,
// but EIP-1559 prepends a version byte, so we need to encode the data first to get a
// valid rlp and then rlp decode impl of `TypedTransaction` will remove and check the
// version byte
let extend = rlp::encode(&data);
let tx = match rlp::decode::<TypedTransaction>(&extend[..]) {
Ok(transaction) => transaction,
Err(_) => return Err(BlockchainError::FailedToDecodeSignedTransaction),
};
self.ensure_typed_transaction_supported(&tx)?;
tx
};
let pending_transaction = PendingTransaction::new(transaction)?;
// pre-validate
self.backend.validate_pool_transaction(&pending_transaction).await?;
let on_chain_nonce = self.backend.current_nonce(*pending_transaction.sender()).await?;
let from = *pending_transaction.sender();
let nonce = *pending_transaction.transaction.nonce();
let requires = required_marker(nonce, on_chain_nonce, from);
let priority = self.transaction_priority(&pending_transaction.transaction);
let pool_transaction = PoolTransaction {
requires,
provides: vec![to_marker(nonce.as_u64(), *pending_transaction.sender())],
pending_transaction,
priority,
};
let tx = self.pool.add_transaction(pool_transaction)?;
trace!(target: "node", "Added transaction: [{:?}] sender={:?}", tx.hash(), from);
Ok(*tx.hash())
}
/// Call contract, returning the output data.
///
/// Handler for ETH RPC call: `eth_call`
pub async fn call(
&self,
request: EthTransactionRequest,
block_number: Option<BlockId>,
overrides: Option<StateOverride>,
) -> Result<Bytes> {
node_info!("eth_call");
let block_request = self.block_request(block_number).await?;
// check if the number predates the fork, if in fork mode
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
if fork.predates_fork(number.as_u64()) {
if overrides.is_some() {
return Err(BlockchainError::StateOverrideError(
"not available on past forked blocks".to_string(),
))
}
return Ok(fork.call(&request, Some(number.into())).await?)
}
}
}
let fees = FeeDetails::new(
request.gas_price,
request.max_fee_per_gas,
request.max_priority_fee_per_gas,
)?
.or_zero_fees();
// this can be blocking for a bit, especially in forking mode
// <https://github.com/foundry-rs/foundry/issues/6036>
self.on_blocking_task(|this| async move {
let (exit, out, gas, _) =
this.backend.call(request, fees, Some(block_request), overrides).await?;
trace!(target : "node", "Call status {:?}, gas {}", exit, gas);
ensure_return_ok(exit, &out)
})
.await
}
/// This method creates an EIP2930 type accessList based on a given Transaction. The accessList
/// contains all storage slots and addresses read and written by the transaction, except for the
/// sender account and the precompiles.
///
/// It returns list of addresses and storage keys used by the transaction, plus the gas
/// consumed when the access list is added. That is, it gives you the list of addresses and
/// storage keys that will be used by that transaction, plus the gas consumed if the access
/// list is included. Like eth_estimateGas, this is an estimation; the list could change
/// when the transaction is actually mined. Adding an accessList to your transaction does
/// not necessary result in lower gas usage compared to a transaction without an access
/// list.
///
/// Handler for ETH RPC call: `eth_createAccessList`
pub async fn create_access_list(
&self,
mut request: EthTransactionRequest,
block_number: Option<BlockId>,
) -> Result<AccessListWithGasUsed> {
node_info!("eth_createAccessList");
let block_request = self.block_request(block_number).await?;
// check if the number predates the fork, if in fork mode
if let BlockRequest::Number(number) = &block_request {
if let Some(fork) = self.get_fork() {
if fork.predates_fork(number.as_u64()) {
return Ok(fork.create_access_list(&request, Some(number.into())).await?)
}
}
}
self.backend
.with_database_at(Some(block_request), |state, block_env| {
let (exit, out, _, access_list) = self.backend.build_access_list_with_state(
&state,
request.clone(),
FeeDetails::zero(),
block_env.clone(),
)?;
ensure_return_ok(exit, &out)?;
// execute again but with access list set