Skip to main content

openmls/treesync/
mod.rs

1//! This module implements the ratchet tree component of MLS.
2//!
3//! It exposes the [`Node`] enum that can contain either a [`LeafNode`] or a [`ParentNode`].
4
5// # Internal documentation
6//
7// This module provides the [`TreeSync`] struct, which contains the state
8// shared between a group of MLS clients in the shape of a tree, where each
9// non-blank leaf corresponds to one group member. The functions provided by
10// its implementation allow the creation of a [`TreeSyncDiff`] instance, which
11// in turn can be mutably operated on and merged back into the original
12// [`TreeSync`] instance.
13//
14// The submodules of this module define the nodes of the tree (`nodes`),
15// helper functions and structs for the algorithms used to sync the tree across
16// the group ([`hashes`]) and the diff functionality ([`diff`]).
17//
18// Finally, this module contains the [`treekem`] module, which allows the
19// encryption and decryption of updates to the tree.
20
21#[cfg(any(feature = "test-utils", test))]
22use std::fmt;
23
24use openmls_traits::{
25    crypto::OpenMlsCrypto,
26    signatures::Signer,
27    types::{Ciphersuite, CryptoError},
28};
29use serde::{Deserialize, Serialize};
30use thiserror::Error;
31use tls_codec::{TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize};
32
33use self::{
34    diff::{StagedTreeSyncDiff, TreeSyncDiff},
35    node::{
36        leaf_node::{
37            Capabilities, NewLeafNodeParams, TreeInfoTbs, TreePosition, VerifiableLeafNode,
38        },
39        NodeIn,
40    },
41    treesync_node::{TreeSyncLeafNode, TreeSyncNode, TreeSyncParentNode},
42};
43#[cfg(any(feature = "test-utils", test))]
44use crate::{binary_tree::array_representation::level, test_utils::bytes_to_hex};
45use crate::{
46    binary_tree::array_representation::ParentNodeIndex, treesync::node::leaf_node::LeafNodeIn,
47};
48use crate::{
49    binary_tree::{
50        array_representation::{is_node_in_tree, LeafNodeIndex, TreeSize},
51        MlsBinaryTree, MlsBinaryTreeError,
52    },
53    ciphersuite::{signable::Verifiable, Secret},
54    credentials::CredentialWithKey,
55    error::LibraryError,
56    extensions::Extensions,
57    group::{GroupId, Member},
58    key_packages::Lifetime,
59    messages::{PathSecret, PathSecretError},
60    schedule::CommitSecret,
61    storage::OpenMlsProvider,
62};
63
64// Private
65mod hashes;
66use errors::*;
67
68// Crate
69pub(crate) mod diff;
70pub(crate) mod node;
71pub(crate) mod treekem;
72pub(crate) mod treesync_node;
73
74use node::encryption_keys::EncryptionKeyPair;
75
76// Public
77pub mod errors;
78#[cfg(feature = "test-utils")]
79pub use node::encryption_keys::test_utils;
80pub use node::encryption_keys::EncryptionKey;
81
82// Public re-exports
83pub use node::{
84    leaf_node::{
85        LeafNode, LeafNodeParameters, LeafNodeParametersBuilder, LeafNodeSource,
86        LeafNodeUpdateError,
87    },
88    parent_node::ParentNode,
89    Node,
90};
91
92// Tests
93#[cfg(any(feature = "test-utils", test))]
94pub mod tests_and_kats;
95
96/// An exported ratchet tree as used in, e.g., [`GroupInfo`](crate::messages::group_info::GroupInfo).
97#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize, TlsSerialize, TlsSize)]
98pub struct RatchetTree(Vec<Option<Node>>);
99
100/// An error during processing of an incoming ratchet tree.
101#[derive(Error, Debug, PartialEq, Clone)]
102pub enum RatchetTreeError {
103    /// The ratchet tree is empty.
104    #[error("The ratchet tree has no nodes.")]
105    MissingNodes,
106    /// The ratchet tree has a trailing blank node.
107    #[error("The ratchet tree has trailing blank nodes.")]
108    TrailingBlankNodes,
109    /// Invalid node signature.
110    #[error("Invalid node signature.")]
111    InvalidNodeSignature,
112    /// Wrong node type.
113    #[error("Wrong node type.")]
114    WrongNodeType,
115}
116
117impl RatchetTree {
118    /// Create a [`RatchetTree`] from a vector of nodes stripping all trailing blank nodes.
119    ///
120    /// Note: The caller must ensure to call this with a vector that is *not* empty after removing all trailing blank nodes.
121    fn trimmed(mut nodes: Vec<Option<Node>>) -> Self {
122        // Remove all trailing blank nodes.
123        match nodes.iter().enumerate().rfind(|(_, node)| node.is_some()) {
124            Some((rightmost_nonempty_position, _)) => {
125                // We need to add 1 to `rightmost_nonempty_position` to keep the rightmost node.
126                nodes.resize(rightmost_nonempty_position + 1, None);
127            }
128            None => {
129                // If there is no rightmost non-blank node, the vector consist of blank nodes only.
130                nodes.clear();
131            }
132        }
133
134        debug_assert!(!nodes.is_empty(), "Caller should have ensured that `RatchetTree::trimmed` is not called with a vector that is empty after removing all trailing blank nodes.");
135        Self(nodes)
136    }
137
138    /// Create a new [`RatchetTree`] from a vector of nodes.
139    pub(crate) fn try_from_nodes(
140        ciphersuite: Ciphersuite,
141        crypto: &impl OpenMlsCrypto,
142        nodes: Vec<Option<NodeIn>>,
143        group_id: &GroupId,
144    ) -> Result<Self, RatchetTreeError> {
145        // ValSem300: "Exported ratchet trees must not have trailing blank nodes."
146        //
147        // We can check this by only looking at the last node (if any).
148        match nodes.last() {
149            Some(None) => {
150                // The ratchet tree is not empty, i.e., has a last node, *but* the last node *is* blank.
151                Err(RatchetTreeError::TrailingBlankNodes)
152            }
153            None => {
154                // The ratchet tree is empty.
155                Err(RatchetTreeError::MissingNodes)
156            }
157            Some(Some(_)) => {
158                // The ratchet tree is not empty, i.e., has a last node, and the last node is not blank.
159
160                // Verify the nodes.
161                // https://validation.openmls.tech/#valn1407
162                let mut verified_nodes = Vec::new();
163                for (index, node) in nodes.into_iter().enumerate() {
164                    let verified_node = match (index % 2, node) {
165                        // Even indices must be leaf nodes.
166                        (0, Some(NodeIn::LeafNode(leaf_node))) => {
167                            let tree_position = TreePosition::new(
168                                group_id.clone(),
169                                LeafNodeIndex::new((index / 2) as u32),
170                            );
171                            let verifiable_leaf_node = leaf_node.into_verifiable_leaf_node();
172                            let signature_key = verifiable_leaf_node
173                                .signature_key()
174                                .clone()
175                                .into_signature_public_key_enriched(
176                                    ciphersuite.signature_algorithm(),
177                                );
178                            Some(Node::leaf_node(match verifiable_leaf_node {
179                                VerifiableLeafNode::KeyPackage(leaf_node) => leaf_node
180                                    .verify(crypto, &signature_key)
181                                    .map_err(|_| RatchetTreeError::InvalidNodeSignature)?,
182                                VerifiableLeafNode::Update(mut leaf_node) => {
183                                    leaf_node.add_tree_position(tree_position);
184                                    leaf_node
185                                        .verify(crypto, &signature_key)
186                                        .map_err(|_| RatchetTreeError::InvalidNodeSignature)?
187                                }
188                                VerifiableLeafNode::Commit(mut leaf_node) => {
189                                    leaf_node.add_tree_position(tree_position);
190                                    leaf_node
191                                        .verify(crypto, &signature_key)
192                                        .map_err(|_| RatchetTreeError::InvalidNodeSignature)?
193                                }
194                            }))
195                        }
196                        // Odd indices must be parent nodes.
197                        (1, Some(NodeIn::ParentNode(parent_node))) => {
198                            Some(Node::ParentNode(parent_node))
199                        }
200                        // Blank nodes.
201                        (_, None) => None,
202                        // All other cases are invalid.
203                        _ => {
204                            return Err(RatchetTreeError::WrongNodeType);
205                        }
206                    };
207                    verified_nodes.push(verified_node);
208                }
209                Ok(Self::trimmed(verified_nodes))
210            }
211        }
212    }
213
214    /// Returns an iterator over all nodes in the ratchet tree.
215    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
216        self.0.iter().flatten()
217    }
218
219    /// Returns an iterator over all leaf nodes in the ratchet tree.
220    pub fn leaves(&self) -> impl Iterator<Item = &LeafNode> {
221        self.nodes().filter_map(|node| match node {
222            Node::LeafNode(leaf_node) => Some(&**leaf_node),
223            Node::ParentNode(_parent_node) => None,
224        })
225    }
226
227    /// Returns an iterator over all parent nodes in the ratchet tree.
228    pub fn parents(&self) -> impl Iterator<Item = &ParentNode> {
229        self.nodes().filter_map(|node| match node {
230            Node::ParentNode(parent_node) => Some(&**parent_node),
231            Node::LeafNode(_leaf_node) => None,
232        })
233    }
234}
235
236/// A ratchet tree made of unverified nodes. This is used for deserialization
237/// and verification.
238#[derive(
239    PartialEq,
240    Eq,
241    Clone,
242    Debug,
243    Serialize,
244    Deserialize,
245    TlsDeserialize,
246    TlsDeserializeBytes,
247    TlsSerialize,
248    TlsSize,
249)]
250pub struct RatchetTreeIn(Vec<Option<NodeIn>>);
251
252impl RatchetTreeIn {
253    /// Create a new [`RatchetTreeIn`] from a vector of nodes after verifying
254    /// the nodes.
255    pub fn into_verified(
256        self,
257        ciphersuite: Ciphersuite,
258        crypto: &impl OpenMlsCrypto,
259        group_id: &GroupId,
260    ) -> Result<RatchetTree, RatchetTreeError> {
261        RatchetTree::try_from_nodes(ciphersuite, crypto, self.0, group_id)
262    }
263
264    /// Returns an iterator over all nodes in the ratchet tree.
265    pub fn nodes(&self) -> impl Iterator<Item = &NodeIn> {
266        self.0.iter().flatten()
267    }
268
269    /// Returns an iterator over all leaf nodes in the ratchet tree.
270    pub fn leaves(&self) -> impl Iterator<Item = &LeafNodeIn> {
271        self.nodes().filter_map(|node| match node {
272            NodeIn::LeafNode(leaf_node) => Some(&**leaf_node),
273            NodeIn::ParentNode(_parent_node) => None,
274        })
275    }
276
277    /// Returns an iterator over all parent nodes in the ratchet tree.
278    pub fn parents(&self) -> impl Iterator<Item = &ParentNode> {
279        self.nodes().filter_map(|node| match node {
280            NodeIn::ParentNode(parent_node) => Some(&**parent_node),
281            NodeIn::LeafNode(_leaf_node) => None,
282        })
283    }
284
285    fn from_ratchet_tree(ratchet_tree: RatchetTree) -> Self {
286        let nodes = ratchet_tree
287            .0
288            .into_iter()
289            .map(|node| node.map(NodeIn::from))
290            .collect();
291        Self(nodes)
292    }
293
294    #[cfg(test)]
295    pub(crate) fn from_nodes(nodes: Vec<Option<NodeIn>>) -> Self {
296        Self(nodes)
297    }
298}
299
300impl From<RatchetTree> for RatchetTreeIn {
301    fn from(ratchet_tree: RatchetTree) -> Self {
302        RatchetTreeIn::from_ratchet_tree(ratchet_tree)
303    }
304}
305
306// The following `From` implementation breaks abstraction layers and MUST
307// NOT be made available outside of tests or "test-utils".
308#[cfg(any(feature = "test-utils", test))]
309impl From<RatchetTreeIn> for RatchetTree {
310    fn from(ratchet_tree_in: RatchetTreeIn) -> Self {
311        Self(
312            ratchet_tree_in
313                .0
314                .into_iter()
315                .map(|node| node.map(Node::from))
316                .collect(),
317        )
318    }
319}
320
321#[cfg(any(feature = "test-utils", test))]
322fn log2(x: u32) -> usize {
323    if x == 0 {
324        return 0;
325    }
326    (31 - x.leading_zeros()) as usize
327}
328
329#[cfg(any(feature = "test-utils", test))]
330pub(crate) fn root(size: u32) -> u32 {
331    (1 << log2(size)) - 1
332}
333
334#[cfg(any(feature = "test-utils", test))]
335impl fmt::Display for RatchetTree {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        let factor = 3;
338        let nodes = &self.0;
339        let tree_size = nodes.len() as u32;
340
341        for (i, node) in nodes.iter().enumerate() {
342            let level = level(i as u32);
343            write!(f, "{i:04}")?;
344            if let Some(node) = node {
345                let (key_bytes, parent_hash_bytes) = match node {
346                    Node::LeafNode(leaf_node) => {
347                        write!(f, "\tL      ")?;
348                        let key_bytes = leaf_node.encryption_key().as_slice();
349                        let parent_hash_bytes = leaf_node
350                            .parent_hash()
351                            .map(bytes_to_hex)
352                            .unwrap_or_default();
353                        (key_bytes, parent_hash_bytes)
354                    }
355                    Node::ParentNode(parent_node) => {
356                        if root(tree_size) == i as u32 {
357                            write!(f, "\tP (*)  ")?;
358                        } else {
359                            write!(f, "\tP      ")?;
360                        }
361                        let key_bytes = parent_node.public_key().as_slice();
362                        let parent_hash_string = bytes_to_hex(parent_node.parent_hash());
363                        (key_bytes, parent_hash_string)
364                    }
365                };
366                write!(
367                    f,
368                    "PK: {}  PH: {} | ",
369                    bytes_to_hex(key_bytes),
370                    if !parent_hash_bytes.is_empty() {
371                        parent_hash_bytes
372                    } else {
373                        str::repeat("  ", 32)
374                    }
375                )?;
376
377                write!(f, "{}◼︎", str::repeat(" ", level * factor))?;
378            } else {
379                if root(tree_size) == i as u32 {
380                    write!(
381                        f,
382                        "\t_ (*)  PK: {}  PH: {} | ",
383                        str::repeat("__", 32),
384                        str::repeat("__", 32)
385                    )?;
386                } else {
387                    write!(
388                        f,
389                        "\t_      PK: {}  PH: {} | ",
390                        str::repeat("__", 32),
391                        str::repeat("__", 32)
392                    )?;
393                }
394
395                write!(f, "{}❑", str::repeat(" ", level * factor))?;
396            }
397            writeln!(f)?;
398        }
399
400        Ok(())
401    }
402}
403
404/// The [`TreeSync`] struct holds an `MlsBinaryTree` instance, which contains
405/// the state that is synced across the group, as well as the [`LeafNodeIndex`]
406/// pointing to the leaf of this group member and the current hash of the tree.
407///
408/// It follows the same pattern of tree and diff as the underlying
409/// `MlsBinaryTree`, where the [`TreeSync`] instance is immutable safe for
410/// merging a `TreeSyncDiff`, which can be created, staged and merged (see
411/// `TreeSyncDiff`).
412///
413/// [`TreeSync`] instance guarantee a few invariants that are checked upon
414/// creating a new instance from an imported set of nodes, as well as when
415/// merging a diff.
416#[derive(Debug, Serialize, Deserialize)]
417#[cfg_attr(any(test, feature = "test-utils"), derive(PartialEq, Clone))]
418pub struct TreeSync {
419    tree: MlsBinaryTree<TreeSyncLeafNode, TreeSyncParentNode>,
420    tree_hash: Vec<u8>,
421}
422
423impl TreeSync {
424    /// Create a new tree with an own leaf for the given credential.
425    ///
426    /// Returns the resulting [`TreeSync`] instance, as well as the
427    /// corresponding [`CommitSecret`].
428    pub(crate) fn new(
429        provider: &impl OpenMlsProvider,
430        signer: &impl Signer,
431        ciphersuite: Ciphersuite,
432        credential_with_key: CredentialWithKey,
433        life_time: Lifetime,
434        capabilities: Capabilities,
435        extensions: Extensions<LeafNode>,
436    ) -> Result<(Self, CommitSecret, EncryptionKeyPair), LibraryError> {
437        let new_leaf_node_params = NewLeafNodeParams {
438            ciphersuite,
439            credential_with_key,
440            // Creation of a group is considered to be from a key package.
441            leaf_node_source: LeafNodeSource::KeyPackage(life_time),
442            capabilities,
443            extensions,
444            tree_info_tbs: TreeInfoTbs::KeyPackage,
445        };
446        let (leaf, encryption_key_pair) = LeafNode::new(provider, signer, new_leaf_node_params)?;
447
448        let node = Node::leaf_node(leaf);
449        let path_secret: PathSecret = Secret::random(ciphersuite, provider.rand())
450            .map_err(LibraryError::unexpected_crypto_error)?
451            .into();
452        let commit_secret: CommitSecret = path_secret
453            .derive_path_secret(provider.crypto(), ciphersuite)?
454            .into();
455        let nodes = vec![TreeSyncNode::from(node).into()];
456        let tree = MlsBinaryTree::new(nodes)
457            .map_err(|_| LibraryError::custom("Unexpected error creating the binary tree."))?;
458        let mut tree_sync = Self {
459            tree,
460            tree_hash: vec![],
461        };
462        // Populate tree hash caches.
463        tree_sync.populate_parent_hashes(provider.crypto(), ciphersuite)?;
464
465        Ok((tree_sync, commit_secret, encryption_key_pair))
466    }
467
468    /// Create a new single-leaf tree for a virtual-client-created group.
469    ///
470    /// The creator's leaf uses the caller-supplied `encryption_key_pair`
471    /// (derived from a `key_package` operation secret) and carries a
472    /// `key_package` `leaf_node_source` with `life_time`, matching the
473    /// `DerivationInfoTBE` selector a sibling uses to reconstruct the leaf. As
474    /// the sole leaf is also the root, it has an empty parent hash.
475    /// `leaf_extensions` already carries the VC derivation info. No commit
476    /// secret is returned: epoch-0 secrets come from the `epoch_secret` derived
477    /// from the KeyPackage seed, not the joiner key schedule.
478    #[cfg(feature = "virtual-clients-draft")]
479    #[allow(clippy::too_many_arguments)]
480    pub(crate) fn new_vc(
481        provider: &impl OpenMlsProvider,
482        signer: &impl Signer,
483        ciphersuite: Ciphersuite,
484        credential_with_key: CredentialWithKey,
485        life_time: Lifetime,
486        capabilities: Capabilities,
487        leaf_extensions: Extensions<LeafNode>,
488        encryption_key_pair: EncryptionKeyPair,
489    ) -> Result<(Self, EncryptionKeyPair), LibraryError> {
490        let new_leaf_node_params = NewLeafNodeParams {
491            ciphersuite,
492            credential_with_key,
493            // A virtual-client-created group's creator leaf is key_package-sourced,
494            // matching the non-VC creator path.
495            leaf_node_source: LeafNodeSource::KeyPackage(life_time),
496            capabilities,
497            extensions: leaf_extensions,
498            tree_info_tbs: TreeInfoTbs::KeyPackage,
499        };
500        let (leaf, encryption_key_pair) = LeafNode::new_with_encryption_key_pair(
501            signer,
502            new_leaf_node_params,
503            encryption_key_pair,
504        )?;
505
506        let node = Node::leaf_node(leaf);
507        let nodes = vec![TreeSyncNode::from(node).into()];
508        let tree = MlsBinaryTree::new(nodes)
509            .map_err(|_| LibraryError::custom("Unexpected error creating the binary tree."))?;
510        let mut tree_sync = Self {
511            tree,
512            tree_hash: vec![],
513        };
514        tree_sync.populate_parent_hashes(provider.crypto(), ciphersuite)?;
515
516        Ok((tree_sync, encryption_key_pair))
517    }
518
519    /// Return the full tree
520    pub(crate) fn tree(&self) -> &MlsBinaryTree<TreeSyncLeafNode, TreeSyncParentNode> {
521        &self.tree
522    }
523
524    /// Return the tree hash of the root node of the tree.
525    pub(crate) fn tree_hash(&self) -> &[u8] {
526        self.tree_hash.as_slice()
527    }
528
529    /// Merge the given diff into this `TreeSync` instance, refreshing the
530    /// `tree_hash` value in the process.
531    pub(crate) fn merge_diff(&mut self, tree_sync_diff: StagedTreeSyncDiff) {
532        let (diff, new_tree_hash) = tree_sync_diff.into_parts();
533        self.tree_hash = new_tree_hash;
534        self.tree.merge_diff(diff);
535    }
536
537    /// Create an empty diff based on this [`TreeSync`] instance all operations
538    /// are created based on an initial, empty [`TreeSyncDiff`].
539    pub(crate) fn empty_diff(&self) -> TreeSyncDiff<'_> {
540        self.into()
541    }
542
543    /// A helper function that generates a [`TreeSync`] instance from the given
544    /// slice of nodes. It verifies that the provided encryption key is present
545    /// in the tree and that the invariants documented in [`TreeSync`] hold.
546    pub(crate) fn from_ratchet_tree(
547        crypto: &impl OpenMlsCrypto,
548        ciphersuite: Ciphersuite,
549        ratchet_tree: RatchetTree,
550    ) -> Result<Self, TreeSyncFromNodesError> {
551        // TODO #800: Unmerged leaves should be checked
552        let total_nodes = ratchet_tree.0.len();
553        let mut leaf_nodes = Vec::with_capacity(total_nodes.div_ceil(2));
554        let mut parent_nodes = Vec::with_capacity(total_nodes / 2);
555
556        // Set the leaf indices in all the leaves and convert the node types.
557        for (node_index, node_option) in ratchet_tree.0.into_iter().enumerate() {
558            if node_index % 2 == 0 {
559                let leaf = match node_option {
560                    Some(node) => match TreeSyncNode::from(node) {
561                        TreeSyncNode::Leaf(l) => *l,
562                        TreeSyncNode::Parent(_) => {
563                            return Err(TreeSyncFromNodesError::from(
564                                PublicTreeError::MalformedTree,
565                            ))
566                        }
567                    },
568                    None => TreeSyncLeafNode::blank(),
569                };
570                leaf_nodes.push(leaf);
571            } else {
572                let parent = match node_option {
573                    Some(node) => match TreeSyncNode::from(node) {
574                        TreeSyncNode::Parent(p) => *p,
575                        TreeSyncNode::Leaf(_) => {
576                            return Err(TreeSyncFromNodesError::from(
577                                PublicTreeError::MalformedTree,
578                            ))
579                        }
580                    },
581                    None => TreeSyncParentNode::blank(),
582                };
583                parent_nodes.push(parent);
584            }
585        }
586
587        let tree = MlsBinaryTree::from_components(leaf_nodes, parent_nodes)
588            .map_err(|_| PublicTreeError::MalformedTree)?;
589        let mut tree_sync = Self {
590            tree,
591            tree_hash: vec![],
592        };
593
594        // Verify all parent hashes.
595        tree_sync
596            .verify_parent_hashes(crypto, ciphersuite)
597            .map_err(|e| match e {
598                TreeSyncParentHashError::LibraryError(e) => e.into(),
599                TreeSyncParentHashError::InvalidParentHash => {
600                    TreeSyncFromNodesError::from(PublicTreeError::InvalidParentHash)
601                }
602            })?;
603
604        // Populate tree hash caches.
605        tree_sync.populate_parent_hashes(crypto, ciphersuite)?;
606        Ok(tree_sync)
607    }
608
609    /// Find the `LeafNodeIndex` which a new leaf would have if it were added to the
610    /// tree. This is either the left-most blank node or, if there are no blank
611    /// leaves, the leaf count, since adding a member would extend the tree by
612    /// one leaf.
613    pub(crate) fn free_leaf_index(&self) -> LeafNodeIndex {
614        let diff = self.empty_diff();
615        diff.free_leaf_index()
616    }
617
618    /// Populate the parent hash caches of all nodes in the tree.
619    fn populate_parent_hashes(
620        &mut self,
621        crypto: &impl OpenMlsCrypto,
622        ciphersuite: Ciphersuite,
623    ) -> Result<(), LibraryError> {
624        let diff = self.empty_diff();
625        // Make the diff into a staged diff. This implicitly computes the
626        // tree hashes and poulates the tree hash caches.
627        let staged_diff = diff.into_staged_diff(crypto, ciphersuite)?;
628        // Merge the diff.
629        self.merge_diff(staged_diff);
630        Ok(())
631    }
632
633    /// Verify the parent hashes of all parent nodes in the tree.
634    ///
635    /// Returns an error if one of the parent nodes in the tree has an invalid
636    /// parent hash.
637    fn verify_parent_hashes(
638        &self,
639        crypto: &impl OpenMlsCrypto,
640        ciphersuite: Ciphersuite,
641    ) -> Result<(), TreeSyncParentHashError> {
642        // The ability to verify parent hashes is required both for diffs and
643        // treesync instances. We choose the computationally slightly more
644        // expensive solution of implementing parent hash verification for the
645        // diff and creating an empty diff whenever we need to verify parent
646        // hashes for a `TreeSync` instance. At the time of writing, this
647        // happens only upon construction of a `TreeSync` instance from a vector
648        // of nodes. The alternative solution would be to create a `TreeLike`
649        // trait, which allows tree navigation and node access. We could then
650        // implement `TreeLike` for both `TreeSync` and `TreeSyncDiff` and
651        // finally implement parent hash verification for any struct that
652        // implements `TreeLike`. We choose the less complex version for now.
653        // Should this turn out to cause too much computational overhead, we
654        // should reconsider and choose the alternative sketched above
655        let diff = self.empty_diff();
656        // No need to merge the diff, since we didn't actually modify any state.
657        diff.verify_parent_hashes(crypto, ciphersuite)
658    }
659
660    /// Returns the tree size
661    pub(crate) fn tree_size(&self) -> TreeSize {
662        self.tree.tree_size()
663    }
664
665    /// Returns a vec of all leaf slots, including blanks.
666    pub fn leaves(&self) -> Vec<Option<&LeafNode>> {
667        self.tree
668            .leaves()
669            .map(|(_, tsn)| tsn.node().as_ref())
670            .collect()
671    }
672
673    /// Returns an iterator over the (non-blank) [`LeafNode`]s in the tree.
674    pub fn full_leaves(&self) -> impl Iterator<Item = (LeafNodeIndex, &LeafNode)> {
675        self.tree
676            .leaves()
677            .filter_map(|(index, tsn)| tsn.node().as_ref().map(|ln| (index, ln)))
678    }
679
680    /// Returns an iterator over the (non-blank) [`ParentNode`]s in the tree.
681    pub fn full_parents(&self) -> impl Iterator<Item = (ParentNodeIndex, &ParentNode)> {
682        self.tree
683            .parents()
684            .filter_map(|(index, tsn)| tsn.node().as_ref().map(|pn| (index, pn)))
685    }
686
687    /// Returns an iterator over the [`ParentNodeIndex`]es of blank [`ParentNode`]s in the tree.
688    pub fn blank_parents<'a>(&'a self) -> impl Iterator<Item = ParentNodeIndex> + 'a {
689        self.tree
690            .parents()
691            .filter_map(|(index, tsn)| tsn.node().as_ref().map_or(Some(index), |_| None))
692    }
693
694    /// Returns an iterator over the [`LeafNodeIndex`]es of blank [`LeafNode`]s in the tree.
695    pub fn blank_leaves<'a>(&'a self) -> impl Iterator<Item = LeafNodeIndex> + 'a {
696        self.tree
697            .leaves()
698            .filter_map(|(index, tsn)| tsn.node().as_ref().map_or(Some(index), |_| None))
699    }
700
701    /// Returns the index of the last full leaf in the tree.
702    fn rightmost_full_leaf(&self) -> LeafNodeIndex {
703        let mut index = LeafNodeIndex::new(0);
704        for (leaf_index, leaf) in self.tree.leaves() {
705            if leaf.node().as_ref().is_some() {
706                index = leaf_index;
707            }
708        }
709        index
710    }
711
712    /// Returns a list of [`Member`]s containing only full nodes.
713    ///
714    /// XXX: For performance reasons we probably want to have this in a borrowing
715    ///      version as well. But it might well go away again.
716    pub(crate) fn full_leaf_members(&self) -> impl Iterator<Item = Member> + '_ {
717        self.tree
718            .leaves()
719            // Filter out blank nodes
720            .filter_map(|(index, tsn)| tsn.node().as_ref().map(|node| (index, node)))
721            // Map to `Member`
722            .map(|(index, leaf_node)| {
723                Member::new(
724                    index,
725                    leaf_node.encryption_key().as_slice().to_vec(),
726                    leaf_node.signature_key().as_slice().to_vec(),
727                    leaf_node.credential().clone(),
728                )
729            })
730    }
731
732    /// Returns the nodes in the tree ordered according to the
733    /// array-representation of the underlying binary tree.
734    pub fn export_ratchet_tree(&self) -> RatchetTree {
735        let mut nodes = Vec::new();
736
737        // Determine the index of the rightmost full leaf.
738        let max_length = self.rightmost_full_leaf();
739
740        // We take all the leaves including the rightmost full leaf, blank
741        // leaves beyond that are trimmed.
742        let mut leaves = self
743            .tree
744            .leaves()
745            .map(|(_, leaf)| leaf)
746            .take(max_length.usize() + 1);
747
748        // Get the first leaf.
749        if let Some(leaf) = leaves.next() {
750            nodes.push(leaf.node().clone().map(Node::leaf_node));
751        } else {
752            // The tree was empty.
753            return RatchetTree::trimmed(vec![]);
754        }
755
756        // Blank parent node used for padding
757        let default_parent = TreeSyncParentNode::default();
758
759        // Get the parents.
760        let parents = self
761            .tree
762            .parents()
763            // Drop the index
764            .map(|(_, parent)| parent)
765            // Take the parents up to the max length
766            .take(max_length.usize())
767            // Pad the parents with blank nodes if needed
768            .chain(
769                (self.tree.parents().count()..self.tree.leaves().count() - 1)
770                    .map(|_| &default_parent),
771            );
772
773        // Interleave the leaves and parents.
774        for (leaf, parent) in leaves.zip(parents) {
775            nodes.push(parent.node().clone().map(Node::parent_node));
776            nodes.push(leaf.node().clone().map(Node::leaf_node));
777        }
778
779        RatchetTree::trimmed(nodes)
780    }
781
782    /// Return a reference to the leaf at the given `LeafNodeIndex` or `None` if the
783    /// leaf is blank.
784    pub(crate) fn leaf(&self, leaf_index: LeafNodeIndex) -> Option<&LeafNode> {
785        let tsn = self.tree.leaf(leaf_index);
786        tsn.node().as_ref()
787    }
788
789    /// Returns a [`TreeSyncError`] if the `leaf_index` is not a leaf in this
790    /// tree or empty.
791    pub(crate) fn is_leaf_in_tree(&self, leaf_index: LeafNodeIndex) -> bool {
792        is_node_in_tree(leaf_index.into(), self.tree.tree_size())
793    }
794
795    /// Return a vector containing all [`EncryptionKey`]s for which the owner of
796    /// the given `leaf_index` should have private key material.
797    pub(crate) fn owned_encryption_keys(&self, leaf_index: LeafNodeIndex) -> Vec<EncryptionKey> {
798        self.empty_diff()
799            .encryption_keys(leaf_index)
800            .cloned()
801            .collect::<Vec<EncryptionKey>>()
802    }
803
804    /// Derives [`EncryptionKeyPair`]s for the nodes in the shared direct path
805    /// of the leaves with index `leaf_index` and `sender_index`.  This function
806    /// also checks that the derived public keys match the existing public keys.
807    ///
808    /// Returns the `CommitSecret` derived from the path secret of the root
809    /// node, as well as the derived [`EncryptionKeyPair`]s. Returns an error if
810    /// the target leaf is outside of the tree.
811    ///
812    /// Returns TreeSyncSetPathError::PublicKeyMismatch if the derived keys don't
813    /// match with the existing ones.
814    ///
815    /// Returns TreeSyncSetPathError::LibraryError if the sender_index is not
816    /// in the tree.
817    pub(crate) fn derive_path_secrets(
818        &self,
819        crypto: &impl OpenMlsCrypto,
820        ciphersuite: Ciphersuite,
821        mut path_secret: PathSecret,
822        sender_index: LeafNodeIndex,
823        leaf_index: LeafNodeIndex,
824    ) -> Result<(Vec<EncryptionKeyPair>, CommitSecret), DerivePathError> {
825        // We assume both nodes are in the tree, since the sender_index must be in the tree
826        // Skip the nodes in the subtree path for which we are an unmerged leaf.
827        let subtree_path = self.tree.subtree_path(leaf_index, sender_index);
828        let mut keypairs = Vec::new();
829        for parent_index in subtree_path {
830            // We know the node is in the tree, since it is in the subtree path
831            let tsn = self.tree.parent_by_index(parent_index);
832            // We only care about non-blank nodes.
833            if let Some(ref parent_node) = tsn.node() {
834                // If our own leaf index is not in the list of unmerged leaves
835                // then we should have the secret for this node.
836                if !parent_node.unmerged_leaves().contains(&leaf_index) {
837                    let keypair = path_secret.derive_key_pair(crypto, ciphersuite)?;
838                    // The derived public key should match the one in the node.
839                    // If not, the tree is corrupt.
840                    if parent_node.encryption_key() != keypair.public_key() {
841                        return Err(DerivePathError::PublicKeyMismatch);
842                    } else {
843                        // If everything is ok, set the private key and derive
844                        // the next path secret.
845                        keypairs.push(keypair);
846                        path_secret = path_secret.derive_path_secret(crypto, ciphersuite)?;
847                    }
848                };
849                // If the leaf is blank or our index is in the list of unmerged
850                // leaves, go to the next node.
851            }
852        }
853        Ok((keypairs, path_secret.into()))
854    }
855
856    /// Return a reference to the parent node at the given `ParentNodeIndex` or
857    /// `None` if the node is blank.
858    pub(crate) fn parent(&self, node_index: ParentNodeIndex) -> Option<&ParentNode> {
859        let tsn = self.tree.parent(node_index);
860        tsn.node().as_ref()
861    }
862}
863
864#[cfg(test)]
865impl TreeSync {
866    pub(crate) fn leaf_count(&self) -> u32 {
867        self.tree.leaf_count()
868    }
869}
870
871#[cfg(test)]
872mod test {
873    use super::*;
874
875    #[cfg(debug_assertions)]
876    #[test]
877    #[should_panic]
878    /// This should only panic in debug-builds.
879    fn test_ratchet_tree_internal_empty() {
880        RatchetTree::trimmed(vec![]);
881    }
882
883    #[cfg(debug_assertions)]
884    #[test]
885    #[should_panic]
886    /// This should only panic in debug-builds.
887    fn test_ratchet_tree_internal_empty_after_trim() {
888        RatchetTree::trimmed(vec![None]);
889    }
890
891    #[openmls_test::openmls_test]
892    fn test_ratchet_tree_trailing_blank_nodes() {
893        let provider = &Provider::default();
894        let (key_package, _, _) = crate::key_packages::tests::key_package(ciphersuite, provider);
895        let node_in = NodeIn::from(Node::leaf_node(LeafNode::from(key_package)));
896        let tests = [
897            (vec![], false),
898            (vec![None], false),
899            (vec![None, None], false),
900            (vec![None, None, None], false),
901            (vec![Some(node_in.clone())], true),
902            (vec![Some(node_in.clone()), None], false),
903            (
904                vec![Some(node_in.clone()), None, Some(node_in.clone())],
905                true,
906            ),
907            (
908                vec![Some(node_in.clone()), None, Some(node_in), None],
909                false,
910            ),
911        ];
912
913        for (test, expected) in tests.into_iter() {
914            let got = RatchetTree::try_from_nodes(
915                ciphersuite,
916                provider.crypto(),
917                test,
918                &GroupId::random(provider.rand()),
919            )
920            .is_ok();
921            assert_eq!(got, expected);
922        }
923    }
924
925    #[cfg(not(debug_assertions))]
926    #[test]
927    /// This should not panic in release-builds.
928    fn test_ratchet_tree_internal_empty() {
929        RatchetTree::trimmed(vec![]);
930    }
931
932    #[cfg(not(debug_assertions))]
933    #[test]
934    /// This should not panic in release-builds.
935    fn test_ratchet_tree_internal_empty_after_trim() {
936        RatchetTree::trimmed(vec![None]);
937    }
938}