Skip to content

Commit 371a083

Browse files
committed
fix: address PR concerns
1 parent 4f2dd61 commit 371a083

File tree

5 files changed

+50
-95
lines changed

5 files changed

+50
-95
lines changed

bin/e2hs-writer/src/reader.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -70,17 +70,14 @@ impl EpochReader {
7070

7171
let starting_block = epoch_index * EPOCH_SIZE;
7272
let epoch_accumulator = match starting_block < MERGE_BLOCK_NUMBER {
73-
true => {
74-
let header_validator = HeaderValidator::new();
75-
Some(Arc::new(
76-
lookup_epoch_acc(
77-
epoch_index,
78-
&header_validator.pre_merge_acc,
79-
&epoch_acc_path,
80-
)
81-
.await?,
82-
))
83-
}
73+
true => Some(Arc::new(
74+
lookup_epoch_acc(
75+
epoch_index,
76+
&HeaderValidator::default().pre_merge_acc,
77+
&epoch_acc_path,
78+
)
79+
.await?,
80+
)),
8481
false => None,
8582
};
8683

bin/portal-bridge/src/api/execution.rs

+1-7
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,7 @@ use ethportal_api::{
1919
use serde_json::{json, Value};
2020
use tokio::time::sleep;
2121
use tracing::{debug, error, info, warn};
22-
use trin_validation::{
23-
accumulator::PreMergeAccumulator, constants::MERGE_BLOCK_NUMBER,
24-
header_validator::HeaderValidator,
25-
};
22+
use trin_validation::{accumulator::PreMergeAccumulator, constants::MERGE_BLOCK_NUMBER};
2623
use url::Url;
2724

2825
use crate::{
@@ -40,7 +37,6 @@ const BATCH_LIMIT: usize = 10;
4037
pub struct ExecutionApi {
4138
pub primary: Url,
4239
pub fallback: Url,
43-
pub header_validator: HeaderValidator,
4440
pub request_timeout: u64,
4541
}
4642

@@ -60,11 +56,9 @@ impl ExecutionApi {
6056
if let Err(err) = check_provider(&client).await {
6157
error!("Primary el provider is offline: {err:?}");
6258
}
63-
let header_validator = HeaderValidator::default();
6459
Ok(Self {
6560
primary,
6661
fallback,
67-
header_validator,
6862
request_timeout,
6963
})
7064
}

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

+3-4
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ use tokio::{
4141
};
4242
use tracing::{debug, error, info, warn};
4343
use trin_metrics::bridge::BridgeMetricsReporter;
44-
use trin_validation::header_validator::{HeaderValidator, HistoricalSummariesProvider};
44+
use trin_validation::header_validator::HeaderValidator;
4545

4646
use super::offer_report::{GlobalOfferReport, OfferReport};
4747
use crate::{
@@ -80,7 +80,6 @@ impl E2HSBridge {
8080
let block_semaphore = Arc::new(Semaphore::new(offer_limit));
8181
let mode = format!("{}-{}:{}", block_range.start, block_range.end, random_fill);
8282
let metrics = BridgeMetricsReporter::new("e2hs".to_string(), &mode);
83-
let header_validator = HeaderValidator::new();
8483
let http_client = Client::builder()
8584
.default_headers(HeaderMap::from_iter([(
8685
CONTENT_TYPE,
@@ -99,7 +98,7 @@ impl E2HSBridge {
9998
Ok(Self {
10099
gossiper,
101100
block_semaphore,
102-
header_validator,
101+
header_validator: HeaderValidator::default(),
103102
block_range,
104103
random_fill,
105104
e2hs_files,
@@ -219,7 +218,7 @@ impl E2HSBridge {
219218
BlockHeaderProof::HistoricalSummaries(_)
220219
) {
221220
self.header_validator
222-
.validate_header_with_proof(header_with_proof, HistoricalSummariesProvider::None)
221+
.validate_header_with_proof(header_with_proof)
223222
.await?;
224223
}
225224
let body = &block_tuple.body.body;

crates/subnetworks/history/src/validation.rs

+5-9
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ pub struct ChainHistoryValidator {
2626

2727
impl ChainHistoryValidator {
2828
pub fn new(header_oracle: Arc<RwLock<HeaderOracle>>) -> Self {
29-
let header_validator = HeaderValidator::default();
29+
let header_validator = HeaderValidator::new(HistoricalSummariesProvider::HeaderOracle(
30+
header_oracle.clone(),
31+
));
3032
info!(
3133
hash_tree_root = %hex_encode(header_validator.pre_merge_acc.tree_hash_root().0),
3234
"Loaded pre-merge accumulator."
@@ -57,10 +59,7 @@ impl Validator<HistoryContentKey> for ChainHistoryValidator {
5759
hex_encode(header_hash)
5860
);
5961
self.header_validator
60-
.validate_header_with_proof(
61-
&header_with_proof,
62-
HistoricalSummariesProvider::HeaderOracle(self.header_oracle.clone()),
63-
)
62+
.validate_header_with_proof(&header_with_proof)
6463
.await?;
6564

6665
Ok(ValidationResult::new(true))
@@ -77,10 +76,7 @@ impl Validator<HistoryContentKey> for ChainHistoryValidator {
7776
key.block_number
7877
);
7978
self.header_validator
80-
.validate_header_with_proof(
81-
&header_with_proof,
82-
HistoricalSummariesProvider::HeaderOracle(self.header_oracle.clone()),
83-
)
79+
.validate_header_with_proof(&header_with_proof)
8480
.await?;
8581

8682
Ok(ValidationResult::new(true))

crates/validation/src/header_validator.rs

+33-64
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@ use crate::{
2020
oracle::HeaderOracle,
2121
};
2222

23-
#[derive(Debug, Clone)]
23+
#[derive(Debug, Default, Clone)]
2424
pub enum HistoricalSummariesProvider {
2525
/// The historical summaries are provided by the header oracle.
2626
HeaderOracle(Arc<RwLock<HeaderOracle>>),
2727
/// The historical summaries are provided by passed historical summaries.
2828
HistoricalSummaries(HistoricalSummaries),
2929
/// We don't have historical summaries, for example the E2HS bridge doesn't use a provider and
3030
/// hence can't get HistoricalSummaries. HistoricalSummary proof validation will fail.
31+
#[default]
3132
None,
3233
}
3334

@@ -63,29 +64,33 @@ impl HistoricalSummariesProvider {
6364

6465
/// HeaderValidator is responsible for validating pre-merge and post-merge headers with their
6566
/// respective proofs.
66-
#[derive(Debug, Clone, PartialEq, Eq, Default)]
67+
///
68+
/// Default can only be used for validating pre-capella headers.
69+
#[derive(Debug, Clone, Default)]
6770
pub struct HeaderValidator {
6871
/// Pre-merge accumulator used to validate pre-merge headers.
6972
pub pre_merge_acc: PreMergeAccumulator,
7073
/// Historical roots accumulator used to validate post-merge/pre-Capella headers.
7174
pub historical_roots_acc: HistoricalRootsAccumulator,
75+
/// Historical summaries provider used to validate post-Capella headers.
76+
pub historical_summaries_provider: HistoricalSummariesProvider,
7277
}
7378

7479
impl HeaderValidator {
75-
pub fn new() -> Self {
80+
pub fn new(historical_summaries_provider: HistoricalSummariesProvider) -> Self {
7681
let pre_merge_acc = PreMergeAccumulator::default();
7782
let historical_roots_acc = HistoricalRootsAccumulator::default();
7883

7984
Self {
8085
pre_merge_acc,
8186
historical_roots_acc,
87+
historical_summaries_provider,
8288
}
8389
}
8490

8591
pub async fn validate_header_with_proof(
8692
&self,
8793
header_with_proof: &HeaderWithProof,
88-
historical_summaries_provider: HistoricalSummariesProvider,
8994
) -> anyhow::Result<()> {
9095
match &header_with_proof.proof {
9196
BlockHeaderProof::HistoricalHashes(proof) => {
@@ -123,7 +128,6 @@ impl HeaderValidator {
123128
header_with_proof.header.number,
124129
header_with_proof.header.hash_slow(),
125130
proof,
126-
historical_summaries_provider,
127131
)
128132
.await
129133
}
@@ -182,7 +186,6 @@ impl HeaderValidator {
182186
block_number: u64,
183187
header_hash: B256,
184188
proof: &BlockProofHistoricalSummaries,
185-
historical_summaries_provider: HistoricalSummariesProvider,
186189
) -> anyhow::Result<()> {
187190
if block_number < SHANGHAI_BLOCK_NUMBER {
188191
return Err(anyhow!(
@@ -202,7 +205,8 @@ impl HeaderValidator {
202205
let historical_summary_index =
203206
(proof.slot - CAPELLA_FORK_EPOCH * SLOTS_PER_EPOCH) / EPOCH_SIZE;
204207

205-
let block_summary_root = historical_summaries_provider
208+
let block_summary_root = self
209+
.historical_summaries_provider
206210
.get_historical_summary(
207211
proof.slot / SLOTS_PER_EPOCH,
208212
historical_summary_index as usize,
@@ -320,7 +324,6 @@ mod test {
320324
.unwrap();
321325
let json: Value = serde_json::from_str(&file).unwrap();
322326
let hwps = json.as_object().unwrap();
323-
let header_validator = get_mainnet_header_validator();
324327
let obj = hwps.get(&block_number.to_string()).unwrap();
325328
// Validate content_key decodes
326329
let raw_ck = obj.get("content_key").unwrap().as_str().unwrap();
@@ -340,17 +343,12 @@ mod test {
340343
_ => panic!("test reached invalid state"),
341344
};
342345
assert_eq!(trin_proof, fluffy_proof);
343-
let hwp = HeaderWithProof {
346+
let header_with_proof = HeaderWithProof {
344347
header,
345348
proof: BlockHeaderProof::HistoricalHashes(trin_proof),
346349
};
347-
header_validator
348-
.validate_header_with_proof(
349-
&hwp,
350-
HistoricalSummariesProvider::HeaderOracle(Arc::new(RwLock::new(
351-
HeaderOracle::default(),
352-
))),
353-
)
350+
HeaderValidator::default()
351+
.validate_header_with_proof(&header_with_proof)
354352
.await
355353
.unwrap();
356354
}
@@ -374,46 +372,37 @@ mod test {
374372
header,
375373
proof: BlockHeaderProof::HistoricalHashes(proof),
376374
};
377-
HeaderValidator::new()
378-
.validate_header_with_proof(
379-
&header_with_proof,
380-
HistoricalSummariesProvider::HeaderOracle(Arc::new(RwLock::new(
381-
HeaderOracle::default(),
382-
))),
383-
)
375+
HeaderValidator::default()
376+
.validate_header_with_proof(&header_with_proof)
384377
.await
385378
.unwrap();
386-
let encoded_hwp = hex_encode(header_with_proof.as_ssz_bytes());
379+
let encoded_header_with_proof = hex_encode(header_with_proof.as_ssz_bytes());
387380

388-
let hwp_test_vector = serde_yaml::from_str::<serde_yaml::Value>(
381+
let header_with_proof_test_vector = serde_yaml::from_str::<serde_yaml::Value>(
389382
&read_portal_spec_tests_file(format!(
390383
"tests/mainnet/history/headers_with_proof/{block_number}.yaml",
391384
))
392385
.unwrap(),
393386
)
394387
.unwrap();
395-
let expected_hwp = hwp_test_vector["content_value"].as_str().unwrap();
396-
assert_eq!(encoded_hwp, expected_hwp);
388+
let expected_header_with_proof = header_with_proof_test_vector["content_value"]
389+
.as_str()
390+
.unwrap();
391+
assert_eq!(encoded_header_with_proof, expected_header_with_proof);
397392
}
398393

399394
#[tokio::test]
400395
async fn invalidate_invalid_proofs() {
401-
let header_validator = get_mainnet_header_validator();
402396
let header = get_header(1_000_001);
403397
let epoch_accumulator = read_epoch_accumulator_122();
404398
let mut proof = PreMergeAccumulator::construct_proof(&header, &epoch_accumulator).unwrap();
405399
proof.swap(0, 1);
406-
let hwp = HeaderWithProof {
400+
let header_with_proof = HeaderWithProof {
407401
header,
408402
proof: BlockHeaderProof::HistoricalHashes(proof),
409403
};
410-
assert!(header_validator
411-
.validate_header_with_proof(
412-
&hwp,
413-
HistoricalSummariesProvider::HeaderOracle(Arc::new(RwLock::new(
414-
HeaderOracle::default(),
415-
))),
416-
)
404+
assert!(HeaderValidator::default()
405+
.validate_header_with_proof(&header_with_proof)
417406
.await
418407
.unwrap_err()
419408
.to_string()
@@ -423,27 +412,19 @@ mod test {
423412
#[tokio::test]
424413
#[should_panic(expected = "Invalid proof type found for post-merge header.")]
425414
async fn header_validator_invalidates_post_merge_header_with_accumulator_proof() {
426-
let header_validator = get_mainnet_header_validator();
427415
let future_height = MERGE_BLOCK_NUMBER + 1;
428416
let future_header = generate_random_header(&future_height);
429417
let future_hwp = HeaderWithProof {
430418
header: future_header,
431419
proof: BlockHeaderProof::HistoricalHashes(Default::default()),
432420
};
433-
header_validator
434-
.validate_header_with_proof(
435-
&future_hwp,
436-
HistoricalSummariesProvider::HeaderOracle(Arc::new(RwLock::new(
437-
HeaderOracle::default(),
438-
))),
439-
)
421+
HeaderValidator::default()
422+
.validate_header_with_proof(&future_hwp)
440423
.await
441424
.unwrap();
442425
}
443426
#[tokio::test]
444427
async fn header_validator_validate_post_merge_pre_capella_header() {
445-
let header_validator = get_mainnet_header_validator();
446-
447428
// Read the historical roots block proof from a test file
448429
let file = read_portal_spec_tests_file(PathBuf::from(SPEC_TESTS_DIR).join(
449430
"headers_with_proof/block_proofs_bellatrix/beacon_block_proof-15539558-cdf9ed89b0c43cda17398dc4da9cfc505e5ccd19f7c39e3b43474180f1051e01.yaml",
@@ -460,6 +441,7 @@ mod test {
460441
let historical_roots_block_proof: BlockProofHistoricalRoots =
461442
serde_yaml::from_value(value).unwrap();
462443

444+
let header_validator = HeaderValidator::default();
463445
header_validator
464446
.verify_historical_roots(block_number, header_hash, &historical_roots_block_proof)
465447
.unwrap();
@@ -486,8 +468,6 @@ mod test {
486468
#[case(17062257)]
487469
#[tokio::test]
488470
async fn header_validator_validate_post_capella_header(#[case] block_number: u64) {
489-
let header_validator = get_mainnet_header_validator();
490-
491471
// Read the historical roots block proof from a test file
492472
let file = read_portal_spec_tests_file(PathBuf::from(SPEC_TESTS_DIR).join(format!(
493473
"headers_with_proof/block_proofs_capella/beacon_block_proof-{block_number}.yaml"
@@ -512,12 +492,15 @@ mod test {
512492
let historical_summaries = HistoricalSummaries::from_ssz_bytes(&historical_summaries_bytes)
513493
.expect("cannot decode HistoricalSummaries bytes");
514494

495+
let header_validator = HeaderValidator::new(
496+
HistoricalSummariesProvider::HistoricalSummaries(historical_summaries),
497+
);
498+
515499
header_validator
516500
.verify_historical_summaries(
517501
block_number,
518502
header_hash,
519503
&historical_summaries_block_proof,
520-
HistoricalSummariesProvider::HistoricalSummaries(historical_summaries.clone()),
521504
)
522505
.await
523506
.unwrap();
@@ -528,24 +511,11 @@ mod test {
528511
SHANGHAI_BLOCK_NUMBER - 1,
529512
header_hash,
530513
&historical_summaries_block_proof,
531-
HistoricalSummariesProvider::HistoricalSummaries(historical_summaries),
532514
)
533515
.await;
534516
assert!(validator_result.is_err());
535517
}
536518

537-
//
538-
// Testing utils
539-
//
540-
fn get_mainnet_header_validator() -> HeaderValidator {
541-
let header_validator = HeaderValidator::default();
542-
assert_eq!(
543-
header_validator.pre_merge_acc.tree_hash_root(),
544-
B256::from_str(DEFAULT_PRE_MERGE_ACC_HASH).unwrap()
545-
);
546-
header_validator
547-
}
548-
549519
pub(crate) fn get_header(number: u64) -> Header {
550520
let file = fs::read_to_string("./src/assets/header_rlps.json").unwrap();
551521
let json: Value = serde_json::from_str(&file).unwrap();
@@ -581,9 +551,8 @@ mod test {
581551

582552
#[tokio::test]
583553
async fn header_oracle_bootstraps_with_default_pre_merge_acc() {
584-
let header_validator = HeaderValidator::default();
585554
assert_eq!(
586-
header_validator.pre_merge_acc.tree_hash_root(),
555+
HeaderValidator::default().pre_merge_acc.tree_hash_root(),
587556
B256::from_str(DEFAULT_PRE_MERGE_ACC_HASH).unwrap(),
588557
);
589558
}

0 commit comments

Comments
 (0)