1use std::collections::HashSet;
15
16use openmls_traits::{crypto::OpenMlsCrypto, types::Ciphersuite};
17use serde::{Deserialize, Serialize};
18
19use self::{
20 diff::{PublicGroupDiff, StagedPublicGroupDiff},
21 errors::CreationFromExternalError,
22};
23use super::{
24 proposal_store::{ProposalStore, QueuedProposal},
25 GroupContext, GroupId, Member, StagedCommit,
26};
27#[cfg(test)]
28use crate::treesync::{node::parent_node::PlainUpdatePathNode, treekem::UpdatePathNode};
29use crate::{
30 binary_tree::{
31 array_representation::{direct_path, TreeSize},
32 LeafNodeIndex,
33 },
34 ciphersuite::{hash_ref::ProposalRef, signable::Verifiable},
35 error::LibraryError,
36 extensions::RequiredCapabilitiesExtension,
37 framing::{InterimTranscriptHashInput, Sender},
38 group::mls_group::creation::LeafNodeLifetimePolicy,
39 messages::{
40 group_info::{GroupInfo, VerifiableGroupInfo},
41 proposals::Proposal,
42 ConfirmationTag, PathSecret,
43 },
44 schedule::CommitSecret,
45 storage::PublicStorageProvider,
46 treesync::{
47 errors::{DerivePathError, TreeSyncFromNodesError},
48 node::{
49 encryption_keys::{EncryptionKey, EncryptionKeyPair},
50 leaf_node::LeafNode,
51 },
52 RatchetTree, RatchetTreeIn, TreeSync,
53 },
54 versions::ProtocolVersion,
55};
56#[cfg(doc)]
57use crate::{framing::PublicMessage, group::MlsGroup};
58
59pub(crate) mod builder;
60pub(crate) mod diff;
61pub mod errors;
62pub mod process;
63pub(crate) mod staged_commit;
64#[cfg(test)]
65mod tests;
66mod validation;
67
68#[derive(Debug)]
70#[cfg_attr(any(test, feature = "test-utils"), derive(PartialEq, Clone))]
71pub struct PublicGroup {
72 treesync: TreeSync,
73 proposal_store: ProposalStore,
74 group_context: GroupContext,
75 interim_transcript_hash: Vec<u8>,
76 confirmation_tag: ConfirmationTag,
78}
79
80#[derive(Debug, Serialize, Deserialize)]
82pub struct InterimTranscriptHash(pub Vec<u8>);
83
84impl PublicGroup {
85 pub(crate) fn new(
88 crypto: &impl OpenMlsCrypto,
89 treesync: TreeSync,
90 group_context: GroupContext,
91 initial_confirmation_tag: ConfirmationTag,
92 ) -> Result<Self, LibraryError> {
93 let interim_transcript_hash = {
94 let input = InterimTranscriptHashInput::from(&initial_confirmation_tag);
95
96 input.calculate_interim_transcript_hash(
97 crypto,
98 group_context.ciphersuite(),
99 group_context.confirmed_transcript_hash(),
100 )?
101 };
102
103 Ok(PublicGroup {
104 treesync,
105 proposal_store: ProposalStore::new(),
106 group_context,
107 interim_transcript_hash,
108 confirmation_tag: initial_confirmation_tag,
109 })
110 }
111
112 pub fn from_external<StorageProvider, StorageError>(
118 crypto: &impl OpenMlsCrypto,
119 storage: &StorageProvider,
120 ratchet_tree: RatchetTreeIn,
121 verifiable_group_info: VerifiableGroupInfo,
122 proposal_store: ProposalStore,
123 ) -> Result<(Self, GroupInfo), CreationFromExternalError<StorageError>>
124 where
125 StorageProvider: PublicStorageProvider<Error = StorageError>,
126 {
127 let (public_group, group_info) = PublicGroup::from_ratchet_tree(
128 crypto,
129 ratchet_tree,
130 verifiable_group_info,
131 proposal_store,
132 LeafNodeLifetimePolicy::Verify,
133 )?;
134
135 public_group
136 .store(storage)
137 .map_err(CreationFromExternalError::WriteToStorageError)?;
138
139 Ok((public_group, group_info))
140 }
141
142 pub(crate) fn from_ratchet_tree<StorageError>(
143 crypto: &impl OpenMlsCrypto,
144 ratchet_tree: RatchetTreeIn,
145 verifiable_group_info: VerifiableGroupInfo,
146 proposal_store: ProposalStore,
147 validate_lifetimes: LeafNodeLifetimePolicy,
148 ) -> Result<(Self, GroupInfo), CreationFromExternalError<StorageError>> {
149 let ciphersuite = verifiable_group_info.ciphersuite();
150
151 let group_id = verifiable_group_info.group_id();
152 let ratchet_tree = ratchet_tree
153 .into_verified(ciphersuite, crypto, group_id)
154 .map_err(|e| {
155 CreationFromExternalError::TreeSyncError(TreeSyncFromNodesError::RatchetTreeError(
156 e,
157 ))
158 })?;
159
160 let treesync = TreeSync::from_ratchet_tree(crypto, ciphersuite, ratchet_tree)?;
164
165 let mut encryption_keys = HashSet::new();
166
167 treesync.full_leaves().try_for_each(|leaf_node| {
171 leaf_node.validate_locally()?;
172
173 if !encryption_keys.insert(leaf_node.encryption_key()) {
180 return Err(CreationFromExternalError::DuplicateEncryptionKey);
181 }
182
183 Ok(())
184 })?;
185
186 treesync
188 .full_parents()
189 .try_for_each(|(parent_index, parent_node)| {
190 if !encryption_keys.insert(parent_node.encryption_key()) {
197 return Err(CreationFromExternalError::DuplicateEncryptionKey);
198 }
199
200 parent_node
201 .unmerged_leaves()
202 .iter()
203 .try_for_each(|leaf_index| {
204 let path = direct_path(*leaf_index, treesync.tree_size());
205
206 let this_parent_offset = path
210 .iter()
211 .position(|x| x == &parent_index)
212 .ok_or(
213 CreationFromExternalError::<StorageError>::UnmergedLeafNotADescendant,
214 )?;
215 let path_leaf_to_this = &path[..this_parent_offset];
216
217
218 path_leaf_to_this
222 .iter()
223 .try_for_each(|intermediate_index| {
224 if let Some(intermediate_node) = treesync
226 .parent(*intermediate_index) {
227 if !intermediate_node.unmerged_leaves().contains(leaf_index) {
228 return Err(CreationFromExternalError::<StorageError>::IntermediateNodeMissingUnmergedLeaf);
229 }
230 }
231
232 Ok(())
233 })
234 })
235 })?;
236
237 let group_info: GroupInfo = {
239 let signer_signature_key = treesync
240 .leaf(verifiable_group_info.signer())
241 .ok_or(CreationFromExternalError::UnknownSender)?
242 .signature_key()
243 .clone()
244 .into_signature_public_key_enriched(ciphersuite.signature_algorithm());
245
246 verifiable_group_info
247 .verify(crypto, &signer_signature_key)
248 .map_err(|_| CreationFromExternalError::InvalidGroupInfoSignature)?
249 };
250
251 if treesync.tree_hash() != group_info.group_context().tree_hash() {
253 return Err(CreationFromExternalError::TreeHashMismatch);
254 }
255
256 if group_info.group_context().protocol_version() != ProtocolVersion::Mls10 {
257 return Err(CreationFromExternalError::UnsupportedMlsVersion);
258 }
259
260 let group_context = group_info.group_context().clone();
261
262 let interim_transcript_hash = {
263 let input = InterimTranscriptHashInput::from(group_info.confirmation_tag());
264
265 input.calculate_interim_transcript_hash(
266 crypto,
267 group_context.ciphersuite(),
268 group_context.confirmed_transcript_hash(),
269 )?
270 };
271
272 let public_group = Self {
273 treesync,
274 group_context,
275 interim_transcript_hash,
276 confirmation_tag: group_info.confirmation_tag().clone(),
277 proposal_store,
278 };
279
280 public_group
283 .treesync
284 .full_leaves()
285 .try_for_each(|leaf_node| {
286 public_group.validate_leaf_node_inner(leaf_node, validate_lifetimes)
287 })?;
288
289 Ok((public_group, group_info))
290 }
291
292 pub fn ext_commit_sender_index(
294 &self,
295 commit: &StagedCommit,
296 ) -> Result<LeafNodeIndex, LibraryError> {
297 self.leftmost_free_index(commit.queued_proposals())
298 }
299
300 pub(crate) fn leftmost_free_index<'a>(
307 &self,
308 queued_proposals: impl Iterator<Item = &'a QueuedProposal>,
309 ) -> Result<LeafNodeIndex, LibraryError> {
310 let free_leaf_index = self.treesync().free_leaf_index();
312 let removed_indices = queued_proposals.filter_map(|proposal| {
315 match (proposal.proposal(), proposal.sender()) {
316 (Proposal::Remove(r), _) => Some(r.removed),
317 (Proposal::SelfRemove, Sender::Member(sender)) => Some(*sender),
318 _ => None, }
320 });
321 removed_indices
324 .into_iter()
325 .chain(std::iter::once(free_leaf_index))
326 .min()
327 .ok_or_else(|| LibraryError::custom("No free leaf index found"))
328 }
329
330 pub(crate) fn empty_diff(&self) -> PublicGroupDiff<'_> {
332 PublicGroupDiff::new(self)
333 }
334
335 pub(crate) fn merge_diff(&mut self, diff: StagedPublicGroupDiff) {
341 self.treesync.merge_diff(diff.staged_diff);
342 self.group_context = diff.group_context;
343 self.interim_transcript_hash = diff.interim_transcript_hash;
344 self.confirmation_tag = diff.confirmation_tag;
345 }
346
347 pub(crate) fn derive_path_secrets(
361 &self,
362 crypto: &impl OpenMlsCrypto,
363 ciphersuite: Ciphersuite,
364 path_secret: PathSecret,
365 sender_index: LeafNodeIndex,
366 leaf_index: LeafNodeIndex,
367 ) -> Result<(Vec<EncryptionKeyPair>, CommitSecret), DerivePathError> {
368 self.treesync.derive_path_secrets(
369 crypto,
370 ciphersuite,
371 path_secret,
372 sender_index,
373 leaf_index,
374 )
375 }
376
377 pub fn members(&self) -> impl Iterator<Item = Member> + '_ {
379 self.treesync().full_leave_members()
380 }
381
382 pub fn export_ratchet_tree(&self) -> RatchetTree {
384 self.treesync().export_ratchet_tree()
385 }
386
387 pub fn add_proposal<Storage: PublicStorageProvider>(
389 &mut self,
390 storage: &Storage,
391 proposal: QueuedProposal,
392 ) -> Result<(), Storage::Error> {
393 storage.queue_proposal(self.group_id(), &proposal.proposal_reference(), &proposal)?;
394 self.proposal_store.add(proposal);
395 Ok(())
396 }
397
398 pub fn remove_proposal<Storage: PublicStorageProvider>(
400 &mut self,
401 storage: &Storage,
402 proposal_ref: &ProposalRef,
403 ) -> Result<(), Storage::Error> {
404 storage.remove_proposal(self.group_id(), proposal_ref)?;
405 self.proposal_store.remove(proposal_ref);
406 Ok(())
407 }
408
409 pub fn queued_proposals<Storage: PublicStorageProvider>(
411 &self,
412 storage: &Storage,
413 ) -> Result<Vec<(ProposalRef, QueuedProposal)>, Storage::Error> {
414 storage.queued_proposals(self.group_id())
415 }
416}
417
418impl PublicGroup {
420 pub fn ciphersuite(&self) -> Ciphersuite {
422 self.group_context.ciphersuite()
423 }
424
425 pub fn version(&self) -> ProtocolVersion {
427 self.group_context.protocol_version()
428 }
429
430 pub fn group_id(&self) -> &GroupId {
432 self.group_context.group_id()
433 }
434
435 pub fn group_context(&self) -> &GroupContext {
437 &self.group_context
438 }
439
440 pub fn required_capabilities(&self) -> Option<&RequiredCapabilitiesExtension> {
442 self.group_context.required_capabilities()
443 }
444
445 fn treesync(&self) -> &TreeSync {
447 &self.treesync
448 }
449
450 pub fn confirmation_tag(&self) -> &ConfirmationTag {
452 &self.confirmation_tag
453 }
454
455 pub fn leaf(&self, leaf_index: LeafNodeIndex) -> Option<&LeafNode> {
458 self.treesync().leaf(leaf_index)
459 }
460
461 pub(crate) fn tree_size(&self) -> TreeSize {
463 self.treesync().tree_size()
464 }
465
466 fn interim_transcript_hash(&self) -> &[u8] {
467 &self.interim_transcript_hash
468 }
469
470 pub(crate) fn owned_encryption_keys(&self, leaf_index: LeafNodeIndex) -> Vec<EncryptionKey> {
473 self.treesync().owned_encryption_keys(leaf_index)
474 }
475
476 pub(crate) fn store<Storage: PublicStorageProvider>(
481 &self,
482 storage: &Storage,
483 ) -> Result<(), Storage::Error> {
484 let group_id = self.group_context.group_id();
485 storage.write_tree(group_id, self.treesync())?;
486 storage.write_confirmation_tag(group_id, self.confirmation_tag())?;
487 storage.write_context(group_id, self.group_context())?;
488 storage.write_interim_transcript_hash(
489 group_id,
490 &InterimTranscriptHash(self.interim_transcript_hash.clone()),
491 )?;
492 Ok(())
493 }
494
495 pub fn delete<Storage: PublicStorageProvider>(
497 storage: &Storage,
498 group_id: &GroupId,
499 ) -> Result<(), Storage::Error> {
500 storage.delete_tree(group_id)?;
501 storage.delete_confirmation_tag(group_id)?;
502 storage.delete_context(group_id)?;
503 storage.delete_interim_transcript_hash(group_id)?;
504
505 Ok(())
506 }
507
508 pub fn load<Storage: PublicStorageProvider>(
510 storage: &Storage,
511 group_id: &GroupId,
512 ) -> Result<Option<Self>, Storage::Error> {
513 let treesync = storage.tree(group_id)?;
514 let proposals: Vec<(ProposalRef, QueuedProposal)> = storage.queued_proposals(group_id)?;
515 let group_context = storage.group_context(group_id)?;
516 let interim_transcript_hash: Option<InterimTranscriptHash> =
517 storage.interim_transcript_hash(group_id)?;
518 let confirmation_tag = storage.confirmation_tag(group_id)?;
519 let mut proposal_store = ProposalStore::new();
520
521 for (_ref, proposal) in proposals {
522 proposal_store.add(proposal);
523 }
524
525 let build = || -> Option<Self> {
526 Some(Self {
527 treesync: treesync?,
528 proposal_store,
529 group_context: group_context?,
530 interim_transcript_hash: interim_transcript_hash?.0,
531 confirmation_tag: confirmation_tag?,
532 })
533 };
534
535 Ok(build())
536 }
537
538 pub(crate) fn proposal_store(&self) -> &ProposalStore {
540 &self.proposal_store
541 }
542
543 pub(crate) fn proposal_store_mut(&mut self) -> &mut ProposalStore {
545 &mut self.proposal_store
546 }
547}
548
549#[cfg(any(feature = "test-utils", test))]
551impl PublicGroup {
552 pub(crate) fn context_mut(&mut self) -> &mut GroupContext {
553 &mut self.group_context
554 }
555
556 #[cfg(test)]
557 pub(crate) fn set_group_context(&mut self, group_context: GroupContext) {
558 self.group_context = group_context;
559 }
560
561 #[cfg(test)]
562 pub(crate) fn encrypt_path(
563 &self,
564 provider: &impl crate::storage::OpenMlsProvider,
565 ciphersuite: Ciphersuite,
566 path: &[PlainUpdatePathNode],
567 group_context: &[u8],
568 exclusion_list: &HashSet<&LeafNodeIndex>,
569 own_leaf_index: LeafNodeIndex,
570 ) -> Result<Vec<UpdatePathNode>, LibraryError> {
571 self.treesync().empty_diff().encrypt_path(
572 provider.crypto(),
573 ciphersuite,
574 path,
575 group_context,
576 exclusion_list,
577 own_leaf_index,
578 )
579 }
580}