aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/properties.rs
blob: 9f7f975ae473dd265d72bce4bd3581a1fd945aaf (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
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! The federation's properties over generated histories (`docs/federation-tests.md`,
//! Properties): three to five parties write, change their key sets and node lists, propose
//! versions and checkpoints, vote, and write the versions that pass, each on what it last
//! caught up with, and their nodes merge; an adversary signs with its keys or stolen ones whatever it likes. The
//! store is checked against the model, which reads every history anew, against itself in
//! other orders, and read from a document against itself given the events alone. And
//! nodes voting by themselves get on: a history is gone on with by them and by parties
//! voting by hand (`gone_on`), and what they cast is taken, what they back is written once
//! it passes, and what some votes can write, a node writes. A failing history is cut down,
//! events taken out with what builds on them for as long as it still fails, and printed.

use std::collections::{BTreeMap, BTreeSet};

use ed25519_dalek::SigningKey;

use super::client::Record;
use super::event::{Checkpoint, Does, Event, Signed};
use super::fold::Federation;
use super::harness::{self, Party, Spec};
use super::held::Holding;
use super::jcs::Json;
use super::model::{Model, Verdict};
use super::revision::{Feature, Revision};
use super::store::memory::{Offered, Refusal, Store};
use super::store::{Fold, Id};
use super::version::Version;
use super::vote::{self, Act, Rules, Seen};
use crate::access::sshsig::PublicKey;
use crate::document::events;
use crate::testrand::{Rng, for_seeds};

/// The most events a history has.
const MOST: usize = 30;

/// A root, and events in the order written.
#[derive(Clone)]
pub(super) struct History {
    pub(super) root: Vec<u8>,
    pub(super) events: Vec<Vec<u8>>,
}

impl History {
    fn root_id(&self) -> Id {
        Id::of(&self.root)
    }

    fn store(&self, order: &[usize]) -> (Store<Federation>, Vec<Offered>) {
        let mut store = Store::new(self.root.clone(), Vec::new()).expect("a root");
        let offered = order
            .iter()
            .map(|&i| store.offer(self.events[i].clone()))
            .collect();
        (store, offered)
    }

    fn written(&self) -> Vec<usize> {
        (0..self.events.len()).collect()
    }

    /// The history without the event at `i`, and what builds on it.
    fn without(&self, i: usize) -> History {
        let mut gone = BTreeSet::from([Id::of(&self.events[i])]);
        let mut events = Vec::new();
        for event in &self.events {
            let id = Id::of(event);
            let deps = Federation::dependencies(event).unwrap_or_default();
            if gone.contains(&id) || deps.iter().any(|dep| gone.contains(dep)) {
                gone.insert(id);
            } else {
                events.push(event.clone());
            }
        }
        History {
            root: self.root.clone(),
            events,
        }
    }

    fn show(&self) -> String {
        std::iter::once(format!("root {}", String::from_utf8_lossy(&self.root)))
            .chain(
                self.events
                    .iter()
                    .map(|event| format!("{} {}", Id::of(event), String::from_utf8_lossy(event))),
            )
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// How a history is written: whether an adversary takes part, whether versions name
/// checkpoints, and whether parties propose versions this continuum doesn't read, at
/// which a store stops, which events then take in the order they come.
#[derive(Clone, Copy, Debug)]
pub(super) struct Kind {
    pub(super) adversary: bool,
    pub(super) checkpoints: bool,
    pub(super) unread: bool,
}

/// One of `ids`, of the latest five more often than not.
fn pick(rng: &mut Rng, ids: &[Id]) -> Id {
    if rng.chance(0.6) {
        *rng.pick(&ids[ids.len().saturating_sub(5)..])
    } else {
        *rng.pick(ids)
    }
}

fn generate(rng: &mut Rng, kind: Kind) -> History {
    generate_at(rng, kind, None)
}

/// A history of `kind`, its first version following `revision`, or, where none is given,
/// the base revision or the newest alike.
pub(super) fn generate_at(rng: &mut Rng, kind: Kind, revision: Option<Revision>) -> History {
    let count = rng.between(3, 5);
    let parties: Vec<Party> = (0..count)
        .map(|i| Party::new(&format!("p{i}"), i as u8 + 1))
        .collect();
    let adversary = count - 1;
    let refs: Vec<&Party> = parties.iter().collect();
    let mut first = Spec::first(&refs, &[("names/{party}", harness::str("{party}"))]);
    // Half the federations begin at the newest revision: with merge events, which nodes
    // then sign, and a name, which versions change.
    let newest = rng.chance(0.5);
    first.revision = revision.unwrap_or(if newest {
        Revision::newest()
    } else {
        Revision::default()
    });
    let naming = first.revision.has(Feature::FederationName);
    if naming {
        first.name = Some("f".to_owned());
    }
    let root = first.root();
    let root_id = Id::of(&root);
    let mut world: Store<Federation> = Store::new(root.clone(), Vec::new()).expect("a root");
    let mut specs: BTreeMap<Id, Spec> = BTreeMap::from([(first.hash(), first)]);
    // The key each party signs its writes with: its version's, or its set's.
    let mut signing: Vec<SigningKey> = parties.iter().map(|party| party.key.clone()).collect();
    let mut known: Vec<Vec<Id>> = vec![vec![root_id]; count];
    // Each proposal: its event, the version it proposes, the version it is on, and
    // whether it names a checkpoint.
    let mut proposals: Vec<(Id, Id, Id, bool)> = Vec::new();
    let mut votes: Vec<(Id, Id)> = Vec::new();
    let mut backed: Vec<BTreeSet<Id>> = vec![BTreeSet::new(); count];
    let mut events: Vec<Vec<u8>> = Vec::new();
    for step in 0..rng.between(1, MOST) {
        let w = rng.below(count);
        let party = &parties[w];
        if rng.chance(0.25) {
            known[w] = std::iter::once(root_id)
                .chain(events.iter().map(|event| Id::of(event)))
                .collect();
        }
        let mut deps = vec![pick(rng, &known[w])];
        let other = pick(rng, &known[w]);
        if rng.chance(0.3) && !deps.contains(&other) {
            deps.push(other);
        }
        let current = world.state_at(&deps).current().clone();
        let writer = Party {
            name: party.name.clone(),
            key: signing[w].clone(),
        };
        let mine: Vec<&(Id, Id, Id, bool)> = proposals
            .iter()
            .filter(|(id, ..)| known[w].contains(id))
            .collect();
        // Of the proposals it knows, more often than not the earliest on the version current
        // where it writes, else any: so that parties vote alike and versions pass, of those
        // this continuum doesn't read too.
        let earliest = mine.iter().position(|(_, _, on, _)| *on == current.hash);
        let chosen = |rng: &mut Rng| -> (Id, Id, Id, bool) {
            match earliest {
                Some(at) if rng.chance(0.6) => *mine[at],
                _ => **rng.pick(&mine),
            }
        };
        let roll = rng.below(100);
        let event = if roll < 4 {
            // A node merges: one its party lists there, more often than not, else any.
            let listed = world.state_at(&deps).nodes_of(&party.name, &current);
            let ours: Vec<u8> = (0..10)
                .filter(|seed| listed.contains(&harness::node_id(*seed)))
                .collect();
            let seed = if !ours.is_empty() && rng.chance(0.75) {
                *rng.pick(&ours)
            } else {
                rng.below(10) as u8
            };
            harness::merge(&party.name, seed, &deps)
        } else if roll < 35 || (roll >= 60 && mine.is_empty()) {
            let path = format!("home/{}/k{}", party.name, rng.below(3));
            writer.write(&deps, &path, harness::str(&step.to_string()))
        } else if roll < 43 {
            let new = SigningKey::from_bytes(&[(100 + step as u8).wrapping_add(w as u8 * 31); 32]);
            let line = PublicKey(new.verifying_key().to_bytes()).line();
            signing[w] = new;
            party.keys(&deps, &[line])
        } else if roll < 48 {
            party.nodes(&deps, &[harness::node_id(rng.below(10) as u8)])
        } else if roll < 60 {
            match specs.get(&current.hash) {
                None => writer.write(&deps, &format!("home/{}/x", party.name), harness::str("x")),
                Some(base) => {
                    let mut next = base.after(current.hash);
                    let named = kind.checkpoints
                        && rng.chance(0.5)
                        && deps.iter().any(|dep| *dep != root_id);
                    if named {
                        let head = *deps.iter().find(|dep| **dep != root_id).expect("one");
                        next.checkpoint = Some(vec![head]);
                        deps = vec![head];
                    } else if naming && rng.chance(0.3) {
                        next.name = Some(format!("f{step}"));
                    } else {
                        next.rules
                            .push((format!("names/x{step}"), harness::str(&party.name)));
                    }
                    if kind.unread && rng.chance(0.5) {
                        // A field this continuum doesn't know: none here.
                        let Json::Object(mut members) = next.json() else {
                            unreachable!("a version is an object")
                        };
                        members.push(("later".to_owned(), Json::Bool(true)));
                        let later = Json::object(members).expect("names once each");
                        let bytes = party.propose(&deps, &later);
                        proposals.push((
                            Id::of(&bytes),
                            Id::of(&later.bytes()),
                            current.hash,
                            named,
                        ));
                        bytes
                    } else {
                        let bytes = party.propose(&deps, &next.json());
                        proposals.push((Id::of(&bytes), next.hash(), current.hash, named));
                        specs.insert(next.hash(), next);
                        bytes
                    }
                }
            }
        } else if roll < 85 {
            let (proposal, hash, on, named) = chosen(rng);
            let yes = if kind.adversary && w == adversary {
                rng.chance(0.7)
            } else {
                backed[w].insert(on)
            };
            if !named && rng.chance(0.3) {
                deps.push(proposal);
            } else {
                deps = vec![proposal];
            }
            let bytes = party.vote(&deps, on, hash, yes);
            votes.push((Id::of(&bytes), proposal));
            bytes
        } else if roll < 96 || !kind.adversary {
            let (proposal, hash, ..) = chosen(rng);
            let on_it: Vec<Id> = votes
                .iter()
                .filter(|(vote, voted)| *voted == proposal && known[w].contains(vote))
                .map(|(vote, _)| *vote)
                .collect();
            let deps = if on_it.is_empty() {
                vec![proposal]
            } else {
                on_it
            };
            harness::version_event(&deps, hash)
        } else {
            // The adversary signs as another party with its own key, or writes elsewhere.
            let victim = &parties[rng.below(count)];
            let thief = Party {
                name: victim.name.clone(),
                key: parties[adversary].key.clone(),
            };
            if rng.chance(0.5) {
                thief.write(
                    &deps,
                    &format!("home/{}/k0", victim.name),
                    harness::str("stolen"),
                )
            } else {
                parties[adversary].write(
                    &deps,
                    &format!("names/{}", victim.name),
                    harness::str("x"),
                )
            }
        };
        let id = Id::of(&event);
        world.offer(event.clone());
        known[w].push(id);
        events.push(event);
    }
    History { root, events }
}

fn check(cases: u64, kind: Kind, property: impl Fn(&History) -> Result<(), String>) {
    for_seeds(cases, |rng| {
        let history = generate(rng, kind);
        if let Err(why) = property(&history) {
            let (history, why) = cut_down(history, why, &property);
            panic!("{why}, in the history\n{}", history.show());
        }
    });
}

fn cut_down(
    mut history: History,
    mut why: String,
    property: &impl Fn(&History) -> Result<(), String>,
) -> (History, String) {
    'shorter: loop {
        for i in (0..history.events.len()).rev() {
            let shorter = history.without(i);
            if let Err(still) = property(&shorter) {
                (history, why) = (shorter, still);
                continue 'shorter;
            }
        }
        return (history, why);
    }
}

/// The current version's hash, the values at places, and the members.
type Reads = (
    Id,
    BTreeMap<String, super::jcs::Json>,
    BTreeSet<(String, String)>,
);

/// What a store reads, to compare with the model or another store.
fn reads(store: &Store<Federation>) -> Reads {
    let state = store.state();
    (
        state.current().hash,
        state.values(),
        state.members().into_iter().collect(),
    )
}

fn model_reads(model: &Model) -> Reads {
    (model.version().hash, model.values(), model.members())
}

/// What a store holds, to compare with another store: its checkpoint, the events it took
/// after it, and what it reads.
fn holds(store: &Store<Federation>) -> (Vec<u8>, BTreeSet<Id>, Reads) {
    (
        store.checkpoint().to_vec(),
        store.taken().iter().copied().collect(),
        reads(store),
    )
}

/// The verdict a store's answer stands for.
fn verdict(offered: &Offered) -> Verdict {
    match offered {
        Offered::Taken(_) => Verdict::Taken,
        Offered::Held => Verdict::Held,
        Offered::Waiting => Verdict::Waiting,
        Offered::Refused(_) => Verdict::Refused,
        Offered::Stopped => Verdict::Stopped,
    }
}

/// Whether the store judges and reads `history` as the model does, its events offered in
/// the order written; and whether it stopped.
fn judged_as_the_model(history: &History) -> Result<bool, String> {
    let mut model = Model::new(&history.root);
    let mut store: Store<Federation> =
        Store::new(history.root.clone(), Vec::new()).expect("a root");
    for event in &history.events {
        let id = Id::of(event);
        let stored = verdict(&store.offer(event.clone()));
        let modelled = model.offer(event);
        if stored != modelled {
            return Err(format!(
                "{id}: the store says {stored:?}, the model {modelled:?}"
            ));
        }
    }
    if reads(&store) != model_reads(&model) {
        return Err(format!(
            "the store reads {:?}, the model {:?}",
            reads(&store),
            model_reads(&model)
        ));
    }
    Ok(store.stopped().is_some())
}

/// Seeds of the kinds with versions this continuum doesn't read scanned beyond the cases
/// where none of those stopped a store, till one does.
const SCANNED_FOR_A_STOP: u64 = 1000;

/// Where parties propose versions this continuum doesn't read too, the store stops where
/// the model does: written in order, events come after what they build on, and both stop
/// at the same event, taking the same before it. Where none of the cases stops a store,
/// later seeds are scanned for one that does, which is checked too: a stop is checked
/// whatever the generator's luck.
#[test]
fn the_store_judges_and_reads_as_the_model() {
    let stopped = std::cell::Cell::new(0);
    let kinds = [
        (false, false, 48),
        (true, false, 48),
        (false, true, 32),
        (true, true, 32),
    ];
    let kind = |adversary, unread| Kind {
        adversary,
        checkpoints: false,
        unread,
    };
    for (adversary, unread, cases) in kinds {
        check(cases, kind(adversary, unread), |history| {
            if judged_as_the_model(history)? {
                stopped.set(stopped.get() + 1);
            }
            Ok(())
        });
    }
    // Past the seeds of the cases of the kinds with versions this continuum doesn't read.
    let mut seed = kinds
        .iter()
        .filter(|(_, unread, _)| *unread)
        .map(|(_, _, cases)| *cases)
        .max()
        .unwrap_or(0);
    while stopped.get() == 0 && seed < SCANNED_FOR_A_STOP {
        for adversary in [false, true] {
            let history = generate(&mut Rng::new(seed), kind(adversary, true));
            match judged_as_the_model(&history) {
                Ok(true) => stopped.set(stopped.get() + 1),
                Ok(false) => {}
                Err(why) => {
                    let (history, why) = cut_down(history, why, &|history: &History| {
                        judged_as_the_model(history).map(|_| ())
                    });
                    panic!("{why}, for seed {seed}, in the history\n{}", history.show());
                }
            }
        }
        seed += 1;
    }
    assert!(
        stopped.get() > 0,
        "no history of the first {SCANNED_FOR_A_STOP} seeds stopped a store"
    );
}

#[test]
fn what_builds_on_a_refused_event_is_refused() {
    check(
        48,
        Kind {
            adversary: true,
            checkpoints: true,
            unread: false,
        },
        |history| {
            let (store, _) = history.store(&history.written());
            for event in &history.events {
                let id = Id::of(event);
                let deps = Federation::dependencies(event).unwrap_or_default();
                if let Some(dep) = deps.iter().find(|dep| store.refusal(dep).is_some())
                    && store.refusal(&id).is_none()
                {
                    return Err(format!("{id} is taken, built on {dep}, which is refused"));
                }
            }
            Ok(())
        },
    );
}

#[test]
fn honest_parties_read_the_same_whatever_order_events_come_in() {
    check(
        32,
        Kind {
            adversary: false,
            checkpoints: true,
            unread: false,
        },
        |history| {
            let held = holds(&history.store(&history.written()).0);
            let mut rng = Rng::new(history.events.len() as u64);
            let mut orders = vec![history.written().into_iter().rev().collect::<Vec<usize>>()];
            for _ in 0..3 {
                let mut order = history.written();
                rng.shuffle(&mut order);
                orders.push(order);
            }
            for order in orders {
                if holds(&history.store(&order).0) != held {
                    return Err(format!(
                        "offered in the order {order:?}, a store holds otherwise"
                    ));
                }
            }
            Ok(())
        },
    );
}

/// The events of a history put into a document by two writers, in batches of a shuffled
/// order, some by both at once, the writers merging now and then; a node reads its store
/// from each writer's document as it grows, and once more after both merged.
#[test]
fn a_store_read_from_its_document_holds_what_one_given_the_events_alone_holds() {
    check(
        24,
        Kind {
            adversary: false,
            checkpoints: true,
            unread: false,
        },
        |history| {
            let alone = holds(&history.store(&history.written()).0);
            let mut rng = Rng::new(history.events.len() as u64);
            let started = events::started(Federation::NAME, &history.root, &[]).expect("a root");
            let mut docs = [started.fork(), started.fork()];
            let holdings = [Holding::default(), Holding::default()];
            let read = |holdings: &[Holding; 2], docs: &[_; 2]| {
                for (holding, doc) in holdings.iter().zip(docs) {
                    holding.read(holding.unread(doc, 0).expect("a store"));
                }
            };
            let mut order = history.written();
            rng.shuffle(&mut order);
            let mut rest = order.as_slice();
            while !rest.is_empty() {
                let (batch, after) = rest.split_at(rng.between(1, 4).min(rest.len()));
                rest = after;
                let batch: Vec<&[u8]> = batch.iter().map(|&i| &history.events[i][..]).collect();
                let at = usize::from(rng.chance(0.5));
                events::put(&mut docs[at], &batch);
                if rng.chance(0.2) {
                    events::put(&mut docs[1 - at], &batch);
                }
                if rng.chance(0.3) {
                    let [one, other] = &mut docs;
                    one.merge(other).expect("merged");
                    other.merge(one).expect("merged");
                }
                read(&holdings, &docs);
            }
            let [one, other] = &mut docs;
            one.merge(other).expect("merged");
            other.merge(one).expect("merged");
            read(&holdings, &docs);
            for (n, holding) in holdings.iter().enumerate() {
                if holding.with(holds).as_ref() != Some(&alone) {
                    return Err(format!(
                        "the store read from writer {n}'s document holds otherwise than one \
                         given the events alone"
                    ));
                }
            }
            Ok(())
        },
    );
}

#[test]
fn after_a_checkpoint_the_store_judges_and_reads_as_the_whole_history() {
    check(
        48,
        Kind {
            adversary: false,
            checkpoints: true,
            unread: false,
        },
        |history| {
            let (store, _) = history.store(&history.written());
            // What the store refused as not above a checkpoint, and what builds on it, the
            // model is never given: it reads every history from the root, never moving.
            let mut beside = BTreeSet::new();
            let mut model = Model::new(&history.root);
            for event in &history.events {
                let id = Id::of(event);
                let deps = Federation::dependencies(event).unwrap_or_default();
                if store.refusal(&id) == Some(&Refusal::NotAbove)
                    || deps.iter().any(|dep| beside.contains(dep))
                {
                    beside.insert(id);
                    continue;
                }
                model.offer(event);
            }
            let taken = model.taken();
            for id in store.taken() {
                if !taken.contains(id) {
                    return Err(format!(
                        "{id} is taken after the checkpoint, not by the model"
                    ));
                }
            }
            if reads(&store) != model_reads(&model) {
                return Err(format!(
                    "the store reads {:?}, the whole history {:?}",
                    reads(&store),
                    model_reads(&model)
                ));
            }
            // Moving refused nothing that decided it: the version naming the checkpoint is
            // written there, its proposal held.
            let (at, _) = Federation::parts(store.checkpoint()).expect("a checkpoint");
            if !at.is_empty() {
                let held: Vec<Event> = store
                    .taken()
                    .iter()
                    .filter_map(|id| store.get(id).and_then(Event::read_taken))
                    .collect();
                let written: BTreeSet<Id> = held
                    .iter()
                    .filter_map(|event| match event {
                        Event::Version { version, .. } => Some(*version),
                        Event::Signed(_) => None,
                    })
                    .collect();
                let named = held.iter().any(|event| match event {
                    Event::Signed(signed) => match &signed.does {
                        Does::Proposal { hash, version } => {
                            written.contains(hash)
                                && Version::read(version).is_ok_and(|version| {
                                    version.checkpoint.as_deref() == Some(&at[..])
                                })
                        }
                        _ => false,
                    },
                    Event::Version { .. } => false,
                });
                if !named {
                    return Err("the version naming the checkpoint isn't taken".to_owned());
                }
            }
            Ok(())
        },
    );
}

#[test]
fn every_version_a_store_takes_was_passed_by_two_thirds_in_its_history() {
    check(
        48,
        Kind {
            adversary: true,
            checkpoints: false,
            unread: false,
        },
        |history| {
            let (store, _) = history.store(&history.written());
            let first = Checkpoint::read(&history.root).expect("a root").version;
            for id in store.taken() {
                let Some(Event::Version { deps, version }) =
                    store.get(id).and_then(Event::read_taken)
                else {
                    continue;
                };
                // Its history, read from what the store holds.
                let mut seen = BTreeSet::new();
                let mut todo = deps.clone();
                let mut events = Vec::new();
                while let Some(dep) = todo.pop() {
                    if let Some(bytes) = store.get(&dep)
                        && seen.insert(dep)
                    {
                        let event = Event::read_taken(bytes).expect("an event");
                        todo.extend_from_slice(event.deps());
                        events.push(event);
                    }
                }
                let proposed = |hash: &Id| {
                    events.iter().find_map(|event| match event {
                        Event::Signed(signed) => match &signed.does {
                            Does::Proposal {
                                hash: proposed,
                                version,
                            } if proposed == hash => Version::read(version).ok(),
                            _ => None,
                        },
                        Event::Version { .. } => None,
                    })
                };
                let next = proposed(&version).ok_or(format!("{id}: no proposal in its history"))?;
                let changed = match next.changes {
                    Some(hash) if hash == first.hash => first.clone(),
                    Some(hash) => proposed(&hash).ok_or(format!("{id}: no version it changes"))?,
                    None => return Err(format!("{id}: a first version written")),
                };
                let yes: BTreeSet<&str> = events
                    .iter()
                    .filter_map(|event| match event {
                        Event::Signed(signed) => match signed.does {
                            Does::Vote {
                                on,
                                proposal,
                                yes: true,
                            } if on == changed.hash && proposal == version => {
                                Some(signed.party.as_str())
                            }
                            _ => None,
                        },
                        Event::Version { .. } => None,
                    })
                    .collect();
                if 3 * yes.len() < 2 * changed.parties.len() {
                    return Err(format!(
                        "{id}: written with {} of {} parties",
                        yes.len(),
                        changed.parties.len()
                    ));
                }
            }
            Ok(())
        },
    );
}

#[test]
fn without_a_party_voting_twice_no_two_versions_change_one() {
    check(
        48,
        Kind {
            adversary: false,
            checkpoints: true,
            unread: false,
        },
        |history| {
            let (store, _) = history.store(&history.written());
            if let Some((id, _)) = store.refused().find(|(_, why)| **why == Refusal::Own) {
                return Err(format!("{id}: a version changing one another changes"));
            }
            Ok(())
        },
    );
}

/// A fork at the heads of a history's first half, by the version current there, numbered
/// one past it and changing it: its root keeps what counts at those heads, with its
/// version current; it takes nothing else of the history; and the store it came from
/// takes nothing built on the fork's root.
#[test]
fn a_fork_keeps_what_counts_at_its_heads_and_takes_nothing_of_the_other() {
    check(
        32,
        Kind {
            adversary: false,
            checkpoints: false,
            unread: false,
        },
        |history| {
            let (mut whole, _) = history.store(&history.written());
            let half: Vec<usize> = (0..history.events.len() / 2).collect();
            let (at, _) = history.store(&half);
            let heads = at.heads();
            let current = at.state().current();
            let super::jcs::Json::Object(mut members) = current
                .json
                .without("number")
                .without("changes")
                .without("checkpoint")
            else {
                return Err("a version that is no object".to_owned());
            };
            members.push((
                "number".to_owned(),
                super::jcs::Json::Int(current.number as i64 + 1),
            ));
            members.push((
                "changes".to_owned(),
                super::jcs::Json::Str(current.hash.to_string()),
            ));
            let spec = super::jcs::Json::object(members).expect("names once each");
            let (root, kept) = whole
                .fork(&heads, &spec.bytes())
                .map_err(|why| format!("no fork at {heads:?}: {}", why.0))?;
            let mut fork: Store<Federation> =
                Store::new(root.clone(), kept).map_err(|why| format!("no root: {}", why.0))?;
            if fork.state().current().hash != Id::of(&spec.bytes()) {
                return Err("the fork's version isn't current at its root".to_owned());
            }
            if fork.state().values() != at.state().values()
                || fork.state().members() != at.state().members()
            {
                return Err("the fork's root doesn't keep what counts at its heads".to_owned());
            }
            for event in &history.events {
                if let Offered::Taken(ids) = fork.offer(event.clone()) {
                    return Err(format!("the fork takes {ids:?} of the history"));
                }
            }
            let on_the_fork = harness::version_event(&[Id::of(&root)], Id::of(b"a version"));
            if matches!(whole.offer(on_the_fork), Offered::Taken(_)) {
                return Err("the store it came from takes what builds on the fork".to_owned());
            }
            Ok(())
        },
    );
}

/// The parties of a history, with the keys its first version names: those sign its
/// votes and proposals throughout, as no generated version changes them.
fn parties(history: &History) -> Vec<Party> {
    let first = Checkpoint::read(&history.root).expect("a root").version;
    (0..first.parties.len())
        .map(|i| Party::new(&format!("p{i}"), i as u8 + 1))
        .collect()
}

/// What the node voting by itself for a party sees and goes by: which events it held for
/// a while, which when it started, and its operator's rules.
struct Voting {
    party: Party,
    rules: Rules,
    long: BTreeSet<Id>,
    from_start: BTreeSet<Id>,
}

impl Voting {
    /// A node voting for `party`, following the others, as it may see `history`: each
    /// event held for a while or new, more often than not held when it started or none.
    fn new(rng: &mut Rng, history: &History, party: &Party, others: &[Party]) -> Voting {
        let ids = || history.events.iter().map(|event| Id::of(event));
        let old = rng.next_f64();
        let started = if rng.chance(0.5) { rng.next_f64() } else { 0.0 };
        Voting {
            party: Party::new(&party.name, party.key.to_bytes()[0]),
            rules: Rules {
                follow: others
                    .iter()
                    .filter(|other| other.name != party.name && rng.chance(0.7))
                    .map(|other| other.name.clone())
                    .collect(),
                follow_any: rng.chance(0.5),
                propose_events: Some(1),
                held_for: std::time::Duration::from_secs(60),
                ..Rules::default()
            },
            long: ids().filter(|_| rng.chance(old)).collect(),
            from_start: ids().filter(|_| rng.chance(started)).collect(),
        }
    }

    /// Its party's record, as restored from `store`: its votes on the current version, and
    /// the events proposing on it that it signed.
    fn record(&self, store: &Store<Federation>) -> Record {
        let state = store.state();
        let current = state.current();
        let mut record = Record::before(store.id(), &self.party.name);
        for ballot in state.ballots(&current.hash).values() {
            let votes: Vec<Vec<u8>> = ballot
                .votes
                .iter()
                .filter_map(|id| store.get(id).map(<[u8]>::to_vec))
                .collect();
            record.restore(current, &votes);
            for bytes in ballot.proposals.iter().filter_map(|id| store.get(id)) {
                if let Some(Event::Signed(signed)) = Event::read_taken(bytes)
                    && signed.party == self.party.name
                {
                    record.signed(bytes);
                }
            }
        }
        record
    }

    /// What it signs now, as `Holding::sign` does: its votes on what `vote::builds_on`
    /// says, a checkpoint's proposal on the heads it names. An error where a vote its rules
    /// cast builds on nothing its store takes it on.
    fn signs(&self, store: &Store<Federation>, record: &Record) -> Result<Vec<Vec<u8>>, String> {
        let hour = std::time::Duration::from_secs(3600);
        let held = |id: &Id| {
            Some(if self.long.contains(id) {
                hour
            } else {
                std::time::Duration::ZERO
            })
        };
        let from_start = |id: &Id| self.from_start.contains(id);
        let seen = Seen {
            store,
            held: &held,
            from_start: &from_start,
            since_move: hour,
        };
        let current = store.state().current().hash;
        let mut signed = Vec::new();
        for act in vote::decide(&seen, &self.rules, record) {
            match act {
                Act::Vote {
                    proposal,
                    yes,
                    nays,
                } => {
                    let on = vote::builds_on(store, &self.party.name, &proposal, yes, &nays)
                        .map_err(|why| {
                            format!(
                                "{}'s node casts {yes} on {proposal}, and builds it on nothing: \
                                 {why}",
                                self.party.name
                            )
                        })?;
                    signed.push(self.party.vote(&on, current, proposal, yes));
                }
                Act::Propose(version) => {
                    let at = Version::read(&version)
                        .ok()
                        .and_then(|version| version.checkpoint)
                        .unwrap_or_else(|| store.building_on());
                    signed.push(self.party.propose(&at, &version));
                }
            }
        }
        Ok(signed)
    }

    /// Signs as `signs`, and offers it to `store`: the proposals it backs with a `true`
    /// then, its own, proposed now, among them, which it backs next. An error where the
    /// store takes one not, or where it backs its own proposal not.
    fn acts(&self, store: &mut Store<Federation>) -> Result<Vec<Id>, String> {
        let name = &self.party.name;
        let mut backs = Vec::new();
        let mut proposed = None;
        for round in 0..2 {
            let record = self.record(store);
            for bytes in self.signs(store, &record)? {
                let id = Id::of(&bytes);
                let offered = store.offer(bytes.clone());
                if !matches!(offered, Offered::Taken(_)) {
                    return Err(format!(
                        "{name}'s node casts {}, and its store says {offered:?}",
                        String::from_utf8_lossy(&bytes)
                    ));
                }
                match Event::read_taken(&bytes) {
                    Some(Event::Signed(Signed {
                        does: Does::Proposal { hash, .. },
                        ..
                    })) => proposed = Some(hash),
                    Some(Event::Signed(Signed {
                        does:
                            Does::Vote {
                                proposal,
                                yes: true,
                                ..
                            },
                        ..
                    })) => backs.push(proposal),
                    _ => return Err(format!("{name}'s node signs {id}, no vote or proposal")),
                }
            }
            match proposed {
                Some(hash) if round == 1 && !backs.contains(&hash) => {
                    return Err(format!("{name}'s node proposes {hash}, and backs it not"));
                }
                Some(_) => {}
                None => break,
            }
        }
        Ok(backs)
    }
}

/// A version changing `current`: naming `checkpoint`, with a rule giving `rule`'s path to
/// its party, or both.
fn next(current: &Version, checkpoint: Option<&[Id]>, rule: Option<(&str, &str)>) -> Option<Json> {
    let Json::Object(mut members) = current
        .json
        .without("number")
        .without("changes")
        .without("checkpoint")
    else {
        return None;
    };
    members.push(("number".to_owned(), Json::Int(current.number as i64 + 1)));
    members.push(("changes".to_owned(), Json::Str(current.hash.to_string())));
    if let Some(heads) = checkpoint {
        members.push(("checkpoint".to_owned(), harness::ids(heads)));
    }
    if let Some((path, writer)) = rule {
        let mut rules = current
            .json
            .get("rules")
            .and_then(Json::as_array)
            .map(<[Json]>::to_vec)
            .unwrap_or_default();
        rules.push(harness::object(vec![
            ("path", harness::str(path)),
            ("writer", harness::str(writer)),
        ]));
        members.retain(|(name, _)| name != "rules");
        members.push(("rules".to_owned(), Json::Array(rules)));
    }
    Json::object(members)
}

/// The parties that haven't yet back the proposal of hash `backed`, on the version
/// current in `store`, by hand: as many as their records and the store let, each on what
/// `vote::builds_on` says, their votes added to `events`. An error where the store takes
/// such a vote not.
fn backed_by_the_rest(
    store: &mut Store<Federation>,
    nodes: &[Voting],
    backed: Id,
    events: &mut Vec<Vec<u8>>,
) -> Result<(), String> {
    let current = store.state().current().clone();
    for other in nodes {
        let state = store.state();
        let Some(json) = state.proposal(&backed).cloned() else {
            continue;
        };
        let nays: Vec<Vec<u8>> = state
            .ballots(&current.hash)
            .values()
            .flat_map(|ballot| &ballot.votes)
            .filter_map(|id| store.get(id).map(<[u8]>::to_vec))
            .collect();
        let name = &other.party.name;
        let Ok(kept) = other
            .record(store)
            .may_vote(&current, backed, &json, true, &nays)
        else {
            continue;
        };
        let Ok(on) = vote::builds_on(store, name, &backed, true, &kept) else {
            continue;
        };
        let bytes = other.party.vote(&on, current.hash, backed, true);
        events.push(bytes.clone());
        let offered = store.offer(bytes);
        if !matches!(offered, Offered::Taken(_)) {
            return Err(format!(
                "{name} backs {backed} as its node says, and the store says {offered:?}"
            ));
        }
    }
    Ok(())
}

/// Writes the proposal of hash `proposal`, on the version current in `store`, as a node
/// does, by the event `State::version_event` gives, added to `events`: whether the store
/// takes it. An error where it is taken and the version isn't current then; or where none
/// is given, or the store takes it not, and some votes make a version event it takes:
/// every choice of a `true` of each party is tried, as many as pass it or more.
fn one_is_written(
    store: &mut Store<Federation>,
    proposal: Id,
    events: &mut Vec<Vec<u8>>,
) -> Result<bool, String> {
    let state = store.state();
    let current = state.current().clone();
    let needed = (2 * current.parties.len()).div_ceil(3);
    let written = state.version_event(&proposal);
    // Each party's `true`s on it.
    let mut yes: BTreeMap<String, Vec<Id>> = BTreeMap::new();
    for id in state
        .ballots(&current.hash)
        .get(&proposal)
        .map(|ballot| ballot.votes.clone())
        .unwrap_or_default()
    {
        if let Some(Event::Signed(Signed {
            party,
            does: Does::Vote { yes: true, .. },
            ..
        })) = store.get(&id).and_then(Event::read_taken)
        {
            yes.entry(party).or_default().push(id);
        }
    }
    if let Some(bytes) = &written {
        events.push(bytes.clone());
        if matches!(store.offer(bytes.clone()), Offered::Taken(_)) {
            return if store.state().current().hash == proposal {
                Ok(true)
            } else {
                Err(format!("{proposal} is written, and isn't current"))
            };
        }
    }
    if yes.len() < needed {
        return Ok(false);
    }
    // Every choice: of each party none of its votes, or one.
    let mut choices: Vec<Vec<Id>> = vec![Vec::new()];
    for votes in yes.values() {
        choices = choices
            .into_iter()
            .flat_map(|chosen| {
                std::iter::once(chosen.clone()).chain(votes.iter().map(move |vote| {
                    let mut with = chosen.clone();
                    with.push(*vote);
                    with
                }))
            })
            .collect();
    }
    for mut deps in choices {
        deps.sort_unstable();
        if deps.len() >= needed
            && matches!(
                store.offer(harness::version_event(&deps, proposal)),
                Offered::Taken(_)
            )
        {
            return Err(match &written {
                None => format!(
                    "a version event on {deps:?} writes {proposal}, and `version_event` \
                     returns none"
                ),
                Some(bytes) => format!(
                    "a version event on {deps:?} writes {proposal}, and the store refuses \
                     the one `version_event` returns, {}",
                    Id::of(bytes)
                ),
            });
        }
    }
    Ok(false)
}

/// The most steps a history is gone on with.
const STEPS: usize = 24;

/// A history gone on with, and how its nodes got on: the first of each that came up.
struct Went {
    history: History,
    nodes: Vec<Voting>,
    /// How many of the history's events it was gone on with after: all, or none.
    kept: usize,
    /// A node cast by itself what its store took not.
    cast: Result<(), String>,
    /// What a node backed by itself passed, by votes on events a vote may build on, and
    /// no version event the store takes writes it.
    backed: Result<(), String>,
    /// Some votes make a version event the store takes, and `State::version_event`
    /// returns none it takes.
    written: Result<(), String>,
}

/// A history gone on with, seeded by its bytes, half the time from its root alone, where
/// no party is bound by a vote yet. Step by step: a party's node votes by itself, time
/// passing for it now and then; or a party, by hand, proposes a checkpoint at heads of its
/// choosing, some no version may name, on them or beside them, backing it more often than
/// not, another party proposing it again now and then where it writes, and backing it
/// there; proposes a change; proposes again what is proposed; votes as its record lets,
/// on any event proposing what it votes on; or writes. Now and then the parties that
/// haven't yet back what was backed too (`backed_by_the_rest`). After each step, a node
/// writes what passed (`one_is_written`).
fn gone_on(base: &History) -> Went {
    let parties = parties(base);
    let all: Vec<u8> = std::iter::once(&base.root)
        .chain(&base.events)
        .flatten()
        .copied()
        .collect();
    let seed = u64::from_str_radix(&Id::of(&all).to_string()[..16], 16).unwrap_or_default();
    let mut rng = Rng::new(seed);
    // Half from the root alone, where no party is bound by a vote yet.
    let base = &History {
        root: base.root.clone(),
        events: if rng.chance(0.5) {
            Vec::new()
        } else {
            base.events.clone()
        },
    };
    let kept = base.events.len();
    let mut nodes: Vec<Voting> = parties
        .iter()
        .map(|party| Voting::new(&mut rng, base, party, &parties))
        .collect();
    let mut history = base.clone();
    let (mut store, _) = base.store(&base.written());
    let (mut cast, mut backed, mut written) = (Ok(()), Ok(()), Ok(()));
    // The proposals a node backed by itself; and those with a `true` on an event proposing
    // them that a vote may not build on, which counts for passing, and no version event
    // is written on.
    let mut by_nodes = BTreeSet::new();
    let mut beside = BTreeSet::new();
    'steps: for step in 0..rng.between(4, STEPS) {
        let w = rng.below(parties.len());
        let party = &parties[w];
        let current = store.state().current().clone();
        let taken = store.taken().to_vec();
        let ballots = store.state().ballots(&current.hash);
        let nays: Vec<Vec<u8>> = ballots
            .values()
            .flat_map(|ballot| &ballot.votes)
            .filter_map(|id| store.get(id).map(<[u8]>::to_vec))
            .collect();
        let roll = rng.below(100);
        let by_node = roll < 35;
        let signed: Vec<Vec<u8>> = if by_node {
            if rng.chance(0.5) {
                nodes[w].long.extend(taken.iter().copied());
            }
            let record = nodes[w].record(&store);
            match nodes[w].signs(&store, &record) {
                Ok(signed) => signed,
                Err(why) => {
                    cast = Err(why);
                    break;
                }
            }
        } else if roll < 58 && !taken.is_empty() {
            let mut heads = if rng.chance(0.4) {
                store.heads()
            } else {
                vec![*rng.pick(&taken)]
            };
            if rng.chance(0.2) {
                heads.push(*rng.pick(&taken));
            }
            heads.sort_unstable();
            heads.dedup();
            let on = if rng.chance(0.7) {
                heads.clone()
            } else {
                store.building_on()
            };
            // Its proposer backs it, more often than not, where its record lets; and now
            // and then another party proposes it again where it writes, beside the heads,
            // say, and backs it there.
            let backs = rng.chance(0.7);
            let again = rng.chance(0.5).then(|| rng.below(parties.len()));
            let beside = store.building_on();
            next(&current, Some(&heads), None)
                .map(|version| {
                    let hash = Id::of(&version.bytes());
                    let mut signed = Vec::new();
                    let mut propose = |by: usize, on: &[Id], backs: bool| {
                        let proposing = parties[by].propose(on, &version);
                        let vote = nodes[by]
                            .record(&store)
                            .may_vote(&current, hash, &version, true, &nays)
                            .ok()
                            .filter(|_| backs)
                            .map(|_| {
                                parties[by].vote(&[Id::of(&proposing)], current.hash, hash, true)
                            });
                        signed.push(proposing);
                        signed.extend(vote);
                    };
                    propose(w, &on, backs);
                    if let Some(other) = again.filter(|other| *other != w) {
                        propose(other, &beside, true);
                    }
                    signed
                })
                .unwrap_or_default()
        } else if roll < 63 {
            next(
                &current,
                None,
                Some((&format!("names/w{step}"), &party.name)),
            )
            .map(|version| party.propose(&store.building_on(), &version))
            .into_iter()
            .collect()
        } else if roll < 68 && !ballots.is_empty() {
            // Proposed again, where the party writes now: beside a checkpoint's heads, say.
            let hashes: Vec<Id> = ballots.keys().copied().collect();
            store
                .state()
                .proposal(rng.pick(&hashes))
                .map(|version| party.propose(&store.building_on(), version))
                .into_iter()
                .collect()
        } else if roll < 87 && !ballots.is_empty() {
            let hashes: Vec<Id> = ballots.keys().copied().collect();
            let hash = *rng.pick(&hashes);
            let yes = rng.chance(0.6);
            let json = store.state().proposal(&hash).cloned();
            let checkpoint = json
                .as_ref()
                .and_then(|json| Version::read(json).ok())
                .is_some_and(|version| version.checkpoint.is_some());
            let kept = json.and_then(|json| {
                nodes[w]
                    .record(&store)
                    .may_vote(&current, hash, &json, yes, &nays)
                    .ok()
            });
            match (kept, ballots[&hash].proposals.as_slice()) {
                (Some(kept), proposing) if !proposing.is_empty() => {
                    super::client::building(*rng.pick(proposing), checkpoint, &kept)
                        .map(|on| party.vote(&on, current.hash, hash, yes))
                        .into_iter()
                        .collect()
                }
                _ => Vec::new(),
            }
        } else if roll < 94 {
            let deps = if taken.is_empty() || rng.chance(0.6) {
                store.building_on()
            } else {
                vec![*rng.pick(&taken)]
            };
            vec![party.write(
                &deps,
                &format!("home/{}/w", party.name),
                harness::str(&step.to_string()),
            )]
        } else {
            ballots
                .keys()
                .filter_map(|hash| store.state().version_event(hash))
                .collect()
        };
        let mut by_hand = Vec::new();
        for bytes in signed {
            let offered = store.offer(bytes.clone());
            let vote = match Event::read_taken(&bytes) {
                Some(Event::Signed(Signed {
                    deps,
                    does:
                        Does::Vote {
                            proposal,
                            yes: true,
                            ..
                        },
                    ..
                })) => Some((proposal, deps)),
                _ => None,
            };
            history.events.push(bytes.clone());
            if !by_node {
                by_hand.extend(vote);
                continue;
            }
            if !matches!(offered, Offered::Taken(_)) {
                cast = Err(format!(
                    "{}'s node casts {}, and its store says {offered:?}",
                    party.name,
                    String::from_utf8_lossy(&bytes)
                ));
                break 'steps;
            }
            if let Some((proposal, _)) = vote {
                by_nodes.insert(proposal);
                if rng.chance(0.5)
                    && let Err(why) =
                        backed_by_the_rest(&mut store, &nodes, proposal, &mut history.events)
                {
                    backed = Err(why);
                    break 'steps;
                }
            }
        }
        // Now and then the rest back by hand what a party backed by hand.
        if let Some((proposal, _)) = by_hand.first()
            && rng.chance(0.3)
            && let Err(why) = backed_by_the_rest(&mut store, &nodes, *proposal, &mut history.events)
        {
            backed = Err(why);
            break 'steps;
        }
        if store.state().current().hash != current.hash {
            continue;
        }
        for (proposal, deps) in by_hand {
            let proposing = store.state().proposing(&current.hash, &proposal);
            if !deps.iter().any(|dep| proposing.contains(dep)) {
                beside.insert(proposal);
            }
        }
        for proposal in store.state().ballots(&current.hash).into_keys() {
            match one_is_written(&mut store, proposal, &mut history.events) {
                Err(why) => {
                    written = Err(why);
                    break 'steps;
                }
                Ok(true) => break,
                Ok(false) => {
                    if by_nodes.contains(&proposal)
                        && !beside.contains(&proposal)
                        && store.state().tally(&current, &proposal).passed
                    {
                        backed = Err(format!(
                            "{proposal}, which a node backs by itself, passed, and no version \
                             event the store takes writes it"
                        ));
                        break 'steps;
                    }
                }
            }
        }
    }
    Went {
        history,
        nodes,
        kept,
        cast,
        backed,
        written,
    }
}

/// Checks on the histories of `cases` seeds, with an adversary and without, each gone on
/// with (`gone_on`), what `got_on` says of how its nodes got on; a failing history is cut
/// down and printed, with what it was gone on with.
fn check_going_on(cases: u64, got_on: impl Fn(&Went) -> Result<(), String>) {
    for adversary in [false, true] {
        check(
            cases,
            Kind {
                adversary,
                checkpoints: true,
                unread: false,
            },
            |base| {
                let went = gone_on(base);
                got_on(&went).map_err(|why| {
                    let after: Vec<String> = went.history.events[went.kept..]
                        .iter()
                        .map(|event| {
                            format!("{} {}", Id::of(event), String::from_utf8_lossy(event))
                        })
                        .collect();
                    format!(
                        "{why}; gone on with\n{}\nafter the first {} events of",
                        after.join("\n"),
                        went.kept
                    )
                })
            },
        );
    }
}

/// What a node's rules cast, its own store takes: a vote or a proposal it signs by itself
/// that its store refuses binds its party by its record, and counts nowhere. And it backs
/// the checkpoint it proposes.
#[test]
fn what_a_node_casts_by_itself_its_store_takes() {
    check_going_on(32, |went| {
        went.cast.clone()?;
        // And after: one of the nodes, each history another's.
        let node = &went.nodes[went.history.events.len() % went.nodes.len()];
        let (mut store, _) = went.history.store(&went.history.written());
        node.acts(&mut store).map(|_| ())
    });
}

/// What a node's rules back, a version event can name: where the parties that may back it
/// too, each on an event a vote may build on, and it passes, a node writes it, by the
/// event `State::version_event` gives, which the store takes.
#[test]
fn what_a_node_backs_by_itself_is_written_once_it_passes() {
    check_going_on(32, |went| went.backed.clone());
}

/// Where some votes make a version event a store takes, `State::version_event` returns
/// one it takes, and the version it writes is current.
#[test]
fn where_votes_make_a_version_event_one_is_written() {
    check_going_on(32, |went| went.written.clone());
}