forked from paradigmxyz/reth
-
Notifications
You must be signed in to change notification settings - Fork 4
/
spec.rs
2313 lines (2131 loc) · 102 KB
/
spec.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
pub use alloy_eips::eip1559::BaseFeeParams;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use alloy_chains::{Chain, NamedChain};
use alloy_consensus::constants::EMPTY_WITHDRAWALS;
use alloy_eips::{
eip1559::INITIAL_BASE_FEE, eip6110::MAINNET_DEPOSIT_CONTRACT_ADDRESS,
eip7685::EMPTY_REQUESTS_HASH,
};
use alloy_genesis::Genesis;
use alloy_primitives::{address, b256, Address, BlockNumber, B256, U256};
use derive_more::From;
use alloy_consensus::{
constants::{
DEV_GENESIS_HASH, HOLESKY_GENESIS_HASH, MAINNET_GENESIS_HASH, SEPOLIA_GENESIS_HASH,
},
Header,
};
use alloy_eips::eip1559::ETHEREUM_BLOCK_GAS_LIMIT;
use reth_ethereum_forks::{
ChainHardforks, DisplayHardforks, EthereumHardfork, EthereumHardforks, ForkCondition,
ForkFilter, ForkFilterKey, ForkHash, ForkId, Hardfork, Hardforks, Head, DEV_HARDFORKS,
};
use reth_network_peers::{
base_nodes, base_testnet_nodes, holesky_nodes, mainnet_nodes, op_nodes, op_testnet_nodes,
sepolia_nodes, NodeRecord,
};
use reth_primitives_traits::SealedHeader;
use reth_trie_common::root::state_root_ref_unhashed;
use crate::{constants::MAINNET_DEPOSIT_CONTRACT, once_cell_set, EthChainSpec, LazyLock, OnceLock};
/// The Ethereum mainnet spec
pub static MAINNET: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
let mut spec = ChainSpec {
chain: Chain::mainnet(),
genesis: serde_json::from_str(include_str!("../res/genesis/mainnet.json"))
.expect("Can't deserialize Mainnet genesis json"),
genesis_hash: once_cell_set(MAINNET_GENESIS_HASH),
genesis_header: Default::default(),
// <https://etherscan.io/block/15537394>
paris_block_and_final_difficulty: Some((
15537394,
U256::from(58_750_003_716_598_352_816_469u128),
)),
hardforks: EthereumHardfork::mainnet().into(),
// https://etherscan.io/tx/0xe75fb554e433e03763a1560646ee22dcb74e5274b34c5ad644e7c0f619a7e1d0
deposit_contract: Some(DepositContract::new(
MAINNET_DEPOSIT_CONTRACT_ADDRESS,
11052984,
b256!("649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
)),
base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
max_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
prune_delete_limit: 20000,
};
spec.genesis.config.dao_fork_support = true;
spec.into()
});
/// The Sepolia spec
pub static SEPOLIA: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
let mut spec = ChainSpec {
chain: Chain::sepolia(),
genesis: serde_json::from_str(include_str!("../res/genesis/sepolia.json"))
.expect("Can't deserialize Sepolia genesis json"),
genesis_hash: once_cell_set(SEPOLIA_GENESIS_HASH),
genesis_header: Default::default(),
// <https://sepolia.etherscan.io/block/1450409>
paris_block_and_final_difficulty: Some((1450409, U256::from(17_000_018_015_853_232u128))),
hardforks: EthereumHardfork::sepolia().into(),
// https://sepolia.etherscan.io/tx/0x025ecbf81a2f1220da6285d1701dc89fb5a956b62562ee922e1a9efd73eb4b14
deposit_contract: Some(DepositContract::new(
address!("7f02c3e3c98b133055b8b348b2ac625669ed295d"),
1273020,
b256!("649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
)),
base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
max_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
prune_delete_limit: 10000,
};
spec.genesis.config.dao_fork_support = true;
spec.into()
});
/// The Holesky spec
pub static HOLESKY: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
let mut spec = ChainSpec {
chain: Chain::holesky(),
genesis: serde_json::from_str(include_str!("../res/genesis/holesky.json"))
.expect("Can't deserialize Holesky genesis json"),
genesis_hash: once_cell_set(HOLESKY_GENESIS_HASH),
genesis_header: Default::default(),
paris_block_and_final_difficulty: Some((0, U256::from(1))),
hardforks: EthereumHardfork::holesky().into(),
deposit_contract: Some(DepositContract::new(
address!("4242424242424242424242424242424242424242"),
0,
b256!("649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
)),
base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
max_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
prune_delete_limit: 10000,
};
spec.genesis.config.dao_fork_support = true;
spec.into()
});
/// Dev testnet specification
///
/// Includes 20 prefunded accounts with `10_000` ETH each derived from mnemonic "test test test test
/// test test test test test test test junk".
pub static DEV: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
ChainSpec {
chain: Chain::dev(),
genesis: serde_json::from_str(include_str!("../res/genesis/dev.json"))
.expect("Can't deserialize Dev testnet genesis json"),
genesis_hash: once_cell_set(DEV_GENESIS_HASH),
paris_block_and_final_difficulty: Some((0, U256::from(0))),
hardforks: DEV_HARDFORKS.clone(),
base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
deposit_contract: None, // TODO: do we even have?
..Default::default()
}
.into()
});
/// A wrapper around [`BaseFeeParams`] that allows for specifying constant or dynamic EIP-1559
/// parameters based on the active [Hardfork].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BaseFeeParamsKind {
/// Constant [`BaseFeeParams`]; used for chains that don't have dynamic EIP-1559 parameters
Constant(BaseFeeParams),
/// Variable [`BaseFeeParams`]; used for chains that have dynamic EIP-1559 parameters like
/// Optimism
Variable(ForkBaseFeeParams),
}
impl Default for BaseFeeParamsKind {
fn default() -> Self {
BaseFeeParams::ethereum().into()
}
}
impl From<BaseFeeParams> for BaseFeeParamsKind {
fn from(params: BaseFeeParams) -> Self {
Self::Constant(params)
}
}
impl From<ForkBaseFeeParams> for BaseFeeParamsKind {
fn from(params: ForkBaseFeeParams) -> Self {
Self::Variable(params)
}
}
/// A type alias to a vector of tuples of [Hardfork] and [`BaseFeeParams`], sorted by [Hardfork]
/// activation order. This is used to specify dynamic EIP-1559 parameters for chains like Optimism.
#[derive(Clone, Debug, PartialEq, Eq, From)]
pub struct ForkBaseFeeParams(Vec<(Box<dyn Hardfork>, BaseFeeParams)>);
impl core::ops::Deref for ChainSpec {
type Target = ChainHardforks;
fn deref(&self) -> &Self::Target {
&self.hardforks
}
}
/// An Ethereum chain specification.
///
/// A chain specification describes:
///
/// - Meta-information about the chain (the chain ID)
/// - The genesis block of the chain ([`Genesis`])
/// - What hardforks are activated, and under which conditions
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChainSpec {
/// The chain ID
pub chain: Chain,
/// The genesis block.
pub genesis: Genesis,
/// The hash of the genesis block.
///
/// This is either stored at construction time if it is known using [`once_cell_set`], or
/// computed once on the first access.
pub genesis_hash: OnceLock<B256>,
/// The header corresponding to the genesis block.
///
/// This is either stored at construction time if it is known using [`once_cell_set`], or
/// computed once on the first access.
pub genesis_header: OnceLock<Header>,
/// The block at which [`EthereumHardfork::Paris`] was activated and the final difficulty at
/// this block.
pub paris_block_and_final_difficulty: Option<(u64, U256)>,
/// The active hard forks and their activation conditions
pub hardforks: ChainHardforks,
/// The deposit contract deployed for `PoS`
pub deposit_contract: Option<DepositContract>,
/// The parameters that configure how a block's base fee is computed
pub base_fee_params: BaseFeeParamsKind,
/// The maximum gas limit
pub max_gas_limit: u64,
/// The delete limit for pruner, per run.
pub prune_delete_limit: usize,
}
impl Default for ChainSpec {
fn default() -> Self {
Self {
chain: Default::default(),
genesis_hash: Default::default(),
genesis: Default::default(),
genesis_header: Default::default(),
paris_block_and_final_difficulty: Default::default(),
hardforks: Default::default(),
deposit_contract: Default::default(),
base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
max_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
prune_delete_limit: MAINNET.prune_delete_limit,
}
}
}
impl ChainSpec {
/// Get information about the chain itself
pub const fn chain(&self) -> Chain {
self.chain
}
/// Returns `true` if this chain contains Ethereum configuration.
#[inline]
pub const fn is_ethereum(&self) -> bool {
self.chain.is_ethereum()
}
/// Returns `true` if this chain is Optimism mainnet.
#[inline]
pub fn is_optimism_mainnet(&self) -> bool {
self.chain == Chain::optimism_mainnet()
}
/// Get the genesis block specification.
///
/// To get the header for the genesis block, use [`Self::genesis_header`] instead.
pub const fn genesis(&self) -> &Genesis {
&self.genesis
}
/// Get the header for the genesis block.
pub fn genesis_header(&self) -> &Header {
self.genesis_header.get_or_init(|| self.make_genesis_header())
}
fn make_genesis_header(&self) -> Header {
// If London is activated at genesis, we set the initial base fee as per EIP-1559.
let base_fee_per_gas = self.initial_base_fee();
// If shanghai is activated, initialize the header with an empty withdrawals hash, and
// empty withdrawals list.
let withdrawals_root = self
.fork(EthereumHardfork::Shanghai)
.active_at_timestamp(self.genesis.timestamp)
.then_some(EMPTY_WITHDRAWALS);
// If Cancun is activated at genesis, we set:
// * parent beacon block root to 0x0
// * blob gas used to provided genesis or 0x0
// * excess blob gas to provided genesis or 0x0
let (parent_beacon_block_root, blob_gas_used, excess_blob_gas) =
if self.is_cancun_active_at_timestamp(self.genesis.timestamp) {
let blob_gas_used = self.genesis.blob_gas_used.unwrap_or(0);
let excess_blob_gas = self.genesis.excess_blob_gas.unwrap_or(0);
(Some(B256::ZERO), Some(blob_gas_used as u64), Some(excess_blob_gas as u64))
} else {
(None, None, None)
};
// If Prague is activated at genesis we set requests root to an empty trie root.
let requests_hash = self
.is_prague_active_at_timestamp(self.genesis.timestamp)
.then_some(EMPTY_REQUESTS_HASH);
Header {
gas_limit: self.genesis.gas_limit,
difficulty: self.genesis.difficulty,
nonce: self.genesis.nonce.into(),
extra_data: self.genesis.extra_data.clone(),
state_root: state_root_ref_unhashed(&self.genesis.alloc),
timestamp: self.genesis.timestamp,
mix_hash: self.genesis.mix_hash,
beneficiary: self.genesis.coinbase,
base_fee_per_gas: base_fee_per_gas.map(Into::into),
withdrawals_root,
parent_beacon_block_root,
blob_gas_used: blob_gas_used.map(Into::into),
excess_blob_gas: excess_blob_gas.map(Into::into),
requests_hash,
..Default::default()
}
}
/// Get the sealed header for the genesis block.
pub fn sealed_genesis_header(&self) -> SealedHeader {
SealedHeader::new(self.genesis_header().clone(), self.genesis_hash())
}
/// Get the initial base fee of the genesis block.
pub fn initial_base_fee(&self) -> Option<u64> {
// If the base fee is set in the genesis block, we use that instead of the default.
let genesis_base_fee =
self.genesis.base_fee_per_gas.map(|fee| fee as u64).unwrap_or(INITIAL_BASE_FEE);
// If London is activated at genesis, we set the initial base fee as per EIP-1559.
self.hardforks.fork(EthereumHardfork::London).active_at_block(0).then_some(genesis_base_fee)
}
/// Get the [`BaseFeeParams`] for the chain at the given timestamp.
pub fn base_fee_params_at_timestamp(&self, timestamp: u64) -> BaseFeeParams {
match self.base_fee_params {
BaseFeeParamsKind::Constant(bf_params) => bf_params,
BaseFeeParamsKind::Variable(ForkBaseFeeParams(ref bf_params)) => {
// Walk through the base fee params configuration in reverse order, and return the
// first one that corresponds to a hardfork that is active at the
// given timestamp.
for (fork, params) in bf_params.iter().rev() {
if self.hardforks.is_fork_active_at_timestamp(fork.clone(), timestamp) {
return *params
}
}
bf_params.first().map(|(_, params)| *params).unwrap_or(BaseFeeParams::ethereum())
}
}
}
/// Get the [`BaseFeeParams`] for the chain at the given block number
pub fn base_fee_params_at_block(&self, block_number: u64) -> BaseFeeParams {
match self.base_fee_params {
BaseFeeParamsKind::Constant(bf_params) => bf_params,
BaseFeeParamsKind::Variable(ForkBaseFeeParams(ref bf_params)) => {
// Walk through the base fee params configuration in reverse order, and return the
// first one that corresponds to a hardfork that is active at the
// given timestamp.
for (fork, params) in bf_params.iter().rev() {
if self.hardforks.is_fork_active_at_block(fork.clone(), block_number) {
return *params
}
}
bf_params.first().map(|(_, params)| *params).unwrap_or(BaseFeeParams::ethereum())
}
}
}
/// Get the hash of the genesis block.
pub fn genesis_hash(&self) -> B256 {
*self.genesis_hash.get_or_init(|| self.genesis_header().hash_slow())
}
/// Get the timestamp of the genesis block.
pub const fn genesis_timestamp(&self) -> u64 {
self.genesis.timestamp
}
/// Returns the final total difficulty if the Paris hardfork is known.
pub fn get_final_paris_total_difficulty(&self) -> Option<U256> {
self.paris_block_and_final_difficulty.map(|(_, final_difficulty)| final_difficulty)
}
/// Returns the final total difficulty if the given block number is after the Paris hardfork.
///
/// Note: technically this would also be valid for the block before the paris upgrade, but this
/// edge case is omitted here.
#[inline]
pub fn final_paris_total_difficulty(&self, block_number: u64) -> Option<U256> {
self.paris_block_and_final_difficulty.and_then(|(activated_at, final_difficulty)| {
(block_number >= activated_at).then_some(final_difficulty)
})
}
/// Get the fork filter for the given hardfork
pub fn hardfork_fork_filter<H: Hardfork + Clone>(&self, fork: H) -> Option<ForkFilter> {
match self.hardforks.fork(fork.clone()) {
ForkCondition::Never => None,
_ => Some(self.fork_filter(self.satisfy(self.hardforks.fork(fork)))),
}
}
/// Returns the hardfork display helper.
pub fn display_hardforks(&self) -> DisplayHardforks {
DisplayHardforks::new(&self, self.paris_block_and_final_difficulty.map(|(block, _)| block))
}
/// Get the fork id for the given hardfork.
#[inline]
pub fn hardfork_fork_id<H: Hardfork + Clone>(&self, fork: H) -> Option<ForkId> {
let condition = self.hardforks.fork(fork);
match condition {
ForkCondition::Never => None,
_ => Some(self.fork_id(&self.satisfy(condition))),
}
}
/// Convenience method to get the fork id for [`EthereumHardfork::Shanghai`] from a given
/// chainspec.
#[inline]
pub fn shanghai_fork_id(&self) -> Option<ForkId> {
self.hardfork_fork_id(EthereumHardfork::Shanghai)
}
/// Convenience method to get the fork id for [`EthereumHardfork::Cancun`] from a given
/// chainspec.
#[inline]
pub fn cancun_fork_id(&self) -> Option<ForkId> {
self.hardfork_fork_id(EthereumHardfork::Cancun)
}
/// Convenience method to get the latest fork id from the chainspec. Panics if chainspec has no
/// hardforks.
#[inline]
pub fn latest_fork_id(&self) -> ForkId {
self.hardfork_fork_id(self.hardforks.last().unwrap().0).unwrap()
}
/// Creates a [`ForkFilter`] for the block described by [Head].
pub fn fork_filter(&self, head: Head) -> ForkFilter {
let forks = self.hardforks.forks_iter().filter_map(|(_, condition)| {
// We filter out TTD-based forks w/o a pre-known block since those do not show up in the
// fork filter.
Some(match condition {
ForkCondition::Block(block) |
ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block),
ForkCondition::Timestamp(time) => ForkFilterKey::Time(time),
_ => return None,
})
});
ForkFilter::new(head, self.genesis_hash(), self.genesis_timestamp(), forks)
}
/// Compute the [`ForkId`] for the given [`Head`] following eip-6122 spec
pub fn fork_id(&self, head: &Head) -> ForkId {
let mut forkhash = ForkHash::from(self.genesis_hash());
let mut current_applied = 0;
// handle all block forks before handling timestamp based forks. see: https://eips.ethereum.org/EIPS/eip-6122
for (_, cond) in self.hardforks.forks_iter() {
// handle block based forks and the sepolia merge netsplit block edge case (TTD
// ForkCondition with Some(block))
if let ForkCondition::Block(block) |
ForkCondition::TTD { fork_block: Some(block), .. } = cond
{
if cond.active_at_head(head) {
if block != current_applied {
forkhash += block;
current_applied = block;
}
} else {
// we can return here because this block fork is not active, so we set the
// `next` value
return ForkId { hash: forkhash, next: block }
}
}
}
// timestamp are ALWAYS applied after the merge.
//
// this filter ensures that no block-based forks are returned
for timestamp in self.hardforks.forks_iter().filter_map(|(_, cond)| {
cond.as_timestamp().filter(|time| time > &self.genesis.timestamp)
}) {
let cond = ForkCondition::Timestamp(timestamp);
if cond.active_at_head(head) {
if timestamp != current_applied {
forkhash += timestamp;
current_applied = timestamp;
}
} else {
// can safely return here because we have already handled all block forks and
// have handled all active timestamp forks, and set the next value to the
// timestamp that is known but not active yet
return ForkId { hash: forkhash, next: timestamp }
}
}
ForkId { hash: forkhash, next: 0 }
}
/// An internal helper function that returns a head block that satisfies a given Fork condition.
pub(crate) fn satisfy(&self, cond: ForkCondition) -> Head {
match cond {
ForkCondition::Block(number) => Head { number, ..Default::default() },
ForkCondition::Timestamp(timestamp) => {
// to satisfy every timestamp ForkCondition, we find the last ForkCondition::Block
// if one exists, and include its block_num in the returned Head
Head {
timestamp,
number: self.last_block_fork_before_merge_or_timestamp().unwrap_or_default(),
..Default::default()
}
}
ForkCondition::TTD { total_difficulty, .. } => {
Head { total_difficulty, ..Default::default() }
}
ForkCondition::Never => unreachable!(),
}
}
/// This internal helper function retrieves the block number of the last block-based fork
/// that occurs before:
/// - Any existing Total Terminal Difficulty (TTD) or
/// - Timestamp-based forks in the current [`ChainSpec`].
///
/// The function operates by examining the configured hard forks in the chain. It iterates
/// through the fork conditions and identifies the most recent block-based fork that
/// precedes any TTD or timestamp-based conditions.
///
/// If there are no block-based forks found before these conditions, or if the [`ChainSpec`]
/// is not configured with a TTD or timestamp fork, this function will return `None`.
pub(crate) fn last_block_fork_before_merge_or_timestamp(&self) -> Option<u64> {
let mut hardforks_iter = self.hardforks.forks_iter().peekable();
while let Some((_, curr_cond)) = hardforks_iter.next() {
if let Some((_, next_cond)) = hardforks_iter.peek() {
// Match against the `next_cond` to see if it represents:
// - A TTD (merge)
// - A timestamp-based fork
match next_cond {
// If the next fork is TTD and specifies a specific block, return that block
// number
ForkCondition::TTD { fork_block: Some(block), .. } => return Some(*block),
// If the next fork is TTD without a specific block or is timestamp-based,
// return the block number of the current condition if it is block-based.
ForkCondition::TTD { .. } | ForkCondition::Timestamp(_) => {
// Check if `curr_cond` is a block-based fork and return its block number if
// true.
if let ForkCondition::Block(block_num) = curr_cond {
return Some(block_num);
}
}
ForkCondition::Block(_) | ForkCondition::Never => continue,
}
}
}
None
}
/// Build a chainspec using [`ChainSpecBuilder`]
pub fn builder() -> ChainSpecBuilder {
ChainSpecBuilder::default()
}
/// Returns the known bootnode records for the given chain.
pub fn bootnodes(&self) -> Option<Vec<NodeRecord>> {
use NamedChain as C;
let chain = self.chain;
match chain.try_into().ok()? {
C::Mainnet => Some(mainnet_nodes()),
C::Sepolia => Some(sepolia_nodes()),
C::Holesky => Some(holesky_nodes()),
C::Base => Some(base_nodes()),
C::Optimism => Some(op_nodes()),
C::BaseGoerli | C::BaseSepolia => Some(base_testnet_nodes()),
C::OptimismSepolia | C::OptimismGoerli | C::OptimismKovan => Some(op_testnet_nodes()),
_ => None,
}
}
}
impl From<Genesis> for ChainSpec {
fn from(genesis: Genesis) -> Self {
// Block-based hardforks
let hardfork_opts = [
(EthereumHardfork::Homestead.boxed(), genesis.config.homestead_block),
(EthereumHardfork::Dao.boxed(), genesis.config.dao_fork_block),
(EthereumHardfork::Tangerine.boxed(), genesis.config.eip150_block),
(EthereumHardfork::SpuriousDragon.boxed(), genesis.config.eip155_block),
(EthereumHardfork::Byzantium.boxed(), genesis.config.byzantium_block),
(EthereumHardfork::Constantinople.boxed(), genesis.config.constantinople_block),
(EthereumHardfork::Petersburg.boxed(), genesis.config.petersburg_block),
(EthereumHardfork::Istanbul.boxed(), genesis.config.istanbul_block),
(EthereumHardfork::MuirGlacier.boxed(), genesis.config.muir_glacier_block),
(EthereumHardfork::Berlin.boxed(), genesis.config.berlin_block),
(EthereumHardfork::London.boxed(), genesis.config.london_block),
(EthereumHardfork::ArrowGlacier.boxed(), genesis.config.arrow_glacier_block),
(EthereumHardfork::GrayGlacier.boxed(), genesis.config.gray_glacier_block),
];
let mut hardforks = hardfork_opts
.into_iter()
.filter_map(|(hardfork, opt)| opt.map(|block| (hardfork, ForkCondition::Block(block))))
.collect::<Vec<_>>();
// Paris
let paris_block_and_final_difficulty =
if let Some(ttd) = genesis.config.terminal_total_difficulty {
hardforks.push((
EthereumHardfork::Paris.boxed(),
ForkCondition::TTD {
total_difficulty: ttd,
fork_block: genesis.config.merge_netsplit_block,
},
));
genesis.config.merge_netsplit_block.map(|block| (block, ttd))
} else {
None
};
// Time-based hardforks
let time_hardfork_opts = [
(EthereumHardfork::Shanghai.boxed(), genesis.config.shanghai_time),
(EthereumHardfork::Cancun.boxed(), genesis.config.cancun_time),
(EthereumHardfork::Prague.boxed(), genesis.config.prague_time),
(EthereumHardfork::Osaka.boxed(), genesis.config.osaka_time),
];
let mut time_hardforks = time_hardfork_opts
.into_iter()
.filter_map(|(hardfork, opt)| {
opt.map(|time| (hardfork, ForkCondition::Timestamp(time)))
})
.collect::<Vec<_>>();
hardforks.append(&mut time_hardforks);
// Ordered Hardforks
let mainnet_hardforks: ChainHardforks = EthereumHardfork::mainnet().into();
let mainnet_order = mainnet_hardforks.forks_iter();
let mut ordered_hardforks = Vec::with_capacity(hardforks.len());
for (hardfork, _) in mainnet_order {
if let Some(pos) = hardforks.iter().position(|(e, _)| **e == *hardfork) {
ordered_hardforks.push(hardforks.remove(pos));
}
}
// append the remaining unknown hardforks to ensure we don't filter any out
ordered_hardforks.append(&mut hardforks);
// NOTE: in full node, we prune all receipts except the deposit contract's. We do not
// have the deployment block in the genesis file, so we use block zero. We use the same
// deposit topic as the mainnet contract if we have the deposit contract address in the
// genesis json.
let deposit_contract = genesis.config.deposit_contract_address.map(|address| {
DepositContract { address, block: 0, topic: MAINNET_DEPOSIT_CONTRACT.topic }
});
Self {
chain: genesis.config.chain_id.into(),
genesis,
genesis_hash: OnceLock::new(),
hardforks: ChainHardforks::new(ordered_hardforks),
paris_block_and_final_difficulty,
deposit_contract,
..Default::default()
}
}
}
impl Hardforks for ChainSpec {
fn fork<H: Hardfork>(&self, fork: H) -> ForkCondition {
self.hardforks.fork(fork)
}
fn forks_iter(&self) -> impl Iterator<Item = (&dyn Hardfork, ForkCondition)> {
self.hardforks.forks_iter()
}
fn fork_id(&self, head: &Head) -> ForkId {
self.fork_id(head)
}
fn latest_fork_id(&self) -> ForkId {
self.latest_fork_id()
}
fn fork_filter(&self, head: Head) -> ForkFilter {
self.fork_filter(head)
}
}
impl EthereumHardforks for ChainSpec {
fn get_final_paris_total_difficulty(&self) -> Option<U256> {
self.get_final_paris_total_difficulty()
}
fn final_paris_total_difficulty(&self, block_number: u64) -> Option<U256> {
self.final_paris_total_difficulty(block_number)
}
}
/// A trait for reading the current chainspec.
#[auto_impl::auto_impl(&, Arc)]
pub trait ChainSpecProvider: Send + Sync {
/// The chain spec type.
type ChainSpec: EthChainSpec + 'static;
/// Get an [`Arc`] to the chainspec.
fn chain_spec(&self) -> Arc<Self::ChainSpec>;
}
/// A helper to build custom chain specs
#[derive(Debug, Default, Clone)]
pub struct ChainSpecBuilder {
chain: Option<Chain>,
genesis: Option<Genesis>,
hardforks: ChainHardforks,
}
impl ChainSpecBuilder {
/// Construct a new builder from the mainnet chain spec.
pub fn mainnet() -> Self {
Self {
chain: Some(MAINNET.chain),
genesis: Some(MAINNET.genesis.clone()),
hardforks: MAINNET.hardforks.clone(),
}
}
}
impl ChainSpecBuilder {
/// Set the chain ID
pub const fn chain(mut self, chain: Chain) -> Self {
self.chain = Some(chain);
self
}
/// Set the genesis block.
pub fn genesis(mut self, genesis: Genesis) -> Self {
self.genesis = Some(genesis);
self
}
/// Add the given fork with the given activation condition to the spec.
pub fn with_fork<H: Hardfork>(mut self, fork: H, condition: ForkCondition) -> Self {
self.hardforks.insert(fork, condition);
self
}
/// Add the given chain hardforks to the spec.
pub fn with_forks(mut self, forks: ChainHardforks) -> Self {
self.hardforks = forks;
self
}
/// Remove the given fork from the spec.
pub fn without_fork<H: Hardfork>(mut self, fork: H) -> Self {
self.hardforks.remove(fork);
self
}
/// Enable the Paris hardfork at the given TTD.
///
/// Does not set the merge netsplit block.
pub fn paris_at_ttd(self, ttd: U256) -> Self {
self.with_fork(
EthereumHardfork::Paris,
ForkCondition::TTD { total_difficulty: ttd, fork_block: None },
)
}
/// Enable Frontier at genesis.
pub fn frontier_activated(mut self) -> Self {
self.hardforks.insert(EthereumHardfork::Frontier, ForkCondition::Block(0));
self
}
/// Enable Homestead at genesis.
pub fn homestead_activated(mut self) -> Self {
self = self.frontier_activated();
self.hardforks.insert(EthereumHardfork::Homestead, ForkCondition::Block(0));
self
}
/// Enable Tangerine at genesis.
pub fn tangerine_whistle_activated(mut self) -> Self {
self = self.homestead_activated();
self.hardforks.insert(EthereumHardfork::Tangerine, ForkCondition::Block(0));
self
}
/// Enable Spurious Dragon at genesis.
pub fn spurious_dragon_activated(mut self) -> Self {
self = self.tangerine_whistle_activated();
self.hardforks.insert(EthereumHardfork::SpuriousDragon, ForkCondition::Block(0));
self
}
/// Enable Byzantium at genesis.
pub fn byzantium_activated(mut self) -> Self {
self = self.spurious_dragon_activated();
self.hardforks.insert(EthereumHardfork::Byzantium, ForkCondition::Block(0));
self
}
/// Enable Constantinople at genesis.
pub fn constantinople_activated(mut self) -> Self {
self = self.byzantium_activated();
self.hardforks.insert(EthereumHardfork::Constantinople, ForkCondition::Block(0));
self
}
/// Enable Petersburg at genesis.
pub fn petersburg_activated(mut self) -> Self {
self = self.constantinople_activated();
self.hardforks.insert(EthereumHardfork::Petersburg, ForkCondition::Block(0));
self
}
/// Enable Istanbul at genesis.
pub fn istanbul_activated(mut self) -> Self {
self = self.petersburg_activated();
self.hardforks.insert(EthereumHardfork::Istanbul, ForkCondition::Block(0));
self
}
/// Enable Berlin at genesis.
pub fn berlin_activated(mut self) -> Self {
self = self.istanbul_activated();
self.hardforks.insert(EthereumHardfork::Berlin, ForkCondition::Block(0));
self
}
/// Enable London at genesis.
pub fn london_activated(mut self) -> Self {
self = self.berlin_activated();
self.hardforks.insert(EthereumHardfork::London, ForkCondition::Block(0));
self
}
/// Enable Paris at genesis.
pub fn paris_activated(mut self) -> Self {
self = self.london_activated();
self.hardforks.insert(
EthereumHardfork::Paris,
ForkCondition::TTD { fork_block: Some(0), total_difficulty: U256::ZERO },
);
self
}
/// Enable Shanghai at genesis.
pub fn shanghai_activated(mut self) -> Self {
self = self.paris_activated();
self.hardforks.insert(EthereumHardfork::Shanghai, ForkCondition::Timestamp(0));
self
}
/// Enable Cancun at genesis.
pub fn cancun_activated(mut self) -> Self {
self = self.shanghai_activated();
self.hardforks.insert(EthereumHardfork::Cancun, ForkCondition::Timestamp(0));
self
}
/// Enable Prague at genesis.
pub fn prague_activated(mut self) -> Self {
self = self.cancun_activated();
self.hardforks.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(0));
self
}
/// Enable Osaka at genesis.
pub fn osaka_activated(mut self) -> Self {
self = self.prague_activated();
self.hardforks.insert(EthereumHardfork::Osaka, ForkCondition::Timestamp(0));
self
}
/// Build the resulting [`ChainSpec`].
///
/// # Panics
///
/// This function panics if the chain ID and genesis is not set ([`Self::chain`] and
/// [`Self::genesis`])
pub fn build(self) -> ChainSpec {
let paris_block_and_final_difficulty = {
self.hardforks.get(EthereumHardfork::Paris).and_then(|cond| {
if let ForkCondition::TTD { fork_block, total_difficulty } = cond {
fork_block.map(|fork_block| (fork_block, total_difficulty))
} else {
None
}
})
};
ChainSpec {
chain: self.chain.expect("The chain is required"),
genesis: self.genesis.expect("The genesis is required"),
genesis_hash: OnceLock::new(),
hardforks: self.hardforks,
paris_block_and_final_difficulty,
deposit_contract: None,
..Default::default()
}
}
}
impl From<&Arc<ChainSpec>> for ChainSpecBuilder {
fn from(value: &Arc<ChainSpec>) -> Self {
Self {
chain: Some(value.chain),
genesis: Some(value.genesis.clone()),
hardforks: value.hardforks.clone(),
}
}
}
/// `PoS` deposit contract details.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DepositContract {
/// Deposit Contract Address
pub address: Address,
/// Deployment Block
pub block: BlockNumber,
/// `DepositEvent` event signature
pub topic: B256,
}
impl DepositContract {
/// Creates a new [`DepositContract`].
pub const fn new(address: Address, block: BlockNumber, topic: B256) -> Self {
Self { address, block, topic }
}
}
/// Verifies [`ChainSpec`] configuration against expected data in given cases.
#[cfg(any(test, feature = "test-utils"))]
pub fn test_fork_ids(spec: &ChainSpec, cases: &[(Head, ForkId)]) {
for (block, expected_id) in cases {
let computed_id = spec.fork_id(block);
assert_eq!(
expected_id, &computed_id,
"Expected fork ID {:?}, computed fork ID {:?} at block {}",
expected_id, computed_id, block.number
);
}
}
#[cfg(test)]
mod tests {
use core::ops::Deref;
use std::{collections::HashMap, str::FromStr};
use alloy_chains::Chain;
use alloy_genesis::{ChainConfig, GenesisAccount};
use alloy_primitives::{b256, hex};
use alloy_trie::EMPTY_ROOT_HASH;
use reth_ethereum_forks::{ForkCondition, ForkHash, ForkId, Head};
use reth_trie_common::TrieAccount;
use super::*;
fn test_hardfork_fork_ids(spec: &ChainSpec, cases: &[(EthereumHardfork, ForkId)]) {
for (hardfork, expected_id) in cases {
if let Some(computed_id) = spec.hardfork_fork_id(*hardfork) {
assert_eq!(
expected_id, &computed_id,
"Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for hardfork {hardfork}"
);
if matches!(hardfork, EthereumHardfork::Shanghai) {
if let Some(shangai_id) = spec.shanghai_fork_id() {
assert_eq!(
expected_id, &shangai_id,
"Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for Shanghai hardfork"
);
} else {
panic!("Expected ForkCondition to return Some for Hardfork::Shanghai");
}
}
}
}
}
#[test]
fn test_hardfork_list_display_mainnet() {
assert_eq!(
MAINNET.display_hardforks().to_string(),
"Pre-merge hard forks (block based):
- Frontier @0
- Homestead @1150000
- Dao @1920000
- Tangerine @2463000
- SpuriousDragon @2675000
- Byzantium @4370000
- Constantinople @7280000
- Petersburg @7280000
- Istanbul @9069000
- MuirGlacier @9200000
- Berlin @12244000
- London @12965000