//! Catching up by ranges (`docs/document.md`, What others do): two nodes that each hold //! a set of names find what the other holds and they don't, knowing nothing of each //! other before, and keeping nothing of each other after. //! //! The names are in one order. A node sends the fingerprint of a range; where the //! other's fingerprint of that range is the same, the range is done; where not, it //! answers with the fingerprints of the range's parts, or with its names there where //! they are few. A message is parts in order, each from where the one before ended, so //! that a node answers one by reading it once: it needs no state between messages, and //! what it holds may change between them. //! //! Names only: what a name stands for, an event or a write, its kind fetches once it //! knows it lacks it. //! //! A fingerprint is the names added up as numbers modulo 2^256, with how many they are, //! hashed: sums combine, so a range's comes from its parts'. A node keeps its names //! (`Names`) in runs, each with its sum, so that a range's fingerprint costs its ends //! and a sum per run between, not its names. Someone who chooses names can make two //! sets collide with about a day of work: a node splits a range where a number of its //! own says (`answer`'s `salt`), so that nobody knows beforehand which ranges it //! compares; and a kind whose names anyone mints has another way to tell that two //! nodes hold the same, and falls back on it. // Used by the kinds to come, behind `federation` so far. #![allow(dead_code)] use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// What is reconciled: 32 bytes, in the order of their bytes. pub(crate) type Name = [u8; 32]; /// Into how many parts a range is split where fingerprints differ. const PARTS: usize = 16; /// A range holding no more names than this is answered with the names themselves. const FEW: usize = 2 * PARTS; /// The most names of a run; one that would hold more is split in two. const RUN: usize = 512; /// What stands for the names of a range: the same for the same names, and, but for /// names made to collide, for no others. #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] pub(crate) struct Fingerprint(pub(crate) [u8; 16]); /// Names added up, and how many. #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] struct Sum { sum: [u8; 32], count: u64, } impl Sum { fn add(&mut self, name: &Name) { self.join(&Sum { sum: *name, count: 1, }); } /// Adds what `other` adds up. fn join(&mut self, other: &Sum) { let mut carry = 0u16; for (digit, other) in self.sum.iter_mut().zip(&other.sum) { let total = u16::from(*digit) + u16::from(*other) + carry; *digit = total as u8; carry = total >> 8; } self.count += other.count; } fn of<'a>(names: impl IntoIterator) -> Self { let mut sum = Sum::default(); for name in names { sum.add(name); } sum } fn fingerprint(&self) -> Fingerprint { let mut hasher = Sha256::new(); hasher.update(self.sum); hasher.update(self.count.to_le_bytes()); let hash = hasher.finalize(); let mut out = [0; 16]; out.copy_from_slice(&hash[..16]); Fingerprint(out) } } /// The fingerprint of `names`. pub(crate) fn fingerprint<'a>(names: impl IntoIterator) -> Fingerprint { Sum::of(names).fingerprint() } /// Names in order, in runs of no more than `RUN`, each with what it adds up to. #[derive(Clone, Default, Debug)] pub(crate) struct Names { runs: Vec, all: Sum, } #[derive(Clone, Debug)] struct Run { names: Vec, sum: Sum, } impl Names { pub(crate) fn new() -> Self { Self::default() } pub(crate) fn len(&self) -> usize { self.all.count as usize } pub(crate) fn is_empty(&self) -> bool { self.all.count == 0 } /// The fingerprint of them all. pub(crate) fn fingerprint(&self) -> Fingerprint { self.all.fingerprint() } /// The run `name` is in, or would be: the last that begins no later than it. fn run_of(&self, name: &Name) -> usize { self.runs .partition_point(|run| run.names[0] <= *name) .saturating_sub(1) } pub(crate) fn contains(&self, name: &Name) -> bool { !self.runs.is_empty() && self.runs[self.run_of(name)] .names .binary_search(name) .is_ok() } /// Adds `name`; whether it wasn't there. pub(crate) fn insert(&mut self, name: Name) -> bool { if self.runs.is_empty() { self.runs.push(Run { names: vec![name], sum: Sum::of([&name]), }); self.all.add(&name); return true; } let at = self.run_of(&name); let run = &mut self.runs[at]; let Err(place) = run.names.binary_search(&name) else { return false; }; run.names.insert(place, name); run.sum.add(&name); self.all.add(&name); if run.names.len() > RUN { let upper = run.names.split_off(RUN / 2); run.sum = Sum::of(&run.names); let sum = Sum::of(&upper); self.runs.insert(at + 1, Run { names: upper, sum }); } true } /// Takes `name` out; whether it was there. pub(crate) fn remove(&mut self, name: &Name) -> bool { if self.runs.is_empty() { return false; } let at = self.run_of(name); let run = &mut self.runs[at]; let Ok(place) = run.names.binary_search(name) else { return false; }; run.names.remove(place); if run.names.is_empty() { self.runs.remove(at); } else { run.sum = Sum::of(&run.names); } // What is left adds up to the runs' sums: taking a name out of a sum would need // subtraction, and a sum of sums is as cheap. self.all = Sum::default(); for run in &self.runs { self.all.join(&run.sum); } true } /// The names in order. pub(crate) fn iter(&self) -> impl Iterator { self.runs.iter().flat_map(|run| run.names.iter()) } /// How many names come before `upper`: all, where it is after every name. fn rank(&self, upper: &Upper) -> usize { let Some(upper) = upper else { return self.len(); }; let mut before = 0; for run in &self.runs { if run.names[run.names.len() - 1] < *upper { before += run.names.len(); } else { return before + run.names.partition_point(|name| name < upper); } } before } /// What the names from the `from`th up to the `to`th add up to. fn sum(&self, from: usize, to: usize) -> Sum { let mut sum = Sum::default(); let mut at = 0; for run in &self.runs { let end = at + run.names.len(); if end > from && at < to { if at >= from && end <= to { sum.join(&run.sum); } else { let low = from.saturating_sub(at); let high = run.names.len().min(to - at); sum.join(&Sum::of(&run.names[low..high])); } } if end >= to { break; } at = end; } sum } /// The names from the `from`th up to the `to`th. fn between(&self, from: usize, to: usize) -> Vec { let mut out = Vec::with_capacity(to.saturating_sub(from)); let mut at = 0; for run in &self.runs { let end = at + run.names.len(); if end > from && at < to { let low = from.saturating_sub(at); let high = run.names.len().min(to - at); out.extend_from_slice(&run.names[low..high]); } if end >= to { break; } at = end; } out } /// The `at`th name. fn at(&self, at: usize) -> Name { let mut before = 0; for run in &self.runs { if at < before + run.names.len() { return run.names[at - before]; } before += run.names.len(); } panic!("no {at}th name among {}", self.len()); } } impl FromIterator for Names { fn from_iter>(names: T) -> Self { let mut out = Names::new(); for name in names { out.insert(name); } out } } /// Where a part ends: before this name, or after every name. pub(crate) type Upper = Option; /// What a message says of one range, which begins where the part before ended (the /// first, before every name) and ends at `upper`. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub(crate) enum Part { /// Nothing to say of it: it is done, or left for another message. Skip { upper: Upper }, /// The fingerprint of the sender's names in it. Fingerprint { upper: Upper, fingerprint: Fingerprint, }, /// Names of the sender's in it: all of them, where `asking`, and the receiver says /// what it holds beside them; else those the receiver said it lacks. Names { upper: Upper, names: Vec, asking: bool, }, } impl Part { fn upper(&self) -> Upper { match self { Part::Skip { upper } | Part::Fingerprint { upper, .. } | Part::Names { upper, .. } => { *upper } } } } /// Parts in order, the last ending after every name. #[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)] pub(crate) struct Message(pub(crate) Vec); /// What a node makes of a message. #[derive(Debug, Default)] pub(crate) struct Answer { /// What to send back; nothing, where every range is done. pub(crate) reply: Option, /// Names the sender holds and this node doesn't, as far as the message says. pub(crate) lacking: Vec, } /// The message that begins: this node's fingerprint of everything. pub(crate) fn open(held: &Names) -> Message { Message(vec![Part::Fingerprint { upper: None, fingerprint: held.fingerprint(), }]) } /// What is being answered with. struct Reply<'a> { held: &'a Names, parts: Vec, /// How many names it holds so far, and the most it may (0: any number). sent: usize, most: usize, salt: u64, } /// Answers `message` by what this node holds, sending no more than `most` names (0: any /// number): ranges it would exceed that with are sent as their fingerprints, for the /// peer to ask again. Where it splits a range, `salt` says where: a number of the /// node's own, another each time. pub(crate) fn answer(held: &Names, message: &Message, most: usize, salt: u64) -> Answer { let mut out = Answer::default(); let mut reply = Reply { held, parts: Vec::new(), sent: 0, most, salt, }; // Each part from where the one before ended; one ending before that holds nothing. let mut from = 0; for part in &message.0 { let upper = part.upper(); let to = held.rank(&upper).max(from); match part { Part::Skip { .. } => reply.parts.push(Part::Skip { upper }), Part::Fingerprint { fingerprint: theirs, .. } => { if held.sum(from, to).fingerprint() == *theirs { reply.parts.push(Part::Skip { upper }); } else if *theirs == fingerprint([]) { // The peer holds nothing here: all of ours is what it lacks. reply.send(upper, held.between(from, to), false); } else if to - from <= FEW { reply.send(upper, held.between(from, to), true); } else { reply.split(upper, from, to); } } Part::Names { names, asking, .. } => { out.lacking .extend(names.iter().filter(|name| !held.contains(name))); if *asking { let theirs: std::collections::BTreeSet<&Name> = names.iter().collect(); let beside: Vec = held .between(from, to) .into_iter() .filter(|name| !theirs.contains(name)) .collect(); if beside.is_empty() { reply.parts.push(Part::Skip { upper }); } else { reply.send(upper, beside, false); } } else { reply.parts.push(Part::Skip { upper }); } } } from = to; if upper.is_none() { break; } } if reply .parts .iter() .any(|part| !matches!(part, Part::Skip { .. })) { out.reply = Some(Message(merged(reply.parts))); } out } impl Reply<'_> { /// Adds `names` as a part ending at `upper`, or their fingerprint where that would /// be more than `most` names in one message. fn send(&mut self, upper: Upper, names: Vec, asking: bool) { let most = self.most; if most != 0 && self.sent + names.len() > most && self.sent > 0 { self.parts.push(Part::Fingerprint { upper, fingerprint: fingerprint(&names), }); return; } if most != 0 && names.len() > most { // More than one message takes by itself: its first names, and the rest as // a fingerprint, which the peer asks about again. let (now, later) = names.split_at(most); self.sent += now.len(); self.parts.push(Part::Names { upper: Some(later[0]), names: now.to_vec(), asking, }); self.parts.push(Part::Fingerprint { upper, fingerprint: fingerprint(later), }); return; } self.sent += names.len(); self.parts.push(Part::Names { upper, names, asking, }); } /// Adds the names from the `from`th up to the `to`th, a range ending at `upper`, in /// `PARTS` parts of about as many names each, the first shorter by what `salt` /// says: the names of a part where they are few, else its fingerprint. fn split(&mut self, upper: Upper, from: usize, to: usize) { let size = (to - from).div_ceil(PARTS); let mut start = from; let mut end = from + 1 + (self.salt % size as u64) as usize; while start < to { let end_here = end.min(to); let ends = if end_here == to { upper } else { Some(self.held.at(end_here)) }; if end_here - start <= FEW / PARTS { let names = self.held.between(start, end_here); self.send(ends, names, true); } else { self.parts.push(Part::Fingerprint { upper: ends, fingerprint: self.held.sum(start, end_here).fingerprint(), }); } start = end_here; end = start + size; } } } /// `parts` with runs of skipped ranges as one. fn merged(parts: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(parts.len()); for part in parts { match (out.last_mut(), &part) { (Some(Part::Skip { upper: last }), Part::Skip { upper }) => *last = *upper, _ => out.push(part), } } out } #[cfg(test)] mod tests { use super::*; use std::cell::Cell; use std::collections::BTreeSet; use crate::testrand::{Rng, for_seeds}; fn of(names: &BTreeSet) -> Names { names.iter().copied().collect() } thread_local! { static SALT: Cell = const { Cell::new(0) }; } /// Another number each time. fn salt() -> u64 { SALT.with(|salt| { salt.set( salt.get() .wrapping_mul(6364136223846793005) .wrapping_add(1442695040888963407), ); salt.get() >> 33 }) } /// Two nodes reconciling until neither has more to say: what each learned it /// lacks, and how many messages went. fn reconcile( a: &BTreeSet, b: &BTreeSet, most: usize, ) -> (BTreeSet, BTreeSet, usize) { let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); let mut message = open(&of(a)); let mut messages = 1; // Whose turn it is to answer: b's first. let mut b_answers = true; loop { let (held, lacks) = if b_answers { (b, &mut b_lacks) } else { (a, &mut a_lacks) }; let answer = answer(&of(held), &message, most, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { return (a_lacks, b_lacks, messages); }; message = reply; messages += 1; b_answers = !b_answers; assert!(messages < 10_000, "reconciling doesn't end"); } } fn names(rng: &mut Rng, count: usize) -> BTreeSet { (0..count).map(|_| rng.bytes32()).collect() } /// Between `min` and `max` names. fn some(rng: &mut Rng, min: usize, max: usize) -> BTreeSet { let count = rng.between(min, max); names(rng, count) } fn differences(a: &BTreeSet, b: &BTreeSet) -> (BTreeSet, BTreeSet) { ( b.difference(a).copied().collect(), a.difference(b).copied().collect(), ) } #[test] fn a_fingerprint_is_of_the_names_whatever_their_order() { let mut rng = Rng::new(1); let mut some: Vec = (0..100).map(|_| rng.bytes32()).collect(); let before = fingerprint(&some); rng.shuffle(&mut some); assert_eq!(fingerprint(&some), before); some.pop(); assert_ne!(fingerprint(&some), before); } #[test] fn a_fingerprint_counts_the_names() { // Names adding up to nothing, as 2^256 does, are not no names. let mut one = [0; 32]; one[0] = 1; let rest = [0xff; 32]; assert_ne!(fingerprint([&one, &rest]), fingerprint([])); } #[test] fn a_sum_carries() { let mut low = [0; 32]; low[0] = 0xff; let mut one = [0; 32]; one[0] = 1; let mut carried = [0; 32]; carried[1] = 1; let mut sum = Sum::default(); sum.add(&low); sum.add(&one); assert_eq!(sum.sum, carried); } #[test] fn the_same_sets_are_done_in_one_message() { let mut rng = Rng::new(2); let held = names(&mut rng, 5000); let (a_lacks, b_lacks, messages) = reconcile(&held, &held, 0); assert!(a_lacks.is_empty() && b_lacks.is_empty()); assert_eq!(messages, 1); } #[test] fn each_learns_what_it_lacks() { for_seeds(200, |rng| { let shared = some(rng, 0, 3000); let mut a = shared.clone(); let mut b = shared; let only_a = rng.between(0, 40); let only_b = rng.between(0, 40); a.extend(names(rng, only_a)); b.extend(names(rng, only_b)); let (a_lacks, b_lacks, _) = reconcile(&a, &b, 0); let (expect_a, expect_b) = differences(&a, &b); assert_eq!(a_lacks, expect_a); assert_eq!(b_lacks, expect_b); }); } #[test] fn one_with_nothing_learns_all() { let mut rng = Rng::new(3); let held = names(&mut rng, 2000); let nothing = BTreeSet::new(); let (a_lacks, b_lacks, _) = reconcile(¬hing, &held, 0); assert_eq!(a_lacks, held); assert!(b_lacks.is_empty()); let (a_lacks, b_lacks, _) = reconcile(&held, ¬hing, 0); assert!(a_lacks.is_empty()); assert_eq!(b_lacks, held); } #[test] fn the_messages_are_few() { // One name apart among many: the longest way down. let mut rng = Rng::new(4); let a = names(&mut rng, 100_000); let mut b = a.clone(); b.insert(rng.bytes32()); let (a_lacks, b_lacks, messages) = reconcile(&a, &b, 0); assert_eq!(a_lacks.len(), 1); assert!(b_lacks.is_empty()); // 16 parts a step: 100 000 names are few within four steps. assert!(messages <= 6, "{messages} messages"); } #[test] fn a_message_holds_no_more_names_than_asked() { for_seeds(50, |rng| { let shared = some(rng, 0, 500); let mut a = shared.clone(); let mut b = shared; a.extend(some(rng, 0, 300)); b.extend(some(rng, 0, 300)); let most = rng.between(1, 50); let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); let mut message = open(&of(&a)); let mut b_answers = true; for _ in 0..10_000 { let (held, lacks) = if b_answers { (&b, &mut b_lacks) } else { (&a, &mut a_lacks) }; let answer = answer(&of(held), &message, most, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { let (expect_a, expect_b) = differences(&a, &b); assert_eq!(a_lacks, expect_a); assert_eq!(b_lacks, expect_b); return; }; let sent: usize = reply .0 .iter() .map(|part| match part { Part::Names { names, .. } => names.len(), _ => 0, }) .sum(); assert!(sent <= most, "{sent} names, {most} asked"); message = reply; b_answers = !b_answers; } panic!("reconciling doesn't end"); }); } #[test] fn what_a_node_holds_may_change_between_messages() { // Names added on either side while they reconcile are found or left for the // next time, and nothing else is missed. for_seeds(50, |rng| { let mut a = some(rng, 100, 2000); let mut b = a.clone(); a.extend(names(rng, 20)); b.extend(names(rng, 20)); let (before_a, before_b) = (a.clone(), b.clone()); let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); let mut message = open(&of(&a)); let mut b_answers = true; for _ in 0..10_000 { if rng.chance(0.5) { a.insert(rng.bytes32()); } if rng.chance(0.5) { b.insert(rng.bytes32()); } let (held, lacks) = if b_answers { (&b, &mut b_lacks) } else { (&a, &mut a_lacks) }; let answer = answer(&of(held), &message, 0, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { let (expect_a, expect_b) = differences(&before_a, &before_b); assert!(a_lacks.is_superset(&expect_a)); assert!(b_lacks.is_superset(&expect_b)); // And nothing a node learned it lacks is something it held then. assert!(a_lacks.is_disjoint(&before_a)); assert!(b_lacks.is_disjoint(&before_b)); return; }; message = reply; b_answers = !b_answers; } panic!("reconciling doesn't end"); }); } #[test] fn a_message_out_of_order_is_answered() { // Parts whose ends go back, or go on after the end, as a peer may send them. let mut rng = Rng::new(5); let held = names(&mut rng, 100); let high = [0xf0; 32]; let low = [0x10; 32]; let message = Message(vec![ Part::Fingerprint { upper: Some(high), fingerprint: Fingerprint([1; 16]), }, Part::Fingerprint { upper: Some(low), fingerprint: Fingerprint([2; 16]), }, Part::Names { upper: None, names: vec![[7; 32]], asking: true, }, Part::Fingerprint { upper: None, fingerprint: Fingerprint([3; 16]), }, ]); let answer = answer(&of(&held), &message, 0, 7); assert_eq!(answer.lacking, vec![[7; 32]]); assert!(answer.reply.is_some()); } #[test] fn names_kept_in_runs_are_the_names_put_and_taken() { for_seeds(40, |rng| { let mut kept = Names::new(); let mut plain = BTreeSet::new(); let mut pool: Vec = (0..rng.between(1, 3000)).map(|_| rng.bytes32()).collect(); pool.push([0; 32]); pool.push([0xff; 32]); for _ in 0..rng.between(0, 6000) { let name = *rng.pick(&pool); if rng.chance(0.7) { assert_eq!(kept.insert(name), plain.insert(name)); } else { assert_eq!(kept.remove(&name), plain.remove(&name)); } } assert_eq!(kept.len(), plain.len()); assert_eq!(kept.is_empty(), plain.is_empty()); assert!(kept.iter().eq(plain.iter())); assert_eq!(kept.fingerprint(), fingerprint(&plain)); assert!( kept.runs .iter() .all(|run| !run.names.is_empty() && run.names.len() <= RUN) ); for name in pool.iter().take(50) { assert_eq!(kept.contains(name), plain.contains(name)); } // Ranges by rank: what they add up to, hold, and where a name comes. let all: Vec = plain.iter().copied().collect(); for _ in 0..20 { let from = rng.between(0, all.len()); let to = rng.between(from, all.len()); assert_eq!(kept.sum(from, to), Sum::of(&all[from..to])); assert_eq!(kept.between(from, to), all[from..to]); if from < all.len() { assert_eq!(kept.at(from), all[from]); assert_eq!(kept.rank(&Some(all[from])), from); } let bound = rng.bytes32(); assert_eq!( kept.rank(&Some(bound)), all.iter().filter(|name| **name < bound).count() ); } assert_eq!(kept.rank(&None), all.len()); }); } }