aboutsummaryrefslogtreecommitdiffstats
path: root/src/simtest/holding.rs
blob: 956bd624646f42a67d892526646bd5af29da9750 (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
//! 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::sync::Arc;
use std::time::Duration;

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

/// 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")
}

/// `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> {
    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),
            )
        })
        .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]));
}