beekem 0.9.0

BeeKEM: a concurrent variant of TreeKEM for Continuous Group Key Agreement
Documentation
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
//! BeeKEM tree: a concurrent variant of TreeKEM for Continuous Group Key Agreement.

use crate::{
    collections::Set,
    error::CgkaError,
    id::{MemberId, TreeId},
    keys::{NodeKeys, ShareKeyMap},
    node_versions::{NodeVersions, VersionOrigin},
    pcs_key::PcsKey,
    secret_store::{PathNode, SecretStore},
    treemath,
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    vec,
    vec::Vec,
};
use keyhive_codec::{
    error::DecodeError,
    prefixed::{decode_len, encode_len},
    traits::{decode_exact, Decode, Encode, StreamDecode},
};
use keyhive_crypto::share_key::{ShareKey, ShareSecretKey};
use nonempty::NonEmpty;
use tracing::instrument;
use treemath::{InnerNodeIndex, LeafNodeIndex, TreeNodeIndex, TreeSize};

/// The [`SecretStore`] versions at an inner node.
pub type InnerNode = NodeVersions<SecretStore>;

const TREE_INDEX_LIMIT: u32 = 1 << 31;

/// A tree of 2^31 leaves has 32 levels, the max that can fit in a `u32` tree
/// index.
const MAX_PATH_LEN: usize = 31;

/// A PathChange represents an update along a path from a leaf to the root.
/// This includes both the leaf's new public key and a new secret store for
/// each inner node on the path.
///
/// The leaf is the signer's: whoever signs the update rotates their own leaf.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct PathChange {
    pub leaf_idx: u32,
    /// The leaf's new key. An update rotates its leaf to one fresh key.
    pub leaf_pk: ShareKey,
    /// Each inner node on the path with what this update puts there.
    pub path: Vec<(u32, PathNode)>,
}

/// `leaf_idx ‖ leaf_pk ‖ count ‖ ( inner_idx ‖ path_node )*`, the path in
/// its order.
impl Encode for PathChange {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.leaf_idx.encode_into(out);
        self.leaf_pk.encode_into(out);
        encode_len(self.path.len(), out);
        for (idx, node) in &self.path {
            idx.encode_into(out);
            node.encode_into(out);
        }
    }
}

impl Decode for PathChange {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for PathChange {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (leaf_idx, rest) = u32::decode_next(bytes)?;
        let (leaf_pk, rest) = ShareKey::decode_next(rest)?;
        let (count, mut rest) = decode_len(rest)?;
        let mut path = Vec::new();
        for _ in 0..count {
            let (idx, after) = u32::decode_next(rest)?;
            let (node, after) = PathNode::decode_next(after)?;
            path.push((idx, node));
            rest = after;
        }
        Ok((
            PathChange {
                leaf_idx,
                leaf_pk,
                path,
            },
            rest,
        ))
    }
}

impl PathChange {
    /// Whether the path's structure is well-formed.
    ///
    /// The path is not empty. Each node is the parent of the one below it,
    /// starting from the leaf, and the last is the root of a tree of some size.
    ///
    /// Every node on the path has an entry under the child below it, which
    /// encrypted it with its new key. No new node key repeats any other new
    /// key. The leaf index is below 2^31, past which it has no tree index.
    ///
    /// This does not check that the entries were encrypted with the leaf key or
    /// that they decrypt to the node keys.
    pub fn is_well_formed(&self) -> bool {
        if self.leaf_idx >= TREE_INDEX_LIMIT || self.path.len() > MAX_PATH_LEN {
            return false;
        }
        let mut new_keys = BTreeSet::from([self.leaf_pk]);
        let mut child = TreeNodeIndex::Leaf(LeafNodeIndex::new(self.leaf_idx));
        for (idx, node) in &self.path {
            let parent = treemath::parent(child);
            if *idx != parent.u32() || !node.sk.contains_key(&child) || !new_keys.insert(node.pk) {
                return false;
            }
            child = TreeNodeIndex::Inner(parent);
        }
        // The roots are the tree indices 2^k - 1, which are the inner indices
        // 2^(k-1) - 1. An empty path has no last node, so it is malformed.
        self.path
            .last()
            .is_some_and(|(idx, _)| (idx + 1).is_power_of_two())
    }

    /// The secret store for each node on the path, with its inner node index.
    /// Each node's encrypter is the next key down the path.
    pub(crate) fn secret_stores(&self) -> impl Iterator<Item = (u32, SecretStore)> + '_ {
        let encrypters =
            core::iter::once(self.leaf_pk).chain(self.path.iter().map(|(_, node)| node.pk));
        self.path
            .iter()
            .zip(encrypters)
            .map(|((idx, node), encrypter_pk)| {
                let store = SecretStore {
                    pk: node.pk,
                    sk: node.sk.clone(),
                    encrypter_pk,
                };
                (*idx, store)
            })
    }

    /// Attempt to decrypt the root secret using only the information in this path
    /// (without the complete tree state corresponding to this update) and the secrets
    /// in `sks`.
    ///
    /// Starting from the root, work backwards down the path until we find an
    /// intersecting node for which we have its child's sibling secret. If one
    /// is found, then decrypt back up the path toward the root. If not, return
    /// `None`.
    pub(crate) fn decrypt_root_secret(
        &self,
        doc_id: TreeId,
        sks: &ShareKeyMap,
    ) -> Option<ShareSecretKey> {
        let stores: Vec<_> = self.secret_stores().map(|(_, store)| store).collect();
        let (intersection_idx, mut secret) =
            stores.iter().enumerate().rev().find_map(|(i, store)| {
                store
                    .decrypt_with_sibling_secret(doc_id, sks)
                    .map(|sk| (i, sk))
            })?;
        for store in &stores[intersection_idx + 1..] {
            secret = store.decrypt_with_child_secret(doc_id, &secret)?;
        }
        Some(secret)
    }
}

/// The outcome of applying an update's path to the tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApplyPathOutcome {
    /// The path was valid from the signer's leaf and is now in the tree.
    Applied,
    /// The path was not valid from the signer's leaf. Only the leaf was
    /// updated and the signer's direct path was blanked.
    BlankedPath,
    /// The signer has no leaf, e.g., after a concurrent remove. There was
    /// no change.
    NoLeafToUpdate,
}

/// BeeKEM is our variant of the [TreeKEM] protocol (used in [MLS]) and inspired by
/// [Matthew Weidner's Causal TreeKEM][Causal TreeKEM]. The distinctive
/// feature of BeeKEM is that when merging concurrent updates, we keep all concurrent
/// public keys at any inner node where there is a conflict (until they are overwritten
/// by a future update along that path). The conflict keys are used to ensure
/// that a passive adversary needs all of the historical secret keys at
/// one of the leaves in order to read the latest root secret after a merge.
///
/// A leaf keeps its concurrent keys in the same way. A leaf belongs to one identity,
/// so a conflict there is between instances of the same member. Unlike a conflicted
/// inner node, such a leaf stays in its parent's resolution, and every encrypter
/// encrypts to its lowest key.
///
/// Each version at a tree node is tagged with the operations that generated it
/// An update drops the origins in its causal past from the versions at its nodes
/// and removes any version left with none, so which versions it removes depends
/// only on which operations were applied, not on the order a replica received
/// them in.
///
/// Leaf nodes represent group members. Each member has a fixed identifier as well
/// as a public key that is rotated over time. Each inner node stores one or more
/// public keys and an encrypted secret used for (deriving a shared key for) decrypting
/// its parent.
///
/// During a key rotation, a leaf will update its public key and then encrypt its path
/// to the root. For each parent it attempts to encrypt, it will encounter one of a few
/// cases:
/// * In the "normal" case, the child's sibling will have a single public key and a
///   corresponding secret key. The child uses the public key of its sibling to derive
///   a shared Diffie Hellman (DH) secret. It then uses this shared DH secret to
///   encrypt the new parent secret.
/// * In case of a blank or conflict sibling, the encrypting child encrypts the secret
///   for each of the nodes in its sibling's resolution (which is the set of the highest
///   descendants of the sibling that are neither blank nor conflicted inner nodes). This means a separate DH per
///   node in that resolution. These encryptions of the secret are stored in a map at
///   the parent.
///
/// [Causal TreeKEM]: https://mattweidner.com/assets/pdf/acs-dissertation.pdf
/// [MLS]: https://messaginglayersecurity.rocks/
/// [TreeKEM]: https://inria.hal.science/hal-02425247/file/treekem+(1).pdf
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BeeKem {
    doc_id: TreeId,
    /// The next [`LeafNodeIndex`] available for adding a new member.
    next_leaf_idx: LeafNodeIndex,
    leaves: Vec<Option<LeafNode>>,
    inner_nodes: Vec<Option<InnerNode>>,
    tree_size: TreeSize,
    id_to_leaf_idx: BTreeMap<MemberId, LeafNodeIndex>,
}

impl BeeKem {
    pub fn new(doc_id: TreeId) -> Self {
        let mut tree = Self {
            doc_id,
            next_leaf_idx: LeafNodeIndex::new(0),
            leaves: Vec::new(),
            inner_nodes: Vec::new(),
            tree_size: TreeSize::from_leaf_count(1),
            id_to_leaf_idx: BTreeMap::new(),
        };
        tree.grow_tree_to_size();
        tree
    }

    pub fn contains_id(&self, id: &MemberId) -> bool {
        self.id_to_leaf_idx.contains_key(id)
    }

    /// The members currently in the tree.
    pub fn member_ids(&self) -> impl Iterator<Item = MemberId> + '_ {
        self.id_to_leaf_idx.keys().copied()
    }

    pub fn node_keys_for_id(&self, id: MemberId) -> Result<NodeKeys, CgkaError> {
        let idx = self.leaf_index_for_id(id)?;
        self.node_keys_for_index((*idx).into())
    }

    /// For concurrent membership changes, we need to ensure that removed paths
    /// are blanked and concurrently added member leaves are sorted (and their
    /// paths blanked) after any other concurrent operations were applied.
    ///
    /// Sorting concurrently added leaves deterministically resolves add conflicts
    /// (e.g., if two members concurrently add distinct members to the same leaf).
    pub fn sort_leaves_and_blank_paths_for_concurrent_membership_changes(
        &mut self,
        mut added_ids: Set<MemberId>,
        removed_ids: Set<(MemberId, u32)>,
    ) {
        let mut leaves_to_sort = Vec::new();
        for (id, idx) in removed_ids {
            added_ids.remove(&id);

            if let Some(leaf_idx) = self.id_to_leaf_idx.remove(&id) {
                self.blank_leaf_and_path(leaf_idx);
            }

            // The member is already gone, but a concurrent update along the
            // recorded path may have left keys it can still decrypt. The leaf
            // is now either blank or contains a different member. We only
            // blank its path.
            if (idx as usize) < self.leaves.len() {
                self.blank_path(treemath::parent(LeafNodeIndex::new(idx).into()));
            }
        }
        while !added_ids.is_empty() && self.next_leaf_idx.u32() > 0 {
            let leaf_idx = self.next_leaf_idx - 1;
            if let Some(next_leaf) = self.leaf(leaf_idx).clone() {
                added_ids.remove(&next_leaf.id);
                leaves_to_sort.push(next_leaf);
            }
            self.blank_leaf_and_path(leaf_idx);
            self.next_leaf_idx = leaf_idx;
        }
        // Reclaim trailing blanks before placing the sorted leaves.
        while self.next_leaf_idx.u32() > 0 && self.leaf(self.next_leaf_idx - 1).is_none() {
            self.blank_path(treemath::parent((self.next_leaf_idx - 1).into()));
            self.next_leaf_idx -= 1;
        }
        leaves_to_sort.sort_by_key(|a| a.id);
        for leaf in leaves_to_sort {
            self.push_leaf_node(leaf);
        }
    }

    /// Blank the leaf at the provided [`LeafNodeIndex`] as well as its path
    /// to the root.
    pub fn blank_leaf_and_path(&mut self, idx: LeafNodeIndex) {
        self.leaves[idx.usize()] = None;
        self.blank_path(treemath::parent(idx.into()));
    }

    /// Add member `id` to the tree with `pk` as its only leaf key, generated by
    /// the add `origin`. Returns the index of its leaf.
    pub fn add_leaf(&mut self, id: MemberId, pk: ShareKey, origin: VersionOrigin) -> u32 {
        self.push_leaf_node(LeafNode {
            id,
            versions: NodeVersions::new(NonEmpty::new(pk), origin),
        })
    }

    /// Place `leaf` at the first available [`LeafNodeIndex`] on the right and
    /// blank that leaf's path to the root. Returns the leaf's index.
    fn push_leaf_node(&mut self, leaf: LeafNode) -> u32 {
        self.maybe_grow_tree(self.next_leaf_idx.u32());
        let l_idx = self.next_leaf_idx;
        self.next_leaf_idx += 1;
        self.id_to_leaf_idx.insert(leaf.id, l_idx);
        self.leaves[l_idx.usize()] = Some(leaf);
        self.blank_path(treemath::parent(l_idx.into()));
        l_idx.u32()
    }

    /// Remove data for the provided [`MemberId`] and blank its leaf's
    /// path to the root. Returns the index of the leaf it held.
    pub fn remove_id(&mut self, id: MemberId) -> Result<u32, CgkaError> {
        let l_idx = *self.leaf_index_for_id(id)?;
        self.blank_leaf_and_path(l_idx);
        self.id_to_leaf_idx.remove(&id);
        // Collect any contiguous "tombstones" at the end of the leaves Vec.
        while self.next_leaf_idx.u32() > 0 && self.leaf(self.next_leaf_idx - 1).is_none() {
            self.blank_path(treemath::parent((self.next_leaf_idx - 1).into()));
            self.next_leaf_idx -= 1;
        }
        Ok(l_idx.u32())
    }

    /// The count of members currently in the tree.
    pub fn member_count(&self) -> u32 {
        self.id_to_leaf_idx.len() as u32
    }

    /// Decrypt the current tree secret.
    ///
    /// Starting from the owner's leaf, move up the tree toward the root (i.e., along the
    /// leaf's path). As you look at each parent node along the way, if the node is not
    /// blank, look up the encrypted secret in the parent's secret store using your child
    /// index. Derive a Diffie Hellman shared key using the encrypter public key stored in
    /// the secret store and use that shared key to decrypt the secret key you looked up.
    ///
    /// Hold on to each idx you've seen along the way since ancestors might have been
    /// encrypted for any of these descendents (in cases like a blank node or
    /// conflicting keys on a node on the path).
    #[instrument(skip_all, fields(doc_id, epochs))]
    pub fn decrypt_tree_secret(
        &self,
        owner_id: MemberId,
        owner_sks: &mut ShareKeyMap,
    ) -> Result<ShareSecretKey, CgkaError> {
        let leaf_idx = *self.leaf_index_for_id(owner_id)?;
        if !self.has_root_key() {
            return Err(CgkaError::NoRootKey);
        }
        let leaf = self
            .leaf(leaf_idx)
            .as_ref()
            .expect("Leaf should not be blank");
        let mut child_idx: TreeNodeIndex = leaf_idx.into();
        let mut seen_idxs = vec![child_idx];
        // We will return this at the end once we've decrypted the root secret.
        let mut maybe_last_secret_decrypted = None;
        let mut child_node_keys = leaf.versions.node_keys();
        let mut parent_idx: TreeNodeIndex = treemath::parent(child_idx).into();
        while !self.is_root(child_idx) {
            // Find the next non-blank, non-conflict parent
            while self.should_skip_for_resolution(parent_idx) {
                child_idx = parent_idx;
                parent_idx = treemath::parent(child_idx).into();
            }
            debug_assert!(!self.is_root(child_idx));
            maybe_last_secret_decrypted =
                self.maybe_decrypt_parent_key(child_idx, &child_node_keys, &seen_idxs, owner_sks)?;
            if maybe_last_secret_decrypted.is_none() {
                panic!("Non-blank, non-conflict parent should have a secret we can decrypt");
            }
            seen_idxs.push(parent_idx);
            child_idx = parent_idx;
            child_node_keys = self.node_keys_for_index(child_idx)?;
            parent_idx = treemath::parent(child_idx).into();
        }
        maybe_last_secret_decrypted.ok_or(CgkaError::NoRootKey)
    }

    /// Rotate `id`'s leaf to the key of `leaf_sk` and encrypt new secrets along
    /// its path. This returns the root secret, the [`PathChange`], and the new
    /// secret of each node on the path, without writing any of them to the tree.
    /// Applying the returned path with [`Self::apply_path`] installs a new root
    /// secret in the tree.
    ///
    /// Starting from the owner's leaf, move up the tree toward the root (i.e., along the
    /// leaf's path). As you look at each parent node along the way, you need to populate
    /// it with a public key and a map from sibling subtree public keys to newly generated
    /// secret keys encrypted pairwise with each node in the sibling resolution (in the
    /// ideal case, this will just be the sibling node itself, but if the sibling is
    /// blank or contains conflict keys it can be many nodes).
    ///
    /// If your sibling node's resolution is empty, then you will generate the new key
    /// pair but encrypt the secret by doing Diffie Hellman with a different key pair
    /// generated just for that purpose. The secret store for that parent will then
    /// only have an entry for you.
    pub(crate) fn encrypt_path<R: rand::CryptoRng + rand::RngCore>(
        &self,
        id: MemberId,
        leaf_sk: &ShareSecretKey,
        csprng: &mut R,
    ) -> Result<Option<(PcsKey, PathChange, ShareKeyMap)>, CgkaError> {
        let leaf_idx = *self.leaf_index_for_id(id)?;
        debug_assert!(self.id_for_leaf(leaf_idx).unwrap() == id);
        let mut new_path = PathChange {
            leaf_idx: leaf_idx.u32(),
            leaf_pk: leaf_sk.share_key(),
            path: Vec::new(),
        };
        let mut new_sks = ShareKeyMap::new();
        let mut child_idx: TreeNodeIndex = leaf_idx.into();
        // Each node is encrypted with the secret of the child below it (`leaf_sk`
        // at the leaf and the fresh secret generated for each ancestor).
        let mut child_sk = leaf_sk.clone();
        let mut parent_idx = treemath::parent(child_idx);
        while !self.is_root(child_idx) {
            let new_parent_sk = ShareSecretKey::generate(csprng);
            let new_parent_pk = new_parent_sk.share_key();
            // Hold on to the secret so we can derive the root key later without
            // having to decrypt our own path.
            new_sks.insert(new_parent_pk, new_parent_sk.clone());
            let node = self.encrypt_new_path_node_for_parent(
                child_idx,
                &child_sk,
                new_parent_pk,
                &new_parent_sk,
                csprng,
            )?;
            new_path.path.push((parent_idx.u32(), node));
            child_idx = parent_idx.into();
            child_sk = new_parent_sk;
            parent_idx = treemath::parent(child_idx);
        }

        debug_assert!(new_path.is_well_formed());
        Ok(Some((child_sk.into(), new_path, new_sks)))
    }

    /// The origins of the versions at the nodes `id`'s [`PathChange`] would
    /// write. This includes its leaf and its path nodes if the path is valid
    /// here. Empty if `id` is not in the tree.
    pub(crate) fn origins_at(
        &self,
        id: MemberId,
        new_path: &PathChange,
    ) -> BTreeSet<VersionOrigin> {
        let Ok(leaf_idx) = self.leaf_index_for_id(id) else {
            return BTreeSet::new();
        };
        let mut origins: BTreeSet<VersionOrigin> = self
            .leaf(*leaf_idx)
            .iter()
            .flat_map(|leaf| leaf.versions.origins())
            .collect();
        if self.is_valid_path(*leaf_idx, new_path) {
            for (idx, _) in &new_path.path {
                if let Some(node) = self.inner_node(InnerNodeIndex::new(*idx)) {
                    origins.extend(node.origins());
                }
            }
        }
        origins
    }

    /// Applies `id`'s [`PathChange`], representing new public and encrypted
    /// secret keys for each node on its path. `id` is the update's signer and
    /// `origin` is the update. `observed` is the origins in the update's causal
    /// past. At each node it writes, those origins are dropped from every
    /// version, and a version with no origins left is removed.
    ///
    /// If `new_path` is not a valid path from `id`'s leaf, only the leaf is
    /// updated and `id`'s direct path is blanked. This is a no-op if `id` has
    /// no leaf.
    pub(crate) fn apply_path(
        &mut self,
        id: MemberId,
        new_path: &PathChange,
        origin: VersionOrigin,
        observed: &BTreeSet<VersionOrigin>,
    ) -> ApplyPathOutcome {
        // If this id has been concurrently removed, it might no longer be present
        // when we try to apply the concurrent update at that id.
        let Ok(&leaf_idx) = self.leaf_index_for_id(id) else {
            return ApplyPathOutcome::NoLeafToUpdate;
        };
        let is_valid_path = self.is_valid_path(leaf_idx, new_path);
        self.leaves[leaf_idx.usize()]
            .as_mut()
            .expect("Leaf for present ID should not be None")
            .versions
            .merge(NonEmpty::new(new_path.leaf_pk), origin, observed);
        if !is_valid_path {
            // Since this path is no longer valid, we can only update the leaf for
            // this id.
            self.blank_path(treemath::parent(leaf_idx.into()));
            return ApplyPathOutcome::BlankedPath;
        }
        for (idx, store) in new_path.secret_stores() {
            let versions = NonEmpty::new(store);
            let slot = &mut self.inner_nodes[InnerNodeIndex::new(idx).usize()];
            match slot {
                Some(current) => current.merge(versions, origin, observed),
                None => *slot = Some(NodeVersions::new(versions, origin)),
            }
        }
        ApplyPathOutcome::Applied
    }

    /// Blank `id`'s direct path if `new_path` is not a valid path from `id`'s
    /// leaf, as [`Self::apply_path`] does when it applies `new_path`. Does
    /// nothing if `id` has no leaf.
    pub(crate) fn blank_path_if_invalid(&mut self, id: MemberId, new_path: &PathChange) {
        let Some(&leaf_idx) = self.id_to_leaf_idx.get(&id) else {
            return;
        };
        if !self.is_valid_path(leaf_idx, new_path) {
            self.blank_path(treemath::parent(leaf_idx.into()));
        }
    }

    /// Whether the tree currently has a root key.
    pub fn has_root_key(&self) -> bool {
        let root_idx: TreeNodeIndex = treemath::root(self.tree_size);
        let TreeNodeIndex::Inner(p_idx) = root_idx else {
            panic!("BeeKEM should always have a root at an inner node.")
        };
        if let Some(r) = self.inner_node(p_idx) {
            !r.has_conflict()
        } else {
            false
        }
    }

    /// Decrypt parent node's [`ShareSecretKey`].
    ///
    /// Returns the secret if there is a single parent public key.
    /// In either case, adds any public key/decrypted secret key pairs
    /// it encounters to the [`ShareKeyMap`].
    fn maybe_decrypt_parent_key(
        &self,
        child_idx: TreeNodeIndex,
        child_node_keys: &NodeKeys,
        seen_idxs: &[TreeNodeIndex],
        child_sks: &mut ShareKeyMap,
    ) -> Result<Option<ShareSecretKey>, CgkaError> {
        debug_assert!(!self.is_root(child_idx));
        let parent_idx = treemath::parent(child_idx);
        let Some(parent) = self.inner_node(parent_idx) else {
            return Ok(None);
        };

        let Some(version) = parent.non_conflict_version() else {
            return Ok(None);
        };
        let parent_pk = version.pk;
        if child_sks.contains_key(&parent_pk) {
            return Ok(child_sks.get(&parent_pk).cloned());
        }
        let secret = version.decrypt_secret(self.doc_id, child_node_keys, child_sks, seen_idxs)?;
        if secret.share_key() != parent_pk {
            return Err(CgkaError::PathSecretMismatch);
        }
        child_sks.insert(parent_pk, secret.clone());
        Ok(Some(secret))
    }

    /// Build the new [`PathNode`] for a parent node.
    ///
    /// Encrypt the new parent [`ShareSecretKey`] for each member of your sibling
    /// node's resolution. These are then stored in the new node, indexed by the
    /// tree index for each member of that resolution.
    #[allow(clippy::type_complexity)]
    fn encrypt_new_path_node_for_parent<R: rand::CryptoRng + rand::RngCore>(
        &self,
        child_idx: TreeNodeIndex,
        child_sk: &ShareSecretKey,
        new_parent_pk: ShareKey,
        new_parent_sk: &ShareSecretKey,
        csprng: &mut R,
    ) -> Result<PathNode, CgkaError> {
        debug_assert!(!self.is_root(child_idx));
        let sibling_idx = treemath::sibling(child_idx);
        let mut secret_map = BTreeMap::new();
        let mut sibling_resolution = Vec::new();
        self.append_resolution(sibling_idx, &mut sibling_resolution);
        if sibling_resolution.is_empty() {
            // Normally you use a DH shared key to encrypt/decrypt the next node up,
            // but if there's a blank sibling subtree, then you generate a key pair
            // just to do DH with when encrypting the new parent secret.
            let paired_sk = ShareSecretKey::generate(csprng);
            let paired_pk = paired_sk.share_key();
            let encrypted_sk =
                crate::encrypted::encrypt_secret(self.doc_id, new_parent_sk, child_sk, &paired_pk)?;
            secret_map.insert(child_idx, encrypted_sk);
        } else {
            // Encrypt the secret for every node in the sibling resolution, using
            // a new DH shared secret to do the encryption for each node.
            let mut used_paired_sibling = false;
            for idx in sibling_resolution {
                let next_pk = self.resolution_key(idx)?;
                let encrypted_sk = crate::encrypted::encrypt_secret(
                    self.doc_id,
                    new_parent_sk,
                    child_sk,
                    &next_pk,
                )?;
                if !used_paired_sibling {
                    secret_map.insert(child_idx, encrypted_sk.clone());
                    used_paired_sibling = true;
                }
                secret_map.insert(idx, encrypted_sk);
            }
        };

        Ok(PathNode {
            pk: new_parent_pk,
            sk: secret_map,
        })
    }

    fn node_keys_for_index(&self, idx: TreeNodeIndex) -> Result<NodeKeys, CgkaError> {
        Ok(match idx {
            TreeNodeIndex::Leaf(l_idx) => self
                .leaf(l_idx)
                .as_ref()
                .ok_or(CgkaError::ShareKeyNotFound)?
                .versions
                .node_keys(),
            TreeNodeIndex::Inner(i_idx) => self
                .inner_node(i_idx)
                .as_ref()
                .ok_or(CgkaError::ShareKeyNotFound)?
                .node_keys(),
        })
    }

    /// The key an encrypter encrypts to for `idx` in a resolution, either a leaf's
    /// lowest key or an inner node's single key.
    ///
    /// Returns [`CgkaError::UnexpectedKeyConflict`] for a conflicted inner node,
    /// which a resolution never contains.
    fn resolution_key(&self, idx: TreeNodeIndex) -> Result<ShareKey, CgkaError> {
        match idx {
            TreeNodeIndex::Leaf(leaf_idx) => Ok(self
                .leaf(leaf_idx)
                .as_ref()
                .ok_or(CgkaError::ShareKeyNotFound)?
                .versions
                .node_keys()
                .lowest()),
            TreeNodeIndex::Inner(_) => match self.node_keys_for_index(idx)? {
                NodeKeys::ShareKey(pk) => Ok(pk),
                NodeKeys::ConflictKeys(_) => Err(CgkaError::UnexpectedKeyConflict),
            },
        }
    }

    fn leaf(&self, idx: LeafNodeIndex) -> &Option<LeafNode> {
        self.leaves
            .get(idx.usize())
            .expect("Leaf index should be in bounds")
    }

    pub fn leaf_index_for_id(&self, id: MemberId) -> Result<&LeafNodeIndex, CgkaError> {
        self.id_to_leaf_idx
            .get(&id)
            .ok_or(CgkaError::IdentifierNotFound)
    }

    fn id_for_leaf(&self, idx: LeafNodeIndex) -> Result<MemberId, CgkaError> {
        Ok(self
            .leaf(idx)
            .as_ref()
            .ok_or(CgkaError::IdentifierNotFound)?
            .id)
    }

    fn inner_node(&self, idx: InnerNodeIndex) -> &Option<InnerNode> {
        self.inner_nodes
            .get(idx.usize())
            .expect("Inner node index should be in bounds")
    }

    fn is_blank(&self, idx: TreeNodeIndex) -> bool {
        match idx {
            TreeNodeIndex::Leaf(l_idx) => self.leaf(l_idx).is_none(),
            TreeNodeIndex::Inner(p_idx) => self.inner_node(p_idx).is_none(),
        }
    }

    fn should_skip_for_resolution(&self, idx: TreeNodeIndex) -> bool {
        match idx {
            TreeNodeIndex::Leaf(_) => self.is_blank(idx),
            TreeNodeIndex::Inner(i_idx) => self
                .inner_node(i_idx)
                .as_ref()
                .is_none_or(|n| n.has_conflict()),
        }
    }

    /// Blank each of `nodes` (and its path) that omits a resolution
    /// node. Returns whether any node was blanked.
    pub(crate) fn blank_nodes_omitting_a_resolution_node(
        &mut self,
        nodes: impl IntoIterator<Item = InnerNodeIndex>,
    ) -> bool {
        let mut blanked = false;
        for idx in nodes {
            if self.omits_a_resolution_node(idx) {
                self.blank_path(idx);
                blanked = true;
            }
        }
        blanked
    }

    /// Whether the node at `idx` has a single version whose encryptions omit a
    /// node in its non-encrypting child's resolution. A node is omitted if there
    /// is no entry for it or the entry is not encrypted to its current key.
    /// If neither child has the node's `encrypter_pk`, its whole resolution is
    /// omitted. Returns `false` for a blank, conflicted, or out-of-range node,
    /// since decryption skips such a node.
    fn omits_a_resolution_node(&self, idx: InnerNodeIndex) -> bool {
        let Some(version) = self
            .inner_nodes
            .get(idx.usize())
            .and_then(Option::as_ref)
            .and_then(InnerNode::non_conflict_version)
        else {
            return false;
        };
        let has_encrypter_key = |child: TreeNodeIndex| {
            self.node_keys_for_index(child)
                .is_ok_and(|key| key.contains_key(&version.encrypter_pk))
        };
        let (l_child, r_child) = (treemath::left(idx), treemath::right(idx));
        let non_encrypter_child = if has_encrypter_key(l_child) {
            r_child
        } else if has_encrypter_key(r_child) {
            l_child
        } else {
            return true;
        };
        let mut resolution = Vec::new();
        self.append_resolution(non_encrypter_child, &mut resolution);
        // Check whether some node in our non-encrypting child's resolution
        // is missing an encryption paired with its current share key.
        resolution.iter().any(|member_idx| {
            !version.sk.get(member_idx).is_some_and(|encrypted| {
                self.resolution_key(*member_idx)
                    .is_ok_and(|pk| pk == encrypted.paired_pk)
            })
        })
    }

    fn blank_path(&mut self, mut idx: InnerNodeIndex) {
        while !self.is_root(idx.into()) {
            self.blank_inner_node(idx);
            idx = treemath::parent(idx.into());
        }
        self.blank_inner_node(idx);
    }

    fn blank_inner_node(&mut self, idx: InnerNodeIndex) {
        self.inner_nodes[idx.usize()] = None;
    }

    /// Whether the [`PathChange`] still makes sense, from the signer's leaf at
    /// `leaf_idx`, given the state of the tree we are attempting to merge it
    /// into.
    fn is_valid_path(&self, leaf_idx: LeafNodeIndex, new_path: &PathChange) -> bool {
        leaf_idx.u32() == new_path.leaf_idx
            && new_path
                .path
                .iter()
                .map(|(idx, _)| *idx)
                .eq(treemath::direct_path(leaf_idx.into(), self.tree_size)
                    .into_iter()
                    .map(|idx| idx.u32()))
    }

    /// Growing the tree will add a new root and a new subtree, all blank.
    fn maybe_grow_tree(&mut self, new_count: u32) {
        if self.tree_size >= TreeSize::from_leaf_count(new_count) {
            return;
        }
        self.tree_size.inc();
        self.grow_tree_to_size();
    }

    fn grow_tree_to_size(&mut self) {
        self.leaves
            .resize(self.tree_size.leaf_count() as usize, None);
        self.inner_nodes
            .resize(self.tree_size.inner_node_count() as usize, None);
    }

    fn is_root(&self, idx: TreeNodeIndex) -> bool {
        idx == treemath::root(self.tree_size)
    }

    /// Highest descendants of a node that are neither blank nor conflicted inner nodes.
    fn append_resolution(&self, idx: TreeNodeIndex, acc: &mut Vec<TreeNodeIndex>) {
        if self.should_skip_for_resolution(idx) {
            if let TreeNodeIndex::Inner(i_idx) = idx {
                let left_idx = treemath::left(i_idx);
                self.append_resolution(left_idx, acc);
                let right_idx = treemath::right(i_idx);
                self.append_resolution(right_idx, acc);
            }
        } else {
            acc.push(idx);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LeafNode {
    pub id: MemberId,
    /// The leaf's key, or the keys of concurrent rotations by the member's
    /// instances, each with the operations that generated it.
    pub versions: NodeVersions<ShareKey>,
}

#[cfg(any(test, feature = "test_utils"))]
impl BeeKem {
    /// Returns one message per invariant the tree breaks. It checks `leaves`
    /// and `inner_nodes` against `tree_size`, `leaves` against `id_to_leaf_idx`
    /// and `next_leaf_idx`, and each inner node with
    /// [`Self::omits_a_resolution_node`].
    pub(crate) fn invariant_violations(&self) -> Vec<alloc::string::String> {
        use alloc::format;

        let mut violations = Vec::new();
        if self.leaves.len() != self.tree_size.leaf_count() as usize {
            violations.push(format!(
                "leaves has {} slots but tree_size calls for {}",
                self.leaves.len(),
                self.tree_size.leaf_count()
            ));
        }
        if self.inner_nodes.len() != self.tree_size.inner_node_count() as usize {
            violations.push(format!(
                "inner_nodes has {} slots but tree_size calls for {}",
                self.inner_nodes.len(),
                self.tree_size.inner_node_count()
            ));
        }
        if self.next_leaf_idx.usize() > self.leaves.len() {
            violations.push(format!(
                "next_leaf_idx is {} but there are only {} leaf slots",
                self.next_leaf_idx,
                self.leaves.len()
            ));
        }
        for (id, idx) in &self.id_to_leaf_idx {
            match self.leaves.get(idx.usize()) {
                Some(Some(leaf)) if leaf.id == *id => {}
                Some(Some(leaf)) => violations.push(format!(
                    "{id:?} is reported at leaf {idx}, which actually has {:?}",
                    leaf.id
                )),
                Some(None) => violations.push(format!(
                    "{id:?} is reported as a member but leaf {idx} is blank"
                )),
                None => violations.push(format!(
                    "{id:?} is reported at leaf {idx}, past the {} slots that exist",
                    self.leaves.len()
                )),
            }
        }
        for (i, slot) in self.leaves.iter().enumerate() {
            let Some(leaf) = slot else { continue };
            match self.id_to_leaf_idx.get(&leaf.id) {
                Some(idx) if idx.usize() == i => {}
                Some(idx) => violations.push(format!(
                    "leaf {i} contains {:?}, whom the map places at leaf {idx}",
                    leaf.id
                )),
                None => violations.push(format!(
                    "leaf {i} contains {:?}, who is not a member",
                    leaf.id
                )),
            }
            if i >= self.next_leaf_idx.usize() {
                violations.push(format!(
                    "leaf {i} is occupied but sits at or above next_leaf_idx ({})",
                    self.next_leaf_idx
                ));
            }
        }
        for i in 0..self.tree_size.inner_node_count() {
            if self.omits_a_resolution_node(InnerNodeIndex::new(i)) {
                violations.push(format!(
                    "inner node {i} omits a node in its non-encrypting child's resolution"
                ));
            }
        }
        violations
    }
}

#[cfg(test)]
impl BeeKem {
    /// Each node that has versions, with each origin of a version there.
    pub(crate) fn origins_by_node(&self) -> Vec<(TreeNodeIndex, VersionOrigin)> {
        let leaves = self.leaves.iter().enumerate().flat_map(|(i, leaf)| {
            let idx = TreeNodeIndex::Leaf(LeafNodeIndex::new(i as u32));
            leaf.iter()
                .flat_map(|leaf| leaf.versions.origins())
                .map(move |origin| (idx, origin))
        });
        let inner = self.inner_nodes.iter().enumerate().flat_map(|(i, node)| {
            let idx = TreeNodeIndex::Inner(InnerNodeIndex::new(i as u32));
            node.iter()
                .flat_map(NodeVersions::origins)
                .map(move |origin| (idx, origin))
        });
        leaves.chain(inner).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::SigningKey;
    use keyhive_crypto::digest::Digest;
    use rand::{rngs::StdRng, SeedableRng};

    /// A stand-in for the digest of operation `n`. Every add in these tests is
    /// operation 0.
    fn origin(n: u8) -> VersionOrigin {
        Digest::from([n; 32])
    }

    /// Apply `path` as operation `n`, signed by `id`, with every version at the
    /// nodes it writes in its causal past.
    fn apply_after_all(tree: &mut BeeKem, id: MemberId, path: &PathChange, n: u8) {
        let observed = tree.origins_at(id, path);
        tree.apply_path(id, path, origin(n), &observed);
    }

    fn join_new_member_to_share_key_map(
        rng: &mut StdRng,
        sks: &mut ShareKeyMap,
    ) -> (MemberId, ShareKey) {
        let id = MemberId::from(&SigningKey::generate(rng));
        let sk = ShareSecretKey::generate(rng);
        let pk = sk.share_key();
        sks.insert(pk, sk);
        (id, pk)
    }

    /// Resolve `tree` for a membership change with `added` and `removed`.
    fn resolve(tree: &mut BeeKem, added: &[MemberId], removed: &[(MemberId, u32)]) {
        tree.sort_leaves_and_blank_paths_for_concurrent_membership_changes(
            added.iter().copied().collect(),
            removed.iter().copied().collect(),
        );
    }

    #[test]
    fn resolving_a_change_ignores_where_the_leaves_were_before_it() {
        let mut rng = StdRng::seed_from_u64(0x0dd0_0001);
        let mut sks = ShareKeyMap::new();
        let (mut base, _owner) = one_member_tree(&mut rng, &mut sks);
        let (x, x_pk) = join_new_member_to_share_key_map(&mut rng, &mut sks);
        let (y, y_pk) = join_new_member_to_share_key_map(&mut rng, &mut sks);
        base.add_leaf(x, x_pk, origin(0));
        base.add_leaf(y, y_pk, origin(0));
        let x_idx = base.id_to_leaf_idx[&x].u32();
        let y_idx = base.id_to_leaf_idx[&y].u32();
        let (joiner, joiner_pk) = join_new_member_to_share_key_map(&mut rng, &mut sks);

        // Whether a member added and removed in one batch is in the tree when the
        // resolution runs depends on which change arrived first.
        let mut still_present = base.clone();
        still_present.add_leaf(joiner, joiner_pk, origin(0));
        let mut already_gone = base.clone();
        already_gone.add_leaf(joiner, joiner_pk, origin(0));
        already_gone
            .remove_id(joiner)
            .expect("the joiner was just added");
        resolve(&mut still_present, &[joiner], &[(joiner, 3)]);
        resolve(&mut already_gone, &[joiner], &[(joiner, 3)]);
        assert_eq!(
            still_present, already_gone,
            "a member added and removed in one batch resolved differently \
             depending on whether it was still in the tree"
        );

        // Whether an added member is locally at a lower leaf then the ones freed
        // by the two removals depends on the order the changes arrived in.
        let mut placed_first = base.clone();
        placed_first.add_leaf(joiner, joiner_pk, origin(0));
        placed_first.remove_id(x).expect("x is present");
        placed_first.remove_id(y).expect("y is present");
        let mut placed_last = base.clone();
        placed_last.remove_id(x).expect("x is present");
        placed_last.remove_id(y).expect("y is present");
        placed_last.add_leaf(joiner, joiner_pk, origin(0));
        resolve(&mut placed_first, &[joiner], &[(x, x_idx), (y, y_idx)]);
        resolve(&mut placed_last, &[joiner], &[(x, x_idx), (y, y_idx)]);
        assert_eq!(
            placed_first, placed_last,
            "an added member resolved to a different leaf depending on whether it \
             was placed before or after the removals"
        );
    }

    #[test]
    fn a_member_decrypts_a_path_written_by_the_higher_of_its_leaf_conflict_keys() {
        let mut rng = StdRng::seed_from_u64(0x0dd0_0002);
        let mut sks = ShareKeyMap::new();
        let (mut base, owner) = one_member_tree(&mut rng, &mut sks);
        let (other, other_pk) = join_new_member_to_share_key_map(&mut rng, &mut ShareKeyMap::new());
        base.add_leaf(other, other_pk, origin(0));

        // Two instances of the owner rotate its leaf concurrently. Others
        // encrypt to the lower key of the conflict, but the path above it was
        // encrypted with the higher key.
        let (a, b) = (
            ShareSecretKey::generate(&mut rng),
            ShareSecretKey::generate(&mut rng),
        );
        let (low, high) = if a.share_key() < b.share_key() {
            (a, b)
        } else {
            (b, a)
        };
        let (_, low_path, _) = base
            .encrypt_path(owner, &low, &mut rng)
            .expect("encrypting a path")
            .expect("the owner is in the tree");
        // A member joins before the second rotation, so the first one's path
        // no longer fits the tree and only its leaf applies.
        let (joiner, joiner_pk) =
            join_new_member_to_share_key_map(&mut rng, &mut ShareKeyMap::new());
        base.add_leaf(joiner, joiner_pk, origin(0));
        let (root_secret, high_path, _) = base
            .encrypt_path(owner, &high, &mut rng)
            .expect("encrypting a path")
            .expect("the owner is in the tree");

        // Each rotation saw only the adds.
        let mut tree = base;
        let adds = BTreeSet::from([origin(0)]);
        tree.apply_path(owner, &low_path, origin(1), &adds);
        tree.apply_path(owner, &high_path, origin(2), &adds);
        assert_eq!(
            tree.node_keys_for_id(owner).map(|keys| keys.keys()).ok(),
            Some(vec![low.share_key(), high.share_key()])
        );

        // Instances share their leaf secrets, but each keeps the path
        // secrets it generated.
        let mut instance_sks = sks;
        instance_sks.insert(low.share_key(), low);
        instance_sks.insert(high.share_key(), high);
        let decrypted = tree.decrypt_tree_secret(owner, &mut instance_sks);
        assert_eq!(
            decrypted.as_ref().ok().cloned().map(PcsKey::from),
            Some(root_secret),
            "{decrypted:?}"
        );
    }

    fn one_member_tree(rng: &mut StdRng, sks: &mut ShareKeyMap) -> (BeeKem, MemberId) {
        let doc_id = TreeId::from(&SigningKey::generate(rng));
        let (owner, owner_pk) = join_new_member_to_share_key_map(rng, sks);
        let mut tree = BeeKem::new(doc_id);
        tree.add_leaf(owner, owner_pk, origin(0));
        (tree, owner)
    }

    /// A four-leaf tree, its members in leaf order, and a genuine path published
    /// by the member at leaf 0 but not yet applied.
    fn seeded() -> (BeeKem, [MemberId; 4], PathChange) {
        fn member(rng: &mut StdRng) -> (MemberId, ShareKey, ShareSecretKey) {
            let id = MemberId::from(&SigningKey::generate(rng));
            let sk = ShareSecretKey::generate(rng);
            (id, sk.share_key(), sk)
        }

        let mut rng = StdRng::seed_from_u64(0);
        let doc_id = TreeId::from(&SigningKey::generate(&mut rng));
        let (owner, owner_pk, owner_sk) = member(&mut rng);
        let mut tree = BeeKem::new(doc_id);
        tree.add_leaf(owner, owner_pk, origin(0));
        let mut ids = [owner; 4];
        for id in ids.iter_mut().skip(1) {
            let (next, pk, _) = member(&mut rng);
            tree.add_leaf(next, pk, origin(0));
            *id = next;
        }

        let (_, path, _) = tree
            .encrypt_path(owner, &owner_sk, &mut rng)
            .expect("encrypting a path")
            .expect("the owner is in the tree");
        (tree, ids, path)
    }

    #[test]
    fn a_removal_blanks_the_leaf_the_removed_member_occupies() {
        let (mut tree, [_owner, alice, _bob, carol], _) = seeded();

        let removed = Set::from([(alice, 3)]);
        tree.sort_leaves_and_blank_paths_for_concurrent_membership_changes(Set::new(), removed);

        assert!(
            !tree.contains_id(&alice),
            "alice was removed and is still here"
        );
        assert!(
            tree.node_keys_for_id(carol).is_ok(),
            "carol was not removed and lost her leaf"
        );
    }

    #[test]
    fn removals_of_one_member_at_two_leaves_blank_both_paths() {
        let (mut seeded_tree, [owner, _alice, _bob, carol], new_path) = seeded();
        apply_after_all(&mut seeded_tree, owner, &new_path, 1);
        // Leaf 0's path fills inner node 0, the parent of leaves 0 and 1.
        assert!(seeded_tree.inner_node(InnerNodeIndex::new(0)).is_some());

        // Two concurrent removals of carol, one where she was at leaf 0
        // and one where she was at leaf 3.
        let remove_in_order = |first: (MemberId, u32), second: (MemberId, u32)| {
            let mut tree = seeded_tree.clone();
            for removal in [first, second] {
                tree.sort_leaves_and_blank_paths_for_concurrent_membership_changes(
                    Set::new(),
                    Set::from([removal]),
                );
            }
            tree
        };
        let leaf_0_first = remove_in_order((carol, 0), (carol, 3));
        let leaf_3_first = remove_in_order((carol, 3), (carol, 0));

        for (order, tree) in [
            ("leaf 0 first", &leaf_0_first),
            ("leaf 3 first", &leaf_3_first),
        ] {
            assert!(
                !tree.contains_id(&carol),
                "{order}: carol was removed and is still here"
            );
            assert!(
                tree.inner_node(InnerNodeIndex::new(0)).is_none(),
                "{order}: the path from a leaf carol was removed from still contains keys"
            );
            assert!(
                tree.inner_node(InnerNodeIndex::new(2)).is_none(),
                "{order}: the path from a leaf carol was removed from still contains keys"
            );
        }
        assert!(
            leaf_0_first == leaf_3_first,
            "the order of the removals changed the resulting tree"
        );
    }

    #[test]
    fn a_path_whose_indices_are_out_of_range_updates_only_the_leaf() {
        let (mut tree, [owner, ..], genuine) = seeded();
        let owner_idx = *tree.leaf_index_for_id(owner).expect("the owner has a leaf");
        let mine = treemath::direct_path(owner_idx.into(), tree.tree_size);

        // As many indices as a real direct path, so a check on the length alone
        // would let them through, and every one of them past the end of the tree.
        let past_the_end = tree.inner_nodes.len() as u32;
        let mut forged = genuine.clone();
        forged.path = genuine
            .path
            .iter()
            .enumerate()
            .map(|(n, (_, store))| (past_the_end + n as u32, store.clone()))
            .collect();

        apply_after_all(&mut tree, owner, &forged, 1);

        assert_eq!(
            tree.node_keys_for_id(owner).expect("the owner is placed"),
            NodeKeys::ShareKey(genuine.leaf_pk),
            "the leaf it names is still its own to rotate"
        );
        for idx in mine {
            assert!(tree.inner_node(idx).is_none(), "the path was not blanked");
        }
        assert_eq!(tree.member_count(), 4, "nobody was removed");
    }

    /// The leaf an update rotates is its signer's: a path naming another
    /// member's leaf, signed by `alice`, leaves that member's key alone.
    #[test]
    fn an_update_rotates_only_its_signers_leaf() {
        let (mut tree, [owner, alice, ..], owners_path) = seeded();
        let owners_key = tree.node_keys_for_id(owner).expect("the owner is placed");

        apply_after_all(&mut tree, alice, &owners_path, 1);

        assert_eq!(
            tree.node_keys_for_id(owner).expect("the owner is placed"),
            owners_key,
            "the owner's key changed under an update alice signed"
        );
        assert!(
            tree.node_keys_for_id(alice)
                .expect("alice is placed")
                .keys()
                .contains(&owners_path.leaf_pk),
            "alice's own leaf took the key she signed"
        );
    }

    #[test]
    fn a_member_should_not_write_to_other_paths() {
        let (tree, [owner, ..], genuine) = seeded();
        assert_eq!(
            genuine.path.iter().map(|(idx, _)| *idx).collect::<Vec<_>>(),
            vec![0, 1],
            "leaf 0's direct path on four leaves"
        );

        let mut accepted = tree.clone();
        let observed = accepted.origins_at(owner, &genuine);
        assert_eq!(
            accepted.apply_path(owner, &genuine, origin(1), &observed),
            ApplyPathOutcome::Applied
        );
        assert!(accepted.has_root_key(), "a genuine path was not applied");

        // Inner node 2 is the parent of leaves 2 and 3. It should not be
        // written by leaf 0.
        let mut forged = genuine;
        forged.path[0].0 = 2;
        let mut denied = tree;
        let observed = denied.origins_at(owner, &forged);
        assert_eq!(
            denied.apply_path(owner, &forged, origin(1), &observed),
            ApplyPathOutcome::BlankedPath
        );
        assert!(
            denied.inner_node(InnerNodeIndex::new(2)).is_none(),
            "a secret store was merged into another member's node"
        );
    }

    #[test]
    fn removing_every_member_empties_the_tree() {
        let (mut tree, ids, path) = seeded();
        apply_after_all(&mut tree, ids[0], &path, 1);
        assert!(
            tree.has_root_key(),
            "the fixture should start with a root key"
        );

        for id in ids {
            tree.remove_id(id).expect("removing a member");
        }

        assert_eq!(tree.member_count(), 0, "the tree still has members");
        assert!(
            !tree.has_root_key(),
            "emptying the tree left a root key behind"
        );
    }

    #[test]
    fn an_emptied_tree_regains_a_root_key_only_once_a_member_encrypts() {
        let mut rng = StdRng::seed_from_u64(1);
        let mut sks = ShareKeyMap::new();
        let (mut tree, owner) = one_member_tree(&mut rng, &mut sks);
        tree.remove_id(owner).expect("removing the last member");

        let (joiner, joiner_pk) = join_new_member_to_share_key_map(&mut rng, &mut sks);
        assert_eq!(
            tree.add_leaf(joiner, joiner_pk, origin(0)),
            0,
            "an emptied tree did not free leaf index 0"
        );
        assert!(!tree.has_root_key(), "a leaf on its own is not a root key");

        let (_, path, _) = tree
            .encrypt_path(
                joiner,
                sks.get(&joiner_pk).expect("the joiner's secret"),
                &mut rng,
            )
            .expect("encrypting a path")
            .expect("the joiner is in the tree");
        apply_after_all(&mut tree, joiner, &path, 1);
        assert!(
            tree.has_root_key(),
            "encrypting a path produced no root key"
        );
    }

    #[test]
    fn removing_a_member_not_in_the_tree_is_an_error() {
        let mut rng = StdRng::seed_from_u64(2);
        let mut sks = ShareKeyMap::new();
        let (mut tree, owner) = one_member_tree(&mut rng, &mut sks);
        let (outsider, _) = join_new_member_to_share_key_map(&mut rng, &mut sks);

        assert!(
            matches!(tree.remove_id(outsider), Err(CgkaError::IdentifierNotFound)),
            "an outsider was not reported as absent from a one-member tree"
        );
        tree.remove_id(owner).expect("removing the last member");
        assert!(
            matches!(tree.remove_id(owner), Err(CgkaError::IdentifierNotFound)),
            "a member removed twice was not reported as absent"
        );
    }

    #[test]
    fn a_concurrent_add_may_reuse_the_leaf_a_removal_freed() {
        let mut rng = StdRng::seed_from_u64(3);
        let mut sks = ShareKeyMap::new();
        let (mut tree, owner) = one_member_tree(&mut rng, &mut sks);

        let freed = tree.remove_id(owner).expect("removing the last member");
        let (joiner, joiner_pk) = join_new_member_to_share_key_map(&mut rng, &mut sks);
        assert_eq!(
            tree.add_leaf(joiner, joiner_pk, origin(0)),
            freed,
            "the add did not reuse the freed leaf"
        );

        tree.sort_leaves_and_blank_paths_for_concurrent_membership_changes(
            Set::from_iter([joiner]),
            Set::from_iter([(owner, freed)]),
        );

        assert!(
            tree.contains_id(&joiner),
            "the concurrently added member was lost"
        );
        assert!(
            tree.node_keys_for_id(joiner).is_ok(),
            "the removal blanked the added member's leaf"
        );
    }

    fn assert_invariant_violation(invariant_test: impl FnOnce(&mut BeeKem, [MemberId; 4])) {
        let (mut tree, ids, _) = seeded();
        invariant_test(&mut tree, ids);
        assert!(
            !tree.invariant_violations().is_empty(),
            "the invariant violation was not caught"
        );
    }

    #[test]
    fn a_member_reported_at_a_leaf_holding_somebody_else_is_caught() {
        assert_invariant_violation(|tree, [a, b, ..]| {
            let a_idx = *tree.leaf_index_for_id(a).expect("a has a leaf");
            let b_idx = *tree.leaf_index_for_id(b).expect("b has a leaf");
            tree.id_to_leaf_idx.insert(a, b_idx);
            tree.leaves[a_idx.usize()] = None;
        });
    }

    #[test]
    fn a_leaf_whose_occupant_the_map_places_elsewhere_is_caught() {
        assert_invariant_violation(|tree, [a, b, ..]| {
            let a_idx = *tree.leaf_index_for_id(a).expect("a has a leaf");
            let b_idx = *tree.leaf_index_for_id(b).expect("b has a leaf");
            let a_leaf = tree.leaves[a_idx.usize()].clone();
            tree.leaves[b_idx.usize()] = a_leaf;
            tree.id_to_leaf_idx.remove(&b);
        });
    }

    #[test]
    fn a_member_incorrectly_reported_at_a_blank_leaf_is_caught() {
        assert_invariant_violation(|tree, [a, ..]| {
            let a_idx = *tree.leaf_index_for_id(a).expect("a has a leaf");
            tree.leaves[a_idx.usize()] = None;
        });
    }

    #[test]
    fn a_leaf_containing_a_non_member_is_caught() {
        assert_invariant_violation(|tree, [a, ..]| {
            tree.id_to_leaf_idx.remove(&a);
        });
    }

    #[test]
    fn a_node_encrypted_to_a_key_its_resolution_no_longer_has_is_caught() {
        let (mut tree, [owner, .., d], path) = seeded();
        apply_after_all(&mut tree, owner, &path, 1);
        assert!(tree.invariant_violations().is_empty());
        let d_idx = *tree.leaf_index_for_id(d).expect("d has a leaf");
        let new_pk = ShareSecretKey::generate(&mut StdRng::seed_from_u64(1)).share_key();
        tree.leaves[d_idx.usize()]
            .as_mut()
            .expect("d's leaf is occupied")
            .versions = NodeVersions::new(NonEmpty::new(new_pk), origin(2));
        let violations = tree.invariant_violations();
        assert!(
            violations.iter().any(|v| v.starts_with("inner node 1 ")),
            "the root, encrypted to d's old key, was not reported: {violations:?}"
        );
    }
}