Skip to main content

vector_core/community/
version.rs

1//! Per-entity version chain for authority editions.
2//!
3//! Every authority record (a Grant, RoleMetadata, RoleOrder, Banlist, ...) is a
4//! sequence of **editions**. Each edition carries a monotonic `version` and the hash of its
5//! predecessor (`prev_hash`), and the actor's real-npub signature covers both — so the chain is over
6//! signed content, not the outer wrap. Clients fold the fetched set into the current
7//! head by the rules:
8//!   - **refuse-downgrade** on the version integer (never accept a version below the floor already held);
9//!   - **equal-version fork** resolves authority first (CORD-04 §1): the author's [`Edition::rank`], which
10//!     the caller resolves against its roster, then the lower **inner edition id** (a commitment hash over
11//!     author+content+tags+time, NOT the author-settable `created_at`, so it can't be cheaply biased);
12//!   - a **gap** (a higher version whose `prev_hash` doesn't link contiguously to what we hold) leaves
13//!     the head at the highest *contiguous* version and is reported, so the caller can fail closed for
14//!     that entity and refetch the missing prereqs from the quorum (H1/M8) rather than fail open.
15
16use crate::crypto::sha256::Sha256;
17
18/// Frozen domain-separation label for the edition canonicalization (never change).
19const EDITION_LABEL: &[u8] = b"vector-community/v1/edition";
20
21/// Domain-separated, length-prefixed canonical bytes an authority edition commits to.
22///
23/// Layout (FROZEN — interop + no-migration depend on it):
24/// `u64_be(label.len) ‖ label ‖ entity_id[32] ‖ u64_be(version) ‖ has_prev(1) ‖ prev_hash[32 or zero]
25///  ‖ u64_be(content.len) ‖ content`.
26/// Every field is fixed-width or length-prefixed so distinct inputs can never collide.
27pub fn edition_signing_bytes(
28    entity_id: &[u8; 32],
29    version: u64,
30    prev_hash: Option<&[u8; 32]>,
31    content: &[u8],
32) -> Vec<u8> {
33    let mut out = Vec::with_capacity(8 + EDITION_LABEL.len() + 32 + 8 + 1 + 32 + 8 + content.len());
34    out.extend_from_slice(&(EDITION_LABEL.len() as u64).to_be_bytes());
35    out.extend_from_slice(EDITION_LABEL);
36    out.extend_from_slice(entity_id);
37    out.extend_from_slice(&version.to_be_bytes());
38    match prev_hash {
39        Some(h) => {
40            out.push(1);
41            out.extend_from_slice(h);
42        }
43        None => {
44            out.push(0);
45            out.extend_from_slice(&[0u8; 32]);
46        }
47    }
48    out.extend_from_slice(&(content.len() as u64).to_be_bytes());
49    out.extend_from_slice(content);
50    out
51}
52
53/// A marked edition's identity (CORD-04 §1): the same bytes, then the signer's key, so a
54/// copy re-signed under another key is another edition, and nothing built on the original
55/// links to it.
56pub fn edition_hash_signed(
57    entity_id: &[u8; 32],
58    version: u64,
59    prev_hash: Option<&[u8; 32]>,
60    content: &[u8],
61    signer: &[u8; 32],
62) -> [u8; 32] {
63    let mut h = signing_hasher(entity_id, version, prev_hash, content);
64    h.update(b"concord/edition-signer");
65    h.update(signer);
66    h.finalize()
67}
68
69/// SHA-256 of [`edition_signing_bytes`] — the edition's identity in the chain. The next edition's
70/// `prev_hash` cites this value.
71pub fn edition_hash(
72    entity_id: &[u8; 32],
73    version: u64,
74    prev_hash: Option<&[u8; 32]>,
75    content: &[u8],
76) -> [u8; 32] {
77    signing_hasher(entity_id, version, prev_hash, content).finalize()
78}
79
80/// A hasher fed [`edition_signing_bytes`], without building them.
81fn signing_hasher(entity_id: &[u8; 32], version: u64, prev_hash: Option<&[u8; 32]>, content: &[u8]) -> Sha256 {
82    let mut h = Sha256::new();
83    h.update((EDITION_LABEL.len() as u64).to_be_bytes());
84    h.update(EDITION_LABEL);
85    h.update(entity_id);
86    h.update(version.to_be_bytes());
87    match prev_hash {
88        Some(prev) => {
89            h.update([1]);
90            h.update(prev);
91        }
92        None => {
93            h.update([0]);
94            h.update([0u8; 32]);
95        }
96    }
97    h.update((content.len() as u64).to_be_bytes());
98    h.update(content);
99    h
100}
101
102/// One fetched edition of an entity, reduced to what the fold needs. (Signature/authority validation
103/// happens before this — only editions whose real-npub signature verified are folded.)
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct Edition {
106    pub version: u64,
107    pub prev_hash: Option<[u8; 32]>,
108    /// `edition_hash` of THIS edition (what the next edition's `prev_hash` must cite).
109    pub self_hash: [u8; 32],
110    /// Inner authored timestamp (secs); the first tiebreak at equal version.
111    pub created_at: u64,
112    /// Inner event id; the deterministic final tiebreak (same for every member).
113    pub tiebreak_id: [u8; 32],
114    /// The author's authority at fold time, lower outranking: 0 for the owner, else their highest
115    /// role's position, `u32::MAX` roleless. Equal-version forks compare this before the id.
116    pub rank: u32,
117}
118
119impl Edition {
120    /// Whether this edition wins an equal-version fork against `other`: authority first, then the
121    /// lower inner id (CORD-04 §1).
122    pub fn wins_fork_over(&self, other: &Edition) -> bool {
123        (self.rank, self.tiebreak_id) < (other.rank, other.tiebreak_id)
124    }
125}
126
127/// The outcome of folding one entity's editions.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct FoldResult {
130    /// Index (into the input slice) of the chosen head edition, or `None` if nothing ≥ floor.
131    pub head: Option<usize>,
132    /// A higher version exists but doesn't link contiguously to the head — withheld prereqs. The
133    /// caller fails CLOSED for the entity (suspends its authority) and refetches (H1/M8).
134    pub gap: bool,
135    /// The BASE anchor test passed: the lowest ≥-floor edition is a genesis, our exact held floor
136    /// edition, or chains directly to it. When true, `head` is a chain-verified extension of the
137    /// committed floor even if `gap` flags withheld versions ABOVE it — adopting that verified
138    /// prefix is sound (refuse-downgrade holds). When false, `head` is unanchored: do not adopt.
139    pub anchored: bool,
140}
141
142/// Fold a set of editions for **one** entity into its current head.
143///
144/// `floor` is the highest version the client has already accepted (0 = none yet) and `floor_hash` is
145/// that held edition's [`Edition::self_hash`] (so a new edition can be proven to link to it).
146/// Editions below the floor are ignored (refuse-downgrade), equal-version forks pick the
147/// deterministic tiebreak winner, and the head walks the contiguous `prev_hash` chain upward.
148///
149/// **`gap` is the safety signal.** It is set whenever the head is NOT chain-anchored — either the
150/// lowest edition isn't a genesis / doesn't link to `floor_hash`, or a link breaks mid-chain. A
151/// **tracking** client (one that already holds the floor) MUST fail closed on `gap` (suspend the
152/// entity and refetch the missing prereqs from the quorum — H1/M8), since an unanchored head can
153/// be a forged or rolled-back edition (a hostile relay serving only a high version). A
154/// **bootstrapping** client (a new joiner, `floor == 0`, who legitimately lacks history because the
155/// state was re-anchored under a later epoch) may accept the head despite `gap` *only* after
156/// independently verifying its author's current authority against the roster + owner attestation.
157pub fn fold(editions: &[Edition], floor: u64, floor_hash: Option<&[u8; 32]>) -> FoldResult {
158    fold_with_rivals(editions, floor, floor_hash, &|_| false)
159}
160
161/// [`fold`], taking the head at the **highest version whose chain is intact** (CORD-04 §1): every
162/// edition reachable by `prev_hash` links from the anchor counts, so a fork's sibling that the chain
163/// went on to extend is followed rather than stranded, and the authority tiebreak decides only
164/// among the reachable editions at the top version.
165///
166/// The anchor is the held floor edition and its same-version rivals, or the genesis siblings at
167/// `floor == 0`. While the held edition is served, a rival competes on the tiebreak like any
168/// sibling. While it is withheld, `admit_rival` decides whether a rival may stand in for it: the
169/// caller knows the held head's rank, which this function does not.
170pub fn fold_with_rivals(editions: &[Edition], floor: u64, floor_hash: Option<&[u8; 32]>, admit_rival: &dyn Fn(&Edition) -> bool) -> FoldResult {
171    fold_linked(editions, floor, floor_hash, admit_rival, &|_| true)
172}
173
174/// [`fold_with_rivals`] with the head taken only among the editions `eligible` admits,
175/// while every served edition carries the chain: an edition the Roster refuses still
176/// links what was built on it.
177pub fn fold_linked(
178    editions: &[Edition],
179    floor: u64,
180    floor_hash: Option<&[u8; 32]>,
181    admit_rival: &dyn Fn(&Edition) -> bool,
182    eligible: &dyn Fn(usize) -> bool,
183) -> FoldResult {
184    let present: Vec<usize> = (0..editions.len()).filter(|&i| editions[i].version >= floor).collect();
185    if present.is_empty() {
186        return FoldResult { head: None, gap: false, anchored: false };
187    }
188    let held_served = floor > 0 && present.iter().any(|&i| editions[i].version == floor && Some(&editions[i].self_hash) == floor_hash);
189    let mut reached = vec![false; editions.len()];
190    for &i in &present {
191        let e = &editions[i];
192        reached[i] = if floor == 0 {
193            // No prior head held → only a genuine genesis (v1, no predecessor) anchors the chain.
194            e.version == 1 && e.prev_hash.is_none()
195        } else if e.version == floor {
196            Some(&e.self_hash) == floor_hash || held_served || admit_rival(e)
197        } else {
198            e.version == floor + 1 && floor_hash.is_some() && e.prev_hash.as_ref() == floor_hash
199        };
200    }
201    // Follow every link upward: an edition is reached when its predecessor was.
202    let mut order = present.clone();
203    order.sort_by_key(|&i| editions[i].version);
204    let mut reached_hashes: std::collections::HashMap<u64, std::collections::HashSet<[u8; 32]>> = Default::default();
205    for &i in &order {
206        let e = &editions[i];
207        if !reached[i] {
208            let links = e.version.checked_sub(1).is_some_and(|pv| {
209                e.prev_hash.is_some_and(|p| reached_hashes.get(&pv).is_some_and(|set| set.contains(&p)))
210            });
211            reached[i] = links;
212        }
213        if reached[i] {
214            reached_hashes.entry(e.version).or_default().insert(e.self_hash);
215        }
216    }
217    let head = order
218        .iter()
219        .copied()
220        .filter(|&i| reached[i] && eligible(i))
221        .max_by(|&a, &b| {
222            let (ea, eb) = (&editions[a], &editions[b]);
223            // Highest version first; at the top, the fork winner (authority, then the lower id).
224            // Identical copies resolve to the first served.
225            ea.version.cmp(&eb.version).then_with(|| (eb.rank, eb.tiebreak_id, b).cmp(&(ea.rank, ea.tiebreak_id, a)))
226        });
227    let Some(head) = head else {
228        // Nothing eligible links to what we hold: withholding, or a forged base. Fail closed,
229        // paging only when an eligible edition is there to be reached.
230        return FoldResult { head: None, gap: present.iter().any(|&i| eligible(i)), anchored: false };
231    };
232    // A higher version that nothing reached is a withheld middle (or a forged link): page for it.
233    let gap = present.iter().any(|&i| eligible(i) && editions[i].version > editions[head].version);
234    FoldResult { head: Some(head), gap, anchored: true }
235}
236
237/// The head a **bootstrapping** client accepts: the per-version winner at the HIGHEST present
238/// version ≥ `floor`, **ignoring chain contiguity**. A fresh joiner whose genesis was re-anchored away
239/// cannot verify lineage at all, so contiguity is the wrong test for it — the real gate is the
240/// edition's signature (verified before folding) plus the author's CURRENT authority, which the caller
241/// resolves against the roster + owner attestation. A relay cannot forge a higher version (no valid
242/// signature), so the worst case is a stale-but-valid head that the union + ratchet later upgrade.
243/// Returns `None` if no edition is ≥ `floor`. Equal-version forks use the same deterministic tiebreak
244/// as [`fold`] (lower inner edition id) so every client converges on one head.
245pub fn bootstrap_head(editions: &[Edition], floor: u64) -> Option<usize> {
246    let mut best: Option<usize> = None;
247    for (i, e) in editions.iter().enumerate() {
248        if e.version < floor {
249            continue; // refuse-downgrade still applies
250        }
251        match best {
252            Some(b) => {
253                let cur = &editions[b];
254                // Higher version wins; at equal version, authority then the lower inner id (see `fold`).
255                let take = e.version > cur.version || (e.version == cur.version && e.wins_fork_over(cur));
256                if take {
257                    best = Some(i);
258                }
259            }
260            None => best = Some(i),
261        }
262    }
263    best
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn id(b: u8) -> [u8; 32] {
271        [b; 32]
272    }
273
274    #[test]
275    fn an_equal_version_fork_goes_to_authority_before_the_lower_id() {
276        let admin = Edition { version: 1, prev_hash: None, self_hash: id(0xAA), created_at: 1, tiebreak_id: id(0x01), rank: 5 };
277        let owner = Edition { version: 1, prev_hash: None, self_hash: id(0xBB), created_at: 1, tiebreak_id: id(0xF0), rank: 0 };
278        for eds in [[admin.clone(), owner.clone()], [owner.clone(), admin.clone()]] {
279            let head = eds[fold(&eds, 0, None).head.unwrap()].self_hash;
280            assert_eq!(head, id(0xBB), "the owner's edition wins despite the higher id");
281            assert_eq!(eds[bootstrap_head(&eds, 0).unwrap()].self_hash, id(0xBB));
282        }
283        // Peers fall back to the lower id.
284        let peer = Edition { rank: 5, tiebreak_id: id(0x00), self_hash: id(0xCC), ..admin.clone() };
285        let eds = [admin, peer];
286        assert_eq!(eds[fold(&eds, 0, None).head.unwrap()].self_hash, id(0xCC));
287    }
288
289    /// Golden vector — the frozen edition canonicalization must never drift (a change reshuffles
290    /// every chain link and forces a migration).
291    #[test]
292    fn the_streamed_hash_is_the_hash_of_the_signing_bytes() {
293        use sha2::Digest;
294        for prev in [None, Some([9u8; 32])] {
295            for len in [0usize, 1, 55, 64, 1000] {
296                let content: Vec<u8> = (0..len).map(|i| i as u8).collect();
297                let bytes = edition_signing_bytes(&[3; 32], 7, prev.as_ref(), &content);
298                let want: [u8; 32] = sha2::Sha256::digest(&bytes).into();
299                assert_eq!(edition_hash(&[3; 32], 7, prev.as_ref(), &content), want);
300                let signed: [u8; 32] = sha2::Sha256::new().chain_update(&bytes).chain_update(b"concord/edition-signer").chain_update([5u8; 32]).finalize().into();
301                assert_eq!(edition_hash_signed(&[3; 32], 7, prev.as_ref(), &content, &[5; 32]), signed);
302            }
303        }
304    }
305
306    #[test]
307    fn edition_hash_golden_vector() {
308        let h = edition_hash(&id(0x11), 1, None, b"hello");
309        assert_eq!(
310            crate::simd::hex::bytes_to_hex_32(&h),
311            "2daf42e65a6bc259a4c99fac6df754a5d3d92310607cf13e2a1e8c94d42f6303"
312        );
313    }
314
315    /// Distinct fields never collide (length-prefixing): same bytes split differently differ.
316    #[test]
317    fn edition_hash_is_field_unambiguous() {
318        // version vs content boundary can't be confused.
319        assert_ne!(
320            edition_hash(&id(1), 2, None, b"x"),
321            edition_hash(&id(1), 0, None, b"x"),
322        );
323        let with_prev = edition_hash(&id(1), 2, Some(&id(9)), b"x");
324        let without = edition_hash(&id(1), 2, None, b"x");
325        assert_ne!(with_prev, without, "prev presence changes the hash");
326    }
327
328    /// A linked v1→v2→v3 chain folds to v3 with no gap.
329    #[test]
330    fn contiguous_chain_folds_to_latest() {
331        let e1 = Edition { version: 1, prev_hash: None, self_hash: id(1), created_at: 100, tiebreak_id: id(0xa1), rank: 0 };
332        let e2 = Edition { version: 2, prev_hash: Some(id(1)), self_hash: id(2), created_at: 101, tiebreak_id: id(0xa2), rank: 0 };
333        let e3 = Edition { version: 3, prev_hash: Some(id(2)), self_hash: id(3), created_at: 102, tiebreak_id: id(0xa3), rank: 0 };
334        let r = fold(&[e1, e2, e3], 0, None);
335        assert_eq!(r, FoldResult { head: Some(2), gap: false, anchored: true });
336    }
337
338    #[test]
339    fn bootstrap_head_takes_highest_version_across_gaps() {
340        let ed = |v: u64| Edition {
341            version: v,
342            prev_hash: if v == 1 { None } else { Some(id(v as u8 - 1)) },
343            self_hash: id(v as u8),
344            created_at: 100 + v,
345            tiebreak_id: id(0xa0 + v as u8),
346            rank: 0,
347        };
348        // GroupRoot shape: 1,2,3,4,(no 5),6..11 — strict fold stops at v4; bootstrap takes v11.
349        let groot: Vec<Edition> = [1u64, 2, 3, 4, 6, 7, 8, 9, 10, 11].iter().map(|&v| ed(v)).collect();
350        assert_eq!(fold(&groot, 0, None).head.map(|i| groot[i].version), Some(4), "strict head stops at the gap");
351        assert!(fold(&groot, 0, None).gap);
352        assert_eq!(bootstrap_head(&groot, 0).map(|i| groot[i].version), Some(11), "bootstrap takes the latest across the gap");
353
354        // Grant shape: 2,3,4 with no v1 to anchor — strict can't anchor; bootstrap takes v4.
355        let grant: Vec<Edition> = [2u64, 3, 4].iter().map(|&v| ed(v)).collect();
356        assert!(fold(&grant, 0, None).gap, "no v1 → strict is unanchored");
357        assert_eq!(bootstrap_head(&grant, 0).map(|i| grant[i].version), Some(4));
358
359        // Refuse-downgrade still holds: nothing below the floor.
360        assert_eq!(bootstrap_head(&grant, 9), None, "all below floor → no head");
361
362        // Equal-version fork resolves to the deterministic tiebreak winner: lower inner id (a: 0xa1 < b: 0xb1).
363        let a = Edition { version: 5, prev_hash: None, self_hash: id(0xAA), created_at: 200, tiebreak_id: id(0xa1), rank: 0 };
364        let b = Edition { version: 5, prev_hash: None, self_hash: id(0xBB), created_at: 100, tiebreak_id: id(0xb1), rank: 0 };
365        assert_eq!(bootstrap_head(&[a, b], 0), Some(0), "lower inner id wins at equal version (not created_at)");
366    }
367
368    // A properly-linked edition: self_hash=id(v), prev=id(v-1) (genesis v1 has no prev).
369    fn linked(v: u64) -> Edition {
370        Edition {
371            version: v,
372            prev_hash: if v == 1 { None } else { Some(id((v - 1) as u8)) },
373            self_hash: id(v as u8),
374            created_at: 100 + v,
375            tiebreak_id: id(0xc0u8.wrapping_add(v as u8)),
376            rank: 0,
377        }
378    }
379
380    /// AGGREGATE LINEARITY — no single relay has the whole chain (relay A: v1,3,5; relay B: v2,4), but the
381    /// UNION computes the full contiguous chain → head v5, no gap. This is the property the whole
382    /// "bad-relay resilient" design rests on: gaps in any one source are filled by the others. `fold_roster`
383    /// inherits this since it folds the per-entity union.
384    #[test]
385    fn union_of_split_relays_folds_contiguously() {
386        let mut union = vec![linked(1), linked(3), linked(5)];
387        union.extend(vec![linked(2), linked(4)]);
388        let r = fold(&union, 0, None);
389        assert_eq!(r.head.map(|i| union[i].version), Some(5));
390        assert!(!r.gap, "the union is contiguous v1..v5 even though neither relay had it alone");
391    }
392
393    /// Arrival order is irrelevant — the fold is a pure function of the SET (so two clients merging the same
394    /// editions in different orders converge identically).
395    #[test]
396    fn fold_is_order_independent_under_scrambled_arrival() {
397        let scrambled = vec![linked(3), linked(1), linked(5), linked(2), linked(4)];
398        let r = fold(&scrambled, 0, None);
399        assert_eq!(r.head.map(|i| scrambled[i].version), Some(5));
400        assert!(!r.gap);
401    }
402
403    /// Multiple holes: strict stops at the FIRST gap (fail-closed prefix), bootstrap takes the highest.
404    #[test]
405    fn multiple_gaps_strict_stops_at_first_bootstrap_takes_highest() {
406        let eds = vec![linked(1), linked(2), linked(4), linked(6)]; // holes at v3 and v5
407        let r = fold(&eds, 0, None);
408        assert_eq!(r.head.map(|i| eds[i].version), Some(2), "strict stops at the first gap");
409        assert!(r.gap);
410        assert_eq!(bootstrap_head(&eds, 0).map(|i| eds[i].version), Some(6), "bootstrap takes the highest");
411    }
412
413    /// The RATCHET click: a gap leaves the head behind; when the missing version streams in from the union,
414    /// the chain advances. Convergence is monotonic and order-free.
415    #[test]
416    fn ratchet_advances_when_the_missing_version_arrives() {
417        let before = vec![linked(1), linked(3)]; // v2 missing
418        let r1 = fold(&before, 0, None);
419        assert_eq!(r1.head.map(|i| before[i].version), Some(1));
420        assert!(r1.gap, "v3 can't link without v2");
421        let after = vec![linked(1), linked(2), linked(3)]; // v2 arrives
422        let r2 = fold(&after, 0, None);
423        assert_eq!(r2.head.map(|i| after[i].version), Some(3));
424        assert!(!r2.gap, "the gap filled → ratchets to v3");
425    }
426
427    /// Duplicate editions (a relay echo, or the same edition from two relays) don't double-count or break
428    /// the chain — dedup by version, fold proceeds cleanly.
429    #[test]
430    fn duplicate_editions_do_not_break_the_fold() {
431        let eds = vec![linked(1), linked(2), linked(2), linked(3)];
432        let r = fold(&eds, 0, None);
433        assert_eq!(r.head.map(|i| eds[i].version), Some(3));
434        assert!(!r.gap);
435    }
436
437    /// A forged MIDDLE edition (wrong prev) must not let a later "linked" edition advance the head —
438    /// the walk breaks at the bad link and the head stays at the last contiguous version.
439    #[test]
440    fn forged_middle_edition_does_not_advance_the_head() {
441        let e1 = linked(1);
442        let e2_bad = Edition { version: 2, prev_hash: Some(id(0xFF)), self_hash: id(2), created_at: 102, tiebreak_id: id(0xc2), rank: 0 };
443        let e3 = linked(3); // links to id(2) — but v2's link to v1 is forged
444        let r = fold(&[e1, e2_bad, e3], 0, None);
445        assert_eq!(r.head.map(|i| [1u64, 2, 3][i]), Some(1), "head stays at v1 — the v1→v2 link is broken");
446        assert!(r.gap, "a forged middle edition is a gap, not a silent advance");
447    }
448
449    /// A held floor whose hash we've lost (`floor_hash = None`) must FAIL CLOSED at floor+1, not blindly
450    /// anchor — without the hash we can't prove the incoming edition links to what we hold.
451    #[test]
452    fn floor_plus_one_without_a_floor_hash_is_a_gap() {
453        let e6 = Edition { version: 6, prev_hash: Some(id(5)), self_hash: id(6), created_at: 600, tiebreak_id: id(0xa6), rank: 0 };
454        assert!(fold(&[e6], 5, None).gap, "floor+1 with no floor_hash can't be anchored → gap (fail closed)");
455    }
456
457    /// A relay serving ONLY stale editions (all below floor) yields "no change" — `head: None, gap: false`
458    /// — distinct from a gap. The caller keeps its floor; it neither quarantines nor re-authorizes.
459    #[test]
460    fn all_below_floor_is_no_change_not_a_gap() {
461        let r = fold(&[linked(1), linked(2)], 5, Some(&id(5)));
462        assert_eq!(r, FoldResult { head: None, gap: false, anchored: false }, "everything below floor → no candidate, no gap");
463    }
464
465    // ===== Weird / absurd / malformed input — fold must degrade gracefully, NEVER panic =====
466
467    #[test]
468    fn fold_version_zero_does_not_panic() {
469        // v0 is invalid (chains start at v1) but a relay could serve one. Unanchored → gap, no panic.
470        let e0 = Edition { version: 0, prev_hash: None, self_hash: id(0), created_at: 1, tiebreak_id: id(0xe0), rank: 0 };
471        assert!(fold(&[e0], 0, None).gap, "a v0 'genesis' is not a valid anchor → gap, no panic");
472    }
473
474    #[test]
475    fn fold_genesis_with_a_spurious_prev_is_unanchored() {
476        // A v1 carrying a prev_hash (a real genesis has none) is a forged "genesis" → unanchored.
477        let e1 = Edition { version: 1, prev_hash: Some(id(0xFF)), self_hash: id(1), created_at: 100, tiebreak_id: id(0xa1), rank: 0 };
478        assert!(fold(&[e1], 0, None).gap, "v1 with a prev is not a real genesis → gap");
479    }
480
481    #[test]
482    fn fold_near_u64_max_version_does_not_panic() {
483        // A relay serves a wildly high version. fold uses it as a key; the +1 increment lives in the
484        // producer, not here, so no overflow. Must not panic from any floor.
485        let big = Edition { version: u64::MAX, prev_hash: None, self_hash: id(9), created_at: 1, tiebreak_id: id(0xff), rank: 0 };
486        assert!(fold(&[big.clone()], 0, None).gap, "u64::MAX is not a genesis → gap, no overflow");
487        let r = fold(&[big], u64::MAX, Some(&id(9)));
488        assert!(!r.gap, "re-presenting the held u64::MAX floor is anchored, no overflow in the walk");
489    }
490
491    #[test]
492    fn fold_a_million_version_gap_holds_at_the_prefix() {
493        let far = Edition { version: 1_000_000, prev_hash: Some(id(2)), self_hash: id(0x77), created_at: 200, tiebreak_id: id(0xb7), rank: 0 };
494        let r = fold(&[linked(1), far], 0, None);
495        assert_eq!(r.head.map(|i| [1u64, 1_000_000][i]), Some(1), "head stays at the genesis prefix");
496        assert!(r.gap, "a million-version jump is a gap, not a silent advance");
497    }
498
499    #[test]
500    fn fold_mass_identical_duplicates_collapse() {
501        let e = linked(1);
502        let r = fold(&[e.clone(), e.clone(), e.clone(), e], 0, None);
503        assert_eq!(r.head, Some(0));
504        assert!(!r.gap, "N identical genesis copies collapse to one, no gap");
505    }
506
507    #[test]
508    fn fold_a_large_noisy_scrambled_input_does_not_panic() {
509        // A contiguous v1..v50 chain buried in duplicates and reversed arrival order.
510        let mut eds: Vec<Edition> = (1..=50).map(linked).collect();
511        eds.extend((1..=50).map(linked)); // every edition twice
512        eds.reverse();
513        let r = fold(&eds, 0, None);
514        assert_eq!(r.head.map(|i| eds[i].version), Some(50), "folds to v50 through all the noise");
515        assert!(!r.gap);
516    }
517
518    #[test]
519    fn bootstrap_head_on_pathological_inputs() {
520        assert_eq!(bootstrap_head(&[], 0), None, "empty → None");
521        assert_eq!(bootstrap_head(&[linked(1), linked(2)], 999), None, "all below floor → None");
522        let v0 = Edition { version: 0, prev_hash: None, self_hash: id(0), created_at: 1, tiebreak_id: id(0xe0), rank: 0 };
523        assert!(bootstrap_head(&[v0], 0).is_some(), "a v0 edition still surfaces (≥ floor 0), no panic");
524    }
525
526    #[test]
527    fn unanchored_head_is_flagged_as_gap() {
528        // A hostile relay serves only v5 with a forged prev_hash, withholding v1..v4. The head is
529        // returned but MUST be flagged gap=true — it isn't anchored to genesis, so a tracking client
530        // fails closed instead of installing a possibly forged/rolled-back edition.
531        let e5 = Edition { version: 5, prev_hash: Some(id(0xFF)), self_hash: id(5), created_at: 500, tiebreak_id: id(0xa5), rank: 0 };
532        assert!(fold(&[e5], 0, None).gap, "a lone non-genesis edition is unanchored → gap");
533
534        // With the held floor + its hash, a genuine v6 linking to v5 IS anchored (no gap).
535        let floor_hash = id(0x55);
536        let e6 = Edition { version: 6, prev_hash: Some(floor_hash), self_hash: id(6), created_at: 600, tiebreak_id: id(0xa6), rank: 0 };
537        let r = fold(&[e6], 5, Some(&floor_hash));
538        assert_eq!(r, FoldResult { head: Some(0), gap: false, anchored: true }, "v6 linking to the held v5 hash is anchored");
539
540        // A v6 whose prev_hash does NOT match the held floor is unanchored → gap.
541        let e6_bad = Edition { version: 6, prev_hash: Some(id(0xAB)), self_hash: id(6), created_at: 600, tiebreak_id: id(0xa6), rank: 0 };
542        assert!(fold(&[e6_bad], 5, Some(&floor_hash)).gap, "v6 not linking to the floor is a gap");
543    }
544
545    /// At the FLOOR version, a re-presented edition must be the exact one we hold.
546    /// A relay that withholds our floor edition A and serves a DIFFERENT same-version fork B must be
547    /// rejected (gap → fail closed) so it can't silently swap our committed head. The genuine re-anchor
548    /// case (same inner edition → identical self_hash) still anchors cleanly.
549    #[test]
550    fn tracking_rejects_a_forked_floor_edition() {
551        let a_hash = id(0xAA);
552        // Re-presenting OUR floor edition (same self_hash) → anchored, no gap (the legit re-anchor path).
553        let a = Edition { version: 5, prev_hash: Some(id(4)), self_hash: a_hash, created_at: 500, tiebreak_id: id(0xa5), rank: 0 };
554        assert!(!fold(&[a], 5, Some(&a_hash)).gap, "re-presenting our own floor edition is anchored");
555        // A DIFFERENT edition at the floor version (a withheld-original fork) → gap, fail closed.
556        let b = Edition { version: 5, prev_hash: Some(id(4)), self_hash: id(0xBB), created_at: 600, tiebreak_id: id(0xb5), rank: 0 };
557        assert!(fold(&[b], 5, Some(&a_hash)).gap, "a different same-version edition is a fork → rejected, not anchored");
558    }
559
560    /// Refuse-downgrade: an edition below the floor is ignored entirely.
561    #[test]
562    fn refuses_to_downgrade_below_floor() {
563        let e1 = Edition { version: 1, prev_hash: None, self_hash: id(1), created_at: 100, tiebreak_id: id(0xa1), rank: 0 };
564        let e2 = Edition { version: 2, prev_hash: Some(id(1)), self_hash: id(2), created_at: 101, tiebreak_id: id(0xa2), rank: 0 };
565        // Floor already at 2 (we hold v2 = self_hash id(2)) → only v2 is a candidate; v1 is a downgrade and
566        // dropped. Pass the held floor hash, as production does — the ==floor anchor now verifies it.
567        let r = fold(&[e1, e2], 2, Some(&id(2)));
568        assert_eq!(r.head, Some(1));
569        assert!(!r.gap);
570    }
571
572    /// Equal-version fork resolves to the deterministic tiebreak winner (lower created_at, then id),
573    /// not to arrival order — so every client converges on the same head.
574    #[test]
575    fn equal_version_fork_resolves_by_lower_inner_id_not_created_at() {
576        // Two distinct v1 editions. Winner = lower inner edition id; `created_at` is IGNORED, so an author
577        // can't set created_at=0 to force a win. `a` has the LATER created_at but the LOWER id → `a` wins,
578        // proving created_at is not the lever (the anti-gaming fix).
579        let a = Edition { version: 1, prev_hash: None, self_hash: id(0xAA), created_at: 999, tiebreak_id: id(0x01), rank: 0 };
580        let b = Edition { version: 1, prev_hash: None, self_hash: id(0xBB), created_at: 0, tiebreak_id: id(0x02), rank: 0 };
581        assert_eq!(fold(&[a.clone(), b.clone()], 0, None).head, Some(0), "lower id wins even though `a` has the later created_at");
582        assert_eq!(fold(&[b, a], 0, None).head, Some(1), "and it's independent of arrival order");
583    }
584
585    /// A missing or mismatched predecessor is a gap: the head stays at the highest CONTIGUOUS version
586    /// and `gap` flags the break (caller fails closed + refetches).
587    #[test]
588    fn detects_a_gap_in_the_chain() {
589        let e1 = Edition { version: 1, prev_hash: None, self_hash: id(1), created_at: 100, tiebreak_id: id(0xa1), rank: 0 };
590        // v3 present but v2 missing → not contiguous from v1.
591        let e3 = Edition { version: 3, prev_hash: Some(id(2)), self_hash: id(3), created_at: 102, tiebreak_id: id(0xa3), rank: 0 };
592        let r = fold(&[e1.clone(), e3], 0, None);
593        assert_eq!(r.head, Some(0), "head stays at the highest contiguous version (v1)");
594        assert!(r.gap, "the v2 gap is reported");
595
596        // Present-but-wrong prev_hash is also a gap (a forked/forged link).
597        let e2_bad = Edition { version: 2, prev_hash: Some(id(0xFF)), self_hash: id(2), created_at: 101, tiebreak_id: id(0xa2), rank: 0 };
598        let r2 = fold(&[e1.clone(), e2_bad], 0, None);
599        assert_eq!(r2.head, Some(0));
600        assert!(r2.gap, "a wrong prev_hash link does not advance the head");
601    }
602
603    /// The CORD-04 §1 test vector: a plain and a marked edition over the same bytes.
604    #[test]
605    fn edition_hashes_match_the_spec_vectors() {
606        let (entity, prev, signer) = ([0x11u8; 32], [0x22u8; 32], [0x33u8; 32]);
607        let content = br#"{"name":"Mods"}"#;
608        let hex = |h: [u8; 32]| crate::simd::hex::bytes_to_hex_32(&h);
609        assert_eq!(hex(edition_hash(&entity, 2, Some(&prev), content)), "3c1d4111bff28cea4c1f237dcce34efbc227db6e304cdd1146e1413657972475");
610        assert_eq!(hex(edition_hash_signed(&entity, 2, Some(&prev), content, &signer)), "462cc81a6f74622e5ff660ab3efcc007527c8d108e8242942f7ba7787a27d0ed");
611    }
612}