aboutsummaryrefslogtreecommitdiffstats
path: root/src/simtest/holding.rs
blob: 955b2c0e0fa65e574939e86d167b93548380f649 (plain)
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
//! Swarms holding a store (`docs/store.md`, Members), the federation its fold: nodes
//! started from its root, or joining by its ID, sync with the members its store names;
//! the events put on any of them reach all of them, and none reaches a node its party
//! doesn't list; and the attack rows marked sim, each by its test.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use super::{SOON, Sim, sim_key};
use crate::document::events;
use crate::federation::client::Record;
use crate::federation::event::Event;
use crate::federation::fold::Federation;
use crate::federation::harness::{self, Party, Spec};
use crate::federation::held::{self, Holding, Voter};
use crate::federation::jcs::Json;
use crate::federation::store::memory::Store;
use crate::federation::store::{Fold, Id};
use crate::federation::version::Version;
use crate::federation::vote::Rules;
use crate::files::Files;
use crate::node::NodeConfig;
use crate::state::AppState;
use crate::swarm::bootstrap::{Origin, Start};
use crate::swarm::topology;

/// How long a test waits for what takes a few rounds of syncs, writes and reads.
const LONG: Duration = Duration::from_secs(30);

/// A federation of `parties`, each listing the simulated nodes named with it: its first
/// version, its root, and its ID.
fn federation(parties: &[(&Party, &[&str])]) -> (Spec, Vec<u8>, Id) {
    let named: Vec<&Party> = parties.iter().map(|(party, _)| *party).collect();
    let mut first = Spec::first(&named, &[]);
    for (spec, (_, nodes)) in first.parties.iter_mut().zip(parties) {
        spec.nodes = nodes.iter().map(|node| sim_key(node).id()).collect();
    }
    let root = first.root();
    let id = Id::of(&root);
    (first, root, id)
}

/// tv, lass and makefu.
fn three() -> (Party, Party, Party) {
    (
        Party::new("tv", 1),
        Party::new("lass", 2),
        Party::new("makefu", 3),
    )
}

fn s(text: &str) -> Json {
    harness::str(text)
}

/// What a node of `party` keeps of its store, without a file (`--store-party`).
fn holding(party: &str) -> Holding {
    Holding::open(
        None,
        Arc::new(Files::default()),
        None,
        Some(party.to_owned()),
    )
    .expect("no file to read")
}

/// What a node of `party` keeps of its store, starting from the checkpoint `pin`, found in
/// the document (`--store-checkpoint`).
fn pinned(party: &str, pin: Id) -> Holding {
    Holding::open(
        None,
        Arc::new(Files::default()),
        Some(pin),
        Some(party.to_owned()),
    )
    .expect("no file to read")
}

/// What a node of `party` keeps of its store, voting for its party by itself by `rules`
/// with its key, its party's record in `dir`, begun before the federation `first` spells
/// out: so it casts on the first version too.
fn voting(party: &Party, rules: Rules, dir: &Path, first: &Spec) -> Holding {
    let record = dir.join(format!("{}.json", party.name));
    let version = Version::read(&first.json()).expect("a version");
    let mut begun = Record::begin(Id::of(&first.root()), &party.name, &version);
    begun.began = Id::of(b"before the federation").to_string();
    begun.save(&record).expect("a record");
    holding(&party.name).voting(Some(Voter {
        key: party.key.clone(),
        record,
        rules,
    }))
}

/// `config`, of a node of the swarm holding the store `id`, keeping `holding`: started
/// from the store's `root` where given (`--store-root`), else joining by its ID
/// (`--store-id`).
fn of_the_store(config: &mut NodeConfig, id: Id, root: Option<&[u8]>, holding: Holding) {
    config.store = Some(id);
    config.holding = holding;
    if let Some(root) = root {
        config.initial_doc = events::started(Federation::NAME, root).expect("a root");
    }
}

/// Starts `nodes`, each by its name with what it keeps of its store, from the store's
/// `root`, the first one the others' seed, and waits until each holds the store.
async fn started(sim: &Sim, root: &[u8], nodes: Vec<(&str, Holding)>) -> Vec<AppState> {
    started_with(sim, root, nodes, |_| {}).await
}

/// [`started`], each node's configuration adjusted by `adjust` too.
async fn started_with(
    sim: &Sim,
    root: &[u8],
    nodes: Vec<(&str, Holding)>,
    adjust: fn(&mut NodeConfig),
) -> Vec<AppState> {
    let id = Id::of(root);
    let first = nodes[0].0.to_owned();
    let states: Vec<AppState> = nodes
        .into_iter()
        .map(|(name, holding)| {
            let seeds: Vec<&str> = if name == first {
                Vec::new()
            } else {
                vec![first.as_str()]
            };
            let root = root.to_vec();
            sim.start_with(
                name,
                &seeds,
                Start::FromDocument(Origin::Root),
                move |config| {
                    of_the_store(config, id, Some(&root), holding);
                    adjust(config);
                },
            )
        })
        .collect();
    let all: Vec<&AppState> = states.iter().collect();
    sim.wait_ready(&all, SOON).await;
    let all = &all;
    sim.wait_until("every node holds the store", SOON, move || async move {
        all.iter().all(|node| node.holding.tells_members())
    })
    .await;
    states
}

/// Puts `events` on `node`, each in a change of its own.
async fn put(node: &AppState, events: &[&[u8]]) {
    for event in events {
        held::write(node, None, event.to_vec())
            .await
            .expect("an event put");
    }
}

/// What `f` reads of `node`'s store, while it holds one.
fn read<T>(node: &AppState, f: impl FnOnce(&Store<Federation>) -> T) -> Option<T> {
    node.holding.with(f)
}

/// Whether `node` holds every event of `ids`.
fn holds(node: &AppState, ids: &[Id]) -> bool {
    read(node, |store| ids.iter().all(|id| store.holds(id))) == Some(true)
}

/// The version current, as `node`'s store reads, by its hash.
fn current(node: &AppState) -> Option<Id> {
    read(node, |store| store.state().current().hash)
}

/// The ID of the checkpoint `node`'s store holds.
fn checkpoint(node: &AppState) -> Option<Id> {
    read(node, |store| Id::of(store.checkpoint()))
}

/// The version event writing `version` that `node`'s store took after its checkpoint.
fn written(node: &AppState, version: Id) -> Option<Id> {
    read(node, |store| {
        store.taken().iter().copied().find(|id| {
            matches!(
                store.get(id).and_then(Event::read_taken),
                Some(Event::Version { version: writes, .. }) if writes == version
            )
        })
    })
    .flatten()
}

/// What counts, as `node`'s store reads: the current version, the values at places, and
/// the members; and the events it took after its checkpoint.
type Counts = (
    Id,
    BTreeMap<String, Json>,
    Vec<(String, String)>,
    BTreeSet<Id>,
);

fn counts(node: &AppState) -> Option<Counts> {
    read(node, |store| {
        let state = store.state();
        (
            state.current().hash,
            state.values(),
            state.members(),
            store.taken().iter().copied().collect(),
        )
    })
}

/// tv lists a and b, which start from the root; lass lists c, which joins by the store's
/// ID; d is of lass too, which doesn't list it. Events put on a and on c reach a, b and
/// c; d, which no member syncs with, gets nothing.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_events_put_on_a_member_reach_every_member_alone() {
    let sim = Sim::with_identity(81);
    let (tv, lass, _) = three();
    let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]);
    let mut nodes = started(
        &sim,
        &root,
        vec![("a", holding("tv")), ("b", holding("tv"))],
    )
    .await;
    nodes.push(sim.start_with("c", &["a"], Start::Join, |config| {
        of_the_store(config, id, None, holding("lass"))
    }));
    let [a, b, c] = [&nodes[0], &nodes[1], &nodes[2]];
    let members = [a, b, c];
    sim.wait_ready(&members, SOON).await;
    sim.wait_until("a, b and c hold the store", SOON, move || async move {
        members.iter().all(|node| node.holding.tells_members())
    })
    .await;

    let d = sim.start_with("d", &["a"], Start::Join, |config| {
        of_the_store(config, id, None, holding("lass"))
    });
    let on_a = tv.write(&[id], "home/tv/x", s("1"));
    let on_c = lass.write(&[id], "home/lass/y", s("2"));
    let ids = [Id::of(&on_a), Id::of(&on_c)];
    put(a, &[&on_a]).await;
    put(c, &[&on_c]).await;
    sim.wait_until("a, b and c hold both events", SOON, move || async move {
        members.iter().all(|node| holds(node, &ids))
    })
    .await;
    sim.wait_converged(&members, SOON).await;
    for node in members {
        assert_eq!(read(node, |store| store.state().values().len()), Some(2));
    }
    // Long enough for d to have joined, were it let in.
    tokio::time::sleep(Duration::from_secs(3)).await;
    assert!(!d.is_ready().await);
    assert!(!d.holding.tells_members());
    assert!(events::ids(&d.doc.read().await.doc).is_empty());
}

/// Different events to different peers: tv, lass and makefu, a node each, apart while
/// each is given its own: two writes of tv's at one place, a write of lass's, and a
/// proposal and the votes that pass it, each on another node. Together, they read the
/// same, the version that passed current, written by whichever held it passed.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn federation_attack_28() {
    let sim = Sim::with_identity(82);
    let (tv, lass, makefu) = three();
    let (first, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"]), (&makefu, &["c"])]);
    let nodes = started(
        &sim,
        &root,
        vec![
            ("a", holding("tv")),
            ("b", holding("lass")),
            ("c", holding("makefu")),
        ],
    )
    .await;
    for name in ["a", "b", "c"] {
        sim.net.take_down(name);
    }
    let on = first.hash();
    let mut next = first.after(on);
    next.rules.push(("names/x".to_owned(), s("tv")));
    let proposal = makefu.propose(&[id], &next.json());
    let given = [
        [tv.write(&[id], "home/tv/x", s("a")), proposal.clone()],
        [
            tv.write(&[id], "home/tv/x", s("b")),
            tv.vote(&[Id::of(&proposal)], on, next.hash(), true),
        ],
        [
            lass.write(&[id], "home/lass/y", s("c")),
            lass.vote(&[Id::of(&proposal)], on, next.hash(), true),
        ],
    ];
    for (node, events) in nodes.iter().zip(&given) {
        put(node, &[&events[0], &events[1]]).await;
    }
    let (all, writes) = (&nodes, [0, 1, 2].map(|i| Id::of(&given[i][0])));
    sim.wait_until(
        "each holds the write it was given",
        SOON,
        move || async move {
            all.iter()
                .zip(writes)
                .all(|(node, write)| holds(node, &[write]))
        },
    )
    .await;
    // Apart, a and b read their own write at one place.
    let at = |node: &AppState| read(node, |store| store.state().value("home/tv/x").cloned());
    assert_eq!(at(&nodes[0]), Some(Some(s("a"))));
    assert_eq!(at(&nodes[1]), Some(Some(s("b"))));

    for name in ["a", "b", "c"] {
        sim.net.bring_up(name);
    }
    let passed = next.hash();
    sim.wait_until("every node reads the same", LONG, move || async move {
        let first = counts(&all[0]);
        first.as_ref().is_some_and(|counts| counts.0 == passed)
            && all.iter().all(|node| counts(node) == first)
    })
    .await;
    let counts = counts(&nodes[0]).expect("a store");
    assert!(writes.iter().all(|write| counts.3.contains(write)));
}

/// The version passing on the first version of tv, lass and makefu that only moves to a
/// checkpoint at `heads`, proposed by tv, and backed by tv and lass: its spec, and the
/// proposal and votes.
fn checkpoint_at(
    (tv, lass, _): &(Party, Party, Party),
    first: &Spec,
    heads: &[Id],
) -> (Spec, [Vec<u8>; 3]) {
    let on = first.hash();
    let mut next = first.after(on);
    next.checkpoint = Some(heads.to_vec());
    let proposal = tv.propose(heads, &next.json());
    let votes = [tv, lass].map(|party| party.vote(&[Id::of(&proposal)], on, next.hash(), true));
    let [tv_yes, lass_yes] = votes;
    (next, [proposal, tv_yes, lass_yes])
}

/// A node away while the others moved to a checkpoint and forgot what came before: c,
/// back, builds the checkpoint from the document, which holds what came before, and
/// reads what a and b read, what came after it too.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn store_attack_24() {
    let sim = Sim::with_identity(83);
    let parties = three();
    let (tv, lass, makefu) = &parties;
    let (first, root, id) = federation(&[(tv, &["a"]), (lass, &["b"]), (makefu, &["c"])]);
    let nodes = started(
        &sim,
        &root,
        vec![
            ("a", holding("tv")),
            ("b", holding("lass")),
            ("c", holding("makefu")),
        ],
    )
    .await;
    sim.net.take_down("c");
    let gone = tv.write(&[id], "home/tv/a", s("0"));
    let head = tv.write(&[Id::of(&gone)], "home/tv/a", s("1"));
    let (next, [proposal, tv_yes, lass_yes]) = checkpoint_at(&parties, &first, &[Id::of(&head)]);
    put(&nodes[0], &[&gone, &head, &proposal, &tv_yes]).await;
    put(&nodes[1], &[&lass_yes]).await;
    let (all, passed) = (&nodes, next.hash());
    sim.wait_until(
        "a and b moved to the checkpoint",
        LONG,
        move || async move {
            all[..2]
                .iter()
                .all(|node| current(node) == Some(passed) && checkpoint(node) != Some(id))
        },
    )
    .await;
    let after = tv.write(&[Id::of(&head)], "home/tv/b", s("2"));
    put(&nodes[0], &[&after]).await;
    let moved = checkpoint(&nodes[0]).expect("a store");
    assert_eq!(checkpoint(&nodes[1]), Some(moved));
    assert_eq!(
        read(&nodes[0], |store| store.holds(&Id::of(&gone))),
        Some(false)
    );

    sim.net.bring_up("c");
    let after = Id::of(&after);
    sim.wait_until(
        "c moved there, and holds what came after",
        LONG,
        move || async move {
            checkpoint(&all[2]) == Some(moved)
                && holds(&all[2], &[after])
                && holds(&all[0], &[after])
        },
    )
    .await;
    assert_eq!(counts(&nodes[2]), counts(&nodes[0]));
    assert!(events::ids(&nodes[2].doc.read().await.doc).contains(&Id::of(&gone)));
}

/// Keys voting twice part honest nodes: tv backs a proposal of its own with lass, and one
/// of lass's with makefu; b, apart, takes the other version than a and c. Together, they
/// stay parted, and b's operator has it drop what it took and take the other side's; or,
/// where the versions named checkpoints, starts it again from the checkpoint the others
/// moved to, pinned. No fork.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn federation_attack_49() {
    for (seed, checkpoints) in [(84, false), (85, true)] {
        parted(seed, checkpoints).await;
    }
}

async fn parted(seed: u64, checkpoints: bool) {
    let sim = Sim::with_identity(seed);
    let (tv, lass, makefu) = three();
    let (first, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"]), (&makefu, &["c"])]);
    let nodes = started(
        &sim,
        &root,
        vec![
            ("a", holding("tv")),
            ("b", holding("lass")),
            ("c", holding("makefu")),
        ],
    )
    .await;
    sim.net.take_down("b");
    let on = first.hash();
    let (mut one, mut two) = (first.after(on), first.after(on));
    two.rules.push(("names/x".to_owned(), s("tv")));
    let heads = [
        tv.write(&[id], "home/tv/a", s("1")),
        lass.write(&[id], "home/lass/b", s("2")),
    ];
    if checkpoints {
        one.checkpoint = Some(vec![Id::of(&heads[0])]);
        two.checkpoint = Some(vec![Id::of(&heads[1])]);
    }
    let p1 = tv.propose(&[Id::of(&heads[0])], &one.json());
    let p2 = lass.propose(&[Id::of(&heads[1])], &two.json());
    let ones = [&tv, &lass].map(|party| party.vote(&[Id::of(&p1)], on, one.hash(), true));
    let twos = [&tv, &makefu].map(|party| party.vote(&[Id::of(&p2)], on, two.hash(), true));
    put(&nodes[0], &[&heads[0], &p1, &ones[0], &ones[1]]).await;
    put(&nodes[1], &[&heads[1], &p2, &twos[0], &twos[1]]).await;
    let (all, one_hash, two_hash) = (&nodes, one.hash(), two.hash());
    sim.wait_until(
        "a and c take one version, b the other",
        LONG,
        move || async move {
            current(&all[0]) == Some(one_hash)
                && current(&all[2]) == Some(one_hash)
                && current(&all[1]) == Some(two_hash)
        },
    )
    .await;
    sim.net.bring_up("b");
    let members: Vec<&AppState> = nodes.iter().collect();
    sim.wait_converged(&members, LONG).await;
    // Parted: each keeps the version it took.
    assert_eq!(current(&nodes[0]), Some(one_hash));
    assert_eq!(current(&nodes[1]), Some(two_hash));
    assert_eq!(current(&nodes[2]), Some(one_hash));

    let b = if checkpoints {
        let pin = checkpoint(&nodes[0]).expect("a store");
        sim.restart_with("b", &["a"], Start::Join, move |config| {
            of_the_store(config, id, None, pinned("lass", pin))
        })
    } else {
        let took = written(&nodes[1], two_hash).expect("b wrote what it took");
        let other = written(&nodes[0], one_hash).expect("a wrote what it took");
        let dropped = nodes[1].holding.drop_taken(&[took]);
        assert!(matches!(dropped, Some(Ok(_))), "{dropped:?}");
        assert!(nodes[1].holding.allow(&[other]));
        nodes[1].clone()
    };
    let b = &b;
    sim.wait_until("b takes the others' version", LONG, move || async move {
        current(b) == Some(one_hash)
    })
    .await;
    assert_eq!(checkpoint(b), checkpoint(&nodes[0]));
}

/// A party keeps a proposal alive that nobody else backs, to hold back automatic
/// checkpoints: makefu proposes a version and backs it alone. a votes for tv by itself,
/// proposing a checkpoint once its store took five events; b votes for lass, following
/// tv. a proposes one beside makefu's, b backs it, and every node moves there.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn federation_attack_67() {
    let sim = Sim::with_identity(86);
    let (tv, lass, makefu) = three();
    let (first, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"]), (&makefu, &["c"])]);
    let dir = crate::files::scratch_dir("sim-attack-67");
    let proposing = Rules {
        propose_events: Some(5),
        ..Rules::default()
    };
    let following = Rules {
        follow: vec!["tv".to_owned()],
        ..Rules::default()
    };
    let nodes = started(
        &sim,
        &root,
        vec![
            ("a", voting(&tv, proposing, &dir, &first)),
            ("b", voting(&lass, following, &dir, &first)),
            ("c", holding("makefu")),
        ],
    )
    .await;
    let on = first.hash();
    let mut other = first.after(on);
    other.rules.push(("names/x".to_owned(), s("makefu")));
    let alive = makefu.propose(&[id], &other.json());
    let backed = makefu.vote(&[Id::of(&alive)], on, other.hash(), true);
    put(&nodes[2], &[&alive, &backed]).await;
    let writes: Vec<Vec<u8>> = (1..=3)
        .map(|n| tv.write(&[id], &format!("home/tv/{n}"), s("1")))
        .collect();
    let writes: Vec<&[u8]> = writes.iter().map(Vec::as_slice).collect();
    put(&nodes[0], &writes).await;
    let (all, kept_alive) = (&nodes, other.hash());
    sim.wait_until(
        "every node moved to a checkpoint",
        LONG,
        move || async move {
            all.iter().all(|node| {
                let named = read(node, |store| {
                    let current = store.state().current();
                    current.number == 1
                        && current.checkpoint.is_some()
                        && current.hash != kept_alive
                });
                named == Some(true) && checkpoint(node) != Some(id)
            })
        },
    )
    .await;
}

/// A group naming many nodes, to be every node's neighbours: makefu lists five, tv two,
/// and lass one, whose operator names tv's too (`--store-neighbour-parties`); each node
/// keeps two neighbours by the graph among all members. a and b keep each other, and c
/// one of them, whatever makefu's nodes are.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn store_attack_19() {
    let sim = Sim::with_identity(87);
    let (tv, lass, makefu) = three();
    let many = ["m1", "m2", "m3", "m4", "m5"];
    let (_, root, _) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"]), (&makefu, &many)]);
    let mut named = vec![
        ("a", holding("tv")),
        ("b", holding("tv")),
        ("c", holding("lass").near(vec!["tv".to_owned()])),
    ];
    named.extend(many.iter().map(|name| (*name, holding("makefu"))));
    let nodes = started_with(&sim, &root, named, |config| config.neighbours_k = 2).await;
    let [a, b, c] = [&nodes[0], &nodes[1], &nodes[2]];
    let (a_id, b_id) = (a.local_id().to_owned(), b.local_id().to_owned());
    sim.wait_until(
        "a and b keep each other, and c one of them",
        LONG,
        move || {
            let (a_id, b_id) = (a_id.clone(), b_id.clone());
            async move {
                let known = [a, b, c].iter().all(|node| topology::view_known(node));
                known
                    && topology::is_neighbour(a, &b_id)
                    && topology::is_neighbour(b, &a_id)
                    && (topology::is_neighbour(c, &a_id) || topology::is_neighbour(c, &b_id))
            }
        },
    )
    .await;
}

/// A writer forked: x1 and x2, tv's, start apart from one document under one writer,
/// and each puts an event: changes of one writer at one number. Together, the documents
/// part, each refusing the other's changes; the events reach every node, put again from
/// the changes refused, and every node reads the same.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn store_attack_10() {
    let sim = Sim::with_identity(88);
    let (tv, lass, _) = three();
    let (_, root, id) = federation(&[(&tv, &["a", "x1", "x2"]), (&lass, &["b"])]);
    let mut nodes = started(
        &sim,
        &root,
        vec![("a", holding("tv")), ("b", holding("lass"))],
    )
    .await;
    let one = events::started(Federation::NAME, &root).expect("a root");
    for name in ["x1", "x2"] {
        sim.net.take_down(name);
        let doc = one.clone();
        nodes.push(sim.start_with(
            name,
            &["a"],
            Start::FromDocument(Origin::Root),
            move |config| {
                of_the_store(config, id, None, holding("tv"));
                config.initial_doc = doc;
            },
        ));
    }
    let twins = [&nodes[2], &nodes[3]];
    sim.wait_ready(&twins, SOON).await;
    sim.wait_until("x1 and x2 hold the store", SOON, move || async move {
        twins.iter().all(|node| node.holding.tells_members())
    })
    .await;
    let given = [
        tv.write(&[id], "home/tv/x1", s("1")),
        tv.write(&[id], "home/tv/x2", s("2")),
    ];
    put(twins[0], &[&given[0]]).await;
    put(twins[1], &[&given[1]]).await;
    for name in ["x1", "x2"] {
        sim.net.bring_up(name);
    }
    let (all, ids) = (&nodes, given.each_ref().map(|event| Id::of(event)));
    sim.wait_until(
        "every node holds both events, and reads the same",
        Duration::from_secs(60),
        move || async move {
            let first = counts(&all[0]);
            all.iter()
                .all(|node| holds(node, &ids) && counts(node) == first)
        },
    )
    .await;
    // Each refuses the other's changes for good: their documents part.
    assert_ne!(super::heads(twins[0]).await, super::heads(twins[1]).await);
}