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
// Copyright (c) 2020 OpenMLS Authors

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use alloc::{vec, vec::Vec};
use core::{
    cmp::Ordering,
    ops::{Add, AddAssign, Sub, SubAssign},
};
use keyhive_codec::{
    error::DecodeError,
    traits::{decode_exact, Decode, Encode, StreamDecode},
};

/// LeafNodeIndex references a leaf node in a tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LeafNodeIndex(u32);

impl core::fmt::Display for LeafNodeIndex {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{:?}", self.0))
    }
}

impl LeafNodeIndex {
    /// Create a new `LeafNodeIndex` from a `u32`.
    pub fn new(index: u32) -> Self {
        LeafNodeIndex(index)
    }

    /// Return the inner value as `u32`.
    pub fn u32(&self) -> u32 {
        self.0
    }

    /// Return the inner value as `usize`.
    pub fn usize(&self) -> usize {
        self.u32() as usize
    }

    /// Return the index as a TreeNodeIndex value.
    fn to_tree_index(self) -> u32 {
        self.0 * 2
    }

    /// Warning: Only use when the node index represents a leaf node
    fn from_tree_index(node_index: u32) -> Self {
        debug_assert!(node_index.is_multiple_of(2));
        LeafNodeIndex(node_index / 2)
    }
}

impl Add<u32> for LeafNodeIndex {
    type Output = Self;

    fn add(self, rhs: u32) -> Self::Output {
        LeafNodeIndex::new(self.0 + rhs)
    }
}

impl AddAssign<u32> for LeafNodeIndex {
    fn add_assign(&mut self, rhs: u32) {
        self.0 = self.0 + rhs;
    }
}

impl Sub<u32> for LeafNodeIndex {
    type Output = Self;

    fn sub(self, rhs: u32) -> Self::Output {
        LeafNodeIndex::new(self.0 - rhs)
    }
}

impl SubAssign<u32> for LeafNodeIndex {
    fn sub_assign(&mut self, rhs: u32) {
        self.0 = self.0 - rhs;
    }
}

/// InnerNodeIndex references a parent node in a tree.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct InnerNodeIndex(u32);

impl InnerNodeIndex {
    /// Create a new `InnerNodeIndex` from a `u32`.
    pub(crate) fn new(index: u32) -> Self {
        InnerNodeIndex(index)
    }

    /// Return the inner value as `u32`.
    pub(crate) fn u32(&self) -> u32 {
        self.0
    }

    pub(crate) fn usize(&self) -> usize {
        self.0 as usize
    }

    /// Return the index as a TreeNodeIndex value.
    fn to_tree_index(self) -> u32 {
        self.0 * 2 + 1
    }

    /// Warning: Only use when the node index represents a parent node
    fn from_tree_index(node_index: u32) -> Self {
        debug_assert!(node_index > 0);
        debug_assert!(node_index % 2 == 1);
        InnerNodeIndex((node_index - 1) / 2)
    }
}

impl Add<u32> for InnerNodeIndex {
    type Output = Self;

    fn add(self, rhs: u32) -> Self::Output {
        InnerNodeIndex::new(self.0 + rhs)
    }
}

impl AddAssign<u32> for InnerNodeIndex {
    fn add_assign(&mut self, rhs: u32) {
        self.0 = self.0 + rhs;
    }
}

impl Sub<u32> for InnerNodeIndex {
    type Output = Self;

    fn sub(self, rhs: u32) -> Self::Output {
        InnerNodeIndex::new(self.0 - rhs)
    }
}

impl SubAssign<u32> for InnerNodeIndex {
    fn sub_assign(&mut self, rhs: u32) {
        self.0 = self.0 - rhs;
    }
}

impl From<LeafNodeIndex> for TreeNodeIndex {
    fn from(leaf_index: LeafNodeIndex) -> Self {
        TreeNodeIndex::Leaf(leaf_index)
    }
}

impl From<InnerNodeIndex> for TreeNodeIndex {
    fn from(parent_index: InnerNodeIndex) -> Self {
        TreeNodeIndex::Inner(parent_index)
    }
}

/// TreeNodeIndex references a node in a tree.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum TreeNodeIndex {
    Leaf(LeafNodeIndex),
    Inner(InnerNodeIndex),
}

#[cfg(any(test, feature = "arbitrary"))]
impl arbitrary::Arbitrary<'_> for TreeNodeIndex {
    fn arbitrary(g: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let index = u32::arbitrary(g)?;
        Ok(TreeNodeIndex::new(index))
    }
}

impl TreeNodeIndex {
    /// Create a new `TreeNodeIndex` from a `u32`.
    fn new(index: u32) -> Self {
        if index.is_multiple_of(2) {
            TreeNodeIndex::Leaf(LeafNodeIndex::from_tree_index(index))
        } else {
            TreeNodeIndex::Inner(InnerNodeIndex::from_tree_index(index))
        }
    }

    /// Return the inner value as `u32`.
    pub fn u32(&self) -> u32 {
        match self {
            TreeNodeIndex::Leaf(index) => index.to_tree_index(),
            TreeNodeIndex::Inner(index) => index.to_tree_index(),
        }
    }
}

/// The tree index as bijou32: even for a leaf, odd for an inner node. Every
/// number is exactly one index, and encoded order is [`Ord`]'s.
impl Encode for TreeNodeIndex {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.u32().encode_into(out);
    }
}

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

impl StreamDecode for TreeNodeIndex {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (index, rest) = u32::decode_next(bytes)?;
        Ok((TreeNodeIndex::new(index), rest))
    }
}

impl Ord for TreeNodeIndex {
    fn cmp(&self, other: &TreeNodeIndex) -> Ordering {
        self.u32().cmp(&other.u32())
    }
}

impl PartialOrd for TreeNodeIndex {
    fn partial_cmp(&self, other: &TreeNodeIndex) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct TreeSize(u32);

impl TreeSize {
    /// Create a new `TreeSize` from `nodes`, which will be rounded up to the
    /// next power of 2. The tree size then reflects the smallest tree that can
    /// contain the number of nodes.
    pub(crate) fn new(nodes: u32) -> Self {
        let k = log2(nodes);
        TreeSize((1 << (k + 1)) - 1)
    }

    /// Creates a new `TreeSize` from a specific leaf count
    pub(crate) fn from_leaf_count(leaf_count: u32) -> Self {
        TreeSize::new(leaf_count * 2)
    }

    /// Return the number of leaf nodes in the tree.
    pub(crate) fn leaf_count(&self) -> u32 {
        (self.0 / 2) + 1
    }

    /// Return the number of inner nodes in the tree.
    pub(crate) fn inner_node_count(&self) -> u32 {
        self.0 / 2
    }

    /// Return the inner value as `u32`.
    pub(crate) fn u32(&self) -> u32 {
        self.0
    }

    // /// Returns `true` if the leaf is in the left subtree and `false` otherwise.
    // /// If there is only one leaf in the tree, it returns `false`.
    #[allow(dead_code)]
    #[cfg(any(feature = "test_utils", test))]
    pub(crate) fn leaf_is_left(&self, leaf_index: LeafNodeIndex) -> bool {
        leaf_index.u32() < self.leaf_count() / 2
    }

    /// Increase the size.
    pub(super) fn inc(&mut self) {
        self.0 = self.0 * 2 + 1;
    }
}

#[test]
fn tree_size() {
    assert_eq!(TreeSize::new(1).u32(), 1);
    assert_eq!(TreeSize::new(3).u32(), 3);
    assert_eq!(TreeSize::new(5).u32(), 7);
    assert_eq!(TreeSize::new(7).u32(), 7);
    assert_eq!(TreeSize::new(9).u32(), 15);
    assert_eq!(TreeSize::new(11).u32(), 15);
    assert_eq!(TreeSize::new(13).u32(), 15);
    assert_eq!(TreeSize::new(15).u32(), 15);
    assert_eq!(TreeSize::new(17).u32(), 31);
}

/// Test if the leaf is in the left subtree.
#[test]
fn test_leaf_is_left() {
    assert!(!TreeSize::new(1).leaf_is_left(LeafNodeIndex::new(0)));

    assert!(TreeSize::new(3).leaf_is_left(LeafNodeIndex::new(0)));
    assert!(!TreeSize::new(3).leaf_is_left(LeafNodeIndex::new(1)));

    assert!(TreeSize::new(5).leaf_is_left(LeafNodeIndex::new(0)));
    assert!(TreeSize::new(5).leaf_is_left(LeafNodeIndex::new(1)));
    assert!(!TreeSize::new(5).leaf_is_left(LeafNodeIndex::new(2)));
    assert!(!TreeSize::new(5).leaf_is_left(LeafNodeIndex::new(3)));

    assert!(TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(0)));
    assert!(TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(1)));
    assert!(TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(2)));
    assert!(TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(3)));
    assert!(!TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(4)));
    assert!(!TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(5)));
    assert!(!TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(6)));
    assert!(!TreeSize::new(15).leaf_is_left(LeafNodeIndex::new(7)));
}

fn log2(x: u32) -> usize {
    if x == 0 {
        return 0;
    }
    let mut k = 0;
    while (x >> k) > 0 {
        k += 1
    }
    k - 1
}

pub fn level(index: u32) -> usize {
    let x = index;
    if (x & 0x01) == 0 {
        return 0;
    }
    let mut k = 0;
    while ((x >> k) & 0x01) == 1 {
        k += 1;
    }
    k
}

pub(crate) fn root(size: TreeSize) -> TreeNodeIndex {
    let size = size.u32();
    debug_assert!(size > 0);
    TreeNodeIndex::new((1 << log2(size)) - 1)
}

pub(crate) fn left(index: InnerNodeIndex) -> TreeNodeIndex {
    let x = index.to_tree_index();
    let k = level(x);
    debug_assert!(k > 0);
    let index = x ^ (0x01 << (k - 1));
    TreeNodeIndex::new(index)
}

pub(crate) fn right(index: InnerNodeIndex) -> TreeNodeIndex {
    let x = index.to_tree_index();
    let k = level(x);
    debug_assert!(k > 0);
    let index = x ^ (0x03 << (k - 1));
    TreeNodeIndex::new(index)
}

/// Warning: There is no check about the tree size and whether the parent is
/// beyond the root
pub(crate) fn parent(x: TreeNodeIndex) -> InnerNodeIndex {
    let x = x.u32();
    let k = level(x);
    let b = (x >> (k + 1)) & 0x01;
    let index = (x | (1 << k)) ^ (b << (k + 1));
    InnerNodeIndex::from_tree_index(index)
}

pub(crate) fn sibling(index: TreeNodeIndex) -> TreeNodeIndex {
    let p = parent(index);
    match index.u32().cmp(&p.to_tree_index()) {
        Ordering::Less => right(p),
        Ordering::Greater => left(p),
        Ordering::Equal => left(p),
    }
}

/// Direct path from a node to the root.
/// Does not include the node itself.
///
/// Returns an empty path for a node outside a tree of this size.
pub(crate) fn direct_path(node_index: TreeNodeIndex, size: TreeSize) -> Vec<InnerNodeIndex> {
    if node_index.u32() >= size.u32() {
        return vec![];
    }

    let r = root(size).u32();

    let mut d = vec![];
    let mut x = node_index.u32();
    while x != r {
        let parent = parent(TreeNodeIndex::new(x));
        d.push(parent);
        x = parent.to_tree_index();
    }
    d
}

#[allow(dead_code)]
#[cfg(any(feature = "test_utils", test))]
pub(crate) fn is_node_in_tree(node_index: TreeNodeIndex, size: TreeSize) -> bool {
    node_index.u32() < size.u32()
}

#[test]
fn tree_node_index_codec_laws() {
    keyhive_codec::laws::round_trip::<TreeNodeIndex>();
    keyhive_codec::laws::canonical_near::<TreeNodeIndex>();
    keyhive_codec::laws::stream::<TreeNodeIndex>();
}

#[test]
fn tree_node_index_parity_is_its_variant() {
    assert_eq!(
        TreeNodeIndex::decode(&[4]),
        Ok(TreeNodeIndex::Leaf(LeafNodeIndex::new(2)))
    );
    assert_eq!(
        TreeNodeIndex::decode(&[5]),
        Ok(TreeNodeIndex::Inner(InnerNodeIndex::new(2)))
    );
}

#[test]
fn direct_path_of_a_node_outside_the_tree_is_empty() {
    assert_eq!(
        direct_path(TreeNodeIndex::new(2), TreeSize::new(7)).len(),
        2
    );
    assert!(direct_path(TreeNodeIndex::new(7), TreeSize::new(7)).is_empty());
}

#[test]
fn test_node_in_tree() {
    let tests = [(0u32, 3u32), (1, 3), (2, 5), (5, 7), (2, 11)];
    for test in tests.iter() {
        assert!(is_node_in_tree(
            TreeNodeIndex::new(test.0),
            TreeSize::new(test.1)
        ));
    }
}

#[test]
fn test_node_not_in_tree() {
    let tests = [(3u32, 1u32), (13, 7)];
    for test in tests.iter() {
        assert!(!is_node_in_tree(
            TreeNodeIndex::new(test.0),
            TreeSize::new(test.1)
        ));
    }
}