Skip to content

Commit c773305

Browse files
authored
refactor: move consensus related constants into ethportal-api (#1825)
1 parent 5dca37d commit c773305

File tree

16 files changed

+87
-66
lines changed

16 files changed

+87
-66
lines changed

bin/e2hs-writer/src/subcommands/head_generator/e2hs_builder.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ use std::path::PathBuf;
22

33
use anyhow::ensure;
44
use e2store::e2hs::{E2HSWriter, BLOCKS_PER_E2HS};
5-
use ethportal_api::consensus::{beacon_block::BeaconBlockElectra, beacon_state::HistoricalBatch};
5+
use ethportal_api::consensus::{
6+
beacon_block::BeaconBlockElectra, beacon_state::HistoricalBatch,
7+
historical_summaries::historical_summary_index,
8+
};
69
use ssz_types::FixedVector;
710
use tempfile::TempDir;
811
use tracing::info;
9-
use trin_validation::{
10-
constants::{CAPELLA_FORK_EPOCH, SLOTS_PER_EPOCH, SLOTS_PER_HISTORICAL_ROOT},
11-
header_validator::HeaderValidator,
12-
};
12+
use trin_validation::header_validator::HeaderValidator;
1313

1414
use super::ethereum_api::EthereumApi;
1515
use crate::{
@@ -19,7 +19,7 @@ use crate::{
1919

2020
struct ProvingAnchors {
2121
current_historical_batch: HistoricalBatch,
22-
current_historical_summaries_index: u64,
22+
current_historical_summary_index: usize,
2323
header_validator: HeaderValidator,
2424
}
2525

@@ -34,7 +34,7 @@ impl ProvingAnchors {
3434
block_roots: FixedVector::default(),
3535
state_roots: FixedVector::default(),
3636
},
37-
current_historical_summaries_index: 0,
37+
current_historical_summary_index: 0,
3838
header_validator: HeaderValidator::new_with_historical_summaries(Default::default()),
3939
}
4040
}
@@ -112,8 +112,9 @@ impl E2HSBuilder {
112112

113113
/// If the historical summaries index has changed, update the proving anchors.
114114
async fn update_proving_anchors(&mut self, slot: u64) -> anyhow::Result<()> {
115-
let historical_summaries_index = historical_summaries_index(slot);
116-
if historical_summaries_index == self.proving_anchors.current_historical_summaries_index {
115+
let historical_summary_index = historical_summary_index(slot)
116+
.expect("Relevant slot must have historical_summary_index");
117+
if historical_summary_index == self.proving_anchors.current_historical_summary_index {
117118
return Ok(());
118119
}
119120

@@ -122,7 +123,7 @@ impl E2HSBuilder {
122123
.get_state_for_start_of_next_period(slot)
123124
.await?;
124125

125-
self.proving_anchors.current_historical_summaries_index = historical_summaries_index;
126+
self.proving_anchors.current_historical_summary_index = historical_summary_index;
126127
self.proving_anchors.header_validator =
127128
HeaderValidator::new_with_historical_summaries(state.historical_summaries);
128129
self.proving_anchors.current_historical_batch = HistoricalBatch {
@@ -155,8 +156,3 @@ impl E2HSBuilder {
155156
})
156157
}
157158
}
158-
159-
/// Calculate the historical summaries index for a given slot.
160-
pub fn historical_summaries_index(slot: u64) -> u64 {
161-
(slot - CAPELLA_FORK_EPOCH * SLOTS_PER_EPOCH) / SLOTS_PER_HISTORICAL_ROOT
162-
}

bin/e2hs-writer/src/subcommands/head_generator/ethereum_api.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
use anyhow::{anyhow, bail, ensure};
22
use ethportal_api::{
3-
consensus::{beacon_block::SignedBeaconBlockElectra, beacon_state::BeaconStateElectra},
3+
consensus::{
4+
beacon_block::SignedBeaconBlockElectra, beacon_state::BeaconStateElectra,
5+
constants::SLOTS_PER_HISTORICAL_ROOT,
6+
},
47
Receipts,
58
};
69
use portal_bridge::api::{consensus::ConsensusApi, execution::ExecutionApi};
710
use tracing::warn;
8-
use trin_validation::constants::SLOTS_PER_HISTORICAL_ROOT;
911
use url::Url;
1012

1113
pub struct EthereumApi {

bin/e2hs-writer/src/subcommands/head_generator/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ use anyhow::{bail, ensure};
1212
use e2hs_builder::E2HSBuilder;
1313
use e2store::e2hs::BLOCKS_PER_E2HS;
1414
use ethereum_api::first_slot_in_a_period;
15+
use ethportal_api::consensus::constants::SLOTS_PER_EPOCH;
1516
use humanize_duration::{prelude::DurationExt, Truncate};
1617
use s3_bucket::S3Bucket;
1718
use tokio::time::sleep;
1819
use tracing::{error, info};
19-
use trin_validation::constants::SLOTS_PER_EPOCH;
2020

2121
use crate::cli::HeadGeneratorConfig;
2222

bin/e2hs-writer/src/subcommands/single_generator/provider.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use e2store::{
1111
use ethportal_api::{
1212
consensus::{
1313
beacon_block::SignedBeaconBlock, beacon_state::HistoricalBatch,
14-
historical_summaries::HistoricalSummaries,
14+
constants::SLOTS_PER_HISTORICAL_ROOT, historical_summaries::HistoricalSummaries,
1515
},
1616
types::network_spec::network_spec,
1717
};
@@ -21,7 +21,6 @@ use reqwest::{
2121
};
2222
use tracing::info;
2323
use trin_execution::era::binary_search::EraBinarySearch;
24-
use trin_validation::constants::SLOTS_PER_HISTORICAL_ROOT;
2524

2625
pub enum EraSource {
2726
// processed era1 file

bin/portal-bridge/src/bridge/beacon.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ use std::{
77
use alloy::primitives::B256;
88
use anyhow::bail;
99
use ethportal_api::{
10-
consensus::historical_summaries::HistoricalSummariesWithProof,
10+
consensus::{
11+
constants::{SLOTS_PER_EPOCH, SLOTS_PER_HISTORICAL_ROOT},
12+
historical_summaries::HistoricalSummariesWithProof,
13+
},
1114
types::{
1215
consensus::fork::ForkName,
1316
content_key::beacon::{
@@ -31,7 +34,6 @@ use tokio::{
3134
use tracing::{error, info, warn, Instrument};
3235
use trin_beacon::network::BeaconNetwork;
3336
use trin_metrics::bridge::BridgeMetricsReporter;
34-
use trin_validation::constants::SLOTS_PER_EPOCH;
3537

3638
use super::{constants::SERVE_BLOCK_TIMEOUT, offer_report::OfferReport};
3739
use crate::{
@@ -42,9 +44,6 @@ use crate::{
4244
utils::{duration_until_next_update, expected_current_slot},
4345
};
4446

45-
/// The number of slots in a sync committee period.
46-
const SLOTS_PER_PERIOD: u64 = SLOTS_PER_EPOCH * 256;
47-
4847
/// A helper struct to hold the finalized beacon state metadata.
4948
#[derive(Clone, Debug, Default)]
5049
pub struct FinalizedBeaconState {
@@ -317,7 +316,7 @@ impl BeaconBridge {
317316
) -> anyhow::Result<()> {
318317
let now = SystemTime::now();
319318
let expected_current_period =
320-
expected_current_slot(BEACON_GENESIS_TIME, now) / SLOTS_PER_PERIOD;
319+
expected_current_slot(BEACON_GENESIS_TIME, now) / SLOTS_PER_HISTORICAL_ROOT;
321320
match expected_current_period.cmp(&*current_period.lock().await) {
322321
Ordering::Equal => {
323322
// We already gossiped the latest data from the current period, no need to serve it
@@ -337,7 +336,8 @@ impl BeaconBridge {
337336
.get_light_client_updates(expected_current_period, 1)
338337
.await?
339338
.remove(0);
340-
let finalized_header_period = update.finalized_header.beacon.slot / SLOTS_PER_PERIOD;
339+
let finalized_header_period =
340+
update.finalized_header.beacon.slot / SLOTS_PER_HISTORICAL_ROOT;
341341

342342
// We don't serve a `LightClientUpdate` if its finalized header slot is not within the
343343
// expected current period.

bin/portal-bridge/src/types/range.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::collections::HashMap;
22

3-
use trin_validation::constants::SLOTS_PER_HISTORICAL_ROOT;
3+
use ethportal_api::consensus::constants::SLOTS_PER_HISTORICAL_ROOT;
44

55
/// Converts a block range into a mapping of epoch indexes to block ranges.
66
///

bin/trin-execution/src/era/binary_search.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,6 @@ impl EraBinarySearch {
128128
}
129129

130130
fn start_slot_index(era_index: u64) -> u64 {
131-
(era_index - 1) * SLOTS_PER_HISTORICAL_ROOT as u64
131+
(era_index - 1) * SLOTS_PER_HISTORICAL_ROOT
132132
}
133133
}

crates/e2store/src/era.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ impl Era {
148148
}
149149

150150
pub fn epoch_index(&self) -> u64 {
151-
self.slot_index_state.slot_index.starting_slot / SLOTS_PER_HISTORICAL_ROOT as u64
151+
self.slot_index_state.slot_index.starting_slot / SLOTS_PER_HISTORICAL_ROOT
152152
}
153153
}
154154

@@ -284,25 +284,26 @@ impl From<&SlotIndexBlockEntry> for Entry {
284284
#[derive(Clone, Eq, PartialEq, Debug)]
285285
pub struct SlotIndexBlock {
286286
pub starting_slot: u64,
287-
pub indices: [i64; SLOTS_PER_HISTORICAL_ROOT],
287+
pub indices: [i64; SLOTS_PER_HISTORICAL_ROOT as usize],
288288
pub count: u64,
289289
}
290290

291291
impl SlotIndexBlock {
292-
pub const SERIALIZED_SIZE: usize = 8 * (1 + SLOTS_PER_HISTORICAL_ROOT + 1);
292+
pub const SERIALIZED_SIZE: usize = 8 * (1 + SLOTS_PER_HISTORICAL_ROOT as usize + 1);
293293
}
294294

295295
impl TryFrom<Entry> for SlotIndexBlock {
296296
type Error = anyhow::Error;
297297

298298
fn try_from(entry: Entry) -> Result<Self, Self::Error> {
299299
let starting_slot = u64::from_le_bytes(entry.value[0..8].try_into()?);
300-
let mut indices = [0i64; SLOTS_PER_HISTORICAL_ROOT];
300+
let mut indices = [0i64; SLOTS_PER_HISTORICAL_ROOT as usize];
301301
for (i, index) in indices.iter_mut().enumerate() {
302302
*index = i64::from_le_bytes(entry.value[(i * 8 + 8)..(i * 8 + 16)].try_into()?);
303303
}
304304
let count = u64::from_le_bytes(
305-
entry.value[(SLOTS_PER_HISTORICAL_ROOT * 8 + 8)..(SLOTS_PER_HISTORICAL_ROOT * 8 + 16)]
305+
entry.value[(SLOTS_PER_HISTORICAL_ROOT * 8 + 8) as usize
306+
..(SLOTS_PER_HISTORICAL_ROOT * 8 + 16) as usize]
306307
.try_into()?,
307308
);
308309
Ok(Self {
Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,21 @@
1-
//! Consensus specs values, taken from: https://github.com/ethereum/consensus-specs/blob/d8cfdf2626c1219a40048f8fa3dd103ae8c0b040/presets/mainnet/phase0.yaml
1+
//! Consensus specs constants.
2+
//!
3+
//! Mostly taken from: https://github.com/ethereum/consensus-specs/blob/d8cfdf2626c1219a40048f8fa3dd103ae8c0b040/presets/mainnet/phase0.yaml
4+
//!
5+
//! These should eventually be part of the Chain configuration parameters.
26
3-
pub const SLOTS_PER_HISTORICAL_ROOT: usize = 8192;
7+
/// Number of slots per Epoch.
8+
///
9+
/// 2**5 (= 32) slots 6.4 minutes
10+
pub const SLOTS_PER_EPOCH: u64 = 32;
11+
12+
/// Number of slots per HistoricalRoot / HistoricalSummary.
13+
///
14+
/// 2**13 (= 8,192) slots ~27 hours
15+
pub const SLOTS_PER_HISTORICAL_ROOT: u64 = 8192;
16+
17+
/// The Epoch of the mainnet Capella fork.
18+
///
19+
/// April 12, 2023, 10:27:35pm UTC
20+
/// Source: https://github.com/ethereum/consensus-specs/blob/d8cfdf2626c1219a40048f8fa3dd103ae8c0b040/configs/mainnet.yaml
21+
pub const CAPELLA_FORK_EPOCH: u64 = 194_048;

crates/ethportal-api/src/types/consensus/historical_summaries.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use ssz_derive::{Decode, Encode};
44
use ssz_types::{typenum, FixedVector, VariableList};
55
use tree_hash_derive::TreeHash;
66

7+
use super::constants::{CAPELLA_FORK_EPOCH, SLOTS_PER_EPOCH, SLOTS_PER_HISTORICAL_ROOT};
8+
79
/// The Generalized Index of the `historical_summaries` field of the
810
/// [BeaconState](super::beacon_state::BeaconState), for Electra fork.
911
pub const HISTORICAL_SUMMARIES_GINDEX: usize = 91;
@@ -36,3 +38,15 @@ pub struct HistoricalSummariesWithProof {
3638
pub historical_summaries: HistoricalSummaries,
3739
pub proof: HistoricalSummariesProof,
3840
}
41+
42+
/// Calculates the index of a [HistoricalSummary] in [HistoricalSummaries] for a given slot.
43+
///
44+
/// Returns `None` is slot is before Capella fork.
45+
pub fn historical_summary_index(slot: u64) -> Option<usize> {
46+
let capella_slot = CAPELLA_FORK_EPOCH * SLOTS_PER_EPOCH;
47+
if slot < capella_slot {
48+
None
49+
} else {
50+
Some(((slot - capella_slot) / SLOTS_PER_HISTORICAL_ROOT) as usize)
51+
}
52+
}

0 commit comments

Comments
 (0)