Skip to main content

forest/chain_sync/
validation.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use crate::blocks::{BLOCK_MESSAGE_LIMIT, Block, FullTipset, GossipBlock, Tipset, TxMeta};
7use crate::chain::ChainStore;
8use crate::shim::clock::ChainEpoch;
9use crate::utils::db::CborStoreExt;
10use cid::Cid;
11use fil_actors_shared::fvm_ipld_amt::{Amtv0 as Amt, Error as IpldAmtError};
12use fvm_ipld_blockstore::Blockstore;
13use fvm_ipld_encoding::Error as EncodingError;
14use thiserror::Error;
15
16use crate::chain_sync::bad_block_cache::{BadBlockCache, SeenBlockCache};
17
18const MAX_HEIGHT_DRIFT: ChainEpoch = 5;
19
20/// Compute the maximum allowed epoch given the current time (seconds since
21/// UNIX epoch). Returns `None` if inputs are nonsensical (clock before
22/// genesis, zero block delay).
23fn max_allowed_epoch(
24    now_secs: u64,
25    genesis_timestamp: u64,
26    block_delay: u32,
27) -> Option<ChainEpoch> {
28    let elapsed = now_secs.checked_sub(genesis_timestamp)?;
29    let delay = u64::from(block_delay);
30    if delay == 0 {
31        return None;
32    }
33    let epoch = ChainEpoch::try_from(elapsed / delay).unwrap_or(ChainEpoch::MAX);
34    Some(epoch.saturating_add(MAX_HEIGHT_DRIFT))
35}
36
37fn now_secs() -> u64 {
38    SystemTime::now()
39        .duration_since(UNIX_EPOCH)
40        .unwrap_or_default()
41        .as_secs()
42}
43
44#[derive(Debug, Error)]
45pub enum TipsetValidationError {
46    #[error("Tipset has no blocks")]
47    NoBlocks,
48    #[error("Tipset has an epoch that is too large")]
49    EpochTooLarge,
50    #[error("Tipset has an insufficient weight")]
51    InsufficientWeight,
52    #[error("Tipset block = [CID = {0}] is invalid")]
53    InvalidBlock(Cid),
54    #[error("Tipset headers are invalid")]
55    InvalidRoots,
56    #[error("Tipset IPLD error: {0}")]
57    IpldAmt(String),
58    #[error("Block store error while validating tipset: {0}")]
59    Blockstore(String),
60    #[error("Encoding error while validating tipset: {0}")]
61    Encoding(EncodingError),
62}
63
64impl From<EncodingError> for TipsetValidationError {
65    fn from(err: EncodingError) -> Self {
66        TipsetValidationError::Encoding(err)
67    }
68}
69
70impl From<IpldAmtError> for TipsetValidationError {
71    fn from(err: IpldAmtError) -> Self {
72        TipsetValidationError::IpldAmt(err.to_string())
73    }
74}
75
76pub struct TipsetValidator<'a>(pub &'a FullTipset);
77
78impl TipsetValidator<'_> {
79    pub fn validate(
80        &self,
81        chainstore: &ChainStore,
82        bad_block_cache: Option<&BadBlockCache>,
83        genesis_tipset: &Tipset,
84        block_delay: u32,
85    ) -> Result<(), TipsetValidationError> {
86        // No empty blocks
87        if self.0.blocks().is_empty() {
88            return Err(TipsetValidationError::NoBlocks);
89        }
90
91        // Tipset epoch must not be behind current max
92        self.validate_epoch(genesis_tipset, block_delay)?;
93
94        // Validate each block in the tipset by:
95        // 1. Calculating the message root using all of the messages to ensure it
96        // matches the mst root in the block header 2. Ensuring it has not
97        // previously been seen in the bad blocks cache
98        for block in self.0.blocks() {
99            Self::validate_msg_root(chainstore.db(), block)?;
100            if let Some(bad_block_cache) = bad_block_cache
101                && bad_block_cache.get(block.cid()).is_some()
102            {
103                return Err(TipsetValidationError::InvalidBlock(*block.cid()));
104            }
105        }
106
107        Ok(())
108    }
109
110    pub fn validate_epoch(
111        &self,
112        genesis_tipset: &Tipset,
113        block_delay: u32,
114    ) -> Result<(), TipsetValidationError> {
115        let max = max_allowed_epoch(now_secs(), genesis_tipset.min_timestamp(), block_delay)
116            .unwrap_or(ChainEpoch::MAX);
117        if self.0.epoch() > max {
118            Err(TipsetValidationError::EpochTooLarge)
119        } else {
120            Ok(())
121        }
122    }
123
124    pub fn validate_msg_root<DB: Blockstore>(
125        blockstore: &DB,
126        block: &Block,
127    ) -> Result<(), TipsetValidationError> {
128        let msg_root = Self::compute_msg_root(
129            blockstore,
130            block.bls_msgs().iter().map(|m| m.cid()),
131            block.secp_msgs().iter().map(|m| m.signed_cid()),
132        )?;
133        if block.header().messages != msg_root {
134            Err(TipsetValidationError::InvalidRoots)
135        } else {
136            Ok(())
137        }
138    }
139
140    pub fn compute_msg_root<DB: Blockstore>(
141        blockstore: &DB,
142        bls_cids: impl IntoIterator<Item = Cid>,
143        secp_cids: impl IntoIterator<Item = Cid>,
144    ) -> Result<Cid, TipsetValidationError> {
145        // Generate Amt and batch set message values
146        let bls_message_root = Amt::new_from_iter(blockstore, bls_cids)?;
147        let secp_message_root = Amt::new_from_iter(blockstore, secp_cids)?;
148        let meta = TxMeta {
149            bls_message_root,
150            secp_message_root,
151        };
152
153        // Store message roots and receive meta_root CID
154        blockstore
155            .put_cbor_default(&meta)
156            .map_err(|e| TipsetValidationError::Blockstore(e.to_string()))
157    }
158}
159
160#[derive(Debug, Error)]
161pub enum GossipBlockRejectReason {
162    #[error("block epoch {0} is too far in the future")]
163    EpochTooFarAhead(ChainEpoch),
164    #[error("block epoch {epoch} is beyond finality (finalized: {finalized_epoch})")]
165    EpochBeyondFinality {
166        epoch: ChainEpoch,
167        finalized_epoch: ChainEpoch,
168    },
169    #[error("block epoch {0} is negative")]
170    NegativeEpoch(ChainEpoch),
171    #[error("block timestamp {timestamp} inconsistent with epoch {epoch} (expected {expected})")]
172    TimestampMismatch {
173        timestamp: u64,
174        epoch: ChainEpoch,
175        expected: u64,
176    },
177    #[error("block has no signature")]
178    MissingSignature,
179    #[error("block has no election proof")]
180    MissingElectionProof,
181    #[error("block election proof has win_count {0} < 1")]
182    InvalidWinCount(i64),
183    #[error("block has {0} messages, exceeding limit of {BLOCK_MESSAGE_LIMIT}")]
184    TooManyMessages(usize),
185    #[error("block CID {0} is in bad block cache")]
186    BadBlock(Cid),
187    #[error("duplicate block CID {0}")]
188    DuplicateBlock(Cid),
189}
190
191impl GossipBlockRejectReason {
192    pub fn label(&self) -> &'static str {
193        match self {
194            Self::EpochTooFarAhead(_) => "epoch_too_far_ahead",
195            Self::EpochBeyondFinality { .. } => "epoch_beyond_finality",
196            Self::NegativeEpoch(_) => "negative_epoch",
197            Self::TimestampMismatch { .. } => "timestamp_mismatch",
198            Self::MissingSignature => "missing_signature",
199            Self::MissingElectionProof => "missing_election_proof",
200            Self::InvalidWinCount(_) => "invalid_win_count",
201            Self::TooManyMessages(_) => "too_many_messages",
202            Self::BadBlock(_) => "bad_block",
203            Self::DuplicateBlock(_) => "duplicate_block",
204        }
205    }
206}
207
208/// Pre-validation of gossip blocks to avoid expensive `get_full_tipset`
209/// network round-trips and DB writes for obviously invalid blocks.
210/// Only uses data already present in the gossip message (header + CIDs).
211pub struct GossipBlockValidator<'a> {
212    block: &'a GossipBlock,
213}
214
215impl<'a> GossipBlockValidator<'a> {
216    pub fn new(block: &'a GossipBlock) -> Self {
217        Self { block }
218    }
219
220    /// Run all pre-fetch validation checks.
221    /// Checks are ordered cheapest/most-likely-to-reject first.
222    pub fn validate_pre_fetch(
223        &self,
224        genesis_tipset: &Tipset,
225        block_delay: u32,
226        finalized_epoch: ChainEpoch,
227        bad_block_cache: Option<&BadBlockCache>,
228        seen_block_cache: &SeenBlockCache,
229    ) -> Result<(), GossipBlockRejectReason> {
230        let cid = *self.block.header.cid();
231        Self::check_bad_block_cache(cid, bad_block_cache)?;
232        self.validate_epoch_range(genesis_tipset, block_delay, finalized_epoch)?;
233        self.validate_timestamp(genesis_tipset, block_delay)?;
234        self.validate_election_proof()?;
235        self.validate_signature_present()?;
236        self.validate_message_count()?;
237        // Insert into seen cache only after all checks pass, so transiently
238        // rejected blocks (e.g., slightly-future epoch) aren't suppressed later.
239        Self::check_duplicate(cid, seen_block_cache)?;
240        Ok(())
241    }
242
243    fn check_duplicate(
244        cid: Cid,
245        seen_block_cache: &SeenBlockCache,
246    ) -> Result<(), GossipBlockRejectReason> {
247        if seen_block_cache.test_and_insert(&cid) {
248            return Err(GossipBlockRejectReason::DuplicateBlock(cid));
249        }
250        Ok(())
251    }
252
253    fn check_bad_block_cache(
254        cid: Cid,
255        bad_block_cache: Option<&BadBlockCache>,
256    ) -> Result<(), GossipBlockRejectReason> {
257        if let Some(cache) = bad_block_cache
258            && cache.get(&cid).is_some()
259        {
260            return Err(GossipBlockRejectReason::BadBlock(cid));
261        }
262        Ok(())
263    }
264
265    fn validate_epoch_range(
266        &self,
267        genesis_tipset: &Tipset,
268        block_delay: u32,
269        finalized_epoch: ChainEpoch,
270    ) -> Result<(), GossipBlockRejectReason> {
271        let epoch = self.block.header.epoch;
272        if epoch < 0 {
273            return Err(GossipBlockRejectReason::NegativeEpoch(epoch));
274        }
275        let max = max_allowed_epoch(now_secs(), genesis_tipset.min_timestamp(), block_delay)
276            .unwrap_or(ChainEpoch::MAX);
277        if epoch > max {
278            return Err(GossipBlockRejectReason::EpochTooFarAhead(epoch));
279        }
280        if epoch < finalized_epoch {
281            return Err(GossipBlockRejectReason::EpochBeyondFinality {
282                epoch,
283                finalized_epoch,
284            });
285        }
286        Ok(())
287    }
288
289    /// Verify that block timestamp is consistent with its epoch:
290    /// `timestamp == genesis_timestamp + epoch * block_delay`
291    fn validate_timestamp(
292        &self,
293        genesis_tipset: &Tipset,
294        block_delay: u32,
295    ) -> Result<(), GossipBlockRejectReason> {
296        let epoch = self.block.header.epoch;
297        let timestamp = self.block.header.timestamp;
298        // epoch is validated non-negative by validate_epoch_range before this
299        // Saturating would let a block claiming `u64::MAX` match the saturated expectation.
300        let expected = (epoch as u64)
301            .checked_mul(u64::from(block_delay))
302            .and_then(|elapsed| genesis_tipset.min_timestamp().checked_add(elapsed))
303            .ok_or(GossipBlockRejectReason::EpochTooFarAhead(epoch))?;
304        if timestamp != expected {
305            return Err(GossipBlockRejectReason::TimestampMismatch {
306                timestamp,
307                epoch,
308                expected,
309            });
310        }
311        Ok(())
312    }
313
314    fn validate_election_proof(&self) -> Result<(), GossipBlockRejectReason> {
315        match &self.block.header.election_proof {
316            None => Err(GossipBlockRejectReason::MissingElectionProof),
317            Some(proof) if proof.win_count < 1 => {
318                Err(GossipBlockRejectReason::InvalidWinCount(proof.win_count))
319            }
320            _ => Ok(()),
321        }
322    }
323
324    fn validate_signature_present(&self) -> Result<(), GossipBlockRejectReason> {
325        if self.block.header.signature.is_none() {
326            return Err(GossipBlockRejectReason::MissingSignature);
327        }
328        Ok(())
329    }
330
331    fn validate_message_count(&self) -> Result<(), GossipBlockRejectReason> {
332        let count = self.block.bls_messages.len() + self.block.secpk_messages.len();
333        if count > BLOCK_MESSAGE_LIMIT {
334            return Err(GossipBlockRejectReason::TooManyMessages(count));
335        }
336        Ok(())
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use std::convert::TryFrom;
343
344    use crate::blocks::{CachingBlockHeader, ElectionProof, GossipBlock, RawBlockHeader, Tipset};
345    use crate::chain_sync::bad_block_cache::{BadBlockCache, SeenBlockCache};
346    use crate::db::MemoryDB;
347    use crate::message::SignedMessage;
348    use crate::shim::crypto::{Signature, SignatureType};
349    use crate::shim::message::Message;
350    use crate::test_utils::construct_messages;
351    use crate::utils::encoding::from_slice_with_fallback;
352    use base64::{Engine, prelude::BASE64_STANDARD};
353    use cid::Cid;
354    use rstest::rstest;
355
356    use super::{GossipBlockRejectReason, GossipBlockValidator, TipsetValidator};
357
358    #[test]
359    fn compute_msg_meta_given_msgs_test() {
360        let blockstore = MemoryDB::default();
361
362        let (bls, secp) = construct_messages();
363
364        let expected_root =
365            Cid::try_from("bafy2bzaceasssikoiintnok7f3sgnekfifarzobyr3r4f25sgxmn23q4c35ic")
366                .unwrap();
367
368        let root = TipsetValidator::compute_msg_root(&blockstore, [bls.cid()], [secp.signed_cid()])
369            .expect("Computing message root should succeed");
370        assert_eq!(root, expected_root);
371    }
372
373    #[test]
374    fn empty_msg_meta_vector() {
375        let blockstore = MemoryDB::default();
376        let usm: Vec<Message> =
377            from_slice_with_fallback(&BASE64_STANDARD.decode("gA==").unwrap()).unwrap();
378        let sm: Vec<SignedMessage> =
379            from_slice_with_fallback(&BASE64_STANDARD.decode("gA==").unwrap()).unwrap();
380
381        assert_eq!(
382            TipsetValidator::compute_msg_root(
383                &blockstore,
384                usm.iter().map(Message::cid),
385                sm.iter().map(SignedMessage::signed_cid),
386            )
387            .expect("Computing message root should succeed")
388            .to_string(),
389            "bafy2bzacecmda75ovposbdateg7eyhwij65zklgyijgcjwynlklmqazpwlhba"
390        );
391    }
392
393    #[test]
394    fn max_allowed_epoch_basic() {
395        // genesis at t=1000, now at t=1300, block_delay=30
396        // elapsed=300, 300/30=10, +5 drift = 15
397        assert_eq!(super::max_allowed_epoch(1300, 1000, 30), Some(15));
398    }
399
400    #[test]
401    fn max_allowed_epoch_at_genesis() {
402        // now == genesis → epoch 0 + drift
403        assert_eq!(super::max_allowed_epoch(1000, 1000, 30), Some(5));
404    }
405
406    #[test]
407    fn max_allowed_epoch_clock_before_genesis() {
408        // clock is behind genesis — should not panic, returns None
409        assert_eq!(super::max_allowed_epoch(500, 1000, 30), None);
410    }
411
412    #[test]
413    fn max_allowed_epoch_zero_block_delay() {
414        // zero block delay would divide by zero — returns None
415        assert_eq!(super::max_allowed_epoch(2000, 1000, 0), None);
416    }
417
418    fn make_gossip_block_with(f: impl FnOnce(&mut RawBlockHeader)) -> GossipBlock {
419        let mut raw = RawBlockHeader {
420            election_proof: Some(ElectionProof {
421                win_count: 1,
422                vrfproof: Default::default(),
423            }),
424            signature: Some(Signature {
425                sig_type: SignatureType::Bls,
426                bytes: vec![0u8; 96],
427            }),
428            ..Default::default()
429        };
430        f(&mut raw);
431        GossipBlock {
432            header: CachingBlockHeader::from(raw),
433            bls_messages: vec![],
434            secpk_messages: vec![],
435        }
436    }
437
438    fn make_valid_gossip_block() -> GossipBlock {
439        make_gossip_block_with(|_| {})
440    }
441
442    fn make_genesis() -> Tipset {
443        Tipset::from(CachingBlockHeader::default())
444    }
445
446    #[test]
447    fn gossip_block_validator_accepts_valid_block() {
448        let block = make_valid_gossip_block();
449        let genesis = make_genesis();
450        let seen = SeenBlockCache::default();
451
452        let result = GossipBlockValidator::new(&block).validate_pre_fetch(
453            &genesis, 30,   // block_delay
454            0,    // finalized_epoch
455            None, // no bad block cache
456            &seen,
457        );
458        assert!(result.is_ok());
459    }
460
461    #[test]
462    fn gossip_block_validator_rejects_duplicate() {
463        let block = make_valid_gossip_block();
464        let genesis = make_genesis();
465        let seen = SeenBlockCache::default();
466
467        assert!(
468            GossipBlockValidator::new(&block)
469                .validate_pre_fetch(&genesis, 30, 0, None, &seen)
470                .is_ok()
471        );
472
473        let err = GossipBlockValidator::new(&block)
474            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
475            .unwrap_err();
476        assert!(matches!(err, GossipBlockRejectReason::DuplicateBlock(_)));
477    }
478
479    #[test]
480    fn gossip_block_validator_rejects_bad_block() {
481        let block = make_valid_gossip_block();
482        let genesis = make_genesis();
483        let seen = SeenBlockCache::default();
484        let bad_cache = BadBlockCache::default();
485        bad_cache.push(*block.header.cid());
486
487        let err = GossipBlockValidator::new(&block)
488            .validate_pre_fetch(&genesis, 30, 0, Some(&bad_cache), &seen)
489            .unwrap_err();
490        assert!(matches!(err, GossipBlockRejectReason::BadBlock(_)));
491    }
492
493    #[test]
494    fn gossip_block_validator_rejects_epoch_too_far_ahead() {
495        let block = make_gossip_block_with(|h| h.epoch = i64::MAX);
496        let genesis = make_genesis();
497        let seen = SeenBlockCache::default();
498
499        let err = GossipBlockValidator::new(&block)
500            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
501            .unwrap_err();
502        assert!(matches!(err, GossipBlockRejectReason::EpochTooFarAhead(_)));
503    }
504
505    #[test]
506    fn gossip_block_validator_rejects_epoch_beyond_finality() {
507        let block = make_valid_gossip_block(); // epoch = 0
508        let genesis = make_genesis();
509        let seen = SeenBlockCache::default();
510
511        let err = GossipBlockValidator::new(&block)
512            .validate_pre_fetch(&genesis, 30, 100, None, &seen)
513            .unwrap_err();
514        assert!(matches!(
515            err,
516            GossipBlockRejectReason::EpochBeyondFinality { .. }
517        ));
518    }
519
520    #[test]
521    fn gossip_block_validator_rejects_missing_election_proof() {
522        let block = make_gossip_block_with(|h| h.election_proof = None);
523        let genesis = make_genesis();
524        let seen = SeenBlockCache::default();
525
526        let err = GossipBlockValidator::new(&block)
527            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
528            .unwrap_err();
529        assert!(matches!(err, GossipBlockRejectReason::MissingElectionProof));
530    }
531
532    #[test]
533    fn gossip_block_validator_rejects_zero_win_count() {
534        let block = make_gossip_block_with(|h| {
535            h.election_proof = Some(ElectionProof {
536                win_count: 0,
537                vrfproof: Default::default(),
538            })
539        });
540        let genesis = make_genesis();
541        let seen = SeenBlockCache::default();
542
543        let err = GossipBlockValidator::new(&block)
544            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
545            .unwrap_err();
546        assert!(matches!(err, GossipBlockRejectReason::InvalidWinCount(0)));
547    }
548
549    #[test]
550    fn gossip_block_validator_rejects_missing_signature() {
551        let block = make_gossip_block_with(|h| h.signature = None);
552        let genesis = make_genesis();
553        let seen = SeenBlockCache::default();
554
555        let err = GossipBlockValidator::new(&block)
556            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
557            .unwrap_err();
558        assert!(matches!(err, GossipBlockRejectReason::MissingSignature));
559    }
560
561    #[test]
562    fn gossip_block_validator_rejects_too_many_messages() {
563        let mut block = make_valid_gossip_block();
564        block.bls_messages = vec![Cid::default(); 10_001];
565        let genesis = make_genesis();
566        let seen = SeenBlockCache::default();
567
568        let err = GossipBlockValidator::new(&block)
569            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
570            .unwrap_err();
571        assert!(matches!(err, GossipBlockRejectReason::TooManyMessages(_)));
572    }
573
574    #[test]
575    fn gossip_block_validator_rejects_negative_epoch() {
576        let block = make_gossip_block_with(|h| h.epoch = -1);
577        let genesis = make_genesis();
578        let seen = SeenBlockCache::default();
579
580        let err = GossipBlockValidator::new(&block)
581            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
582            .unwrap_err();
583        assert!(matches!(err, GossipBlockRejectReason::NegativeEpoch(-1)));
584    }
585
586    #[test]
587    fn gossip_block_validator_rejects_timestamp_mismatch() {
588        // epoch=0, genesis timestamp=0, so expected timestamp = 0 + 0*30 = 0
589        // but we set timestamp=999
590        let block = make_gossip_block_with(|h| h.timestamp = 999);
591        let genesis = make_genesis();
592        let seen = SeenBlockCache::default();
593
594        let err = GossipBlockValidator::new(&block)
595            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
596            .unwrap_err();
597        assert!(matches!(
598            err,
599            GossipBlockRejectReason::TimestampMismatch { .. }
600        ));
601    }
602
603    /// A genesis timestamp ahead of the local clock makes `max_allowed_epoch` fall back to
604    /// `ChainEpoch::MAX`, so the epoch range check no longer bounds what reaches the timestamp
605    /// arithmetic.
606    #[rstest]
607    fn timestamp_check_survives_extreme_epoch_when_clock_is_behind_genesis(
608        // `u64::MAX` is the timestamp that saturating arithmetic would have computed as the expected one, so saturating would have accepted it.
609        #[values(0, u64::MAX)] timestamp: u64,
610    ) {
611        let genesis = Tipset::from(CachingBlockHeader::new(RawBlockHeader {
612            timestamp: u64::MAX,
613            ..Default::default()
614        }));
615
616        let block = make_gossip_block_with(|h| {
617            h.epoch = i64::MAX;
618            h.timestamp = timestamp;
619        });
620        let err = GossipBlockValidator::new(&block)
621            .validate_pre_fetch(&genesis, 30, 0, None, &SeenBlockCache::default())
622            .unwrap_err();
623        assert!(
624            matches!(err, GossipBlockRejectReason::EpochTooFarAhead(_)),
625            "{err}"
626        );
627    }
628
629    #[test]
630    fn rejected_block_not_cached_as_seen() {
631        // A block rejected for a transient reason (e.g., epoch too far ahead)
632        // must NOT be inserted into the seen cache. Otherwise, if the same
633        // block is received later when it becomes valid, it would be
634        // incorrectly suppressed as a duplicate.
635        let block = make_gossip_block_with(|h| h.epoch = i64::MAX);
636        let genesis = make_genesis();
637        let seen = SeenBlockCache::default();
638
639        // First attempt: rejected as too far ahead
640        let err = GossipBlockValidator::new(&block)
641            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
642            .unwrap_err();
643        assert!(matches!(err, GossipBlockRejectReason::EpochTooFarAhead(_)));
644
645        // Second attempt: must still be EpochTooFarAhead, NOT DuplicateBlock
646        let err = GossipBlockValidator::new(&block)
647            .validate_pre_fetch(&genesis, 30, 0, None, &seen)
648            .unwrap_err();
649        assert!(matches!(err, GossipBlockRejectReason::EpochTooFarAhead(_)));
650    }
651
652    #[test]
653    fn seen_block_cache_deduplicates() {
654        let cache = SeenBlockCache::default();
655        let cid = Cid::default();
656
657        assert!(!cache.test_and_insert(&cid));
658        assert!(cache.test_and_insert(&cid));
659    }
660}