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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
|
//! 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<Item = &'a Name>) -> 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<Item = &'a Name>) -> 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<Run>,
all: Sum,
}
#[derive(Clone, Debug)]
struct Run {
names: Vec<Name>,
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<Item = &Name> {
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<Name> {
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<Name> for Names {
fn from_iter<T: IntoIterator<Item = Name>>(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<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, 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<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, Serialize, Deserialize)]
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 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<Part>,
/// 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<Name> = 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<Name>, 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<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 std::cell::Cell;
use std::collections::BTreeSet;
use crate::testrand::{Rng, for_seeds};
fn of(names: &BTreeSet<Name>) -> Names {
names.iter().copied().collect()
}
thread_local! {
static SALT: Cell<u64> = 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<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(&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<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(&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<Name> = (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<Name> = 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());
});
}
}
|