-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
mod.rs
2956 lines (2584 loc) · 124 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 self::state::trie_storage;
use super::executor::new_evm_with_inspector_ref;
use crate::{
config::PruneStateHistoryConfig,
eth::{
backend::{
cheats::CheatsManager,
db::{Db, MaybeFullDatabase, SerializableState},
executor::{ExecutedTransactions, TransactionExecutor},
fork::ClientFork,
genesis::GenesisConfig,
mem::{
state::{storage_root, trie_accounts},
storage::MinedTransactionReceipt,
},
notifications::{NewBlockNotification, NewBlockNotifications},
time::{utc_from_secs, TimeManager},
validate::TransactionValidator,
},
error::{BlockchainError, ErrDetail, InvalidTransactionError},
fees::{FeeDetails, FeeManager, MIN_SUGGESTED_PRIORITY_FEE},
macros::node_info,
pool::transactions::PoolTransaction,
util::get_precompiles_for,
},
inject_precompiles,
mem::{
inspector::Inspector,
storage::{BlockchainStorage, InMemoryBlockStates, MinedBlockOutcome},
},
revm::{db::DatabaseRef, primitives::AccountInfo},
ForkChoice, NodeConfig, PrecompileFactory,
};
use alloy_chains::NamedChain;
use alloy_consensus::{Account, Header, Receipt, ReceiptWithBloom};
use alloy_eips::eip4844::MAX_BLOBS_PER_BLOCK;
use alloy_network::EthereumWallet;
use alloy_primitives::{
address, hex, keccak256, utils::Unit, Address, Bytes, TxHash, TxKind, B256, U256, U64,
};
use alloy_rpc_types::{
anvil::Forking,
request::TransactionRequest,
serde_helpers::JsonStorageKey,
state::StateOverride,
trace::{
filter::TraceFilter,
geth::{
GethDebugBuiltInTracerType, GethDebugTracerType, GethDebugTracingCallOptions,
GethDebugTracingOptions, GethTrace, NoopFrame,
},
parity::LocalizedTransactionTrace,
},
AccessList, AnyNetworkBlock, Block as AlloyBlock, BlockId, BlockNumberOrTag as BlockNumber,
BlockTransactions, EIP1186AccountProofResponse as AccountProof,
EIP1186StorageProof as StorageProof, Filter, FilteredParams, Header as AlloyHeader, Index, Log,
Transaction, TransactionReceipt,
};
use alloy_serde::WithOtherFields;
use alloy_signer_local::PrivateKeySigner;
use alloy_trie::{proof::ProofRetainer, HashBuilder, Nibbles};
use anvil_core::eth::{
block::{Block, BlockInfo},
transaction::{
DepositReceipt, MaybeImpersonatedTransaction, PendingTransaction, ReceiptResponse,
TransactionInfo, TypedReceipt, TypedTransaction,
},
utils::meets_eip155,
wallet::{Capabilities, DelegationCapability, WalletCapabilities},
};
use anvil_rpc::error::RpcError;
use chrono::Datelike;
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use foundry_evm::{
backend::{DatabaseError, DatabaseResult, RevertStateSnapshotAction},
constants::DEFAULT_CREATE2_DEPLOYER_RUNTIME_CODE,
decode::RevertDecoder,
inspectors::AccessListInspector,
revm::{
db::CacheDB,
interpreter::InstructionResult,
primitives::{
BlockEnv, CfgEnvWithHandlerCfg, EnvWithHandlerCfg, ExecutionResult, Output, SpecId,
TxEnv, KECCAK_EMPTY,
},
},
traces::TracingInspectorConfig,
};
use futures::channel::mpsc::{unbounded, UnboundedSender};
use parking_lot::{Mutex, RwLock};
use revm::{
db::WrapDatabaseRef,
primitives::{
calc_blob_gasprice, BlobExcessGasAndPrice, HashMap, OptimismFields, ResultAndState,
},
};
use std::{
collections::BTreeMap,
io::{Read, Write},
sync::Arc,
time::Duration,
};
use storage::{Blockchain, MinedTransaction, DEFAULT_HISTORY_LIMIT};
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;
// 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;
// Executor
pub const EXECUTOR: Address = address!("6634F723546eCc92277e8a2F93d4f248bf1189ea");
pub const EXECUTOR_PK: &str = "0x502d47e1421cb9abef497096728e69f07543232b93ef24de4998e18b5fd9ba0f";
// P256 Batch Delegation Contract: https://odyssey-explorer.ithaca.xyz/address/0x35202a6E6317F3CC3a177EeEE562D3BcDA4a6FcC
pub const P256_DELEGATION_CONTRACT: Address = address!("35202a6e6317f3cc3a177eeee562d3bcda4a6fcc");
// Runtime code of the P256 delegation contract
pub const P256_DELEGATION_RUNTIME_CODE: &[u8] = &hex!("60806040526004361015610018575b361561001657005b005b5f3560e01c806309c5eabe146100c75780630cb6aaf1146100c257806330f6a8e5146100bd5780635fce1927146100b8578063641cdfe2146100b357806376ba882d146100ae5780638d80ff0a146100a9578063972ce4bc146100a4578063a78fc2441461009f578063a82e44e01461009a5763b34893910361000e576108e1565b6108b5565b610786565b610646565b6105ba565b610529565b6103f8565b6103a2565b61034c565b6102c0565b61020b565b634e487b7160e01b5f52604160045260245ffd5b6040810190811067ffffffffffffffff8211176100fc57604052565b6100cc565b6080810190811067ffffffffffffffff8211176100fc57604052565b60a0810190811067ffffffffffffffff8211176100fc57604052565b90601f8019910116810190811067ffffffffffffffff8211176100fc57604052565b6040519061016a608083610139565b565b67ffffffffffffffff81116100fc57601f01601f191660200190565b9291926101948261016c565b916101a26040519384610139565b8294818452818301116101be578281602093845f960137010152565b5f80fd5b9080601f830112156101be578160206101dd93359101610188565b90565b60206003198201126101be576004359067ffffffffffffffff82116101be576101dd916004016101c2565b346101be57610219366101e0565b3033036102295761001690610ae6565b636f6a1b8760e11b5f5260045ffd5b634e487b7160e01b5f52603260045260245ffd5b5f54811015610284575f8080526005919091027f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5630191565b610238565b8054821015610284575f52600560205f20910201905f90565b906040516102af816100e0565b602060018294805484520154910152565b346101be5760203660031901126101be576004355f548110156101be576102e69061024c565b5060ff815416600182015491610306600360ff60028401541692016102a2565b926040519215158352602083015260028110156103385760a09260209160408401528051606084015201516080820152f35b634e487b7160e01b5f52602160045260245ffd5b346101be575f3660031901126101be576020600254604051908152f35b6004359063ffffffff821682036101be57565b6064359063ffffffff821682036101be57565b6084359063ffffffff821682036101be57565b346101be5760203660031901126101be576103bb610369565b303303610229576103cb9061024c565b50805460ff19169055005b60609060231901126101be57602490565b60609060831901126101be57608490565b346101be5760803660031901126101be57610411610369565b60205f61041d366103d6565b60015461043161042c82610a0b565b600155565b60405184810191825260e086901b6001600160e01b031916602083015261046581602484015b03601f198101835282610139565b51902060ff61047660408401610a19565b161583146104fe576104b2601b925b85813591013590604051948594859094939260ff6060936080840197845216602083015260408201520152565b838052039060015afa156104f9575f51306001600160a01b03909116036104ea576104df6100169161024c565b50805460ff19169055565b638baa579f60e01b5f5260045ffd5b610a27565b6104b2601c92610485565b60409060031901126101be57600490565b6044359060028210156101be57565b346101be5760803660031901126101be5761054336610509565b61054b61051a565b606435903033036102295761059192610580610587926040519461056e86610101565b60018652602086015260408501610a32565b36906105f3565b6060820152610a3e565b5f545f1981019081116105b55760405163ffffffff919091168152602090f35b0390f35b6109f7565b6100166105c6366101e0565b610ae6565b60409060231901126101be57604051906105e4826100e0565b60243582526044356020830152565b91908260409103126101be5760405161060b816100e0565b6020808294803584520135910152565b6084359081151582036101be57565b60a4359081151582036101be57565b359081151582036101be57565b346101be5760a03660031901126101be5760043567ffffffffffffffff81116101be576106779036906004016101c2565b610680366105cb565b61068861037c565b61069061061b565b906002546106a56106a082610a0b565b600255565b6040516106bb8161045788602083019586610b6a565b51902091610747575b6106d06106d69161024c565b50610b7b565b906106e86106e48351151590565b1590565b610738576020820151801515908161072e575b5061071f576107129260606106e493015191610ce3565b6104ea5761001690610ae6565b632572e3a960e01b5f5260045ffd5b905042115f6106fb565b637dd286d760e11b5f5260045ffd5b905f61077361045761076760209460405192839187830160209181520190565b60405191828092610b58565b039060025afa156104f9575f51906106c4565b346101be5760e03660031901126101be576107a036610509565b6107a861051a565b6064359060205f6107b8366103e7565b6001546107c761042c82610a0b565b60408051808601928352883560208401528589013591830191909152606082018790526107f78160808401610457565b51902060ff61080860408401610a19565b161583146108aa5760408051918252601b602083015282359082015290830135606082015280608081015b838052039060015afa156104f9575f51306001600160a01b03909116036104ea5761087a926105806105879261086761015b565b6001815294602086015260408501610a32565b6105b161089361088a5f54610ad8565b63ffffffff1690565b60405163ffffffff90911681529081906020820190565b610833601c92610485565b346101be575f3660031901126101be576020600154604051908152f35b359061ffff821682036101be57565b346101be5760c03660031901126101be5760043567ffffffffffffffff81116101be576109129036906004016101c2565b61091b366105cb565b906064359167ffffffffffffffff83116101be5760a060031984360301126101be576040516109498161011d565b836004013567ffffffffffffffff81116101be5761096d90600436918701016101c2565b8152602484013567ffffffffffffffff81116101be57840193366023860112156101be5760846109db916109ae610016973690602460048201359101610188565b60208501526109bf604482016108d2565b60408501526109d0606482016108d2565b606085015201610639565b60808201526109e861038f565b916109f161062a565b93610bc3565b634e487b7160e01b5f52601160045260245ffd5b5f1981146105b55760010190565b3560ff811681036101be5790565b6040513d5f823e3d90fd5b60028210156103385752565b5f54680100000000000000008110156100fc57806001610a6192015f555f610289565b610ac557610a7e82511515829060ff801983541691151516179055565b6020820151600182015560028101604083015160028110156103385761016a9360039260609260ff8019835416911617905501519101906020600191805184550151910155565b634e487b7160e01b5f525f60045260245ffd5b5f198101919082116105b557565b80519060205b828110610af857505050565b808201805160f81c600182015160601c91601581015160358201519384915f9493845f14610b4257505050506001146101be575b15610b3a5701605501610aec565b3d5f803e3d5ffd5b5f95508594506055019130811502175af1610b2c565b805191908290602001825e015f815290565b6020906101dd939281520190610b58565b90604051610b8881610101565b6060610bbe6003839560ff8154161515855260018101546020860152610bb860ff60028301541660408701610a32565b016102a2565b910152565b93909192600254610bd66106a082610a0b565b604051610bec8161045789602083019586610b6a565b51902091610c50575b6106d0610c019161024c565b91610c0f6106e48451151590565b6107385760208301518015159081610c46575b5061071f57610c399360606106e494015192610e0d565b6104ea5761016a90610ae6565b905042115f610c22565b905f610c7061045761076760209460405192839187830160209181520190565b039060025afa156104f9575f5190610bf5565b3d15610cad573d90610c948261016c565b91610ca26040519384610139565b82523d5f602084013e565b606090565b8051601f101561028457603f0190565b8051602010156102845760400190565b908151811015610284570160200190565b5f9291839260208251920151906020815191015191604051936020850195865260408501526060840152608083015260a082015260a08152610d2660c082610139565b519060145afa610d34610c83565b81610d74575b81610d43575090565b600160f81b91506001600160f81b031990610d6f90610d6190610cb2565b516001600160f81b03191690565b161490565b80516020149150610d3a565b60405190610d8f604083610139565b6015825274113a3cb832911d113bb2b130baba34371733b2ba1160591b6020830152565b9061016a6001610de3936040519485916c1131b430b63632b733b2911d1160991b6020840152602d830190610b58565b601160f91b815203601e19810185520183610139565b610e069060209392610b58565b9081520190565b92919281516025815110908115610f0a575b50610ef957610e2c610d80565b90610e596106e460208501938451610e53610e4c606089015161ffff1690565b61ffff1690565b91610f9b565b610f01576106e4610e8d610e88610457610e83610ea1956040519283916020830160209181520190565b611012565b610db3565b8351610e53610e4c604088015161ffff1690565b610ef9575f610eb96020925160405191828092610b58565b039060025afa156104f9575f610ee360209261076783519151610457604051938492888401610df9565b039060025afa156104f9576101dd915f51610ce3565b505050505f90565b50505050505f90565b610f2b9150610f1e610d616106e492610cc2565b6080850151151590610f31565b5f610e1f565b906001600160f81b0319600160f81b831601610f955780610f85575b610f8057601f60fb1b600160fb1b821601610f69575b50600190565b600160fc1b90811614610f7c575f610f63565b5f90565b505f90565b50600160fa1b8181161415610f4d565b50505f90565b80519282515f5b858110610fb457505050505050600190565b8083018084116105b5578281101561100757610fe56001600160f81b0319610fdc8488610cd2565b51169187610cd2565b516001600160f81b03191603610ffd57600101610fa2565b5050505050505f90565b505050505050505f90565b80516060929181611021575050565b9092506003600284010460021b604051937f4142434445464748494a4b4c4d4e4f505152535455565758595a616263646566601f527f6768696a6b6c6d6e6f707172737475767778797a303132333435363738392d5f603f52602085019282860191602083019460208284010190600460038351955f85525b0191603f8351818160121c16515f538181600c1c1651600153818160061c165160025316516003535f5181520190878210156110db5760049060039061109a565b5095505f93600393604092520160405206600204809303613d3d60f01b81525203825256fea26469706673582212200ba93b78f286a25ece47e9403c47be9862f9b8b70ba1a95098667b90c47308b064736f6c634300081a0033");
// Experimental ERC20
pub const EXP_ERC20_CONTRACT: Address = address!("238c8CD93ee9F8c7Edf395548eF60c0d2e46665E");
// Runtime code of the experimental ERC20 contract
pub const EXP_ERC20_RUNTIME_CODE: &[u8] = &hex!("60806040526004361015610010575b005b5f3560e01c806306fdde03146106f7578063095ea7b31461068c57806318160ddd1461066757806323b872dd146105a15780632bb7c5951461050e578063313ce567146104f35780633644e5151461045557806340c10f191461043057806370a08231146103fe5780637ecebe00146103cc57806395d89b4114610366578063a9059cbb146102ea578063ad0c8fdd146102ad578063d505accf146100fb5763dd62ed3e0361000e57346100f75760403660031901126100f7576100d261075c565b6100da610772565b602052637f5e9f20600c525f5260206034600c2054604051908152f35b5f80fd5b346100f75760e03660031901126100f75761011461075c565b61011c610772565b6084359160643560443560ff851685036100f757610138610788565b60208101906e04578706572696d656e74455243323608c1b8252519020908242116102a0576040519360018060a01b03169460018060a01b03169565383775081901600e52855f5260c06020600c20958654957f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252602082019586528660408301967fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc688528b6060850198468a528c608087019330855260a08820602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9885252528688525260a082015220604e526042602c205f5260ff1660205260a43560405260c43560605260208060805f60015afa93853d5103610293577f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92594602094019055856303faf4f960a51b176040526034602c2055a3005b63ddafbaef5f526004601cfd5b631a15a3cc5f526004601cfd5b5f3660031901126100f7576103e834023481046103e814341517156102d65761000e90336107ac565b634e487b7160e01b5f52601160045260245ffd5b346100f75760403660031901126100f75761030361075c565b602435906387a211a2600c52335f526020600c2080548084116103595783900390555f526020600c20818154019055602052600c5160601c335f51602061080d5f395f51905f52602080a3602060405160018152f35b63f4d678b85f526004601cfd5b346100f7575f3660031901126100f757604051604081019080821067ffffffffffffffff8311176103b8576103b491604052600381526204558560ec1b602082015260405191829182610732565b0390f35b634e487b7160e01b5f52604160045260245ffd5b346100f75760203660031901126100f7576103e561075c565b6338377508600c525f52602080600c2054604051908152f35b346100f75760203660031901126100f75761041761075c565b6387a211a2600c525f52602080600c2054604051908152f35b346100f75760403660031901126100f75761000e61044c61075c565b602435906107ac565b346100f7575f3660031901126100f757602060a0610471610788565b828101906e04578706572696d656e74455243323608c1b8252519020604051907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252838201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015220604051908152f35b346100f7575f3660031901126100f757602060405160128152f35b346100f75760203660031901126100f7576004356387a211a2600c52335f526020600c2090815490818111610359575f80806103e88487839688039055806805345cdf77eb68f44c54036805345cdf77eb68f44c5580835282335f51602061080d5f395f51905f52602083a304818115610598575b3390f11561058d57005b6040513d5f823e3d90fd5b506108fc610583565b346100f75760603660031901126100f7576105ba61075c565b6105c2610772565b604435908260601b33602052637f5e9f208117600c526034600c20908154918219610643575b506387a211a2915017600c526020600c2080548084116103595783900390555f526020600c20818154019055602052600c5160601c9060018060a01b03165f51602061080d5f395f51905f52602080a3602060405160018152f35b82851161065a57846387a211a293039055856105e8565b6313be252b5f526004601cfd5b346100f7575f3660031901126100f75760206805345cdf77eb68f44c54604051908152f35b346100f75760403660031901126100f7576106a561075c565b60243590602052637f5e9f20600c52335f52806034600c20555f52602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3602060405160018152f35b346100f7575f3660031901126100f7576103b4610712610788565b6e04578706572696d656e74455243323608c1b6020820152604051918291825b602060409281835280519182918282860152018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b03821682036100f757565b602435906001600160a01b03821682036100f757565b604051906040820182811067ffffffffffffffff8211176103b857604052600f8252565b6805345cdf77eb68f44c548281019081106107ff576805345cdf77eb68f44c556387a211a2600c525f526020600c20818154019055602052600c5160601c5f5f51602061080d5f395f51905f52602080a3565b63e5cfe9575f526004601cfdfeddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220fbe302881d9891005ba1448ba48547cc1cb17dea1a5c4011dfcb035de325bb1d64736f6c634300081b0033");
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 {
Self::Pending(_) => BlockNumber::Pending,
Self::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::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 [`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. 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,
/// Historic states of previous blocks.
states: Arc<RwLock<InMemoryBlockStates>>,
/// Env data of the chain
env: Arc<RwLock<EnvWithHandlerCfg>>,
/// 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,
alphanet: 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>>,
/// 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<()>>,
// === wallet === //
capabilities: Arc<RwLock<WalletCapabilities>>,
executor_wallet: Arc<RwLock<Option<EthereumWallet>>>,
}
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<EnvWithHandlerCfg>>,
genesis: GenesisConfig,
fees: FeeManager,
fork: Arc<RwLock<Option<ClientFork>>>,
enable_steps_tracing: bool,
print_logs: bool,
alphanet: bool,
prune_state_history_config: PruneStateHistoryConfig,
max_persisted_states: Option<usize>,
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(|limit| InMemoryBlockStates::new(limit, 0))
.unwrap_or_default()
.memory_only()
} else if max_persisted_states.is_some() {
max_persisted_states
.map(|limit| InMemoryBlockStates::new(DEFAULT_HISTORY_LIMIT, limit))
.unwrap_or_default()
} else {
Default::default()
};
let (slots_in_an_epoch, precompile_factory) = {
let cfg = node_config.read().await;
(cfg.slots_in_an_epoch, cfg.precompile_factory.clone())
};
let (capabilities, executor_wallet) = if alphanet {
// Insert account that sponsors the delegated txs. And deploy P256 delegation contract.
let mut db = db.write().await;
let _ = db.set_code(
P256_DELEGATION_CONTRACT,
Bytes::from_static(P256_DELEGATION_RUNTIME_CODE),
);
// Insert EXP ERC20 contract
let _ = db.set_code(EXP_ERC20_CONTRACT, Bytes::from_static(EXP_ERC20_RUNTIME_CODE));
let init_balance = Unit::ETHER.wei().saturating_mul(U256::from(10_000)); // 10K ETH
// Add ETH
let _ = db.set_balance(EXP_ERC20_CONTRACT, init_balance);
let _ = db.set_balance(EXECUTOR, init_balance);
let mut capabilities = WalletCapabilities::default();
let chain_id = env.read().cfg.chain_id;
capabilities.insert(
chain_id,
Capabilities {
delegation: DelegationCapability { addresses: vec![P256_DELEGATION_CONTRACT] },
},
);
let signer: PrivateKeySigner = EXECUTOR_PK.parse().unwrap();
let executor_wallet = EthereumWallet::new(signer);
(capabilities, Some(executor_wallet))
} else {
(WalletCapabilities::default(), None)
};
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_state_snapshots: Arc::new(Mutex::new(Default::default())),
enable_steps_tracing,
print_logs,
alphanet,
prune_state_history_config,
transaction_block_keeper,
node_config,
slots_in_an_epoch,
precompile_factory,
mining: Arc::new(tokio::sync::Mutex::new(())),
capabilities: Arc::new(RwLock::new(capabilities)),
executor_wallet: Arc::new(RwLock::new(executor_wallet)),
};
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(())
}
/// Get the capabilities of the wallet.
///
/// Currently the only capability is [`DelegationCapability`].
///
/// [`DelegationCapability`]: anvil_core::eth::wallet::DelegationCapability
pub(crate) fn get_capabilities(&self) -> WalletCapabilities {
self.capabilities.read().clone()
}
/// 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)
}
pub(crate) fn executor_wallet(&self) -> Option<EthereumWallet> {
self.executor_wallet.read().clone()
}
/// Adds an address to the [`DelegationCapability`] of the wallet.
pub(crate) fn add_capability(&self, address: Address) {
let chain_id = self.env.read().cfg.chain_id;
let mut capabilities = self.capabilities.write();
let mut capability = capabilities.get(chain_id).cloned().unwrap_or_default();
capability.delegation.addresses.push(address);
capabilities.insert(chain_id, capability);
}
pub(crate) fn set_executor(&self, executor_pk: String) -> Result<Address, BlockchainError> {
let signer: PrivateKeySigner =
executor_pk.parse().map_err(|_| RpcError::invalid_params("Invalid private key"))?;
let executor = signer.address();
let wallet = EthereumWallet::new(signer);
*self.executor_wallet.write() = Some(wallet);
Ok(executor)
}
/// Applies the configured genesis settings
///
/// This will fund, create the genesis accounts
async fn apply_genesis(&self) -> Result<(), DatabaseError> {
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;
for res in genesis_accounts {
let (address, mut info) = res.unwrap()?;
info.balance = self.genesis.balance;
db.insert_account(address, info.clone());
}
} else {
let mut db = self.db.write().await;
for (account, info) in self.genesis.account_infos() {
db.insert_account(account, info);
}
// insert the new genesis hash to the database so it's available for the next block in
// the evm
db.insert_block_hash(U256::from(self.best_number()), self.best_hash());
}
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 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.cfg.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()
}
pub fn precompiles(&self) -> Vec<Address> {
get_precompiles_for(self.env.read().handler_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
{
if let Some(fork_url) = forking.json_rpc_url {
// Set the fork block number
let mut node_config = self.node_config.write().await;
node_config.fork_choice = Some(ForkChoice::Block(fork_block_number));
let mut env = self.env.read().clone();
let (forked_db, client_fork_config) =
node_config.setup_fork_db_config(fork_url, &mut env, &self.fees).await;
*self.db.write().await = Box::new(forked_db);
let fork = ClientFork::new(client_fork_config, Arc::clone(&self.db));
*self.fork.write() = Some(fork);
*self.env.write() = env;
} else {
let gas_limit = self.node_config.read().await.fork_gas_limit(&fork_block);
let mut env = self.env.write();
env.cfg.chain_id = fork.chain_id();
env.block = BlockEnv {
number: U256::from(fork_block_number),
timestamp: U256::from(fork_block.header.timestamp),
gas_limit: U256::from(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()
};
// 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 as u128,
gas_limit,
fork_block.header.base_fee_per_gas.unwrap_or_default(),
);
self.fees.set_base_fee(next_block_base_fee);
}
// reset the time to the timestamp of the forked block
self.time.reset(fork_block.header.timestamp);
// 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();
self.db.write().await.clear();
self.apply_genesis().await?;
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<EnvWithHandlerCfg>> {
&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.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<u64> {
Ok(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.into(), val)
}
/// Returns the configured specid
pub fn spec_id(&self) -> SpecId {
self.env.read().handler_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 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().handler_cfg.is_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)
}
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) -> u128 {
self.env.read().block.gas_limit.to()
}
/// Sets the block gas limit
pub fn set_gas_limit(&self, gas_limit: u128) {
self.env.write().block.gas_limit = U256::from(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
}
/// Reverts the state to the state snapshot identified by the given `id`.
pub async fn revert_state_snapshot(&self, id: U256) -> Result<bool, BlockchainError> {
let block = { self.active_state_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;
self.time.reset(reset_time);
let mut env = self.env.write();
env.block = BlockEnv {
number: U256::from(num),
timestamp: U256::from(block.header.timestamp),
difficulty: block.header.difficulty,
// ensures prevrandao is set
prevrandao: Some(block.header.mix_hash.unwrap_or_default()),
gas_limit: U256::from(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_state(id, RevertStateSnapshotAction::RevertRemove))
}
pub fn list_state_snapshots(&self) -> BTreeMap<U256, (u64, B256)> {
self.active_state_snapshots.lock().clone().into_iter().collect()
}
/// Get the current state.
pub async fn serialized_state(
&self,
preserve_historical_states: bool,
) -> Result<SerializableState, BlockchainError> {
let at = self.env.read().block.clone();
let best_number = self.blockchain.storage.read().best_number;
let blocks = self.blockchain.storage.read().serialized_blocks();
let transactions = self.blockchain.storage.read().serialized_transactions();
let historical_states = if preserve_historical_states {
Some(self.states.write().serialized_states())
} else {
None
};
let state = self.db.read().await.dump_state(
at,
best_number,
blocks,
transactions,
historical_states,
)?;
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,
preserve_historical_states: bool,
) -> Result<Bytes, BlockchainError> {
let state = self.serialized_state(preserve_historical_states).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> {
// load the blocks and transactions into the storage
self.blockchain.storage.write().load_blocks(state.blocks.clone());
self.blockchain.storage.write().load_transactions(state.transactions.clone());
// reset the block env
if let Some(block) = state.block.clone() {
self.env.write().block = block.clone();
// Set the current best block number.
// Defaults to block number for compatibility with existing state files.
let best_number = state.best_block_number.unwrap_or(block.number.to::<U64>());
self.blockchain.storage.write().best_number = best_number;
// Set the current best block hash;
let best_hash =
self.blockchain.storage.read().hash(best_number.into()).ok_or_else(|| {
BlockchainError::RpcError(RpcError::internal_error_with(format!(
"Best hash not found for best number {best_number}",
)))
})?;
self.blockchain.storage.write().best_hash = best_hash;
}
if !self.db.write().await.load_state(state.clone())? {
return Err(RpcError::invalid_params(
"Loading state not supported with the current configuration",
)
.into());
}
if let Some(historical_states) = state.historical_states {
self.states.write().load_states(historical_states);
}
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) -> EnvWithHandlerCfg {
let mut env = self.env.read().clone();
// increase block number for this block
env.block.number = env.block.number.saturating_add(U256::from(1));
env.block.basefee = U256::from(self.base_fee());
env.block.timestamp = U256::from(self.time.current_call_timestamp());
env
}
/// Creates an EVM instance with optionally injected precompiles.
#[allow(clippy::type_complexity)]
fn new_evm_with_inspector_ref<'i, 'db>(
&self,
db: &'db dyn DatabaseRef<Error = DatabaseError>,
env: EnvWithHandlerCfg,
inspector: &'i mut dyn revm::Inspector<
WrapDatabaseRef<&'db dyn DatabaseRef<Error = DatabaseError>>,
>,
) -> revm::Evm<
'_,
&'i mut dyn revm::Inspector<WrapDatabaseRef<&'db dyn DatabaseRef<Error = DatabaseError>>>,
WrapDatabaseRef<&'db dyn DatabaseRef<Error = DatabaseError>>,
> {
let mut evm = new_evm_with_inspector_ref(db, env, inspector, self.alphanet);
if let Some(factory) = &self.precompile_factory {
inject_precompiles(&mut evm, factory.precompiles());
}
evm
}
/// 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();
if env.handler_cfg.is_optimism {