Skip to main content

hns_light_chain/
lib.rs

1//! Locally validated Handshake header chains and name-tree resources.
2//!
3//! This crate starts at the selected network genesis, validates every
4//! contiguous header with the shared `hns-rs` consensus implementation, and
5//! retains exactly the history required by Handshake's median-time and
6//! difficulty rules. A current-chain attestation can then verify one strict
7//! HSD Urkel inclusion proof and decode the committed `NameState` and resource.
8//! The resulting [`VerifiedHnsResource`] has private fields so downstream
9//! DNSSEC code cannot manufacture a Handshake trust anchor.
10
11#![forbid(unsafe_code)]
12#![allow(
13    clippy::doc_markdown,
14    clippy::missing_errors_doc,
15    clippy::module_name_repetitions,
16    reason = "Handshake, DNSSEC, Urkel, and HSD are protocol names"
17)]
18
19use std::collections::VecDeque;
20use std::net::{Ipv4Addr, Ipv6Addr};
21
22use blake2::Blake2b;
23use blake2::digest::{Digest, consts::U32};
24use hns_covenants::{MAX_RESOURCE_SIZE, Resource as CovenantResource, hash_name, validate_name};
25use hns_encoding::{DecodeError, Decoder, Encoder};
26use hns_header_consensus::{
27    DifficultyPoint, Header, HeaderError, HeaderValidationContext, Network, expected_next_bits,
28    validate_header,
29};
30use hns_primitives::{
31    BlockHash, BlockTime, Chainwork, CompactTarget, Height, MerkleRoot, NameHash, TreeRoot,
32};
33use hns_urkel_proof::{HsdUrkelProof, UrkelError};
34use thiserror::Error;
35
36/// Handshake median-time-past window.
37pub const MEDIAN_TIME_SPAN: usize = 11;
38/// Headers needed for both three-block suitable points around a 144-block window.
39pub const REQUIRED_DIFFICULTY_HISTORY: usize = 147;
40/// Default maximum headers accepted in one transactional batch.
41pub const DEFAULT_MAX_HEADERS_PER_BATCH: usize = 4_096;
42/// Hard upper bound for a configured atomic header batch.
43pub const MAX_HEADERS_PER_BATCH_LIMIT: usize = 4_096;
44/// Maximum exponential locator entries for a 32-bit height plus genesis.
45pub const MAX_LOCATOR_HASHES: usize = 43;
46/// Maximum encoded authenticated light-chain checkpoint.
47pub const MAX_LIGHT_CHAIN_SNAPSHOT_BYTES: usize = 64 * 1024;
48const LIGHT_CHAIN_SNAPSHOT_MAGIC: &[u8] = b"HNS-LIGHT-CHAIN-SNAPSHOT\0";
49const LIGHT_CHAIN_SNAPSHOT_SCHEMA: u16 = 1;
50const LIGHT_CHAIN_SNAPSHOT_CHECKSUM_DOMAIN: &[u8] = b"HNS-LIGHT-CHAIN-SNAPSHOT-V1\0";
51/// HSD currently assigns resource record tags zero through six.
52const MAX_KNOWN_RESOURCE_KIND: u8 = 6;
53/// Bits assigned in HSD's serialized `NameState` field.
54const NAME_STATE_KNOWN_FIELD_BITS: u16 = 0x03ff;
55/// Maximum expanded labels in an HNS resource name.
56const MAX_RESOURCE_NAME_LABELS: usize = 127;
57/// Maximum compression pointers followed in one HNS resource name.
58const MAX_RESOURCE_NAME_JUMPS: usize = 16;
59
60/// One fully validated header summary.
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62pub struct HeaderEntry {
63    height: Height,
64    hash: BlockHash,
65    previous_block: BlockHash,
66    tree_root: TreeRoot,
67    merkle_root: MerkleRoot,
68    time: BlockTime,
69    bits: hns_primitives::CompactTarget,
70    chainwork: Chainwork,
71}
72
73impl HeaderEntry {
74    /// Header height.
75    #[must_use]
76    pub const fn height(self) -> Height {
77        self.height
78    }
79
80    /// Consensus block hash.
81    #[must_use]
82    pub const fn hash(self) -> BlockHash {
83        self.hash
84    }
85
86    /// Previous block hash committed by the validated header.
87    #[must_use]
88    pub const fn previous_block(self) -> BlockHash {
89        self.previous_block
90    }
91
92    /// Committed Urkel root.
93    #[must_use]
94    pub const fn tree_root(self) -> TreeRoot {
95        self.tree_root
96    }
97
98    /// Transaction Merkle root committed by the validated header.
99    #[must_use]
100    pub const fn merkle_root(self) -> MerkleRoot {
101        self.merkle_root
102    }
103
104    /// Header timestamp.
105    #[must_use]
106    pub const fn time(self) -> BlockTime {
107        self.time
108    }
109
110    /// Compact proof-of-work target.
111    #[must_use]
112    pub const fn bits(self) -> hns_primitives::CompactTarget {
113        self.bits
114    }
115
116    /// Cumulative chainwork through this header.
117    #[must_use]
118    pub const fn chainwork(self) -> Chainwork {
119        self.chainwork
120    }
121
122    const fn difficulty_point(self) -> DifficultyPoint {
123        DifficultyPoint {
124            height: self.height,
125            time: self.time,
126            bits: self.bits,
127            chainwork: self.chainwork,
128        }
129    }
130}
131
132/// Bounds for header admission.
133#[derive(Clone, Copy, Debug, Eq, PartialEq)]
134pub struct ChainLimits {
135    /// Maximum headers accepted atomically by [`LightChain::append_batch`].
136    pub max_headers_per_batch: usize,
137}
138
139impl Default for ChainLimits {
140    fn default() -> Self {
141        Self {
142            max_headers_per_batch: DEFAULT_MAX_HEADERS_PER_BATCH,
143        }
144    }
145}
146
147impl ChainLimits {
148    fn validate(self) -> Result<Self, LightChainError> {
149        if self.max_headers_per_batch == 0
150            || self.max_headers_per_batch > MAX_HEADERS_PER_BATCH_LIMIT
151        {
152            return Err(LightChainError::InvalidLimit);
153        }
154        Ok(self)
155    }
156}
157
158/// Caller-held rollback floor for an authenticated checkpoint.
159#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
160pub struct ChainSnapshotFloor {
161    /// Lowest acceptable validated height.
162    pub minimum_height: Height,
163    /// Lowest acceptable cumulative proof of work.
164    pub minimum_chainwork: Chainwork,
165}
166
167/// Currency requirements applied before a name proof becomes authoritative.
168#[derive(Clone, Copy, Debug, Eq, PartialEq)]
169pub struct CurrencyPolicy {
170    /// Explicit local wall-clock time.
171    pub now: BlockTime,
172    /// Maximum permitted age of the validated tip.
173    pub maximum_tip_age_seconds: u64,
174    /// Minimum acceptable validated height.
175    pub minimum_height: Height,
176    /// Minimum acceptable cumulative work.
177    pub minimum_chainwork: Chainwork,
178}
179
180/// A linear, consensus-validated Handshake header chain.
181///
182/// The implementation intentionally admits only a contiguous extension of its
183/// current tip. Fork download, best-chain selection, and persisted checkpoint
184/// recovery belong in `hns-light-sync`; this type is the consensus gate that
185/// such a synchronizer must use.
186#[derive(Clone, Debug)]
187pub struct LightChain {
188    network: Network,
189    limits: ChainLimits,
190    history: VecDeque<HeaderEntry>,
191    tip: HeaderEntry,
192}
193
194impl LightChain {
195    /// Open the selected network at its canonical genesis header.
196    pub fn from_genesis(
197        network: Network,
198        now: BlockTime,
199        limits: ChainLimits,
200    ) -> Result<Self, LightChainError> {
201        let limits = limits.validate()?;
202        let parameters = network.parameters();
203        let header = parameters.genesis_header();
204        let proof = validate_header(
205            parameters,
206            &header,
207            HeaderValidationContext {
208                height: Height::new(0),
209                previous_block: BlockHash::default(),
210                median_time: BlockTime::new(0),
211                now,
212                expected_bits: parameters.pow.bits,
213            },
214        )?;
215        let mut history = VecDeque::with_capacity(REQUIRED_DIFFICULTY_HISTORY);
216        let tip = entry_from_header(Height::new(0), &header, proof);
217        history.push_back(tip);
218        Ok(Self {
219            network,
220            limits,
221            history,
222            tip,
223        })
224    }
225
226    /// Selected Handshake network.
227    #[must_use]
228    pub const fn network(&self) -> Network {
229        self.network
230    }
231
232    /// Current validated tip.
233    #[must_use]
234    pub const fn tip(&self) -> HeaderEntry {
235        self.tip
236    }
237
238    /// Encode the exact consensus lookback window for an authenticated store.
239    ///
240    /// The checksum detects accidental corruption; it does not authenticate or
241    /// rollback-protect the bytes. Callers must persist the blob in their
242    /// wallet-owned authenticated store and retain a monotonic floor.
243    pub fn encode_authenticated_snapshot(&self) -> Result<Vec<u8>, LightChainError> {
244        let mut encoder = Encoder::with_capacity(MAX_LIGHT_CHAIN_SNAPSHOT_BYTES);
245        encoder.put_bytes(LIGHT_CHAIN_SNAPSHOT_MAGIC);
246        encoder.put_u16_le(LIGHT_CHAIN_SNAPSHOT_SCHEMA);
247        encoder.put_u8(self.network.id());
248        encoder.put_u32_le(
249            u32::try_from(self.limits.max_headers_per_batch)
250                .map_err(|_| LightChainError::InvalidSnapshot)?,
251        );
252        encoder.put_u16_le(
253            u16::try_from(self.history.len()).map_err(|_| LightChainError::InvalidSnapshot)?,
254        );
255        for entry in &self.history {
256            encode_header_entry(&mut encoder, *entry);
257        }
258        let mut snapshot_bytes = encoder.into_bytes();
259        let checksum = snapshot_checksum(&snapshot_bytes);
260        snapshot_bytes.extend_from_slice(&checksum);
261        if snapshot_bytes.len() > MAX_LIGHT_CHAIN_SNAPSHOT_BYTES {
262            return Err(LightChainError::SnapshotTooLarge);
263        }
264        Ok(snapshot_bytes)
265    }
266
267    /// Restore a structurally exact checkpoint from an authenticated store.
268    ///
269    /// `expected_network` prevents cross-network reuse and `floor` prevents an
270    /// older otherwise authentic checkpoint from replacing caller-held state.
271    pub fn decode_authenticated_snapshot(
272        input: &[u8],
273        expected_network: Network,
274        floor: ChainSnapshotFloor,
275    ) -> Result<Self, LightChainError> {
276        if input.len() > MAX_LIGHT_CHAIN_SNAPSHOT_BYTES {
277            return Err(LightChainError::SnapshotTooLarge);
278        }
279        let payload_length = input
280            .len()
281            .checked_sub(32)
282            .ok_or(LightChainError::InvalidSnapshot)?;
283        let (payload, encoded_checksum) = input.split_at(payload_length);
284        if encoded_checksum != snapshot_checksum(payload) {
285            return Err(LightChainError::SnapshotChecksumMismatch);
286        }
287        let mut decoder = Decoder::new(payload);
288        if decoder.read_slice(LIGHT_CHAIN_SNAPSHOT_MAGIC.len())? != LIGHT_CHAIN_SNAPSHOT_MAGIC
289            || decoder.read_u16_le()? != LIGHT_CHAIN_SNAPSHOT_SCHEMA
290        {
291            return Err(LightChainError::UnsupportedSnapshot);
292        }
293        let network = decode_network(decoder.read_u8()?)?;
294        if network != expected_network {
295            return Err(LightChainError::SnapshotNetworkMismatch);
296        }
297        let limits = ChainLimits {
298            max_headers_per_batch: usize::try_from(decoder.read_u32_le()?)
299                .map_err(|_| LightChainError::InvalidSnapshot)?,
300        }
301        .validate()?;
302        let count = usize::from(decoder.read_u16_le()?);
303        if count == 0 || count > REQUIRED_DIFFICULTY_HISTORY {
304            return Err(LightChainError::InvalidSnapshot);
305        }
306        let mut history = VecDeque::with_capacity(count);
307        for _ in 0..count {
308            history.push_back(decode_header_entry(&mut decoder)?);
309        }
310        decoder.finish()?;
311        validate_snapshot_history(expected_network, limits, &history, floor)?;
312        let tip = history
313            .back()
314            .copied()
315            .ok_or(LightChainError::InvalidSnapshot)?;
316        Ok(Self {
317            network,
318            limits,
319            history,
320            tip,
321        })
322    }
323
324    /// Build a standard recent-first exponential block locator ending at genesis.
325    #[must_use]
326    pub fn locator(&self) -> Vec<BlockHash> {
327        let mut locator = Vec::with_capacity(MAX_LOCATOR_HASHES);
328        let mut height = self.tip.height.get();
329        let mut step = 1_u32;
330        loop {
331            let entry = self.entry_at(height).ok();
332            let Some(entry) = entry else {
333                break;
334            };
335            locator.push(entry.hash);
336            if height == 0 {
337                break;
338            }
339            if locator.len() >= 10 {
340                step = step.saturating_mul(2);
341            }
342            height = height.saturating_sub(step);
343        }
344        let genesis = self.network.parameters().genesis_hash;
345        if locator.last().copied() != Some(genesis) {
346            locator.push(genesis);
347        }
348        locator
349    }
350
351    /// Append one header after all consensus checks.
352    pub fn append(
353        &mut self,
354        header: &Header,
355        now: BlockTime,
356    ) -> Result<HeaderEntry, LightChainError> {
357        let tip = self.tip();
358        let next_height = tip
359            .height
360            .get()
361            .checked_add(1)
362            .map(Height::new)
363            .ok_or(LightChainError::HeightOverflow)?;
364        let parameters = self.network.parameters();
365        let (first_suitable, last_suitable) =
366            if tip.height.get() >= parameters.pow.target_window.saturating_add(2) {
367                let ancestor_height = tip
368                    .height
369                    .get()
370                    .checked_sub(parameters.pow.target_window)
371                    .ok_or(LightChainError::MissingDifficultyHistory)?;
372                (
373                    Some(self.suitable_entry(ancestor_height)?.difficulty_point()),
374                    Some(self.suitable_entry(tip.height.get())?.difficulty_point()),
375                )
376            } else {
377                (None, None)
378            };
379        let expected_bits = expected_next_bits(
380            parameters.pow,
381            header.time,
382            tip.difficulty_point(),
383            first_suitable,
384            last_suitable,
385        )?;
386        let proof = validate_header(
387            parameters,
388            header,
389            HeaderValidationContext {
390                height: next_height,
391                previous_block: tip.hash,
392                median_time: self.median_time_past(),
393                now,
394                expected_bits,
395            },
396        )?;
397        let chainwork = tip.chainwork.checked_add(proof)?;
398        let entry = entry_from_header(next_height, header, chainwork);
399        self.history.push_back(entry);
400        while self.history.len() > REQUIRED_DIFFICULTY_HISTORY {
401            self.history.pop_front();
402        }
403        self.tip = entry;
404        Ok(entry)
405    }
406
407    /// Append a bounded batch transactionally.
408    ///
409    /// No prefix is retained if any header fails.
410    pub fn append_batch(
411        &mut self,
412        headers: &[Header],
413        now: BlockTime,
414    ) -> Result<HeaderEntry, LightChainError> {
415        if headers.is_empty() || headers.len() > self.limits.max_headers_per_batch {
416            return Err(LightChainError::HeaderBatchLimit);
417        }
418        let mut candidate = self.clone();
419        for header in headers {
420            candidate.append(header, now)?;
421        }
422        let tip = candidate.tip();
423        *self = candidate;
424        Ok(tip)
425    }
426
427    /// Require explicit tip-age, height, and work currency.
428    pub fn require_current(&self, policy: CurrencyPolicy) -> Result<CurrentChain, LightChainError> {
429        let tip = self.tip();
430        if tip.height < policy.minimum_height {
431            return Err(LightChainError::InsufficientHeight);
432        }
433        if tip.chainwork < policy.minimum_chainwork {
434            return Err(LightChainError::InsufficientChainwork);
435        }
436        let valid_until = tip
437            .time
438            .get()
439            .checked_add(policy.maximum_tip_age_seconds)
440            .ok_or(LightChainError::TimeOverflow)?;
441        if policy.now.get() > valid_until {
442            return Err(LightChainError::StaleTip);
443        }
444        if tip.time.get() > policy.now.get().saturating_add(7_200) {
445            return Err(LightChainError::FutureTip);
446        }
447        Ok(CurrentChain {
448            anchor: HnsAnchor {
449                network: self.network,
450                height: tip.height,
451                block_hash: tip.hash,
452                tree_root: tip.tree_root,
453                chainwork: tip.chainwork,
454                validated_at: policy.now,
455                valid_until: BlockTime::new(valid_until),
456            },
457        })
458    }
459
460    /// Consensus median-time-past of the current tip's trailing window.
461    ///
462    /// Wallet transaction and name-action policy uses this exact parent-chain
463    /// clock; wall time and the tip header's raw timestamp are not substitutes.
464    #[must_use]
465    pub fn median_time_past(&self) -> BlockTime {
466        let mut times = self
467            .history
468            .iter()
469            .rev()
470            .take(MEDIAN_TIME_SPAN)
471            .map(|entry| entry.time.get())
472            .collect::<Vec<_>>();
473        times.sort_unstable();
474        BlockTime::new(
475            times
476                .get(times.len() / 2)
477                .copied()
478                .unwrap_or(self.tip.time.get()),
479        )
480    }
481
482    fn suitable_entry(&self, height: u32) -> Result<HeaderEntry, LightChainError> {
483        let first_height = height
484            .checked_sub(2)
485            .ok_or(LightChainError::MissingDifficultyHistory)?;
486        let mut entries = [
487            self.entry_at(first_height)?,
488            self.entry_at(first_height + 1)?,
489            self.entry_at(height)?,
490        ];
491        entries.sort_by_key(|entry| entry.time);
492        Ok(entries[1])
493    }
494
495    fn entry_at(&self, height: u32) -> Result<HeaderEntry, LightChainError> {
496        self.history
497            .iter()
498            .find(|entry| entry.height.get() == height)
499            .copied()
500            .ok_or(LightChainError::MissingDifficultyHistory)
501    }
502}
503
504/// A chain tip that passed explicit currency policy.
505#[derive(Clone, Copy, Debug, Eq, PartialEq)]
506pub struct CurrentChain {
507    anchor: HnsAnchor,
508}
509
510impl CurrentChain {
511    /// Currency-checked anchor metadata.
512    #[must_use]
513    pub const fn anchor(self) -> HnsAnchor {
514        self.anchor
515    }
516
517    /// Verify one canonical HSD inclusion proof and decode its committed name state.
518    pub fn verify_name_resource(
519        &self,
520        name: &[u8],
521        proof_bytes: &[u8],
522    ) -> Result<VerifiedHnsResource, LightChainError> {
523        let name_hash = hash_name(name)?;
524        let proof = HsdUrkelProof::decode_strict(proof_bytes)?;
525        let name_state = proof
526            .verify(self.anchor.tree_root, name_hash)?
527            .ok_or(LightChainError::NameNotFound)?;
528        let decoded = decode_name_state(&name_state, name, self.anchor.height)?;
529        let resource = HnsResource::decode(&decoded.resource)?;
530        Ok(VerifiedHnsResource {
531            anchor: self.anchor,
532            name_hash,
533            name: name.to_vec(),
534            state_height: decoded.height,
535            renewal_height: decoded.renewal,
536            resource,
537        })
538    }
539}
540
541/// Metadata for the exact current header that authenticated a resource.
542#[derive(Clone, Copy, Debug, Eq, PartialEq)]
543pub struct HnsAnchor {
544    network: Network,
545    height: Height,
546    block_hash: BlockHash,
547    tree_root: TreeRoot,
548    chainwork: Chainwork,
549    validated_at: BlockTime,
550    valid_until: BlockTime,
551}
552
553impl HnsAnchor {
554    /// Handshake network.
555    #[must_use]
556    pub const fn network(self) -> Network {
557        self.network
558    }
559
560    /// Header height.
561    #[must_use]
562    pub const fn height(self) -> Height {
563        self.height
564    }
565
566    /// Header block hash.
567    #[must_use]
568    pub const fn block_hash(self) -> BlockHash {
569        self.block_hash
570    }
571
572    /// Header name-tree root.
573    #[must_use]
574    pub const fn tree_root(self) -> TreeRoot {
575        self.tree_root
576    }
577
578    /// Cumulative chainwork.
579    #[must_use]
580    pub const fn chainwork(self) -> Chainwork {
581        self.chainwork
582    }
583
584    /// Local time at which currency was checked.
585    #[must_use]
586    pub const fn validated_at(self) -> BlockTime {
587        self.validated_at
588    }
589
590    /// Last local time for which the configured age policy holds.
591    #[must_use]
592    pub const fn valid_until(self) -> BlockTime {
593        self.valid_until
594    }
595}
596
597/// A name resource authenticated by a current Handshake header and Urkel proof.
598#[derive(Clone, Debug, Eq, PartialEq)]
599pub struct VerifiedHnsResource {
600    anchor: HnsAnchor,
601    name_hash: NameHash,
602    name: Vec<u8>,
603    state_height: Height,
604    renewal_height: Height,
605    resource: HnsResource,
606}
607
608impl VerifiedHnsResource {
609    /// Exact chain anchor that committed this resource.
610    #[must_use]
611    pub const fn anchor(&self) -> HnsAnchor {
612        self.anchor
613    }
614
615    /// Canonical Handshake name hash used as the Urkel key.
616    #[must_use]
617    pub const fn name_hash(&self) -> NameHash {
618        self.name_hash
619    }
620
621    /// Lowercase Handshake TLD label.
622    #[must_use]
623    pub fn name(&self) -> &[u8] {
624        &self.name
625    }
626
627    /// Name-state creation/reset height.
628    #[must_use]
629    pub const fn state_height(&self) -> Height {
630        self.state_height
631    }
632
633    /// Name-state renewal height.
634    #[must_use]
635    pub const fn renewal_height(&self) -> Height {
636        self.renewal_height
637    }
638
639    /// Strictly decoded committed HNS resource.
640    #[must_use]
641    pub const fn resource(&self) -> &HnsResource {
642        &self.resource
643    }
644}
645
646/// Strictly decoded HSD name resource.
647#[derive(Clone, Debug, Eq, PartialEq)]
648pub struct HnsResource {
649    raw: Vec<u8>,
650    records: Vec<HnsResourceRecord>,
651}
652
653impl HnsResource {
654    /// Decode all assigned records and reject unknown tags or trailing fragments.
655    pub fn decode(raw: &[u8]) -> Result<Self, LightChainError> {
656        if raw.len() > MAX_RESOURCE_SIZE {
657            return Err(LightChainError::ResourceTooLarge(raw.len()));
658        }
659        let mut reader = ResourceReader::new(raw);
660        if reader.read_u8()? != 0 {
661            return Err(LightChainError::UnsupportedResourceVersion);
662        }
663        let mut records = Vec::new();
664        while !reader.is_finished() {
665            let kind = reader.read_u8()?;
666            if kind > MAX_KNOWN_RESOURCE_KIND {
667                return Err(LightChainError::UnknownResourceRecord(kind));
668            }
669            let record = match kind {
670                0 => HnsResourceRecord::Ds(DelegationSigner {
671                    key_tag: reader.read_u16_be()?,
672                    algorithm: reader.read_u8()?,
673                    digest_type: reader.read_u8()?,
674                    digest: reader.read_length_prefixed_bytes()?,
675                }),
676                1 => HnsResourceRecord::Ns(reader.read_name()?),
677                2 => HnsResourceRecord::Glue4 {
678                    name: reader.read_name()?,
679                    address: Ipv4Addr::from(reader.read_array()?),
680                },
681                3 => HnsResourceRecord::Glue6 {
682                    name: reader.read_name()?,
683                    address: Ipv6Addr::from(reader.read_array()?),
684                },
685                4 => HnsResourceRecord::Synth4(Ipv4Addr::from(reader.read_array()?)),
686                5 => HnsResourceRecord::Synth6(Ipv6Addr::from(reader.read_array()?)),
687                6 => {
688                    let count = usize::from(reader.read_u8()?);
689                    let mut strings = Vec::with_capacity(count);
690                    for _ in 0..count {
691                        strings.push(reader.read_length_prefixed_bytes()?);
692                    }
693                    HnsResourceRecord::Txt(strings)
694                }
695                _ => unreachable!("assigned resource kinds are exhaustively matched"),
696            };
697            records.push(record);
698        }
699        CovenantResource::new(raw.to_vec())?;
700        Ok(Self {
701            raw: raw.to_vec(),
702            records,
703        })
704    }
705
706    /// Exact bytes committed in the name state.
707    #[must_use]
708    pub fn as_bytes(&self) -> &[u8] {
709        &self.raw
710    }
711
712    /// All assigned records in commitment order.
713    #[must_use]
714    pub fn records(&self) -> &[HnsResourceRecord] {
715        &self.records
716    }
717
718    /// Iterate the DNSSEC delegation signers in commitment order.
719    pub fn delegation_signers(&self) -> impl Iterator<Item = &DelegationSigner> {
720        self.records.iter().filter_map(|record| match record {
721            HnsResourceRecord::Ds(ds) => Some(ds),
722            _ => None,
723        })
724    }
725}
726
727/// One assigned HSD resource record.
728#[derive(Clone, Debug, Eq, PartialEq)]
729pub enum HnsResourceRecord {
730    /// DNSSEC DS record for the TLD zone.
731    Ds(DelegationSigner),
732    /// Authoritative nameserver.
733    Ns(ResourceName),
734    /// Nameserver plus IPv4 glue.
735    Glue4 {
736        /// Nameserver name.
737        name: ResourceName,
738        /// IPv4 address.
739        address: Ipv4Addr,
740    },
741    /// Nameserver plus IPv6 glue.
742    Glue6 {
743        /// Nameserver name.
744        name: ResourceName,
745        /// IPv6 address.
746        address: Ipv6Addr,
747    },
748    /// Synthetic IPv4 nameserver.
749    Synth4(Ipv4Addr),
750    /// Synthetic IPv6 nameserver.
751    Synth6(Ipv6Addr),
752    /// HNS TXT strings.
753    Txt(Vec<Vec<u8>>),
754}
755
756/// One HNS resource DS payload.
757#[derive(Clone, Debug, Eq, PartialEq)]
758pub struct DelegationSigner {
759    /// DNSKEY key tag.
760    pub key_tag: u16,
761    /// DNSSEC algorithm.
762    pub algorithm: u8,
763    /// DS digest algorithm.
764    pub digest_type: u8,
765    /// DS digest bytes.
766    pub digest: Vec<u8>,
767}
768
769/// Expanded uncompressed DNS name from an HNS resource.
770#[derive(Clone, Debug, Eq, PartialEq)]
771pub struct ResourceName {
772    labels: Vec<Vec<u8>>,
773}
774
775impl ResourceName {
776    /// Expanded labels, excluding the terminal root.
777    #[must_use]
778    pub fn labels(&self) -> &[Vec<u8>] {
779        &self.labels
780    }
781}
782
783#[derive(Debug)]
784struct DecodedNameState {
785    resource: Vec<u8>,
786    height: Height,
787    renewal: Height,
788}
789
790fn decode_name_state(
791    raw: &[u8],
792    expected_name: &[u8],
793    tip_height: Height,
794) -> Result<DecodedNameState, LightChainError> {
795    let mut decoder = Decoder::new(raw);
796    let name_length = usize::from(decoder.read_u8()?);
797    let name = decoder.read_slice(name_length)?;
798    if name != expected_name || !validate_name(name) {
799        return Err(LightChainError::NameStateNameMismatch);
800    }
801    let resource_length = usize::from(decoder.read_u16_le()?);
802    if resource_length == 0 {
803        return Err(LightChainError::MissingResource);
804    }
805    if resource_length > MAX_RESOURCE_SIZE {
806        return Err(LightChainError::ResourceTooLarge(resource_length));
807    }
808    let resource = decoder.read_slice(resource_length)?.to_vec();
809    let height = Height::new(decoder.read_u32_le()?);
810    let renewal = Height::new(decoder.read_u32_le()?);
811    let field = decoder.read_u16_le()?;
812    if field & !NAME_STATE_KNOWN_FIELD_BITS != 0 {
813        return Err(LightChainError::UnknownNameStateField);
814    }
815    if height > tip_height || renewal > tip_height {
816        return Err(LightChainError::FutureNameState);
817    }
818    if field & (1 << 0) != 0 {
819        decoder.read_array::<32>()?;
820        let owner_index = decoder.read_compact_size()?;
821        if owner_index > u64::from(u32::MAX) {
822            return Err(LightChainError::InvalidNameStateValue);
823        }
824    }
825    if field & (1 << 1) != 0 {
826        decoder.read_compact_size()?;
827    }
828    if field & (1 << 2) != 0 {
829        decoder.read_compact_size()?;
830    }
831    for bit in [3_u16, 4, 5] {
832        if field & (1 << bit) != 0 {
833            let event_height = Height::new(decoder.read_u32_le()?);
834            if event_height > tip_height {
835                return Err(LightChainError::FutureNameState);
836            }
837        }
838    }
839    if field & (1 << 6) != 0 && decoder.read_compact_size()? > u64::from(u32::MAX) {
840        return Err(LightChainError::InvalidNameStateValue);
841    }
842    decoder.finish()?;
843    Ok(DecodedNameState {
844        resource,
845        height,
846        renewal,
847    })
848}
849
850fn entry_from_header(height: Height, header: &Header, chainwork: Chainwork) -> HeaderEntry {
851    HeaderEntry {
852        height,
853        hash: header.block_hash(),
854        previous_block: header.previous_block,
855        tree_root: header.tree_root,
856        merkle_root: header.merkle_root,
857        time: header.time,
858        bits: header.bits,
859        chainwork,
860    }
861}
862
863fn encode_header_entry(encoder: &mut Encoder, entry: HeaderEntry) {
864    encoder.put_u32_le(entry.height.get());
865    encoder.put_bytes(entry.hash.as_bytes());
866    encoder.put_bytes(entry.previous_block.as_bytes());
867    encoder.put_bytes(entry.tree_root.as_bytes());
868    encoder.put_bytes(entry.merkle_root.as_bytes());
869    encoder.put_u64_le(entry.time.get());
870    encoder.put_u32_le(entry.bits.get());
871    encoder.put_bytes(&entry.chainwork.to_be_bytes());
872}
873
874fn decode_header_entry(decoder: &mut Decoder<'_>) -> Result<HeaderEntry, LightChainError> {
875    Ok(HeaderEntry {
876        height: Height::new(decoder.read_u32_le()?),
877        hash: BlockHash::new(decoder.read_array()?),
878        previous_block: BlockHash::new(decoder.read_array()?),
879        tree_root: TreeRoot::new(decoder.read_array()?),
880        merkle_root: MerkleRoot::new(decoder.read_array()?),
881        time: BlockTime::new(decoder.read_u64_le()?),
882        bits: CompactTarget::new(decoder.read_u32_le()?),
883        chainwork: Chainwork::from_be_bytes(decoder.read_array()?),
884    })
885}
886
887fn validate_snapshot_history(
888    network: Network,
889    limits: ChainLimits,
890    history: &VecDeque<HeaderEntry>,
891    floor: ChainSnapshotFloor,
892) -> Result<(), LightChainError> {
893    let first = history
894        .front()
895        .copied()
896        .ok_or(LightChainError::InvalidSnapshot)?;
897    let tip = history
898        .back()
899        .copied()
900        .ok_or(LightChainError::InvalidSnapshot)?;
901    let expected_length = usize::try_from(u64::from(tip.height.get()) + 1)
902        .map_err(|_| LightChainError::InvalidSnapshot)?
903        .min(REQUIRED_DIFFICULTY_HISTORY);
904    if history.len() != expected_length {
905        return Err(LightChainError::InvalidSnapshot);
906    }
907    if history.iter().any(|entry| {
908        entry.hash == BlockHash::default()
909            || entry.bits.get() == 0
910            || entry.chainwork == Chainwork::ZERO
911    }) {
912        return Err(LightChainError::InvalidSnapshot);
913    }
914    if tip.height < floor.minimum_height || tip.chainwork < floor.minimum_chainwork {
915        return Err(LightChainError::SnapshotRollback);
916    }
917    if first.height.get() == 0 {
918        let expected =
919            LightChain::from_genesis(network, network.parameters().genesis_time, limits)?;
920        if first != expected.tip {
921            return Err(LightChainError::InvalidSnapshot);
922        }
923    }
924    let linear = history.iter().copied().collect::<Vec<_>>();
925    for pair in linear.windows(2) {
926        validate_snapshot_pair(pair)?;
927    }
928    Ok(())
929}
930
931fn validate_snapshot_pair(pair: &[HeaderEntry]) -> Result<(), LightChainError> {
932    let [previous, next] = pair else {
933        return Err(LightChainError::InvalidSnapshot);
934    };
935    if previous.height.get().checked_add(1) != Some(next.height.get())
936        || next.previous_block != previous.hash
937        || next.chainwork <= previous.chainwork
938        || next.bits.get() == 0
939    {
940        return Err(LightChainError::InvalidSnapshot);
941    }
942    Ok(())
943}
944
945fn decode_network(id: u8) -> Result<Network, LightChainError> {
946    match id {
947        0 => Ok(Network::Mainnet),
948        1 => Ok(Network::Testnet),
949        2 => Ok(Network::Regtest),
950        3 => Ok(Network::Simnet),
951        _ => Err(LightChainError::InvalidSnapshot),
952    }
953}
954
955fn snapshot_checksum(payload: &[u8]) -> [u8; 32] {
956    let mut hasher = Blake2b::<U32>::new();
957    hasher.update(LIGHT_CHAIN_SNAPSHOT_CHECKSUM_DOMAIN);
958    hasher.update(payload);
959    hasher.finalize().into()
960}
961
962struct ResourceReader<'a> {
963    input: &'a [u8],
964    position: usize,
965    known_name_offsets: Vec<usize>,
966}
967
968impl<'a> ResourceReader<'a> {
969    const fn new(input: &'a [u8]) -> Self {
970        Self {
971            input,
972            position: 0,
973            known_name_offsets: Vec::new(),
974        }
975    }
976
977    const fn is_finished(&self) -> bool {
978        self.position == self.input.len()
979    }
980
981    fn read_u8(&mut self) -> Result<u8, LightChainError> {
982        Ok(self.read_array::<1>()?[0])
983    }
984
985    fn read_u16_be(&mut self) -> Result<u16, LightChainError> {
986        Ok(u16::from_be_bytes(self.read_array()?))
987    }
988
989    fn read_array<const LENGTH: usize>(&mut self) -> Result<[u8; LENGTH], LightChainError> {
990        let end = self
991            .position
992            .checked_add(LENGTH)
993            .ok_or(LightChainError::ResourceTruncated)?;
994        let bytes = self
995            .input
996            .get(self.position..end)
997            .ok_or(LightChainError::ResourceTruncated)?;
998        self.position = end;
999        bytes
1000            .try_into()
1001            .map_err(|_| LightChainError::ResourceTruncated)
1002    }
1003
1004    fn read_length_prefixed_bytes(&mut self) -> Result<Vec<u8>, LightChainError> {
1005        let length = usize::from(self.read_u8()?);
1006        let end = self
1007            .position
1008            .checked_add(length)
1009            .ok_or(LightChainError::ResourceTruncated)?;
1010        let bytes = self
1011            .input
1012            .get(self.position..end)
1013            .ok_or(LightChainError::ResourceTruncated)?;
1014        self.position = end;
1015        Ok(bytes.to_vec())
1016    }
1017
1018    fn read_name(&mut self) -> Result<ResourceName, LightChainError> {
1019        let mut cursor = self.position;
1020        let mut resume = None;
1021        let mut labels = Vec::new();
1022        let mut expanded_wire_length = 1_usize;
1023        let mut jumps = 0_usize;
1024        let mut visited = Vec::new();
1025
1026        loop {
1027            if visited.contains(&cursor) {
1028                return Err(LightChainError::ResourceNameCompressionLoop);
1029            }
1030            visited.push(cursor);
1031            let length = *self
1032                .input
1033                .get(cursor)
1034                .ok_or(LightChainError::ResourceTruncated)?;
1035            if length & 0xc0 == 0xc0 {
1036                let next = *self
1037                    .input
1038                    .get(cursor + 1)
1039                    .ok_or(LightChainError::ResourceTruncated)?;
1040                let target = (usize::from(length & 0x3f) << 8) | usize::from(next);
1041                if target >= cursor || !self.known_name_offsets.contains(&target) {
1042                    return Err(LightChainError::InvalidResourceNamePointer);
1043                }
1044                if resume.is_none() {
1045                    resume = Some(cursor + 2);
1046                }
1047                jumps += 1;
1048                if jumps > MAX_RESOURCE_NAME_JUMPS {
1049                    return Err(LightChainError::ResourceNameJumpLimit);
1050                }
1051                cursor = target;
1052                continue;
1053            }
1054            if length & 0xc0 != 0 {
1055                return Err(LightChainError::InvalidResourceName);
1056            }
1057            self.known_name_offsets.push(cursor);
1058            cursor += 1;
1059            if length == 0 {
1060                self.position = resume.unwrap_or(cursor);
1061                return Ok(ResourceName { labels });
1062            }
1063            let length = usize::from(length);
1064            if length > 63 || labels.len() >= MAX_RESOURCE_NAME_LABELS {
1065                return Err(LightChainError::InvalidResourceName);
1066            }
1067            expanded_wire_length = expanded_wire_length
1068                .checked_add(length + 1)
1069                .ok_or(LightChainError::InvalidResourceName)?;
1070            if expanded_wire_length > 255 {
1071                return Err(LightChainError::InvalidResourceName);
1072            }
1073            let end = cursor
1074                .checked_add(length)
1075                .ok_or(LightChainError::ResourceTruncated)?;
1076            let label = self
1077                .input
1078                .get(cursor..end)
1079                .ok_or(LightChainError::ResourceTruncated)?;
1080            labels.push(label.to_vec());
1081            cursor = end;
1082            if resume.is_none() {
1083                self.position = cursor;
1084            }
1085        }
1086    }
1087}
1088
1089/// Header, currency, proof, name-state, or HNS resource failure.
1090#[derive(Debug, Error)]
1091#[non_exhaustive]
1092pub enum LightChainError {
1093    /// Shared header consensus rejected a header.
1094    #[error("header consensus failure: {0}")]
1095    Header(#[from] HeaderError),
1096    /// Shared arithmetic rejected chainwork overflow.
1097    #[error("chainwork arithmetic failure: {0}")]
1098    Arithmetic(#[from] hns_primitives::ArithmeticError),
1099    /// Shared Handshake name/resource validation failed.
1100    #[error("covenant value failure: {0}")]
1101    Covenant(#[from] hns_covenants::CovenantError),
1102    /// Strict Urkel proof parsing or verification failed.
1103    #[error("Urkel proof failure: {0}")]
1104    Urkel(#[from] UrkelError),
1105    /// Strict name-state decoding failed.
1106    #[error("name-state decoding failure: {0}")]
1107    NameStateDecode(#[from] DecodeError),
1108    /// A configured bound is zero or exceeds the hard operational maximum.
1109    #[error("chain limit is zero or excessive")]
1110    InvalidLimit,
1111    /// The header batch is empty or exceeds its bound.
1112    #[error("header batch exceeds its configured bound")]
1113    HeaderBatchLimit,
1114    /// Authenticated checkpoint framing or structural invariants are invalid.
1115    #[error("invalid authenticated light-chain checkpoint")]
1116    InvalidSnapshot,
1117    /// Checkpoint exceeds the fixed allocation bound.
1118    #[error("light-chain checkpoint exceeds its size bound")]
1119    SnapshotTooLarge,
1120    /// Checkpoint checksum differs from its payload.
1121    #[error("light-chain checkpoint checksum mismatch")]
1122    SnapshotChecksumMismatch,
1123    /// Checkpoint schema or magic is unsupported.
1124    #[error("unsupported light-chain checkpoint schema")]
1125    UnsupportedSnapshot,
1126    /// Checkpoint belongs to another Handshake network.
1127    #[error("light-chain checkpoint network mismatch")]
1128    SnapshotNetworkMismatch,
1129    /// Checkpoint falls below the caller-held height or chainwork floor.
1130    #[error("light-chain checkpoint rollback detected")]
1131    SnapshotRollback,
1132    /// The next height cannot be represented.
1133    #[error("header height overflow")]
1134    HeightOverflow,
1135    /// Required retarget history is unavailable.
1136    #[error("required difficulty history is unavailable")]
1137    MissingDifficultyHistory,
1138    /// Time arithmetic overflowed.
1139    #[error("time arithmetic overflow")]
1140    TimeOverflow,
1141    /// Validated height is below policy.
1142    #[error("validated chain height is insufficient")]
1143    InsufficientHeight,
1144    /// Validated cumulative work is below policy.
1145    #[error("validated cumulative chainwork is insufficient")]
1146    InsufficientChainwork,
1147    /// The validated tip is older than policy permits.
1148    #[error("validated Handshake tip is stale")]
1149    StaleTip,
1150    /// The validated tip is more than two hours ahead of the supplied clock.
1151    #[error("validated Handshake tip is too far in the future")]
1152    FutureTip,
1153    /// The proof establishes non-inclusion.
1154    #[error("Handshake name is absent at the validated tree root")]
1155    NameNotFound,
1156    /// Serialized name and proof key disagree.
1157    #[error("name-state name does not match the requested proof key")]
1158    NameStateNameMismatch,
1159    /// Name state carries no HNS resource.
1160    #[error("name state has no resource")]
1161    MissingResource,
1162    /// Resource exceeds the consensus covenant bound.
1163    #[error("resource length {0} exceeds the Handshake bound")]
1164    ResourceTooLarge(usize),
1165    /// Name-state bit field has an unknown assignment.
1166    #[error("name state contains unknown field bits")]
1167    UnknownNameStateField,
1168    /// Name-state heights exceed the committing header.
1169    #[error("name state contains a future height")]
1170    FutureNameState,
1171    /// A bounded name-state integer exceeds its protocol domain.
1172    #[error("name state contains an out-of-range integer")]
1173    InvalidNameStateValue,
1174    /// Resource serialization version is unsupported.
1175    #[error("unsupported HNS resource version")]
1176    UnsupportedResourceVersion,
1177    /// An unassigned HNS resource tag was encountered.
1178    #[error("unknown HNS resource record tag {0}")]
1179    UnknownResourceRecord(u8),
1180    /// Resource record ended prematurely.
1181    #[error("truncated HNS resource")]
1182    ResourceTruncated,
1183    /// Resource DNS name is malformed.
1184    #[error("malformed DNS name in HNS resource")]
1185    InvalidResourceName,
1186    /// Resource compression pointer is forward or not at a known name boundary.
1187    #[error("invalid DNS compression pointer in HNS resource")]
1188    InvalidResourceNamePointer,
1189    /// Resource compression pointer graph loops.
1190    #[error("DNS compression loop in HNS resource")]
1191    ResourceNameCompressionLoop,
1192    /// Resource name exceeds its pointer-following bound.
1193    #[error("DNS compression jump bound exceeded in HNS resource")]
1194    ResourceNameJumpLimit,
1195}
1196
1197#[cfg(test)]
1198#[allow(
1199    clippy::expect_used,
1200    clippy::indexing_slicing,
1201    clippy::unwrap_used,
1202    reason = "tests construct compact protocol fixtures and fail immediately"
1203)]
1204mod tests {
1205    use blake2::Blake2bVar;
1206    use blake2::digest::{Update, VariableOutput};
1207
1208    use super::*;
1209
1210    fn blake2b_256(parts: &[&[u8]]) -> [u8; 32] {
1211        let mut hasher = Blake2bVar::new(32).unwrap();
1212        for part in parts {
1213            hasher.update(part);
1214        }
1215        let mut output = [0_u8; 32];
1216        hasher.finalize_variable(&mut output).unwrap();
1217        output
1218    }
1219
1220    fn name_state(name: &[u8], resource: &[u8], height: u32) -> Vec<u8> {
1221        let mut state = Vec::new();
1222        state.push(u8::try_from(name.len()).unwrap());
1223        state.extend_from_slice(name);
1224        state.extend_from_slice(&u16::try_from(resource.len()).unwrap().to_le_bytes());
1225        state.extend_from_slice(resource);
1226        state.extend_from_slice(&height.to_le_bytes());
1227        state.extend_from_slice(&height.to_le_bytes());
1228        state.extend_from_slice(&0_u16.to_le_bytes());
1229        state
1230    }
1231
1232    fn inclusion_proof(value: &[u8]) -> Vec<u8> {
1233        let mut proof = Vec::new();
1234        proof.extend_from_slice(&0xc000_u16.to_le_bytes());
1235        proof.extend_from_slice(&0_u16.to_le_bytes());
1236        proof.extend_from_slice(&u16::try_from(value.len()).unwrap().to_le_bytes());
1237        proof.extend_from_slice(value);
1238        proof
1239    }
1240
1241    fn leaf_root(name: &[u8], value: &[u8]) -> TreeRoot {
1242        let key = hash_name(name).unwrap();
1243        let value_hash = blake2b_256(&[value]);
1244        TreeRoot::new(blake2b_256(&[&[0], key.as_bytes(), &value_hash]))
1245    }
1246
1247    fn mine_regtest_header(previous: HeaderEntry, tree_root: TreeRoot) -> Header {
1248        let mut header = Header {
1249            time: BlockTime::new(previous.time().get() + 1),
1250            previous_block: previous.hash(),
1251            tree_root,
1252            bits: Network::Regtest.parameters().pow.bits,
1253            ..Header::default()
1254        };
1255        while !header.verify_pow() {
1256            header.nonce = header.nonce.checked_add(1).unwrap();
1257        }
1258        header
1259    }
1260
1261    fn ds_resource() -> Vec<u8> {
1262        let mut resource = vec![0, 0];
1263        resource.extend_from_slice(&0x1234_u16.to_be_bytes());
1264        resource.extend_from_slice(&[8, 2, 32]);
1265        resource.extend_from_slice(&[0xab; 32]);
1266        resource
1267    }
1268
1269    #[test]
1270    fn validates_header_currency_urkel_name_state_and_ds_resource() {
1271        let genesis_time = Network::Regtest.parameters().genesis_time;
1272        let now = BlockTime::new(genesis_time.get() + 100);
1273        let mut chain =
1274            LightChain::from_genesis(Network::Regtest, now, ChainLimits::default()).unwrap();
1275        let state = name_state(b"alpha", &ds_resource(), 1);
1276        let proof = inclusion_proof(&state);
1277        let header = mine_regtest_header(chain.tip(), leaf_root(b"alpha", &state));
1278        chain.append(&header, now).unwrap();
1279        let current = chain
1280            .require_current(CurrencyPolicy {
1281                now,
1282                maximum_tip_age_seconds: 3_600,
1283                minimum_height: Height::new(1),
1284                minimum_chainwork: Chainwork::ZERO,
1285            })
1286            .unwrap();
1287        let verified = current.verify_name_resource(b"alpha", &proof).unwrap();
1288        assert_eq!(verified.anchor().height(), Height::new(1));
1289        assert_eq!(verified.name(), b"alpha");
1290        assert_eq!(verified.resource().records().len(), 1);
1291        assert_eq!(
1292            verified.resource().delegation_signers().next(),
1293            Some(&DelegationSigner {
1294                key_tag: 0x1234,
1295                algorithm: 8,
1296                digest_type: 2,
1297                digest: vec![0xab; 32],
1298            })
1299        );
1300
1301        let mut trailing = proof;
1302        trailing.push(0);
1303        assert!(matches!(
1304            current.verify_name_resource(b"alpha", &trailing),
1305            Err(LightChainError::Urkel(UrkelError::TrailingBytes(1)))
1306        ));
1307    }
1308
1309    #[test]
1310    fn header_batches_are_atomic_and_currency_fails_closed() {
1311        let genesis_time = Network::Regtest.parameters().genesis_time;
1312        let now = BlockTime::new(genesis_time.get() + 100);
1313        let mut chain =
1314            LightChain::from_genesis(Network::Regtest, now, ChainLimits::default()).unwrap();
1315        let good = mine_regtest_header(chain.tip(), TreeRoot::new([1; 32]));
1316        let mut bad = good.clone();
1317        bad.previous_block = BlockHash::new([9; 32]);
1318        assert!(chain.append_batch(&[good, bad], now).is_err());
1319        assert_eq!(chain.tip().height(), Height::new(0));
1320        assert_eq!(
1321            chain
1322                .require_current(CurrencyPolicy {
1323                    now: BlockTime::new(genesis_time.get() + 10_000),
1324                    maximum_tip_age_seconds: 10,
1325                    minimum_height: Height::new(0),
1326                    minimum_chainwork: Chainwork::ZERO,
1327                })
1328                .unwrap_err()
1329                .to_string(),
1330            "validated Handshake tip is stale"
1331        );
1332    }
1333
1334    #[test]
1335    fn resource_decoder_handles_names_and_rejects_unknown_or_bad_pointers() {
1336        let resource = [
1337            0, 1, 2, b'n', b's', 7, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 0, 2, 0xc0, 2, 127,
1338            0, 0, 1,
1339        ];
1340        let decoded = HnsResource::decode(&resource).unwrap();
1341        assert_eq!(decoded.records().len(), 2);
1342        assert!(matches!(
1343            &decoded.records()[1],
1344            HnsResourceRecord::Glue4 { name, address }
1345                if name.labels() == [b"ns".to_vec(), b"example".to_vec()]
1346                    && *address == Ipv4Addr::LOCALHOST
1347        ));
1348
1349        assert!(matches!(
1350            HnsResource::decode(&[0, 7]),
1351            Err(LightChainError::UnknownResourceRecord(7))
1352        ));
1353        assert!(matches!(
1354            HnsResource::decode(&[0, 1, 0xc0, 1]),
1355            Err(LightChainError::InvalidResourceNamePointer)
1356        ));
1357    }
1358
1359    #[test]
1360    fn retarget_history_window_is_retained() {
1361        let genesis_time = Network::Regtest.parameters().genesis_time;
1362        let now = BlockTime::new(genesis_time.get() + 10_000);
1363        let mut chain =
1364            LightChain::from_genesis(Network::Regtest, now, ChainLimits::default()).unwrap();
1365        for value in 1_u32..=160 {
1366            let byte = u8::try_from(value).unwrap();
1367            let header = mine_regtest_header(chain.tip(), TreeRoot::new([byte; 32]));
1368            chain.append(&header, now).unwrap();
1369        }
1370        assert_eq!(chain.history.len(), REQUIRED_DIFFICULTY_HISTORY);
1371        assert_eq!(chain.tip().height(), Height::new(160));
1372        let locator = chain.locator();
1373        assert_eq!(locator.first().copied(), Some(chain.tip().hash()));
1374        assert_eq!(
1375            locator.last().copied(),
1376            Some(Network::Regtest.parameters().genesis_hash)
1377        );
1378        assert!(locator.len() <= MAX_LOCATOR_HASHES);
1379
1380        let snapshot = chain.encode_authenticated_snapshot().unwrap();
1381        let floor = ChainSnapshotFloor {
1382            minimum_height: chain.tip().height(),
1383            minimum_chainwork: chain.tip().chainwork(),
1384        };
1385        let mut restored =
1386            LightChain::decode_authenticated_snapshot(&snapshot, Network::Regtest, floor).unwrap();
1387        assert_eq!(restored.tip(), chain.tip());
1388        assert_eq!(restored.history, chain.history);
1389        let next = mine_regtest_header(restored.tip(), TreeRoot::new([161; 32]));
1390        restored.append(&next, now).unwrap();
1391        assert_eq!(restored.tip().height(), Height::new(161));
1392
1393        assert!(matches!(
1394            LightChain::decode_authenticated_snapshot(
1395                &snapshot,
1396                Network::Mainnet,
1397                ChainSnapshotFloor::default()
1398            ),
1399            Err(LightChainError::SnapshotNetworkMismatch)
1400        ));
1401        assert!(matches!(
1402            LightChain::decode_authenticated_snapshot(
1403                &snapshot,
1404                Network::Regtest,
1405                ChainSnapshotFloor {
1406                    minimum_height: Height::new(161),
1407                    minimum_chainwork: Chainwork::ZERO,
1408                }
1409            ),
1410            Err(LightChainError::SnapshotRollback)
1411        ));
1412        let mut corrupted = snapshot;
1413        corrupted[LIGHT_CHAIN_SNAPSHOT_MAGIC.len()] ^= 1;
1414        assert!(matches!(
1415            LightChain::decode_authenticated_snapshot(
1416                &corrupted,
1417                Network::Regtest,
1418                ChainSnapshotFloor::default()
1419            ),
1420            Err(LightChainError::SnapshotChecksumMismatch)
1421        ));
1422    }
1423
1424    #[test]
1425    fn exposes_consensus_median_time_past_for_wallet_policy() {
1426        let genesis_time = Network::Regtest.parameters().genesis_time;
1427        let now = BlockTime::new(genesis_time.get() + 10_000);
1428        let mut chain =
1429            LightChain::from_genesis(Network::Regtest, now, ChainLimits::default()).unwrap();
1430        assert_eq!(chain.median_time_past(), genesis_time);
1431
1432        for value in 1_u8..=11 {
1433            let header = mine_regtest_header(chain.tip(), TreeRoot::new([value; 32]));
1434            chain.append(&header, now).unwrap();
1435        }
1436        assert_eq!(
1437            chain.median_time_past(),
1438            BlockTime::new(genesis_time.get() + 6)
1439        );
1440    }
1441
1442    #[test]
1443    fn compact_target_proof_is_nonzero_for_all_network_genesis_targets() {
1444        for network in [
1445            Network::Mainnet,
1446            Network::Testnet,
1447            Network::Regtest,
1448            Network::Simnet,
1449        ] {
1450            assert!(
1451                hns_header_consensus::DecodedTarget::from_compact(network.parameters().pow.bits)
1452                    .proof()
1453                    .is_some()
1454            );
1455        }
1456    }
1457}