Skip to main content

hns_light_sync/
lib.rs

1//! Bounded multi-peer Handshake light-header synchronization.
2//!
3//! A round requests the same locator from a bounded peer set, validates every
4//! response independently on a clone of the current chain, chooses the
5//! greatest-chainwork result, and requires configurable peer agreement.
6//! Equal-work divergent tips fail closed. Durable checkpoints and deep reorg
7//! recovery remain storage-adapter responsibilities.
8
9#![forbid(unsafe_code)]
10#![allow(
11    clippy::doc_markdown,
12    clippy::missing_errors_doc,
13    clippy::module_name_repetitions,
14    reason = "HNS, P2P, and HSD are protocol names"
15)]
16
17use std::collections::{HashMap, HashSet};
18use std::fmt;
19use std::hash::Hash;
20
21use hns_header_consensus::{Header, Network};
22use hns_light_chain::{
23    ChainLimits, CurrencyPolicy, CurrentChain, HeaderEntry, LightChain, LightChainError,
24};
25use hns_p2p_wire::{LocatorPacket, MAX_HEADERS};
26use hns_primitives::{BlockHash, BlockTime};
27use thiserror::Error;
28
29/// Default maximum simultaneously tracked peers.
30pub const DEFAULT_MAX_PEERS: usize = 8;
31/// Default minimum matching valid responses.
32pub const DEFAULT_MINIMUM_PEER_AGREEMENT: usize = 2;
33/// Default header round deadline.
34pub const DEFAULT_ROUND_TIMEOUT_SECONDS: u64 = 20;
35/// Default invalid-round failures before a peer is locally banned.
36pub const DEFAULT_MAX_PEER_FAILURES: u32 = 3;
37
38/// Opaque peer identity; debug output never reveals it.
39#[derive(Clone, Copy, Eq, Hash, PartialEq)]
40pub struct PeerId([u8; 32]);
41
42impl PeerId {
43    /// Construct from a stable connection-scoped peer identifier.
44    #[must_use]
45    pub const fn new(bytes: [u8; 32]) -> Self {
46        Self(bytes)
47    }
48}
49
50impl fmt::Debug for PeerId {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        formatter.write_str("PeerId([redacted])")
53    }
54}
55
56/// Header synchronization policy.
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub struct SyncConfig {
59    /// Maximum tracked peers.
60    pub max_peers: usize,
61    /// Minimum peers that must return the selected tip.
62    pub minimum_peer_agreement: usize,
63    /// Round response deadline.
64    pub round_timeout_seconds: u64,
65    /// Invalid candidate failures before local ban.
66    pub max_peer_failures: u32,
67}
68
69impl Default for SyncConfig {
70    fn default() -> Self {
71        Self {
72            max_peers: DEFAULT_MAX_PEERS,
73            minimum_peer_agreement: DEFAULT_MINIMUM_PEER_AGREEMENT,
74            round_timeout_seconds: DEFAULT_ROUND_TIMEOUT_SECONDS,
75            max_peer_failures: DEFAULT_MAX_PEER_FAILURES,
76        }
77    }
78}
79
80impl SyncConfig {
81    fn validate(self) -> Result<Self, SyncError> {
82        if self.max_peers == 0
83            || self.max_peers > 64
84            || self.minimum_peer_agreement == 0
85            || self.minimum_peer_agreement > self.max_peers
86            || self.round_timeout_seconds == 0
87            || self.round_timeout_seconds > 300
88            || self.max_peer_failures == 0
89        {
90            return Err(SyncError::InvalidConfig);
91        }
92        Ok(self)
93    }
94}
95
96/// Header authority synchronization state.
97#[derive(Clone, Copy, Debug, Eq, PartialEq)]
98pub enum SyncState {
99    /// More validated headers or peer agreement are required.
100    HeaderSyncing,
101    /// A bounded peer round reports no greater-work extension.
102    HeaderCurrent,
103    /// No valid/agreed candidate was available.
104    Degraded,
105}
106
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108struct PeerRecord {
109    advertised_height: u32,
110    failures: u32,
111    successes: u64,
112    banned: bool,
113}
114
115/// Name-free per-peer synchronization status.
116#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub struct PeerStatus {
118    /// Opaque peer identity.
119    pub id: PeerId,
120    /// Most recently advertised height.
121    pub advertised_height: u32,
122    /// Invalid candidate failures.
123    pub failures: u32,
124    /// Valid candidate responses.
125    pub successes: u64,
126    /// Whether local failure policy banned this peer.
127    pub banned: bool,
128}
129
130/// Request shared by every peer selected for one round.
131#[derive(Clone, Debug, Eq, PartialEq)]
132pub struct HeaderRoundRequest {
133    /// Monotonic round generation.
134    pub generation: u64,
135    /// Standard HSD locator request.
136    pub packet: LocatorPacket,
137    /// Exact local base tip height.
138    pub base_height: u32,
139    /// Exact local base tip hash.
140    pub base_hash: BlockHash,
141    /// Response deadline.
142    pub deadline: u64,
143}
144
145#[derive(Clone, Debug)]
146struct SyncRound {
147    request: HeaderRoundRequest,
148    requested: HashSet<PeerId>,
149    responses: HashMap<PeerId, Vec<Header>>,
150}
151
152/// Immutable synchronization summary.
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub struct SyncStatus {
155    /// Current state.
156    pub state: SyncState,
157    /// State generation.
158    pub generation: u64,
159    /// Validated tip.
160    pub tip: HeaderEntry,
161    /// Tracked peers.
162    pub peers: usize,
163    /// Non-banned peers.
164    pub active_peers: usize,
165    /// Whether a round is collecting responses.
166    pub round_active: bool,
167}
168
169/// Completed agreement round plus the exact newly accepted header batch.
170///
171/// Storage adapters persist `accepted_headers` before starting another round;
172/// the consensus engine itself retains only its small retarget lookback.
173#[derive(Clone, Debug, Eq, PartialEq)]
174pub struct HeaderRoundOutcome {
175    /// Resulting synchronization status.
176    pub status: SyncStatus,
177    /// Exact winning extension, empty only for a no-extension agreement round.
178    pub accepted_headers: Vec<Header>,
179}
180
181/// Bounded multi-peer header synchronizer.
182#[derive(Clone, Debug)]
183pub struct HeaderSync {
184    config: SyncConfig,
185    chain: LightChain,
186    state: SyncState,
187    generation: u64,
188    peers: HashMap<PeerId, PeerRecord>,
189    round: Option<SyncRound>,
190}
191
192impl HeaderSync {
193    /// Begin at canonical network genesis.
194    pub fn from_genesis(
195        network: Network,
196        now: BlockTime,
197        chain_limits: ChainLimits,
198        config: SyncConfig,
199    ) -> Result<Self, SyncError> {
200        let config = config.validate()?;
201        Ok(Self {
202            config,
203            chain: LightChain::from_genesis(network, now, chain_limits)?,
204            state: SyncState::HeaderSyncing,
205            generation: 1,
206            peers: HashMap::with_capacity(config.max_peers),
207            round: None,
208        })
209    }
210
211    /// Resume synchronization from a chain restored out of the caller's
212    /// authenticated wallet store.
213    ///
214    /// Peer scores and an in-flight round are deliberately connection-local:
215    /// reopening starts in `HeaderSyncing` and requires fresh peer agreement
216    /// before current-chain evidence can be issued.
217    pub fn from_chain(chain: LightChain, config: SyncConfig) -> Result<Self, SyncError> {
218        let config = config.validate()?;
219        Ok(Self {
220            config,
221            chain,
222            state: SyncState::HeaderSyncing,
223            generation: 1,
224            peers: HashMap::with_capacity(config.max_peers),
225            round: None,
226        })
227    }
228
229    /// Current validated chain.
230    #[must_use]
231    pub const fn chain(&self) -> &LightChain {
232        &self.chain
233    }
234
235    /// Current name-free summary.
236    #[must_use]
237    pub fn status(&self) -> SyncStatus {
238        SyncStatus {
239            state: self.state,
240            generation: self.generation,
241            tip: self.chain.tip(),
242            peers: self.peers.len(),
243            active_peers: self.peers.values().filter(|record| !record.banned).count(),
244            round_active: self.round.is_some(),
245        }
246    }
247
248    /// Add one peer with its admitted version height.
249    pub fn add_peer(&mut self, id: PeerId, advertised_height: u32) -> Result<(), SyncError> {
250        if self.peers.contains_key(&id) {
251            return Err(SyncError::DuplicatePeer);
252        }
253        if self.peers.len() >= self.config.max_peers {
254            return Err(SyncError::PeerLimit);
255        }
256        self.peers.insert(
257            id,
258            PeerRecord {
259                advertised_height,
260                failures: 0,
261                successes: 0,
262                banned: false,
263            },
264        );
265        Ok(())
266    }
267
268    /// Remove a disconnected peer and any pending response.
269    pub fn remove_peer(&mut self, id: PeerId) -> bool {
270        if let Some(round) = &mut self.round {
271            round.requested.remove(&id);
272            round.responses.remove(&id);
273        }
274        self.peers.remove(&id).is_some()
275    }
276
277    /// Update the peer's current version/announcement height.
278    pub fn update_peer_height(
279        &mut self,
280        id: PeerId,
281        advertised_height: u32,
282    ) -> Result<(), SyncError> {
283        let peer = self.peers.get_mut(&id).ok_or(SyncError::UnknownPeer)?;
284        peer.advertised_height = advertised_height;
285        if advertised_height > self.chain.tip().height().get() {
286            self.state = SyncState::HeaderSyncing;
287        }
288        Ok(())
289    }
290
291    /// Begin one same-base multi-peer header round.
292    pub fn begin_round(
293        &mut self,
294        selected_peers: &[PeerId],
295        now: u64,
296    ) -> Result<HeaderRoundRequest, SyncError> {
297        if self.round.is_some() {
298            return Err(SyncError::RoundAlreadyActive);
299        }
300        let requested = selected_peers.iter().copied().collect::<HashSet<_>>();
301        if requested.len() != selected_peers.len()
302            || requested.len() < self.config.minimum_peer_agreement
303        {
304            return Err(SyncError::InsufficientPeers);
305        }
306        for id in &requested {
307            let peer = self.peers.get(id).ok_or(SyncError::UnknownPeer)?;
308            if peer.banned {
309                return Err(SyncError::PeerBanned);
310            }
311        }
312        let generation = self
313            .generation
314            .checked_add(1)
315            .ok_or(SyncError::GenerationExhausted)?;
316        let deadline = now
317            .checked_add(self.config.round_timeout_seconds)
318            .ok_or(SyncError::TimeOverflow)?;
319        let tip = self.chain.tip();
320        let request = HeaderRoundRequest {
321            generation,
322            packet: LocatorPacket {
323                locator: self.chain.locator(),
324                stop: BlockHash::default(),
325            },
326            base_height: tip.height().get(),
327            base_hash: tip.hash(),
328            deadline,
329        };
330        self.round = Some(SyncRound {
331            request: request.clone(),
332            requested,
333            responses: HashMap::with_capacity(selected_peers.len()),
334        });
335        self.generation = generation;
336        Ok(request)
337    }
338
339    /// Discard one in-flight agreement round without changing authenticated
340    /// chain state, peer scores, or the last committed synchronization state.
341    ///
342    /// Round responses are connection-local, untrusted input until
343    /// `finish_round_with_headers` commits an agreed extension. A transport
344    /// owner may therefore use this only when it has lost the metadata needed
345    /// to finish that round (for example, after controller retirement) and
346    /// must begin a fresh, fully authenticated peer agreement.
347    #[must_use]
348    pub fn abandon_uncommitted_round(&mut self) -> bool {
349        self.round.take().is_some()
350    }
351
352    /// Submit one bounded response for the active round.
353    pub fn submit_headers(
354        &mut self,
355        generation: u64,
356        peer: PeerId,
357        headers: Vec<Header>,
358        now: u64,
359    ) -> Result<(), SyncError> {
360        let round = self.round.as_mut().ok_or(SyncError::NoActiveRound)?;
361        if generation != round.request.generation {
362            return Err(SyncError::StaleRound);
363        }
364        if now > round.request.deadline {
365            return Err(SyncError::RoundExpired);
366        }
367        if !round.requested.contains(&peer) {
368            return Err(SyncError::PeerNotRequested);
369        }
370        if headers.len() > MAX_HEADERS {
371            return Err(SyncError::HeaderResponseLimit);
372        }
373        if round.responses.contains_key(&peer) {
374            return Err(SyncError::DuplicateResponse);
375        }
376        round.responses.insert(peer, headers);
377        Ok(())
378    }
379
380    /// Validate all submitted candidates, select greatest chainwork, and require agreement.
381    pub fn finish_round(&mut self, now: u64) -> Result<SyncStatus, SyncError> {
382        self.finish_round_with_headers(now)
383            .map(|outcome| outcome.status)
384    }
385
386    /// Finish a round and return every agreed header needed by durable wallet
387    /// scanning, rather than discarding the winning batch after validation.
388    #[allow(
389        clippy::too_many_lines,
390        reason = "candidate validation, agreement, peer scoring, and atomic winner installation remain one auditable state transition"
391    )]
392    pub fn finish_round_with_headers(&mut self, now: u64) -> Result<HeaderRoundOutcome, SyncError> {
393        let Some(round) = self.round.take() else {
394            return Err(SyncError::NoActiveRound);
395        };
396        if round.responses.len() < self.config.minimum_peer_agreement {
397            if now <= round.request.deadline {
398                self.round = Some(round);
399                return Err(SyncError::RoundIncomplete);
400            }
401            self.state = SyncState::Degraded;
402            return Err(SyncError::InsufficientResponses);
403        }
404        if self.chain.tip().hash() != round.request.base_hash
405            || self.chain.tip().height().get() != round.request.base_height
406        {
407            return Err(SyncError::StaleRound);
408        }
409
410        let all_requested_responded = round.responses.len() == round.requested.len();
411        let mut candidates = Vec::with_capacity(round.responses.len());
412        for (peer, headers) in round.responses {
413            let mut candidate = self.chain.clone();
414            let valid = if headers.is_empty() {
415                true
416            } else {
417                candidate
418                    .append_batch(&headers, BlockTime::new(now))
419                    .is_ok()
420            };
421            if valid {
422                candidates.push((peer, headers, candidate));
423            } else {
424                self.record_failure(peer);
425            }
426        }
427        if candidates.is_empty() {
428            self.state = SyncState::Degraded;
429            return Err(SyncError::NoValidCandidate);
430        }
431        let maximum_work = candidates
432            .iter()
433            .map(|(_, _, candidate)| candidate.tip().chainwork())
434            .max()
435            .ok_or(SyncError::NoValidCandidate)?;
436        let best_hashes = candidates
437            .iter()
438            .filter(|(_, _, candidate)| candidate.tip().chainwork() == maximum_work)
439            .map(|(_, _, candidate)| candidate.tip().hash())
440            .collect::<HashSet<_>>();
441        if best_hashes.len() != 1 {
442            self.state = SyncState::Degraded;
443            return Err(SyncError::AmbiguousBestChain);
444        }
445        let best_hash = best_hashes
446            .iter()
447            .next()
448            .copied()
449            .ok_or(SyncError::NoValidCandidate)?;
450        let supporters = candidates
451            .iter()
452            .filter(|(_, _, candidate)| candidate.tip().hash() == best_hash)
453            .count();
454        if supporters < self.config.minimum_peer_agreement {
455            self.state = SyncState::Degraded;
456            return Err(SyncError::InsufficientAgreement);
457        }
458
459        let winning_index = candidates
460            .iter()
461            .position(|(_, _, candidate)| candidate.tip().hash() == best_hash)
462            .ok_or(SyncError::NoValidCandidate)?;
463        let accepted_headers = candidates
464            .get(winning_index)
465            .map(|(_, headers, _)| headers.clone())
466            .ok_or(SyncError::NoValidCandidate)?;
467        let winner = candidates
468            .get(winning_index)
469            .map(|(_, _, candidate)| candidate.clone())
470            .ok_or(SyncError::NoValidCandidate)?;
471        let unchanged = winner.tip().hash() == self.chain.tip().hash();
472        for (peer, _, candidate) in &candidates {
473            if candidate.tip().hash() == best_hash {
474                self.record_success(*peer);
475            }
476        }
477        self.chain = winner;
478        let no_active_peer_advertises_an_extension = self.peers.values().all(|record| {
479            record.banned || record.advertised_height <= self.chain.tip().height().get()
480        });
481        self.state = if unchanged
482            && all_requested_responded
483            && no_active_peer_advertises_an_extension
484            && candidates
485                .iter()
486                .filter(|(_, _, candidate)| candidate.tip().hash() == best_hash)
487                .all(|(peer, headers, _)| {
488                    headers.is_empty()
489                        && self.peers.get(peer).is_some_and(|record| {
490                            record.advertised_height <= self.chain.tip().height().get()
491                        })
492                }) {
493            SyncState::HeaderCurrent
494        } else {
495            SyncState::HeaderSyncing
496        };
497        Ok(HeaderRoundOutcome {
498            status: self.status(),
499            accepted_headers,
500        })
501    }
502
503    /// Issue a current-chain token only after a no-extension agreement round.
504    pub fn require_current(&self, policy: CurrencyPolicy) -> Result<CurrentChain, SyncError> {
505        if self.state != SyncState::HeaderCurrent {
506            return Err(SyncError::NotCurrent);
507        }
508        self.chain.require_current(policy).map_err(SyncError::Chain)
509    }
510
511    /// Name-free status for every tracked peer.
512    #[must_use]
513    pub fn peer_statuses(&self) -> Vec<PeerStatus> {
514        self.peers
515            .iter()
516            .map(|(id, record)| PeerStatus {
517                id: *id,
518                advertised_height: record.advertised_height,
519                failures: record.failures,
520                successes: record.successes,
521                banned: record.banned,
522            })
523            .collect()
524    }
525
526    fn record_failure(&mut self, peer: PeerId) {
527        if let Some(record) = self.peers.get_mut(&peer) {
528            record.failures = record.failures.saturating_add(1);
529            if record.failures >= self.config.max_peer_failures {
530                record.banned = true;
531            }
532        }
533    }
534
535    fn record_success(&mut self, peer: PeerId) {
536        if let Some(record) = self.peers.get_mut(&peer) {
537            record.successes = record.successes.saturating_add(1);
538            record.failures = record.failures.saturating_sub(1);
539        }
540    }
541}
542
543/// Header synchronization configuration, round, peer, or consensus failure.
544#[derive(Debug, Error)]
545#[non_exhaustive]
546pub enum SyncError {
547    /// Header consensus/currency gate failed.
548    #[error("light-chain failure: {0}")]
549    Chain(#[from] LightChainError),
550    /// Bounds or agreement policy are invalid.
551    #[error("invalid header-sync configuration")]
552    InvalidConfig,
553    /// Tracked peer bound is full.
554    #[error("header-sync peer bound exceeded")]
555    PeerLimit,
556    /// Peer identity is already tracked.
557    #[error("duplicate header-sync peer")]
558    DuplicatePeer,
559    /// Peer is not tracked.
560    #[error("unknown header-sync peer")]
561    UnknownPeer,
562    /// Peer reached the local invalid-response threshold.
563    #[error("header-sync peer is banned")]
564    PeerBanned,
565    /// Selected peer list is duplicate or below agreement policy.
566    #[error("insufficient distinct peers for header round")]
567    InsufficientPeers,
568    /// Another round is active.
569    #[error("header round is already active")]
570    RoundAlreadyActive,
571    /// No round is active.
572    #[error("no active header round")]
573    NoActiveRound,
574    /// Round generation is stale.
575    #[error("stale header round generation")]
576    StaleRound,
577    /// Round deadline elapsed before submission.
578    #[error("header round deadline elapsed")]
579    RoundExpired,
580    /// Peer was not selected for this round.
581    #[error("peer was not requested in this header round")]
582    PeerNotRequested,
583    /// Peer submitted twice.
584    #[error("duplicate peer response in header round")]
585    DuplicateResponse,
586    /// Response exceeds the standard HSD header bound.
587    #[error("header response exceeds standard bound")]
588    HeaderResponseLimit,
589    /// More responses may arrive before deadline.
590    #[error("header round is incomplete")]
591    RoundIncomplete,
592    /// Deadline elapsed without minimum responses.
593    #[error("header round has insufficient responses")]
594    InsufficientResponses,
595    /// Every candidate failed local consensus validation.
596    #[error("header round has no valid candidate")]
597    NoValidCandidate,
598    /// Equal-work candidates have different tips.
599    #[error("header round has ambiguous equal-work tips")]
600    AmbiguousBestChain,
601    /// Greatest-work candidate lacks minimum peer agreement.
602    #[error("greatest-work header candidate lacks peer agreement")]
603    InsufficientAgreement,
604    /// Current-chain evidence was requested before no-extension agreement.
605    #[error("header chain is not current")]
606    NotCurrent,
607    /// State generation cannot advance.
608    #[error("header-sync generation exhausted")]
609    GenerationExhausted,
610    /// Deadline arithmetic overflowed.
611    #[error("header-sync deadline overflow")]
612    TimeOverflow,
613}
614
615#[cfg(test)]
616#[allow(
617    clippy::unwrap_used,
618    reason = "tests fail immediately on invalid local consensus fixtures"
619)]
620mod tests {
621    use hns_primitives::{Chainwork, Height, TreeRoot};
622
623    use super::*;
624
625    fn config(agreement: usize, failures: u32) -> SyncConfig {
626        SyncConfig {
627            max_peers: 4,
628            minimum_peer_agreement: agreement,
629            round_timeout_seconds: 10,
630            max_peer_failures: failures,
631        }
632    }
633
634    fn peer(value: u8) -> PeerId {
635        PeerId::new([value; 32])
636    }
637
638    fn test_sync(agreement: usize, failures: u32, now: u64) -> HeaderSync {
639        HeaderSync::from_genesis(
640            Network::Regtest,
641            BlockTime::new(now),
642            ChainLimits::default(),
643            config(agreement, failures),
644        )
645        .unwrap()
646    }
647
648    fn mine(previous: HeaderEntry, tree_root: u8) -> Header {
649        let mut header = Header {
650            time: BlockTime::new(previous.time().get() + 1),
651            previous_block: previous.hash(),
652            tree_root: TreeRoot::new([tree_root; 32]),
653            bits: Network::Regtest.parameters().pow.bits,
654            ..Header::default()
655        };
656        while !header.verify_pow() {
657            header.nonce = header.nonce.checked_add(1).unwrap();
658        }
659        header
660    }
661
662    #[test]
663    fn requires_agreed_greatest_work_then_empty_current_round() {
664        let now = Network::Regtest.parameters().genesis_time.get() + 100;
665        let mut sync = test_sync(2, 3, now);
666        sync.add_peer(peer(1), 1).unwrap();
667        sync.add_peer(peer(2), 1).unwrap();
668        let request = sync.begin_round(&[peer(1), peer(2)], now).unwrap();
669        let extension = mine(sync.chain().tip(), 1);
670        for id in [peer(1), peer(2)] {
671            sync.submit_headers(request.generation, id, vec![extension.clone()], now)
672                .unwrap();
673        }
674        let outcome = sync.finish_round_with_headers(now).unwrap();
675        assert_eq!(outcome.accepted_headers, vec![extension]);
676        let status = outcome.status;
677        assert_eq!(status.tip.height(), Height::new(1));
678        assert_eq!(status.state, SyncState::HeaderSyncing);
679
680        let request = sync.begin_round(&[peer(1), peer(2)], now + 1).unwrap();
681        for id in [peer(1), peer(2)] {
682            sync.submit_headers(request.generation, id, Vec::new(), now + 1)
683                .unwrap();
684        }
685        assert_eq!(
686            sync.finish_round(now + 1).unwrap().state,
687            SyncState::HeaderCurrent
688        );
689        assert!(
690            sync.require_current(CurrencyPolicy {
691                now: BlockTime::new(now),
692                maximum_tip_age_seconds: 3_600,
693                minimum_height: Height::new(1),
694                minimum_chainwork: Chainwork::ZERO,
695            })
696            .is_ok()
697        );
698    }
699
700    #[test]
701    fn equal_work_divergent_tips_fail_closed() {
702        let now = Network::Regtest.parameters().genesis_time.get() + 100;
703        let mut sync = test_sync(2, 3, now);
704        sync.add_peer(peer(1), 1).unwrap();
705        sync.add_peer(peer(2), 1).unwrap();
706        let request = sync.begin_round(&[peer(1), peer(2)], now).unwrap();
707        sync.submit_headers(
708            request.generation,
709            peer(1),
710            vec![mine(sync.chain().tip(), 1)],
711            now,
712        )
713        .unwrap();
714        sync.submit_headers(
715            request.generation,
716            peer(2),
717            vec![mine(sync.chain().tip(), 2)],
718            now,
719        )
720        .unwrap();
721        assert!(matches!(
722            sync.finish_round(now),
723            Err(SyncError::AmbiguousBestChain)
724        ));
725        assert_eq!(sync.chain().tip().height(), Height::new(0));
726        assert_eq!(sync.status().state, SyncState::Degraded);
727    }
728
729    #[test]
730    fn invalid_candidates_score_and_ban_only_the_bad_peer() {
731        let now = Network::Regtest.parameters().genesis_time.get() + 100;
732        let mut sync = test_sync(1, 1, now);
733        sync.add_peer(peer(1), 1).unwrap();
734        sync.add_peer(peer(2), 0).unwrap();
735        let request = sync.begin_round(&[peer(1), peer(2)], now).unwrap();
736        let mut invalid = mine(sync.chain().tip(), 1);
737        invalid.previous_block = BlockHash::new([9; 32]);
738        sync.submit_headers(request.generation, peer(1), vec![invalid], now)
739            .unwrap();
740        sync.submit_headers(request.generation, peer(2), Vec::new(), now)
741            .unwrap();
742        assert_eq!(
743            sync.finish_round(now).unwrap().state,
744            SyncState::HeaderCurrent
745        );
746        let statuses = sync.peer_statuses();
747        assert!(
748            statuses
749                .iter()
750                .find(|status| status.id == peer(1))
751                .is_some_and(|status| status.banned)
752        );
753        assert!(
754            statuses
755                .iter()
756                .find(|status| status.id == peer(2))
757                .is_some_and(|status| !status.banned)
758        );
759    }
760
761    #[test]
762    fn rounds_bound_peers_duplicates_generations_and_deadlines() {
763        let now = Network::Regtest.parameters().genesis_time.get() + 100;
764        let mut sync = test_sync(1, 3, now);
765        sync.add_peer(peer(1), 0).unwrap();
766        assert!(matches!(
767            sync.add_peer(peer(1), 0),
768            Err(SyncError::DuplicatePeer)
769        ));
770        let request = sync.begin_round(&[peer(1)], now).unwrap();
771        assert_eq!(
772            request.packet.locator.first().copied(),
773            Some(sync.chain().tip().hash())
774        );
775        assert!(matches!(
776            sync.submit_headers(request.generation + 1, peer(1), Vec::new(), now),
777            Err(SyncError::StaleRound)
778        ));
779        sync.submit_headers(request.generation, peer(1), Vec::new(), now)
780            .unwrap();
781        let rejected_replacement = mine(sync.chain().tip(), 9);
782        assert!(matches!(
783            sync.submit_headers(request.generation, peer(1), vec![rejected_replacement], now),
784            Err(SyncError::DuplicateResponse)
785        ));
786        assert_eq!(
787            sync.finish_round(now).unwrap().state,
788            SyncState::HeaderCurrent
789        );
790
791        let mut timed = test_sync(1, 3, now);
792        timed.add_peer(peer(1), 0).unwrap();
793        let request = timed.begin_round(&[peer(1)], now).unwrap();
794        assert!(matches!(
795            timed.submit_headers(request.generation, peer(1), Vec::new(), now + 11),
796            Err(SyncError::RoundExpired)
797        ));
798        assert!(matches!(
799            timed.finish_round(now + 11),
800            Err(SyncError::InsufficientResponses)
801        ));
802        assert_eq!(timed.status().state, SyncState::Degraded);
803    }
804
805    #[test]
806    fn abandoning_an_uncommitted_round_preserves_chain_state_and_allows_replacement() {
807        let now = Network::Regtest.parameters().genesis_time.get() + 100;
808        let mut sync = test_sync(1, 3, now);
809        sync.add_peer(peer(1), 1).unwrap();
810        let original_tip = sync.chain().tip();
811        let original_state = sync.status().state;
812
813        let first = sync.begin_round(&[peer(1)], now).unwrap();
814        let extension = mine(original_tip, 1);
815        sync.submit_headers(first.generation, peer(1), vec![extension], now)
816            .unwrap();
817        assert!(sync.abandon_uncommitted_round());
818        assert!(!sync.status().round_active);
819        assert_eq!(sync.chain().tip(), original_tip);
820        assert_eq!(sync.status().state, original_state);
821        assert!(!sync.abandon_uncommitted_round());
822
823        let replacement = sync.begin_round(&[peer(1)], now + 1).unwrap();
824        assert!(replacement.generation > first.generation);
825    }
826
827    #[test]
828    fn current_requires_every_selected_response_and_no_advertised_extension() {
829        let now = Network::Regtest.parameters().genesis_time.get() + 100;
830        let mut sync = test_sync(1, 3, now);
831        sync.add_peer(peer(1), 0).unwrap();
832        sync.add_peer(peer(2), 1).unwrap();
833        let request = sync.begin_round(&[peer(1), peer(2)], now).unwrap();
834        sync.submit_headers(request.generation, peer(1), Vec::new(), now)
835            .unwrap();
836        assert_eq!(
837            sync.finish_round(now).unwrap().state,
838            SyncState::HeaderSyncing
839        );
840
841        let request = sync.begin_round(&[peer(1), peer(2)], now + 1).unwrap();
842        for id in [peer(1), peer(2)] {
843            sync.submit_headers(request.generation, id, Vec::new(), now + 1)
844                .unwrap();
845        }
846        assert_eq!(
847            sync.finish_round(now + 1).unwrap().state,
848            SyncState::HeaderSyncing
849        );
850
851        sync.update_peer_height(peer(2), 0).unwrap();
852        let request = sync.begin_round(&[peer(1), peer(2)], now + 2).unwrap();
853        for id in [peer(1), peer(2)] {
854            sync.submit_headers(request.generation, id, Vec::new(), now + 2)
855                .unwrap();
856        }
857        assert_eq!(
858            sync.finish_round(now + 2).unwrap().state,
859            SyncState::HeaderCurrent
860        );
861    }
862
863    #[test]
864    fn authenticated_chain_resume_requires_fresh_peer_agreement() {
865        let now = Network::Regtest.parameters().genesis_time.get() + 100;
866        let mut original = test_sync(1, 3, now);
867        original.add_peer(peer(1), 1).unwrap();
868        let request = original.begin_round(&[peer(1)], now).unwrap();
869        let extension = mine(original.chain().tip(), 1);
870        original
871            .submit_headers(request.generation, peer(1), vec![extension], now)
872            .unwrap();
873        original.finish_round(now).unwrap();
874
875        let snapshot = original.chain().encode_authenticated_snapshot().unwrap();
876        let restored_chain = LightChain::decode_authenticated_snapshot(
877            &snapshot,
878            Network::Regtest,
879            hns_light_chain::ChainSnapshotFloor::default(),
880        )
881        .unwrap();
882        let mut resumed = HeaderSync::from_chain(restored_chain, config(1, 3)).unwrap();
883
884        assert_eq!(resumed.chain().tip(), original.chain().tip());
885        assert_eq!(resumed.status().state, SyncState::HeaderSyncing);
886        assert!(matches!(
887            resumed.require_current(CurrencyPolicy {
888                now: BlockTime::new(now),
889                maximum_tip_age_seconds: 3_600,
890                minimum_height: Height::new(1),
891                minimum_chainwork: Chainwork::ZERO,
892            }),
893            Err(SyncError::NotCurrent)
894        ));
895
896        resumed.add_peer(peer(2), 1).unwrap();
897        let request = resumed.begin_round(&[peer(2)], now + 1).unwrap();
898        resumed
899            .submit_headers(request.generation, peer(2), Vec::new(), now + 1)
900            .unwrap();
901        assert_eq!(
902            resumed.finish_round(now + 1).unwrap().state,
903            SyncState::HeaderCurrent
904        );
905    }
906}