1use std::collections::{BTreeMap, BTreeSet};
19
20use zaun_community_protocol::command::object::VoiceParticipant;
21use zaun_community_protocol::command::voice::{Joined, Keys as KeysBody};
22use zaun_community_protocol::event::{VoiceKeys, VoiceLeft, VoiceLeftReason, VoiceSignal};
23use zaun_community_protocol::ids::{ChannelId, MemberId, VoiceSessionId};
24
25use super::keys::{AddError, StayKeys};
26use super::signal::Signal;
27
28pub(crate) const ACTIVATE_WITHIN_MS: u64 = 3_000;
31const EARLY_SIGNALS: usize = 8;
33const EARLY_SESSIONS: usize = 16;
35
36#[cfg_attr(
38 target_arch = "wasm32",
39 allow(
40 dead_code,
41 reason = "the browser decodes frames itself and says when it connects"
42 )
43)]
44#[derive(Debug, Clone)]
45pub enum VoiceEvent {
46 Joined(VoiceParticipant),
48 Updated(VoiceParticipant),
50 Left {
52 member: MemberId,
54 reason: VoiceLeftReason,
56 },
57 Connected(MemberId),
59 Audio {
61 member: MemberId,
63 frame: Vec<u8>,
65 },
66 Rekeyed(u32),
68 KeyChanged {
73 member: MemberId,
75 },
76 Ended {
80 reason: Option<VoiceLeftReason>,
82 moved_to: Option<ChannelId>,
84 },
85 Warning(String),
88}
89
90#[derive(Debug, Clone)]
92pub(crate) enum HostInput {
93 Joined(VoiceParticipant),
94 Updated(VoiceParticipant),
95 Left(VoiceLeft),
96 Signal(VoiceSignal),
97 Keys(VoiceKeys),
98 Gone,
100}
101
102#[cfg_attr(
104 target_arch = "wasm32",
105 allow(dead_code, reason = "the browser transport looks the member up itself")
106)]
107#[derive(Debug)]
108pub(crate) enum Act {
109 Open {
111 session: VoiceSessionId,
112 member: MemberId,
113 offer: bool,
114 },
115 Close(VoiceSessionId),
117 Signal(VoiceSessionId, Signal),
119 Tell {
121 session: VoiceSessionId,
122 member: MemberId,
123 signal: Signal,
124 },
125 Keys(KeysBody),
127 Event(VoiceEvent),
129 End(VoiceEvent),
131}
132
133pub(crate) struct Stay {
134 me: MemberId,
135 my_session: VoiceSessionId,
136 keys: StayKeys,
137 peers: BTreeMap<VoiceSessionId, MemberId>,
138 early: BTreeMap<VoiceSessionId, Vec<Signal>>,
139 self_mute: bool,
140 self_deaf: bool,
141 server_mute: bool,
142 server_deaf: bool,
143 can_speak: bool,
144 pending: Option<Pending>,
146 deferred: bool,
148 hears: BTreeSet<VoiceSessionId>,
151 late: Option<Pending>,
154}
155
156struct Pending {
158 epoch: u32,
159 recipients: BTreeSet<VoiceSessionId>,
161 waiting: BTreeSet<VoiceSessionId>,
163 deadline: u64,
165 forced: bool,
167}
168
169impl Pending {
170 fn heard_by(&self, hears: &BTreeSet<VoiceSessionId>) -> bool {
172 self.waiting.is_disjoint(hears)
173 }
174}
175
176impl Stay {
177 pub(crate) fn new(
178 me: MemberId,
179 joined: &Joined,
180 keys: StayKeys,
181 self_mute: bool,
182 self_deaf: bool,
183 ) -> Self {
184 let mine = joined.participants.iter().find(|p| p.member_id == me);
185 Self {
186 me,
187 my_session: joined.voice_session,
188 keys,
189 peers: BTreeMap::new(),
190 early: BTreeMap::new(),
191 self_mute,
192 self_deaf,
193 server_mute: mine.is_some_and(|p| p.server_mute),
194 server_deaf: mine.is_some_and(|p| p.server_deaf),
195 can_speak: mine.is_none_or(|p| p.can_speak),
196 pending: None,
197 deferred: false,
198 hears: BTreeSet::new(),
199 late: None,
200 }
201 }
202
203 pub(crate) const fn can_send(&self) -> bool {
205 !self.self_mute && !self.server_mute && self.can_speak
206 }
207
208 pub(crate) const fn deafened(&self) -> bool {
209 self.self_deaf || self.server_deaf
210 }
211
212 pub(crate) fn begin(&mut self, joined: &Joined, wall: u64) -> Vec<Act> {
214 let mut acts = Vec::new();
215 for p in &joined.participants {
216 if p.voice_session == self.my_session || p.member_id == self.me {
217 continue;
218 }
219 if self.add_peer(p, &mut acts) {
220 acts.push(Act::Open {
221 session: p.voice_session,
222 member: p.member_id,
223 offer: true,
224 });
225 }
226 }
227 self.rekey(wall, false, &mut acts);
228 acts
229 }
230
231 pub(crate) fn on_host(&mut self, input: HostInput, wall: u64) -> Vec<Act> {
232 let mut acts = Vec::new();
233 match input {
234 HostInput::Gone => acts.push(Act::End(VoiceEvent::Ended {
235 reason: None,
236 moved_to: None,
237 })),
238 HostInput::Left(l) if l.voice_session == self.my_session => {
240 acts.push(Act::End(VoiceEvent::Ended {
241 reason: Some(l.reason),
242 moved_to: l.moved_to,
243 }));
244 }
245 HostInput::Joined(p) => {
246 if p.member_id != self.me && self.add_peer(&p, &mut acts) {
247 acts.push(Act::Open {
248 session: p.voice_session,
249 member: p.member_id,
250 offer: false,
251 });
252 for s in self.early.remove(&p.voice_session).unwrap_or_default() {
253 acts.push(Act::Signal(p.voice_session, s));
254 }
255 self.rekey(wall, false, &mut acts);
256 }
257 acts.push(Act::Event(VoiceEvent::Joined(public(p))));
258 }
259 HostInput::Updated(p) => {
260 if p.member_id == self.me {
261 self.server_mute = p.server_mute;
262 self.server_deaf = p.server_deaf;
263 self.can_speak = p.can_speak;
264 }
265 acts.push(Act::Event(VoiceEvent::Updated(public(p))));
266 }
267 HostInput::Left(l) => {
268 if self.peers.remove(&l.voice_session).is_some() {
269 acts.push(Act::Close(l.voice_session));
270 }
271 self.early.remove(&l.voice_session);
272 let mut had = self.hears.remove(&l.voice_session);
274 if let Some(late) = self.late.as_mut() {
275 had |= late.waiting.remove(&l.voice_session);
276 if late.waiting.is_empty() {
277 self.late = None;
278 }
279 }
280 if let Some(p) = self.pending.as_mut() {
281 p.recipients.remove(&l.voice_session);
282 p.waiting.remove(&l.voice_session);
283 }
284 if self.keys.remove(&l.voice_session).is_some() {
285 if had
290 && self
291 .pending
292 .as_ref()
293 .is_some_and(|p| p.heard_by(&self.hears))
294 {
295 self.deferred = false;
296 self.activate(wall, &mut acts);
297 }
298 self.rekey(wall, true, &mut acts);
299 }
300 self.activate_if_ready(wall, &mut acts);
301 acts.push(Act::Event(VoiceEvent::Left {
302 member: l.member_id,
303 reason: l.reason,
304 }));
305 }
306 HostInput::Signal(s) => match Signal::decode(s.data.as_bytes()) {
307 Some(Signal::Keyed { epoch }) => {
308 if let Some(p) = self.pending.as_mut()
309 && p.epoch == epoch
310 {
311 p.waiting.remove(&s.voice_session);
312 }
313 if let Some(late) = self.late.as_mut()
314 && late.epoch == epoch
315 && late.waiting.remove(&s.voice_session)
316 {
317 self.hears.insert(s.voice_session);
318 if late.waiting.is_empty() {
319 self.late = None;
320 }
321 }
322 self.activate_if_ready(wall, &mut acts);
323 }
324 Some(signal) if self.peers.contains_key(&s.voice_session) => {
325 acts.push(Act::Signal(s.voice_session, signal));
326 }
327 Some(signal) => self.keep_early(s.voice_session, signal),
328 None => acts.push(warning("a signal did not decode")),
329 },
330 HostInput::Keys(k) => {
331 match self.keys.accept(
332 &k.voice_session,
333 k.sender_keys.as_bytes(),
334 k.wrapped.as_bytes(),
335 ) {
336 Ok(epoch) => {
337 if let Some(member) = self.peers.get(&k.voice_session) {
338 acts.push(Act::Tell {
339 session: k.voice_session,
340 member: *member,
341 signal: Signal::Keyed { epoch },
342 });
343 }
344 }
345 Err(e) => acts.push(Act::Event(VoiceEvent::Warning(format!(
346 "a participant's keys were refused ({e})"
347 )))),
348 }
349 }
350 }
351 acts
352 }
353
354 pub(crate) fn on_time(&mut self, wall: u64) -> Vec<Act> {
357 let mut acts = Vec::new();
358 if self.late.as_ref().is_some_and(|l| l.deadline <= wall)
359 && let Some(late) = self.late.take()
360 {
361 self.hears.extend(late.waiting);
362 }
363 if self.pending.as_ref().is_some_and(|p| p.deadline <= wall) {
364 self.activate(wall, &mut acts);
365 }
366 acts
367 }
368
369 fn activate_if_ready(&mut self, wall: u64, acts: &mut Vec<Act>) {
372 if self
373 .pending
374 .as_ref()
375 .is_some_and(|p| p.waiting.is_empty() || (p.forced && p.heard_by(&self.hears)))
376 {
377 self.activate(wall, acts);
378 }
379 }
380
381 fn activate(&mut self, wall: u64, acts: &mut Vec<Act>) {
384 let Some(mut p) = self.pending.take() else {
385 return;
386 };
387 self.keys.activate();
388 if p.deadline <= wall {
389 p.waiting.clear();
390 }
391 self.hears = p.recipients.difference(&p.waiting).copied().collect();
392 self.late = (!p.waiting.is_empty()).then_some(p);
393 if std::mem::take(&mut self.deferred) {
394 self.rekey(wall, false, acts);
395 }
396 }
397
398 pub(crate) fn sends_to(&self, session: &VoiceSessionId) -> bool {
400 self.hears.contains(session)
401 }
402
403 #[cfg_attr(
405 target_arch = "wasm32",
406 allow(dead_code, reason = "the browser stay runs on the client's tick")
407 )]
408 pub(crate) fn next_deadline(&self) -> Option<u64> {
409 [self.pending.as_ref(), self.late.as_ref()]
410 .into_iter()
411 .flatten()
412 .map(|p| p.deadline)
413 .min()
414 }
415
416 pub(crate) fn set_self(&mut self, mute: Option<bool>, deaf: Option<bool>) {
417 self.self_mute = mute.unwrap_or(self.self_mute);
418 self.self_deaf = deaf.unwrap_or(self.self_deaf);
419 }
420
421 pub(crate) fn seal(&mut self, frame: &[u8]) -> Option<Vec<u8>> {
423 if !self.can_send() {
424 return None;
425 }
426 self.keys.seal(frame).ok()
427 }
428
429 pub(crate) fn open(
432 &mut self,
433 session: &VoiceSessionId,
434 data: &[u8],
435 ) -> Option<(MemberId, Vec<u8>)> {
436 if self.deafened() {
437 return None;
438 }
439 let member = *self.peers.get(session)?;
440 self.keys.open(session, data).ok().map(|f| (member, f))
441 }
442
443 #[cfg_attr(
445 not(target_arch = "wasm32"),
446 allow(dead_code, reason = "the browser transport's; str0m keeps its own")
447 )]
448 pub(crate) fn member(&self, session: &VoiceSessionId) -> Option<MemberId> {
449 self.peers.get(session).copied()
450 }
451
452 fn add_peer(&mut self, p: &VoiceParticipant, acts: &mut Vec<Act>) -> bool {
453 match self.keys.add(p) {
454 Ok(true) => {
455 self.peers.insert(p.voice_session, p.member_id);
456 true
457 }
458 Ok(false) => false,
459 Err(e) => {
460 acts.push(Act::Event(refusal(p.member_id, e)));
461 false
462 }
463 }
464 }
465
466 fn keep_early(&mut self, session: VoiceSessionId, signal: Signal) {
467 if !self.early.contains_key(&session) && self.early.len() >= EARLY_SESSIONS {
468 return;
469 }
470 let list = self.early.entry(session).or_default();
471 if list.len() < EARLY_SIGNALS {
472 list.push(signal);
473 }
474 }
475
476 fn rekey(&mut self, wall: u64, urgent: bool, acts: &mut Vec<Act>) {
479 if !self.keys.needs_rekey() {
480 return;
481 }
482 if self.pending.is_some() && !urgent {
483 self.deferred = true;
484 return;
485 }
486 self.deferred = false;
487 match self.keys.rekey(wall) {
488 Ok((epoch, body)) => {
489 match body {
490 Some(body) => {
491 acts.push(Act::Keys(body));
492 let recipients: BTreeSet<VoiceSessionId> =
493 self.peers.keys().copied().collect();
494 self.pending = Some(Pending {
495 epoch,
496 waiting: recipients.clone(),
497 recipients,
498 deadline: wall + ACTIVATE_WITHIN_MS,
499 forced: urgent,
500 });
501 }
502 None => {
503 self.keys.activate();
504 self.pending = None;
505 self.hears.clear();
506 self.late = None;
507 }
508 }
509 acts.push(Act::Event(VoiceEvent::Rekeyed(epoch)));
510 }
511 Err(e) => acts.push(Act::Event(VoiceEvent::Warning(format!(
512 "rekey failed: {e}"
513 )))),
514 }
515 }
516}
517
518fn warning(text: &str) -> Act {
519 Act::Event(VoiceEvent::Warning(text.into()))
520}
521
522pub(crate) fn refusal(member: MemberId, e: AddError) -> VoiceEvent {
524 match e {
525 AddError::Missing => VoiceEvent::Warning(
526 "a participant came without a key package or member key; skipped".into(),
527 ),
528 AddError::Refused(e) => VoiceEvent::Warning(format!(
529 "a participant's key package was refused ({e}); skipped"
530 )),
531 AddError::KeyChanged => VoiceEvent::KeyChanged { member },
532 AddError::Unpinned(e) => VoiceEvent::Warning(format!(
533 "a participant's key could not be pinned ({e}); skipped"
534 )),
535 }
536}
537
538pub(crate) fn public(mut p: VoiceParticipant) -> VoiceParticipant {
540 p.key_package = None;
541 p.member_public_key = None;
542 p
543}
544
545#[cfg(test)]
546mod tests {
547 use super::*;
548 use crate::pins::tests::Memory;
549 use zaun_community_protocol::command::object::{IcePolicy, Opaque};
550 use zaun_community_protocol::crypto::SecretKey;
551 use zaun_community_protocol::ids::CommunityId;
552
553 const C: CommunityId = CommunityId::from_bytes([1; 32]);
554 const CH: ChannelId = ChannelId::from_bytes([2; 16]);
555
556 struct Who {
557 key: SecretKey,
558 id: MemberId,
559 session: VoiceSessionId,
560 package: Vec<u8>,
561 }
562
563 fn who(n: u8) -> (Who, StayKeys) {
565 let key = SecretKey::generate().unwrap();
566 let id = MemberId::from_bytes([n; 16]);
567 let keys = StayKeys::new(key.clone(), C, CH, id, 0, Box::new(Memory::default())).unwrap();
568 let w = Who {
569 key,
570 id,
571 session: VoiceSessionId::from_bytes([n; 16]),
572 package: keys.key_package(),
573 };
574 (w, keys)
575 }
576
577 fn participant(w: &Who) -> VoiceParticipant {
578 VoiceParticipant {
579 member_id: w.id,
580 voice_session: w.session,
581 key_package: Some(Opaque(w.package.clone())),
582 member_public_key: Some(w.key.public_key()),
583 self_mute: false,
584 self_deaf: false,
585 server_mute: false,
586 server_deaf: false,
587 can_speak: true,
588 }
589 }
590
591 fn join(w: &Who, keys: StayKeys, there: &[&Who], wall: u64) -> (Stay, Vec<Act>) {
593 let mut participants: Vec<VoiceParticipant> =
594 there.iter().map(|o| participant(o)).collect();
595 participants.push(participant(w));
596 let joined = Joined {
597 channel_id: CH,
598 voice_session: w.session,
599 participants,
600 ice_servers: Vec::new(),
601 ice_policy: IcePolicy::Relay,
602 mesh_max: 8,
603 };
604 let mut stay = Stay::new(w.id, &joined, keys, false, false);
605 let acts = stay.begin(&joined, wall);
606 (stay, acts)
607 }
608
609 fn keys_in(acts: &[Act]) -> Option<&KeysBody> {
610 acts.iter().find_map(|a| match a {
611 Act::Keys(k) => Some(k),
612 _ => None,
613 })
614 }
615
616 fn deliver(body: &KeysBody, from: &Who, to: &Who) -> HostInput {
618 let mine = body.keys.iter().find(|k| k.to == to.id).unwrap();
619 HostInput::Keys(VoiceKeys {
620 from: from.id,
621 voice_session: from.session,
622 epoch: body.epoch,
623 sender_keys: body.sender_keys.clone(),
624 wrapped: mine.wrapped.clone(),
625 })
626 }
627
628 fn told(acts: &[Act], from: &Who, to: &Who) -> HostInput {
630 let signal = acts
631 .iter()
632 .find_map(|a| match a {
633 Act::Tell {
634 session, signal, ..
635 } if *session == to.session => Some(signal.clone()),
636 _ => None,
637 })
638 .expect("a Keyed was told");
639 assert!(matches!(signal, Signal::Keyed { .. }));
640 HostInput::Signal(VoiceSignal {
641 from: from.id,
642 voice_session: from.session,
643 data: Opaque(signal.encode().unwrap()),
644 })
645 }
646
647 #[test]
648 fn a_new_epoch_seals_only_once_its_peer_said_it_has_the_keys() {
649 let ((a, ka), (b, kb)) = (who(1), who(2));
650 let (mut sa, acts) = join(&a, ka, &[], 0);
651 assert!(keys_in(&acts).is_none(), "alone, nothing is sent");
652 assert!(
653 sa.seal(b"to nobody").is_some(),
654 "alone, the epoch seals at once"
655 );
656
657 let (mut sb, b_acts) = join(&b, kb, &[&a], 10);
659 let a_acts = sa.on_host(HostInput::Joined(participant(&b)), 20);
660 let (body_a, body_b) = (keys_in(&a_acts).unwrap(), keys_in(&b_acts).unwrap());
661 assert!(!sa.sends_to(&b.session) && !sb.sends_to(&a.session));
662
663 let a_got = sa.on_host(deliver(body_b, &b, &a), 400);
665 assert!(
666 !sb.sends_to(&a.session),
667 "nothing before a said it has the keys"
668 );
669 assert!(sb.on_host(told(&a_got, &a, &b), 900).is_empty());
670 assert!(sb.sends_to(&a.session));
671 let frame = sb.seal(b"from b").unwrap();
672 assert_eq!(sa.open(&b.session, &frame).unwrap().1, b"from b");
673
674 let b_got = sb.on_host(deliver(body_a, &a, &b), 1_000);
676 assert!(!sa.sends_to(&b.session));
677 sa.on_host(told(&b_got, &b, &a), 1_500);
678 assert!(sa.sends_to(&b.session));
679 let frame = sa.seal(b"from a").unwrap();
680 assert_eq!(sb.open(&a.session, &frame).unwrap().1, b"from a");
681 }
682
683 #[test]
684 fn an_epoch_nobody_acknowledges_seals_after_the_wait() {
685 let ((a, ka), (b, _)) = (who(1), who(2));
686 let (mut sa, _) = join(&a, ka, &[], 0);
687 sa.on_host(HostInput::Joined(participant(&b)), 100);
688 assert_eq!(sa.next_deadline(), Some(100 + ACTIVATE_WITHIN_MS));
689 assert!(sa.on_time(99 + ACTIVATE_WITHIN_MS).is_empty());
690 assert!(!sa.sends_to(&b.session));
691 sa.on_time(100 + ACTIVATE_WITHIN_MS);
692 assert!(
693 sa.sends_to(&b.session),
694 "an older peer that never says so has the keys"
695 );
696 assert_eq!(sa.next_deadline(), None);
697 }
698
699 #[test]
700 fn a_join_waits_for_the_pending_epoch_and_a_leave_does_not() {
701 let ((a, ka), (b, kb), (c, _)) = (who(1), who(2), who(3));
702 let (mut sa, _) = join(&a, ka, &[], 0);
703 let (mut sb, _) = join(&b, kb, &[&a], 0);
704 let first = sa.on_host(HostInput::Joined(participant(&b)), 10);
705 let later = sa.on_host(HostInput::Joined(participant(&c)), 20);
707 assert!(keys_in(&later).is_none());
708 let b_got = sb.on_host(deliver(keys_in(&first).unwrap(), &a, &b), 30);
710 let next = sa.on_host(told(&b_got, &b, &a), 40);
711 assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
712 let to: Vec<MemberId> = keys_in(&next).unwrap().keys.iter().map(|k| k.to).collect();
713 assert_eq!(to.len(), 2);
714 let left = sa.on_host(
716 HostInput::Left(VoiceLeft {
717 channel_id: CH,
718 member_id: c.id,
719 voice_session: c.session,
720 reason: VoiceLeftReason::Left,
721 moved_to: None,
722 }),
723 50,
724 );
725 let to: Vec<MemberId> = keys_in(&left).unwrap().keys.iter().map(|k| k.to).collect();
726 assert_eq!(to, vec![b.id]);
727 }
728
729 fn left(w: &Who) -> HostInput {
730 HostInput::Left(VoiceLeft {
731 channel_id: CH,
732 member_id: w.id,
733 voice_session: w.session,
734 reason: VoiceLeftReason::Left,
735 moved_to: None,
736 })
737 }
738
739 fn opens(stay: &mut Stay, from: &Who, frame: &[u8]) -> Option<Vec<u8>> {
740 stay.open(&from.session, frame).map(|(_, f)| f)
741 }
742
743 fn three_hear_and_c_joins() -> (Vec<Who>, Stay, Stay, Stay, Stay, KeysBody) {
746 let ((a, ka), (b, kb), (c, kc), (d, kd)) = (who(1), who(2), who(3), who(4));
747 let (mut sa, first) = join(&a, ka, &[&b, &d], 0);
748 let (mut sb, _) = join(&b, kb, &[&a, &d], 0);
749 let (mut sd, _) = join(&d, kd, &[&a, &b], 0);
750 let first = keys_in(&first).unwrap();
751 for (s, w) in [(&mut sb, &b), (&mut sd, &d)] {
752 let got = s.on_host(deliver(first, &a, w), 10);
753 sa.on_host(told(&got, w, &a), 20);
754 }
755 assert!(sa.sends_to(&b.session) && sa.sends_to(&d.session));
756 let frame = sa.seal(b"first").unwrap();
757 assert_eq!(opens(&mut sb, &a, &frame).unwrap(), b"first");
758
759 let (sc, _) = join(&c, kc, &[&a, &b, &d], 100);
760 let joined = sa.on_host(HostInput::Joined(participant(&c)), 100);
761 let next = keys_in(&joined).unwrap().clone();
762 sd.on_host(deliver(&next, &a, &d), 200);
763 (vec![a, b, c, d], sa, sb, sc, sd, next)
764 }
765
766 #[test]
767 fn a_leave_over_a_pending_epoch_its_hearers_have_does_not_cut_them_off() {
768 let (w, mut sa, mut sb, mut sc, mut sd, next) = three_hear_and_c_joins();
769 let (a, b, c, d) = (&w[0], &w[1], &w[2], &w[3]);
770 let got = sb.on_host(deliver(&next, a, b), 200);
771 sa.on_host(told(&got, b, a), 300);
772
773 let forced = sa.on_host(left(d), 400);
775 let forced = keys_in(&forced).unwrap();
776 assert!(!sa.sends_to(&d.session));
777 let got = sb.on_host(deliver(forced, a, b), 500);
780 let frame = sa.seal(b"while b's word travels").unwrap();
781 assert_eq!(
782 opens(&mut sb, a, &frame).unwrap(),
783 b"while b's word travels"
784 );
785
786 sa.on_host(told(&got, b, a), 600);
789 assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
790 let frame = sa.seal(b"after d left").unwrap();
791 assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"after d left");
792 assert!(
793 opens(&mut sd, a, &frame).is_none(),
794 "the leaver opens nothing"
795 );
796
797 let got = sc.on_host(deliver(forced, a, c), 700);
799 sa.on_host(told(&got, c, a), 800);
800 assert!(sa.sends_to(&c.session));
801 let frame = sa.seal(b"to b and c").unwrap();
802 assert_eq!(opens(&mut sc, a, &frame).unwrap(), b"to b and c");
803 assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"to b and c");
804 assert!(opens(&mut sd, a, &frame).is_none());
805 assert_eq!(sa.next_deadline(), None);
806 }
807
808 #[test]
809 fn a_leave_over_a_pending_epoch_not_all_hearers_have_seals_on_their_word_alone() {
810 let (w, mut sa, mut sb, mut sc, mut sd, next) = three_hear_and_c_joins();
811 let (a, b, c, d) = (&w[0], &w[1], &w[2], &w[3]);
812 let late_word = sb.on_host(deliver(&next, a, b), 200);
814 let forced = sa.on_host(left(d), 400);
815 let forced = keys_in(&forced).unwrap();
816 sa.on_host(told(&late_word, b, a), 450);
817 let got = sb.on_host(deliver(forced, a, b), 500);
818
819 sa.on_host(told(&got, b, a), 600);
821 assert!(sa.sends_to(&b.session) && !sa.sends_to(&c.session));
822 let frame = sa.seal(b"after d left").unwrap();
823 assert_eq!(opens(&mut sb, a, &frame).unwrap(), b"after d left");
824 assert!(
825 opens(&mut sd, a, &frame).is_none(),
826 "the leaver opens nothing"
827 );
828
829 assert_eq!(sa.next_deadline(), Some(400 + ACTIVATE_WITHIN_MS));
831 sc.on_host(deliver(forced, a, c), 700);
832 assert!(sa.on_time(399 + ACTIVATE_WITHIN_MS).is_empty());
833 assert!(!sa.sends_to(&c.session));
834 sa.on_time(400 + ACTIVATE_WITHIN_MS);
835 assert!(sa.sends_to(&c.session));
836 assert_eq!(sa.next_deadline(), None);
837 let frame = sa.seal(b"to c").unwrap();
838 assert_eq!(opens(&mut sc, a, &frame).unwrap(), b"to c");
839 }
840
841 #[test]
842 fn a_joiner_that_leaves_before_its_epoch_seals_opens_nothing_after() {
843 let ((a, ka), (b, kb), (c, kc)) = (who(1), who(2), who(3));
844 let (mut sa, first) = join(&a, ka, &[&b], 0);
845 let (mut sb, _) = join(&b, kb, &[&a], 0);
846 let got = sb.on_host(deliver(keys_in(&first).unwrap(), &a, &b), 10);
847 sa.on_host(told(&got, &b, &a), 20);
848 let (mut sc, _) = join(&c, kc, &[&a, &b], 100);
850 let joined = sa.on_host(HostInput::Joined(participant(&c)), 100);
851 let next = keys_in(&joined).unwrap();
852 let got = sb.on_host(deliver(next, &a, &b), 200);
853 sa.on_host(told(&got, &b, &a), 300);
854 sc.on_host(deliver(next, &a, &c), 200);
855 let forced = sa.on_host(left(&c), 400);
856 let forced = keys_in(&forced).unwrap();
857 let frame = sa.seal(b"after c left").unwrap();
859 assert!(
860 opens(&mut sc, &a, &frame).is_none(),
861 "the leaver opens nothing"
862 );
863 let got = sb.on_host(deliver(forced, &a, &b), 500);
864 sa.on_host(told(&got, &b, &a), 600);
865 let frame = sa.seal(b"to b").unwrap();
866 assert_eq!(opens(&mut sb, &a, &frame).unwrap(), b"to b");
867 assert!(opens(&mut sc, &a, &frame).is_none());
868 }
869
870 #[test]
871 fn a_changed_key_is_reported_with_its_member_and_nothing_else_names_one() {
872 let member = MemberId::from_bytes([2; 16]);
873 assert!(matches!(
874 refusal(member, AddError::KeyChanged),
875 VoiceEvent::KeyChanged { member: m } if m == member
876 ));
877 for e in [
878 AddError::Missing,
879 AddError::Refused(zaun_community_protocol::crypto::voice::VoiceError::Replay),
880 AddError::Unpinned("disk full".into()),
881 ] {
882 assert!(matches!(refusal(member, e), VoiceEvent::Warning(_)));
883 }
884 }
885}