1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
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(¬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(&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());
}
}
|