1use crate::crypto::sha256::Sha256;
17
18const EDITION_LABEL: &[u8] = b"vector-community/v1/edition";
20
21pub 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
53pub 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
69pub 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
80fn 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#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct Edition {
106 pub version: u64,
107 pub prev_hash: Option<[u8; 32]>,
108 pub self_hash: [u8; 32],
110 pub created_at: u64,
112 pub tiebreak_id: [u8; 32],
114 pub rank: u32,
117}
118
119impl Edition {
120 pub fn wins_fork_over(&self, other: &Edition) -> bool {
123 (self.rank, self.tiebreak_id) < (other.rank, other.tiebreak_id)
124 }
125}
126
127#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct FoldResult {
130 pub head: Option<usize>,
132 pub gap: bool,
135 pub anchored: bool,
140}
141
142pub fn fold(editions: &[Edition], floor: u64, floor_hash: Option<&[u8; 32]>) -> FoldResult {
158 fold_with_rivals(editions, floor, floor_hash, &|_| false)
159}
160
161pub 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
174pub 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 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 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 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 return FoldResult { head: None, gap: present.iter().any(|&i| eligible(i)), anchored: false };
231 };
232 let gap = present.iter().any(|&i| eligible(i) && editions[i].version > editions[head].version);
234 FoldResult { head: Some(head), gap, anchored: true }
235}
236
237pub 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; }
251 match best {
252 Some(b) => {
253 let cur = &editions[b];
254 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 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 #[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 #[test]
317 fn edition_hash_is_field_unambiguous() {
318 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 #[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 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 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 assert_eq!(bootstrap_head(&grant, 9), None, "all below floor → no head");
361
362 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 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 #[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 #[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 #[test]
405 fn multiple_gaps_strict_stops_at_first_bootstrap_takes_highest() {
406 let eds = vec![linked(1), linked(2), linked(4), linked(6)]; 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 #[test]
416 fn ratchet_advances_when_the_missing_version_arrives() {
417 let before = vec![linked(1), linked(3)]; 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)]; 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 #[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 #[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); 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 #[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 #[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 #[test]
468 fn fold_version_zero_does_not_panic() {
469 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 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 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 let mut eds: Vec<Edition> = (1..=50).map(linked).collect();
511 eds.extend((1..=50).map(linked)); 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 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 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 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 #[test]
550 fn tracking_rejects_a_forked_floor_edition() {
551 let a_hash = id(0xAA);
552 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 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 #[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 let r = fold(&[e1, e2], 2, Some(&id(2)));
568 assert_eq!(r.head, Some(1));
569 assert!(!r.gap);
570 }
571
572 #[test]
575 fn equal_version_fork_resolves_by_lower_inner_id_not_created_at() {
576 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 #[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 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 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 #[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}