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 crypto
151 .supports(ciphersuite)
152 .map_err(|_| CreationFromExternalError::UnsupportedCiphersuite(ciphersuite))?;
153
154 let group_id = verifiable_group_info.group_id();
155 let ratchet_tree = ratchet_tree
156 .into_verified(ciphersuite, crypto, group_id)
157 .map_err(|e| {
158 CreationFromExternalError::TreeSyncError(TreeSyncFromNodesError::RatchetTreeError(
159 e,
160 ))
161 })?;
162
163 let treesync = TreeSync::from_ratchet_tree(crypto, ciphersuite, ratchet_tree)?;
167
168 let mut encryption_keys = HashSet::new();
169 let mut signature_keys = HashSet::new();
170
171 treesync.full_leaves().try_for_each(|(_, leaf_node)| {
176 leaf_node.validate_locally()?;
177
178 if !signature_keys.insert(leaf_node.signature_key()) {
181 return Err(CreationFromExternalError::DuplicateSignatureKey);
182 }
183
184 if !encryption_keys.insert(leaf_node.encryption_key()) {
187 return Err(CreationFromExternalError::DuplicateEncryptionKey);
188 }
189
190 Ok(())
191 })?;
192
193 treesync
195 .full_parents()
196 .try_for_each(|(parent_index, parent_node)| {
197 if !encryption_keys.insert(parent_node.encryption_key()) {
204 return Err(CreationFromExternalError::DuplicateEncryptionKey);
205 }
206
207 parent_node
208 .unmerged_leaves()
209 .iter()
210 .try_for_each(|leaf_index| {
211 let path = direct_path(*leaf_index, treesync.tree_size());
212
213 let this_parent_offset = path
217 .iter()
218 .position(|x| x == &parent_index)
219 .ok_or(
220 CreationFromExternalError::<StorageError>::UnmergedLeafNotADescendant,
221 )?;
222 let path_leaf_to_this = &path[..this_parent_offset];
223
224
225 path_leaf_to_this
229 .iter()
230 .try_for_each(|intermediate_index| {
231 if let Some(intermediate_node) = treesync
233 .parent(*intermediate_index) {
234 if !intermediate_node.unmerged_leaves().contains(leaf_index) {
235 return Err(CreationFromExternalError::<StorageError>::IntermediateNodeMissingUnmergedLeaf);
236 }
237 }
238
239 Ok(())
240 })
241 })
242 })?;
243
244 let group_info: GroupInfo = {
246 let signer_signature_key = treesync
247 .leaf(verifiable_group_info.signer())
248 .ok_or(CreationFromExternalError::UnknownSender)?
249 .signature_key()
250 .clone()
251 .into_signature_public_key_enriched(ciphersuite.signature_algorithm());
252
253 verifiable_group_info
254 .verify(crypto, &signer_signature_key)
255 .map_err(|_| CreationFromExternalError::InvalidGroupInfoSignature)?
256 };
257
258 if treesync.tree_hash() != group_info.group_context().tree_hash() {
260 return Err(CreationFromExternalError::TreeHashMismatch);
261 }
262
263 if group_info.group_context().protocol_version() != ProtocolVersion::Mls10 {
264 return Err(CreationFromExternalError::UnsupportedMlsVersion);
265 }
266
267 let group_context = group_info.group_context().clone();
268
269 let interim_transcript_hash = {
270 let input = InterimTranscriptHashInput::from(group_info.confirmation_tag());
271
272 input.calculate_interim_transcript_hash(
273 crypto,
274 group_context.ciphersuite(),
275 group_context.confirmed_transcript_hash(),
276 )?
277 };
278
279 let public_group = Self {
280 treesync,
281 group_context,
282 interim_transcript_hash,
283 confirmation_tag: group_info.confirmation_tag().clone(),
284 proposal_store,
285 };
286
287 public_group
290 .treesync
291 .full_leaves()
292 .try_for_each(|(_, leaf_node)| {
293 public_group.validate_leaf_node_inner(leaf_node, validate_lifetimes)
294 })?;
295
296 Ok((public_group, group_info))
297 }
298
299 pub fn ext_commit_sender_index(
301 &self,
302 commit: &StagedCommit,
303 ) -> Result<LeafNodeIndex, LibraryError> {
304 self.leftmost_free_index(commit.queued_proposals())
305 }
306
307 pub(crate) fn leftmost_free_index<'a>(
314 &self,
315 queued_proposals: impl Iterator<Item = &'a QueuedProposal>,
316 ) -> Result<LeafNodeIndex, LibraryError> {
317 let free_leaf_index = self.treesync().free_leaf_index();
319 let removed_indices = queued_proposals.filter_map(|proposal| {
322 match (proposal.proposal(), proposal.sender()) {
323 (Proposal::Remove(r), _) => Some(r.removed),
324 (Proposal::SelfRemove, Sender::Member(sender)) => Some(*sender),
325 _ => None, }
327 });
328 removed_indices
331 .into_iter()
332 .chain(std::iter::once(free_leaf_index))
333 .min()
334 .ok_or_else(|| LibraryError::custom("No free leaf index found"))
335 }
336
337 pub(crate) fn empty_diff(&self) -> PublicGroupDiff<'_> {
339 PublicGroupDiff::new(self)
340 }
341
342 pub(crate) fn merge_diff(&mut self, diff: StagedPublicGroupDiff) {
348 self.treesync.merge_diff(diff.staged_diff);
349 self.group_context = diff.group_context;
350 self.interim_transcript_hash = diff.interim_transcript_hash;
351 self.confirmation_tag = diff.confirmation_tag;
352 }
353
354 pub(crate) fn derive_path_secrets(
368 &self,
369 crypto: &impl OpenMlsCrypto,
370 ciphersuite: Ciphersuite,
371 path_secret: PathSecret,
372 sender_index: LeafNodeIndex,
373 leaf_index: LeafNodeIndex,
374 ) -> Result<(Vec<EncryptionKeyPair>, CommitSecret), DerivePathError> {
375 self.treesync.derive_path_secrets(
376 crypto,
377 ciphersuite,
378 path_secret,
379 sender_index,
380 leaf_index,
381 )
382 }
383
384 pub fn members(&self) -> impl Iterator<Item = Member> + '_ {
386 self.treesync().full_leaf_members()
387 }
388
389 pub fn export_ratchet_tree(&self) -> RatchetTree {
391 self.treesync().export_ratchet_tree()
392 }
393
394 pub fn add_proposal<Storage: PublicStorageProvider>(
396 &mut self,
397 storage: &Storage,
398 proposal: QueuedProposal,
399 ) -> Result<(), Storage::Error> {
400 storage.queue_proposal(self.group_id(), &proposal.proposal_reference(), &proposal)?;
401 self.proposal_store.add(proposal);
402 Ok(())
403 }
404
405 pub fn remove_proposal<Storage: PublicStorageProvider>(
407 &mut self,
408 storage: &Storage,
409 proposal_ref: &ProposalRef,
410 ) -> Result<(), Storage::Error> {
411 storage.remove_proposal(self.group_id(), proposal_ref)?;
412 self.proposal_store.remove(proposal_ref);
413 Ok(())
414 }
415
416 pub fn queued_proposals<Storage: PublicStorageProvider>(
418 &self,
419 storage: &Storage,
420 ) -> Result<Vec<(ProposalRef, QueuedProposal)>, Storage::Error> {
421 storage.queued_proposals(self.group_id())
422 }
423}
424
425impl PublicGroup {
427 pub fn ciphersuite(&self) -> Ciphersuite {
429 self.group_context.ciphersuite()
430 }
431
432 pub fn version(&self) -> ProtocolVersion {
434 self.group_context.protocol_version()
435 }
436
437 pub fn group_id(&self) -> &GroupId {
439 self.group_context.group_id()
440 }
441
442 pub fn group_context(&self) -> &GroupContext {
444 &self.group_context
445 }
446
447 pub fn required_capabilities(&self) -> Option<&RequiredCapabilitiesExtension> {
449 self.group_context.required_capabilities()
450 }
451
452 pub fn treesync(&self) -> &TreeSync {
454 &self.treesync
455 }
456
457 pub fn confirmation_tag(&self) -> &ConfirmationTag {
459 &self.confirmation_tag
460 }
461
462 pub fn leaf(&self, leaf_index: LeafNodeIndex) -> Option<&LeafNode> {
465 self.treesync().leaf(leaf_index)
466 }
467
468 pub(crate) fn tree_size(&self) -> TreeSize {
470 self.treesync().tree_size()
471 }
472
473 fn interim_transcript_hash(&self) -> &[u8] {
474 &self.interim_transcript_hash
475 }
476
477 pub(crate) fn owned_encryption_keys(&self, leaf_index: LeafNodeIndex) -> Vec<EncryptionKey> {
480 self.treesync().owned_encryption_keys(leaf_index)
481 }
482
483 pub(crate) fn store<Storage: PublicStorageProvider>(
488 &self,
489 storage: &Storage,
490 ) -> Result<(), Storage::Error> {
491 let group_id = self.group_context.group_id();
492 storage.write_tree(group_id, self.treesync())?;
493 storage.write_confirmation_tag(group_id, self.confirmation_tag())?;
494 storage.write_context(group_id, self.group_context())?;
495 storage.write_interim_transcript_hash(
496 group_id,
497 &InterimTranscriptHash(self.interim_transcript_hash.clone()),
498 )?;
499 Ok(())
500 }
501
502 pub fn delete<Storage: PublicStorageProvider>(
504 storage: &Storage,
505 group_id: &GroupId,
506 ) -> Result<(), Storage::Error> {
507 storage.delete_tree(group_id)?;
508 storage.delete_confirmation_tag(group_id)?;
509 storage.delete_context(group_id)?;
510 storage.delete_interim_transcript_hash(group_id)?;
511
512 Ok(())
513 }
514
515 pub fn load<Storage: PublicStorageProvider>(
517 storage: &Storage,
518 group_id: &GroupId,
519 ) -> Result<Option<Self>, Storage::Error> {
520 let treesync = storage.tree(group_id)?;
521 let proposals: Vec<(ProposalRef, QueuedProposal)> = storage.queued_proposals(group_id)?;
522 let group_context = storage.group_context(group_id)?;
523 let interim_transcript_hash: Option<InterimTranscriptHash> =
524 storage.interim_transcript_hash(group_id)?;
525 let confirmation_tag = storage.confirmation_tag(group_id)?;
526 let mut proposal_store = ProposalStore::new();
527
528 for (_ref, proposal) in proposals {
529 proposal_store.add(proposal);
530 }
531
532 let build = || -> Option<Self> {
533 Some(Self {
534 treesync: treesync?,
535 proposal_store,
536 group_context: group_context?,
537 interim_transcript_hash: interim_transcript_hash?.0,
538 confirmation_tag: confirmation_tag?,
539 })
540 };
541
542 Ok(build())
543 }
544
545 pub(crate) fn proposal_store(&self) -> &ProposalStore {
547 &self.proposal_store
548 }
549
550 pub(crate) fn proposal_store_mut(&mut self) -> &mut ProposalStore {
552 &mut self.proposal_store
553 }
554}
555
556#[cfg(any(feature = "test-utils", test))]
558impl PublicGroup {
559 pub(crate) fn context_mut(&mut self) -> &mut GroupContext {
560 &mut self.group_context
561 }
562
563 #[cfg(test)]
564 pub(crate) fn set_group_context(&mut self, group_context: GroupContext) {
565 self.group_context = group_context;
566 }
567
568 #[cfg(test)]
569 pub(crate) fn encrypt_path(
570 &self,
571 provider: &impl crate::storage::OpenMlsProvider,
572 ciphersuite: Ciphersuite,
573 path: &[PlainUpdatePathNode],
574 group_context: &[u8],
575 exclusion_list: &HashSet<&LeafNodeIndex>,
576 own_leaf_index: LeafNodeIndex,
577 ) -> Result<Vec<UpdatePathNode>, LibraryError> {
578 self.treesync().empty_diff().encrypt_path(
579 provider.crypto(),
580 ciphersuite,
581 path,
582 group_context,
583 exclusion_list,
584 own_leaf_index,
585 )
586 }
587}