aboutsummaryrefslogtreecommitdiffstats
path: root/src/document/ranges.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 06:54:42 +0000
committertv <tv@krebsco.de>2026-11-29 06:54:42 +0000
commitd7e3a6e4d2ce26dc4abb1be2e3417eb5415257a3 (patch)
tree3ab3e937b000bc334ce328a31ced37099ade19e4 /src/document/ranges.rs
parent81b528be7101635cac2270cc758ce9eea60baa76 (diff)
document: catching up by ranges of names and their fingerprints
Two nodes that each hold a set of names find what the other holds and they don't (document::ranges): a range's fingerprint, the same and it is done, else its parts' fingerprints or its names where few. Names added up modulo 2^256 with their number, hashed; 16 parts a step; a message answered by reading it once, with nothing kept between messages; no more names in a message than asked. Used by nothing yet: the set of events catches up so, and merged state and the document ordered by clocks (docs/document.md).
Diffstat (limited to 'src/document/ranges.rs')
-rw-r--r--src/document/ranges.rs553
1 files changed, 553 insertions, 0 deletions
diff --git a/src/document/ranges.rs b/src/document/ranges.rs
new file mode 100644
index 0000000..8ae71e9
--- /dev/null
+++ b/src/document/ranges.rs
@@ -0,0 +1,553 @@
+//! 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'. Someone who chooses names
+//! can make two sets collide with about a day of work; 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: by tests alone so far.
+#![allow(dead_code)]
+
+use std::collections::BTreeSet;
+use std::ops::Bound;
+
+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;
+
+/// 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)]
+pub(crate) struct Fingerprint(pub(crate) [u8; 16]);
+
+/// The names of a range added up, and how many.
+#[derive(Clone, Copy, Default)]
+struct Sum {
+ sum: [u8; 32],
+ count: u64,
+}
+
+impl Sum {
+ fn add(&mut self, name: &Name) {
+ let mut carry = 0u16;
+ for (digit, other) in self.sum.iter_mut().zip(name) {
+ let total = u16::from(*digit) + u16::from(*other) + carry;
+ *digit = total as u8;
+ carry = total >> 8;
+ }
+ self.count += 1;
+ }
+
+ 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<Item = &'a Name>) -> Fingerprint {
+ let mut sum = Sum::default();
+ for name in names {
+ sum.add(name);
+ }
+ sum.fingerprint()
+}
+
+/// Where a part ends: before this name, or after every name.
+pub(crate) type Upper = Option<Name>;
+
+/// 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)]
+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<Name>,
+ 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)]
+pub(crate) struct Message(pub(crate) Vec<Part>);
+
+/// 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<Message>,
+ /// Names the sender holds and this node doesn't, as far as the message says.
+ pub(crate) lacking: Vec<Name>,
+}
+
+/// The names of `held` from `lower` (where the part before ended) up to `upper`.
+fn within<'a>(
+ held: &'a BTreeSet<Name>,
+ lower: &Upper,
+ upper: &Upper,
+) -> impl Iterator<Item = &'a Name> + Clone {
+ let from = match lower {
+ Some(name) => Bound::Included(*name),
+ None => Bound::Unbounded,
+ };
+ let to = match upper {
+ Some(name) => Bound::Excluded(*name),
+ None => Bound::Unbounded,
+ };
+ // A part ending no later than it begins holds nothing; `BTreeSet::range` panics on
+ // such bounds, which a peer may send.
+ let empty = matches!((lower, upper), (Some(from), Some(to)) if from >= to);
+ if empty {
+ held.range::<Name, _>((Bound::Excluded([0xff; 32]), Bound::Unbounded))
+ } else {
+ held.range((from, to))
+ }
+}
+
+/// The message that begins: this node's fingerprint of everything.
+pub(crate) fn open(held: &BTreeSet<Name>) -> Message {
+ Message(vec![Part::Fingerprint {
+ upper: None,
+ fingerprint: fingerprint(held),
+ }])
+}
+
+/// 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.
+pub(crate) fn answer(held: &BTreeSet<Name>, message: &Message, most: usize) -> Answer {
+ let mut out = Answer::default();
+ let mut reply = Vec::new();
+ let mut sent = 0;
+ // The first part begins before every name; `lower` is `None` only there.
+ let mut lower: Upper = None;
+ let mut first = true;
+ for part in &message.0 {
+ let upper = part.upper();
+ let from = if first { None } else { lower };
+ // A part after one that ended after every name holds nothing.
+ let ours = if !first && lower.is_none() {
+ Vec::new()
+ } else {
+ within(held, &from, &upper).copied().collect::<Vec<Name>>()
+ };
+ match part {
+ Part::Skip { .. } => reply.push(Part::Skip { upper }),
+ Part::Fingerprint {
+ fingerprint: theirs,
+ ..
+ } => {
+ if fingerprint(&ours) == *theirs {
+ reply.push(Part::Skip { upper });
+ } else if *theirs == fingerprint([]) {
+ // The peer holds nothing here: all of ours is what it lacks.
+ send(&mut reply, &mut sent, most, upper, ours, false);
+ } else if ours.len() <= FEW {
+ send(&mut reply, &mut sent, most, upper, ours, true);
+ } else {
+ split(&mut reply, &mut sent, most, upper, &ours);
+ }
+ }
+ Part::Names { names, asking, .. } => {
+ let theirs: BTreeSet<&Name> = names.iter().collect();
+ out.lacking
+ .extend(names.iter().filter(|name| !held.contains(*name)));
+ if *asking {
+ let beside: Vec<Name> = ours
+ .into_iter()
+ .filter(|name| !theirs.contains(name))
+ .collect();
+ if beside.is_empty() {
+ reply.push(Part::Skip { upper });
+ } else {
+ send(&mut reply, &mut sent, most, upper, beside, false);
+ }
+ } else {
+ reply.push(Part::Skip { upper });
+ }
+ }
+ }
+ lower = upper;
+ first = false;
+ if upper.is_none() {
+ break;
+ }
+ }
+ if reply.iter().any(|part| !matches!(part, Part::Skip { .. })) {
+ out.reply = Some(Message(merged(reply)));
+ }
+ out
+}
+
+/// Adds `names` as a part ending at `upper`, or their fingerprint where that would be
+/// more than `most` names in one message.
+fn send(
+ reply: &mut Vec<Part>,
+ sent: &mut usize,
+ most: usize,
+ upper: Upper,
+ names: Vec<Name>,
+ asking: bool,
+) {
+ if most != 0 && *sent + names.len() > most && *sent > 0 {
+ reply.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);
+ *sent += now.len();
+ reply.push(Part::Names {
+ upper: Some(later[0]),
+ names: now.to_vec(),
+ asking,
+ });
+ reply.push(Part::Fingerprint {
+ upper,
+ fingerprint: fingerprint(later),
+ });
+ return;
+ }
+ *sent += names.len();
+ reply.push(Part::Names {
+ upper,
+ names,
+ asking,
+ });
+}
+
+/// Adds `ours`, the names of a range ending at `upper`, in `PARTS` parts of about as
+/// many names each: the names of a part where they are few, else its fingerprint.
+fn split(reply: &mut Vec<Part>, sent: &mut usize, most: usize, upper: Upper, ours: &[Name]) {
+ let size = ours.len().div_ceil(PARTS);
+ let mut chunks = ours.chunks(size).peekable();
+ while let Some(chunk) = chunks.next() {
+ let ends = match chunks.peek() {
+ Some(next) => Some(next[0]),
+ None => upper,
+ };
+ if chunk.len() <= FEW / PARTS {
+ send(reply, sent, most, ends, chunk.to_vec(), true);
+ } else {
+ reply.push(Part::Fingerprint {
+ upper: ends,
+ fingerprint: fingerprint(chunk),
+ });
+ }
+ }
+}
+
+/// `parts` with runs of skipped ranges as one.
+fn merged(parts: Vec<Part>) -> Vec<Part> {
+ let mut out: Vec<Part> = 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 crate::testrand::{Rng, for_seeds};
+
+ /// Two nodes reconciling until neither has more to say: what each learned it
+ /// lacks, and how many messages went.
+ fn reconcile(
+ a: &BTreeSet<Name>,
+ b: &BTreeSet<Name>,
+ most: usize,
+ ) -> (BTreeSet<Name>, BTreeSet<Name>, usize) {
+ let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new());
+ let mut message = open(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(held, &message, most);
+ 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<Name> {
+ (0..count).map(|_| rng.bytes32()).collect()
+ }
+
+ /// Between `min` and `max` names.
+ fn some(rng: &mut Rng, min: usize, max: usize) -> BTreeSet<Name> {
+ let count = rng.between(min, max);
+ names(rng, count)
+ }
+
+ fn differences(a: &BTreeSet<Name>, b: &BTreeSet<Name>) -> (BTreeSet<Name>, BTreeSet<Name>) {
+ (
+ 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<Name> = (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(&nothing, &held, 0);
+ assert_eq!(a_lacks, held);
+ assert!(b_lacks.is_empty());
+ let (a_lacks, b_lacks, _) = reconcile(&held, &nothing, 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(&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(held, &message, most);
+ 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(&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(held, &message, 0);
+ 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(&held, &message, 0);
+ assert_eq!(answer.lacking, vec![[7; 32]]);
+ assert!(answer.reply.is_some());
+ }
+}