1use nostr_sdk::prelude::{Event, EventBuilder, Keys, PublicKey, Tag, Timestamp, UnsignedEvent,
30};
31
32use super::super::{ChannelId, Epoch};
33use crate::event_ext::FinalizeUnsignedWithId;
34use super::derive::{channel_group_key, GroupKey};
35use super::kind;
36use super::stream::{self, OpenedStream, SealForm, StreamError};
37
38const TAG_QUOTE: &str = "q";
39const TAG_TARGET: &str = "e";
40const TAG_TARGET_AUTHOR: &str = "p";
41const TAG_TARGET_KIND: &str = "k";
42const TAG_EMOJI: &str = "emoji";
43const TAG_TRANSPORT: &str = "transport";
44const TAG_ENDPOINT: &str = "endpoint";
45const TAG_RELAY: &str = "relay";
46const TAG_MUTED: &str = "muted";
47const TAG_DEAFENED: &str = "deafened";
48const TAG_VIDEO: &str = "video";
50const VIDEO_SCREEN: &str = "screen";
51const VIDEO_CAMERA: &str = "camera";
52const TAG_DO: &str = "do";
53const TAG_TO: &str = "to";
54pub const TRANSPORT_IROH: &str = "iroh";
56
57#[derive(Debug)]
59pub enum ChatError {
60 Stream(StreamError),
61 NotEncryptedSealed,
64 UnknownKind(u16),
67 MissingTag(&'static str),
68 DuplicateTag(&'static str),
71 BadTag(&'static str),
73 NoHeldEpoch,
75 WriterEpochMismatch,
77}
78
79impl std::fmt::Display for ChatError {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 match self {
82 ChatError::Stream(e) => write!(f, "stream: {e}"),
83 ChatError::NotEncryptedSealed => write!(f, "chat rumor must ride an encrypted seal"),
84 ChatError::UnknownKind(k) => write!(f, "rumor kind {k} is not a chat-plane kind"),
85 ChatError::MissingTag(t) => write!(f, "missing chat tag: {t}"),
86 ChatError::DuplicateTag(t) => write!(f, "duplicate chat tag: {t}"),
87 ChatError::BadTag(t) => write!(f, "malformed chat tag: {t}"),
88 ChatError::NoHeldEpoch => write!(f, "wrap author matches no held epoch key"),
89 ChatError::WriterEpochMismatch => write!(f, "writer epoch doesn't match the address"),
90 }
91 }
92}
93
94impl std::error::Error for ChatError {}
95
96impl From<StreamError> for ChatError {
97 fn from(e: StreamError) -> Self {
98 ChatError::Stream(e)
99 }
100}
101
102pub fn chat_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
110 channel_group_key(secret, channel_id, epoch)
111}
112
113#[allow(clippy::too_many_arguments)]
124pub fn build_message_rumor(
125 author: PublicKey,
126 channel_id: &ChannelId,
127 epoch: Epoch,
128 content: &str,
129 reply_to: Option<(&str, &str)>,
130 emoji: &[(&str, &str)],
131 extra_tags: Vec<Tag>,
132 at_ms: u64,
133) -> UnsignedEvent {
134 let mut tags = stream::channel_binding_tags(channel_id, epoch);
135 if let Some((parent_id, parent_author)) = reply_to {
136 tags.push(Tag::custom(
137 "q",
138 [parent_id.to_string(), String::new(), parent_author.to_string()],
139 ));
140 }
141 for (shortcode, url) in emoji {
142 tags.push(emoji_tag(shortcode, url));
143 }
144 tags.extend(extra_tags);
145 stream::build_rumor_ms(kind::MESSAGE, author, content, tags, at_ms)
146}
147
148pub(crate) fn message_expiration(rumor: &UnsignedEvent) -> Option<u64> {
153 rumor.tags.iter().find_map(|tag| {
154 let s = tag.as_slice();
155 if s.len() >= 2 && s[0] == "expiration" {
156 s[1].parse::<u64>().ok()
157 } else {
158 None
159 }
160 })
161}
162
163#[allow(clippy::too_many_arguments)]
170pub fn build_comment_rumor(
171 author: PublicKey,
172 channel_id: &ChannelId,
173 epoch: Epoch,
174 content: &str,
175 parent_id_hex: &str,
176 parent_kind: u16,
177 parent_author_hex: &str,
178 parent_root: Option<(&str, u16, &str)>,
179 emoji: &[(&str, &str)],
180 at_ms: u64,
181) -> UnsignedEvent {
182 let mut tags = stream::channel_binding_tags(channel_id, epoch);
183 let (root_id, root_kind, root_author) = parent_root.unwrap_or((parent_id_hex, parent_kind, parent_author_hex));
184 tags.push(Tag::custom("K", [root_kind.to_string()]));
185 tags.push(Tag::custom(
186 "E",
187 [root_id.to_string(), String::new(), root_author.to_string()],
188 ));
189 tags.push(Tag::custom("P", [root_author.to_string()]));
190 tags.push(Tag::custom("k", [parent_kind.to_string()]));
191 tags.push(Tag::custom(
192 "e",
193 [parent_id_hex.to_string(), String::new(), parent_author_hex.to_string()],
194 ));
195 tags.push(Tag::custom("p", [parent_author_hex.to_string()]));
196 for (shortcode, url) in emoji {
197 tags.push(emoji_tag(shortcode, url));
198 }
199 stream::build_rumor_ms(kind::COMMENT, author, content, tags, at_ms)
200}
201
202#[allow(clippy::too_many_arguments)]
208pub fn build_reaction_rumor(
209 author: PublicKey,
210 channel_id: &ChannelId,
211 epoch: Epoch,
212 target_rumor_id_hex: &str,
213 target_author_hex: &str,
214 target_kind: u16,
215 emoji_content: &str,
216 emoji: Option<(&str, &str)>,
217 at_ms: u64,
218) -> UnsignedEvent {
219 let mut tags = stream::channel_binding_tags(channel_id, epoch);
220 tags.push(Tag::custom("e", [target_rumor_id_hex.to_string()]));
221 tags.push(Tag::custom("p", [target_author_hex.to_string()]));
222 tags.push(Tag::custom(
223 "k",
224 [target_kind.to_string()],
225 ));
226 if let Some((shortcode, url)) = emoji {
227 tags.push(emoji_tag(shortcode, url));
228 }
229 stream::build_rumor_ms(kind::REACTION, author, emoji_content, tags, at_ms)
230}
231
232pub fn build_delete_rumor(
241 author: PublicKey,
242 channel_id: &ChannelId,
243 epoch: Epoch,
244 target_rumor_id_hex: &str,
245 target_kind: u16,
246 at_ms: u64,
247 citation: Option<&crate::community::edition::AuthorityCitation>,
248) -> UnsignedEvent {
249 build_delete_rumor_until(author, channel_id, epoch, target_rumor_id_hex, target_kind, at_ms, citation, None)
250}
251
252#[allow(clippy::too_many_arguments)]
254pub fn build_delete_rumor_until(
255 author: PublicKey,
256 channel_id: &ChannelId,
257 epoch: Epoch,
258 target_rumor_id_hex: &str,
259 target_kind: u16,
260 at_ms: u64,
261 citation: Option<&crate::community::edition::AuthorityCitation>,
262 expiration: Option<u64>,
263) -> UnsignedEvent {
264 let mut tags = stream::channel_binding_tags(channel_id, epoch);
265 if let Some(exp) = expiration {
266 tags.push(Tag::expiration(Timestamp::from_secs(exp)));
267 }
268 tags.push(Tag::custom("e", [target_rumor_id_hex.to_string()]));
269 tags.push(Tag::custom(
270 "k",
271 [target_kind.to_string()],
272 ));
273 if let Some(c) = citation {
274 tags.push(c.to_tag());
275 }
276 stream::build_rumor_ms(kind::DELETE, author, "", tags, at_ms)
277}
278
279#[allow(clippy::too_many_arguments)]
286pub fn build_edit_rumor(
287 author: PublicKey,
288 channel_id: &ChannelId,
289 epoch: Epoch,
290 target_rumor_id_hex: &str,
291 new_content: &str,
292 emoji: &[(&str, &str)],
293 expiration: Option<u64>,
294 at_ms: u64,
295) -> UnsignedEvent {
296 build_edit_rumor_tagged(author, channel_id, epoch, target_rumor_id_hex, new_content, emoji, expiration, Vec::new(), at_ms)
297}
298
299#[allow(clippy::too_many_arguments)]
301pub fn build_edit_rumor_tagged(
302 author: PublicKey,
303 channel_id: &ChannelId,
304 epoch: Epoch,
305 target_rumor_id_hex: &str,
306 new_content: &str,
307 emoji: &[(&str, &str)],
308 expiration: Option<u64>,
309 extra_tags: Vec<Tag>,
310 at_ms: u64,
311) -> UnsignedEvent {
312 let mut tags = stream::channel_binding_tags(channel_id, epoch);
313 tags.push(Tag::custom("e", [target_rumor_id_hex.to_string()]));
314 for (shortcode, url) in emoji {
315 tags.push(emoji_tag(shortcode, url));
316 }
317 if let Some(exp) = expiration {
318 tags.push(Tag::expiration(Timestamp::from_secs(exp)));
319 }
320 tags.extend(extra_tags);
321 stream::build_rumor_ms(kind::EDIT, author, new_content, tags, at_ms)
322}
323
324pub fn build_webxdc_rumor(
327 author: PublicKey,
328 channel_id: &ChannelId,
329 epoch: Epoch,
330 content: &str,
331 extra_tags: Vec<Tag>,
332 at_ms: u64,
333) -> UnsignedEvent {
334 let mut tags = stream::channel_binding_tags(channel_id, epoch);
335 tags.extend(extra_tags);
336 stream::build_rumor_ms(kind::WEBXDC, author, content, tags, at_ms)
337}
338
339pub fn build_voice_presence_rumor(author: PublicKey, channel_id: &ChannelId, epoch: Epoch, endpoint: Option<(&[u8; 32], Option<&str>)>, showing: super::voice::Showing, at_ms: u64) -> UnsignedEvent {
345 let mut tags = stream::channel_binding_tags(channel_id, epoch);
346 if let Some((ep, relay)) = endpoint {
347 tags.push(Tag::custom(TAG_TRANSPORT, [TRANSPORT_IROH.to_string()]));
348 tags.push(Tag::custom(TAG_ENDPOINT, [crate::simd::hex::bytes_to_hex_32(ep)]));
349 if let Some(r) = relay {
350 tags.push(Tag::custom(TAG_RELAY, [r.to_string()]));
351 }
352 if showing.muted {
353 tags.push(Tag::custom(TAG_MUTED, Vec::<String>::new()));
354 }
355 if showing.deafened {
356 tags.push(Tag::custom(TAG_DEAFENED, Vec::<String>::new()));
357 }
358 if showing.screen {
359 tags.push(Tag::custom(TAG_VIDEO, [VIDEO_SCREEN.to_string()]));
360 }
361 if showing.camera {
362 tags.push(Tag::custom(TAG_VIDEO, [VIDEO_CAMERA.to_string()]));
363 }
364 }
365 stream::build_rumor_ms(kind::VOICE_PRESENCE, author, if endpoint.is_some() { "joined" } else { "left" }, tags, at_ms)
366}
367
368#[allow(clippy::too_many_arguments)]
370pub fn build_voice_directive_rumor(
371 actor: PublicKey,
372 channel_id: &ChannelId,
373 epoch: Epoch,
374 target: &PublicKey,
375 directive: super::voice::Directive,
376 to: Option<&[u8; 32]>,
377 citation: Option<&crate::community::edition::AuthorityCitation>,
378 at_ms: u64,
379) -> UnsignedEvent {
380 let mut tags = stream::channel_binding_tags(channel_id, epoch);
381 tags.push(Tag::public_key(*target));
382 tags.push(Tag::custom(TAG_DO, [directive.as_str().to_string()]));
383 if let Some(to) = to {
384 tags.push(Tag::custom(TAG_TO, [crate::simd::hex::bytes_to_hex_32(to)]));
385 }
386 if let Some(c) = citation {
387 tags.push(c.to_tag());
388 }
389 stream::build_rumor_ms(kind::VOICE_DIRECTIVE, actor, "", tags, at_ms)
390}
391
392pub fn build_typing_rumor(author: PublicKey, channel_id: &ChannelId, epoch: Epoch, at_ms: u64) -> UnsignedEvent {
393 let tags = stream::channel_binding_tags(channel_id, epoch);
394 stream::build_rumor_ms(kind::TYPING, author, "", tags, at_ms)
395}
396
397pub fn seal_chat_rumor(
407 rumor: &UnsignedEvent,
408 group: &GroupKey,
409 author_keys: &Keys,
410 wrap_at: Timestamp,
411 ephemeral: bool,
412) -> Result<(Event, Keys), ChatError> {
413 let k = rumor.kind.as_u16();
414 if !is_chat_kind(k) {
415 return Err(ChatError::UnknownKind(k));
416 }
417 let seal = stream::build_seal(rumor, SealForm::Encrypted, group, author_keys)?;
418 let wrap_kind = if ephemeral { stream::KIND_WRAP_EPHEMERAL } else { stream::KIND_WRAP };
419 let wrap_extra: Vec<Tag> = rumor
423 .tags
424 .iter()
425 .filter(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
426 .cloned()
427 .collect();
428 Ok(stream::wrap_seal_with_tags(&seal, group, wrap_kind, wrap_at, &wrap_extra)?)
429}
430
431pub async fn seal_chat_rumor_signed<S: crate::signer::VectorSigner + ?Sized>(
436 signer: &S,
437 author: nostr_sdk::prelude::PublicKey,
438 rumor: &UnsignedEvent,
439 group: &GroupKey,
440 wrap_at: Timestamp,
441 ephemeral: bool,
442 owner: &nostr_sdk::prelude::PublicKey,
443) -> Result<Event, ChatError> {
444 let k = rumor.kind.as_u16();
445 if !is_chat_kind(k) {
446 return Err(ChatError::UnknownKind(k));
447 }
448 let wrap_kind = if ephemeral { stream::KIND_WRAP_EPHEMERAL } else { stream::KIND_WRAP };
449 let wrap_extra: Vec<Tag> = rumor
450 .tags
451 .iter()
452 .filter(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
453 .cloned()
454 .collect();
455 Ok(stream::seal_and_wrap_signed_for(signer, author, rumor, SealForm::Encrypted, group, wrap_kind, wrap_at, &wrap_extra, owner).await?)
456}
457
458#[derive(Debug, Clone, PartialEq, Eq)]
461pub struct ReplyRef {
462 pub id: [u8; 32],
463 pub author: Option<PublicKey>,
464}
465
466#[derive(Debug, Clone)]
469pub enum ChatEvent {
470 Message {
476 opened: OpenedStream,
477 reply_to: Option<ReplyRef>,
478 emoji: Vec<(String, String)>,
479 },
480 Reaction {
483 opened: OpenedStream,
484 target: [u8; 32],
485 target_author: PublicKey,
486 emoji: String,
487 emoji_url: Option<String>,
488 },
489 Delete {
492 opened: OpenedStream,
493 target: [u8; 32],
494 target_kind: Option<u16>,
495 },
496 Edit {
500 opened: OpenedStream,
501 target: [u8; 32],
502 new_content: String,
503 emoji: Vec<(String, String)>,
504 },
505 Webxdc { opened: OpenedStream },
507 Typing { opened: OpenedStream },
509 VoicePresence { opened: OpenedStream, heard: super::voice::Heard },
512 VoiceDirective { opened: OpenedStream, target: PublicKey, directive: super::voice::Directive, to: Option<[u8; 32]> },
515}
516
517impl ChatEvent {
518 pub fn mark_held(&mut self) {
520 if let ChatEvent::Message { opened, .. } = self {
521 opened.held = true;
522 }
523 }
524
525 pub fn opened(&self) -> &OpenedStream {
527 match self {
528 ChatEvent::Message { opened, .. }
529 | ChatEvent::Reaction { opened, .. }
530 | ChatEvent::Delete { opened, .. }
531 | ChatEvent::Edit { opened, .. }
532 | ChatEvent::Webxdc { opened }
533 | ChatEvent::Typing { opened }
534 | ChatEvent::VoicePresence { opened, .. }
535 | ChatEvent::VoiceDirective { opened, .. } => opened,
536 }
537 }
538}
539
540pub fn open_chat_event(
545 wrap: &Event,
546 group: &GroupKey,
547 channel_id: &ChannelId,
548 epoch: Epoch,
549) -> Result<ChatEvent, ChatError> {
550 open_chat_event_at(wrap, &group.pk(), group.conv_key(), channel_id, epoch)
551}
552
553pub fn open_chat_event_at(
555 wrap: &Event,
556 address: &PublicKey,
557 conv_key: &nostr_sdk::prelude::nip44::v2::ConversationKey,
558 channel_id: &ChannelId,
559 epoch: Epoch,
560) -> Result<ChatEvent, ChatError> {
561 let opened = stream::open_wrap_at(wrap, address, conv_key, false)?;
562 if opened.seal_form != SealForm::Encrypted {
563 return Err(ChatError::NotEncryptedSealed);
564 }
565 stream::check_channel_binding(&opened.rumor, channel_id, epoch)?;
566 if writer_epoch_of(&opened.rumor)?.is_some() {
567 return Err(ChatError::WriterEpochMismatch);
568 }
569 parse_chat_rumor(opened)
570}
571
572pub fn open_writer_chat_event(
576 wrap: &Event,
577 writer: &PublicKey,
578 wepoch: Epoch,
579 conv_key: &nostr_sdk::prelude::nip44::v2::ConversationKey,
580 channel_id: &ChannelId,
581 epoch: Epoch,
582) -> Result<ChatEvent, ChatError> {
583 let opened = stream::open_wrap_at(wrap, writer, conv_key, true)?;
584 if opened.seal_form != SealForm::Encrypted {
585 return Err(ChatError::NotEncryptedSealed);
586 }
587 stream::check_channel_binding(&opened.rumor, channel_id, epoch)?;
588 if writer_epoch_of(&opened.rumor)? != Some(wepoch) {
589 return Err(ChatError::WriterEpochMismatch);
590 }
591 parse_chat_rumor(opened)
592}
593
594const TAG_WEPOCH: &str = "wepoch";
595
596pub(crate) fn writer_epoch_of(rumor: &UnsignedEvent) -> Result<Option<Epoch>, ChatError> {
598 let mut found = None;
599 for t in rumor.tags.iter() {
600 let s = t.as_slice();
601 if s.first().map(String::as_str) != Some(TAG_WEPOCH) {
602 continue;
603 }
604 let n = s.get(1).and_then(|v| v.parse::<u64>().ok().filter(|n| n.to_string() == *v)).ok_or(ChatError::BadTag(TAG_WEPOCH))?;
605 if found.replace(Epoch(n)).is_some() {
606 return Err(ChatError::DuplicateTag(TAG_WEPOCH));
607 }
608 }
609 Ok(found)
610}
611
612pub fn carries_writer_epoch(rumor: &UnsignedEvent) -> bool {
614 writer_epoch_of(rumor).is_ok_and(|e| e.is_some())
615}
616
617const TAG_WCERT: &str = "wcert";
618
619pub fn writer_cert_of(rumor: &UnsignedEvent) -> Option<[u8; 64]> {
621 let s = rumor.tags.iter().map(|t| t.as_slice()).find(|s| s.first().map(String::as_str) == Some(TAG_WCERT))?;
622 crate::simd::hex::hex_string_to_bytes_checked(s.get(1)?)?.try_into().ok()
623}
624
625pub fn with_writer_epoch(rumor: UnsignedEvent, wepoch: Epoch) -> UnsignedEvent {
627 with_writer(rumor, wepoch, None)
628}
629
630pub fn with_writer(rumor: UnsignedEvent, wepoch: Epoch, cert: Option<&[u8; 64]>) -> UnsignedEvent {
632 let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
633 tags.push(Tag::custom(TAG_WEPOCH, [wepoch.0.to_string()]));
634 if let Some(cert) = cert {
635 tags.push(Tag::custom(TAG_WCERT, [crate::simd::hex::bytes_to_hex_string(cert)]));
636 }
637 let mut out = EventBuilder::new(rumor.kind, rumor.content).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
638 out.ensure_id();
639 out
640}
641
642pub fn rides_writer_address(kind: u16) -> bool {
647 !matches!(kind, kind::REACTION | kind::DELETE | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE)
648}
649
650pub fn open_chat_event_multi(
662 wrap: &Event,
663 held: &[(Epoch, [u8; 32])],
664 channel_id: &ChannelId,
665) -> Result<(ChatEvent, Epoch), ChatError> {
666 for (epoch, secret) in held {
667 let group = channel_group_key(secret, channel_id, *epoch);
668 if wrap.pubkey == group.pk() {
669 return open_chat_event(wrap, &group, channel_id, *epoch).map(|ev| (ev, *epoch));
670 }
671 }
672 Err(ChatError::NoHeldEpoch)
673}
674
675fn is_chat_kind(k: u16) -> bool {
678 matches!(
679 k,
680 kind::MESSAGE | kind::COMMENT | kind::REACTION | kind::DELETE | kind::EDIT | kind::WEBXDC | kind::TYPING | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE
681 )
682}
683
684fn parse_chat_rumor(opened: OpenedStream) -> Result<ChatEvent, ChatError> {
688 match opened.rumor.kind.as_u16() {
689 kind::MESSAGE => {
690 let reply_to = match unique_tag(&opened.rumor, TAG_QUOTE)? {
691 None => None,
692 Some(s) => {
693 let id = decode_id32(value_of(s, TAG_QUOTE)?, TAG_QUOTE)?;
694 let author = match s.get(3).map(String::as_str).filter(|a| !a.is_empty()) {
697 Some(hex) => Some(PublicKey::from_hex(hex).map_err(|_| ChatError::BadTag(TAG_QUOTE))?),
698 None => None,
699 };
700 Some(ReplyRef { id, author })
701 }
702 };
703 let emoji = collect_emoji(&opened.rumor);
704 Ok(ChatEvent::Message { opened, reply_to, emoji })
705 }
706 kind::COMMENT => {
707 let reply_to = match unique_tag(&opened.rumor, TAG_TARGET)? {
712 None => None, Some(s) => {
714 let id = decode_id32(value_of(s, TAG_TARGET)?, TAG_TARGET)?;
715 let author = match s.get(3).map(String::as_str).filter(|a| !a.is_empty()) {
717 Some(hex) => Some(PublicKey::from_hex(hex).map_err(|_| ChatError::BadTag(TAG_TARGET))?),
718 None => None,
719 };
720 Some(ReplyRef { id, author })
721 }
722 };
723 let emoji = collect_emoji(&opened.rumor);
724 Ok(ChatEvent::Message { opened, reply_to, emoji })
725 }
726 kind::REACTION => {
727 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
728 let target_author = PublicKey::from_hex(required_tag(&opened.rumor, TAG_TARGET_AUTHOR)?)
729 .map_err(|_| ChatError::BadTag(TAG_TARGET_AUTHOR))?;
730 let emoji = opened.rumor.content.clone();
731 let code = emoji.strip_prefix(':').and_then(|s| s.strip_suffix(':'));
733 let emoji_url = code
734 .and_then(|code| collect_emoji(&opened.rumor).into_iter().find(|(c, _)| c == code))
735 .map(|(_, url)| url);
736 Ok(ChatEvent::Reaction { opened, target, target_author, emoji, emoji_url })
737 }
738 kind::DELETE => {
739 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
740 let target_kind = match unique_tag(&opened.rumor, TAG_TARGET_KIND)? {
741 None => None,
742 Some(s) => Some(
743 value_of(s, TAG_TARGET_KIND)?
744 .parse::<u16>()
745 .map_err(|_| ChatError::BadTag(TAG_TARGET_KIND))?,
746 ),
747 };
748 Ok(ChatEvent::Delete { opened, target, target_kind })
749 }
750 kind::EDIT => {
751 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
752 let new_content = opened.rumor.content.clone();
753 let emoji = collect_emoji(&opened.rumor);
754 Ok(ChatEvent::Edit { opened, target, new_content, emoji })
755 }
756 kind::WEBXDC => Ok(ChatEvent::Webxdc { opened }),
757 kind::TYPING => Ok(ChatEvent::Typing { opened }),
758 kind::VOICE_PRESENCE => {
759 let joined = match opened.rumor.content.as_str() {
760 "joined" => true,
761 "left" => false,
762 _ => return Err(ChatError::BadTag("content")),
763 };
764 let transport = unique_tag(&opened.rumor, TAG_TRANSPORT)?.map(|t| value_of(t, TAG_TRANSPORT).map(str::to_string)).transpose()?;
765 let endpoint = match (joined, transport.as_deref()) {
766 (true, Some(TRANSPORT_IROH)) => Some(decode_id32(required_tag(&opened.rumor, TAG_ENDPOINT)?, TAG_ENDPOINT)?),
767 _ => None,
768 };
769 let relay = match endpoint {
770 Some(_) => unique_tag(&opened.rumor, TAG_RELAY)?.map(|t| value_of(t, TAG_RELAY).map(str::to_string)).transpose()?,
771 None => None,
772 };
773 let flag = |name: &str| opened.rumor.tags.iter().any(|t| t.as_slice().first().map(String::as_str) == Some(name));
774 let (muted, deafened) = (joined && flag(TAG_MUTED), joined && flag(TAG_DEAFENED));
775 let video = |what: &str| joined && opened.rumor.tags.iter().any(|t| matches!(t.as_slice(), [k, v, ..] if k == TAG_VIDEO && v == what));
776 let (screen, camera) = (video(VIDEO_SCREEN), video(VIDEO_CAMERA));
777 Ok(ChatEvent::VoicePresence { opened, heard: super::voice::Heard { joined, transport, endpoint, relay, muted, deafened, screen, camera } })
778 }
779 kind::VOICE_DIRECTIVE => {
780 let target = PublicKey::from_hex(required_tag(&opened.rumor, TAG_TARGET_AUTHOR)?).map_err(|_| ChatError::BadTag(TAG_TARGET_AUTHOR))?;
781 let directive = super::voice::Directive::parse(required_tag(&opened.rumor, TAG_DO)?).ok_or(ChatError::BadTag(TAG_DO))?;
782 let to = match unique_tag(&opened.rumor, TAG_TO)? {
783 Some(t) => Some(decode_id32(value_of(t, TAG_TO)?, TAG_TO)?),
784 None => None,
785 };
786 if directive == super::voice::Directive::Move && to.is_none() {
787 return Err(ChatError::MissingTag(TAG_TO));
788 }
789 Ok(ChatEvent::VoiceDirective { opened, target, directive, to })
790 }
791 k => Err(ChatError::UnknownKind(k)),
792 }
793}
794
795fn emoji_tag(shortcode: &str, url: &str) -> Tag {
798 Tag::custom(TAG_EMOJI, [shortcode.to_string(), url.to_string()])
799}
800
801fn unique_tag<'a>(rumor: &'a UnsignedEvent, name: &'static str) -> Result<Option<&'a [String]>, ChatError> {
804 let mut found: Option<&[String]> = None;
805 for t in rumor.tags.iter() {
806 let s = t.as_slice();
807 if s.first().map(|n| n == name).unwrap_or(false) {
808 if found.is_some() {
809 return Err(ChatError::DuplicateTag(name));
810 }
811 found = Some(s);
812 }
813 }
814 Ok(found)
815}
816
817fn required_tag<'a>(rumor: &'a UnsignedEvent, name: &'static str) -> Result<&'a str, ChatError> {
819 let s = unique_tag(rumor, name)?.ok_or(ChatError::MissingTag(name))?;
820 value_of(s, name)
821}
822
823fn value_of<'a>(slice: &'a [String], name: &'static str) -> Result<&'a str, ChatError> {
824 slice.get(1).map(String::as_str).ok_or(ChatError::BadTag(name))
825}
826
827fn decode_id32(hex: &str, field: &'static str) -> Result<[u8; 32], ChatError> {
828 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
829 return Err(ChatError::BadTag(field));
830 }
831 Ok(crate::simd::hex::hex_to_bytes_32(hex))
832}
833
834fn collect_emoji(rumor: &UnsignedEvent) -> Vec<(String, String)> {
837 rumor
838 .tags
839 .iter()
840 .filter_map(|t| {
841 let s = t.as_slice();
842 (s.len() >= 3 && s[0] == TAG_EMOJI).then(|| (s[1].clone(), s[2].clone()))
843 })
844 .collect()
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850
851 const AT: u64 = 1_686_840_217_417;
852 const WRAP_AT: Timestamp = Timestamp::from_secs(1_700_000_000);
853
854 fn chan() -> ChannelId {
855 ChannelId([0xab; 32])
856 }
857
858 fn secret() -> [u8; 32] {
859 [7u8; 32]
860 }
861
862 fn group() -> GroupKey {
863 chat_group_key(&secret(), &chan(), Epoch(0))
864 }
865
866 fn open(wrap: &Event) -> Result<ChatEvent, ChatError> {
867 open_chat_event(wrap, &group(), &chan(), Epoch(0))
868 }
869
870 #[test]
871 fn a_post_carries_its_first_writer_certificate_and_a_malformed_one_is_none() {
872 let author = Keys::generate();
873 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "hi", None, &[], vec![], AT);
874 let first = with_writer(rumor.clone(), Epoch(1), Some(&[0x11; 64]));
875 let both = with_writer(first.clone(), Epoch(1), Some(&[0x22; 64]));
876 assert_eq!(writer_cert_of(&both), Some([0x11; 64]), "the first one");
877 let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
878 tags.push(Tag::custom(TAG_WCERT, ["zz"]));
879 tags.push(Tag::custom(TAG_WCERT, [crate::simd::hex::bytes_to_hex_string(&[0x33; 64])]));
880 let bad = EventBuilder::new(rumor.kind, rumor.content.clone()).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
881 assert_eq!(writer_cert_of(&bad), None, "a malformed first one hides nothing behind it");
882 assert_eq!(writer_cert_of(&rumor), None);
883 }
884
885 fn seal(rumor: &UnsignedEvent, author: &Keys) -> Event {
886 seal_chat_rumor(rumor, &group(), author, WRAP_AT, false).unwrap().0
887 }
888
889 #[test]
890 fn a_joined_presence_carries_what_its_author_shows_and_a_left_carries_nothing() {
891 use super::super::voice::Showing;
892 let author = Keys::generate();
893 let ep = [0x5a; 32];
894 let showing = Showing { muted: true, deafened: false, screen: true, camera: true };
895 let joined = build_voice_presence_rumor(author.public_key(), &chan(), Epoch(0), Some((&ep, Some("https://relay.example/"))), showing, AT);
896 let ChatEvent::VoicePresence { heard, .. } = open(&seal(&joined, &author)).unwrap() else { panic!("presence expected") };
897 assert!(heard.joined && heard.muted && !heard.deafened && heard.screen && heard.camera);
898 assert_eq!((heard.endpoint, heard.relay.as_deref()), (Some(ep), Some("https://relay.example/")));
899 let left = build_voice_presence_rumor(author.public_key(), &chan(), Epoch(0), None, showing, AT + 1);
900 let ChatEvent::VoicePresence { heard, .. } = open(&seal(&left, &author)).unwrap() else { panic!("presence expected") };
901 assert!(!heard.joined && !heard.muted && !heard.screen && !heard.camera && heard.endpoint.is_none(), "a left says nothing of what it showed");
902 }
903
904 #[test]
905 fn message_round_trip_carries_reply_emoji_and_extra_tags_verbatim() {
906 let author = Keys::generate();
907 let parent = Keys::generate();
908 let parent_id = "aa".repeat(32);
909 let imeta = Tag::custom(
910 "imeta",
911 ["url https://x/f.png".to_string(), "m image/png".to_string()],
912 );
913 let rumor = build_message_rumor(
914 author.public_key(),
915 &chan(),
916 Epoch(0),
917 "welcome :catJAM:",
918 Some((&parent_id, &parent.public_key().to_hex())),
919 &[("catJAM", "https://x/cat.gif")],
920 vec![imeta.clone()],
921 AT,
922 );
923 let wrap = seal(&rumor, &author);
924
925 let ChatEvent::Message { opened, reply_to, emoji } = open(&wrap).unwrap() else {
926 panic!("expected a Message");
927 };
928 assert_eq!(opened.author, author.public_key());
929 assert_eq!(opened.rumor.content, "welcome :catJAM:");
930 assert_eq!(opened.at_ms, AT);
931 let reply = reply_to.expect("reply parses back");
932 assert_eq!(reply.id, [0xaa; 32]);
933 assert_eq!(reply.author, Some(parent.public_key()));
934 assert_eq!(emoji, vec![("catJAM".to_string(), "https://x/cat.gif".to_string())]);
935 assert!(opened.rumor.tags.iter().any(|t| t.as_slice() == imeta.as_slice()));
937 }
938
939 #[test]
940 fn self_destruct_expiration_mirrors_onto_the_wrap_and_round_trips_into_the_message() {
941 const EXP: u64 = 1_700_000_500;
946 let author = Keys::generate();
947 let me = author.public_key();
948
949 let rumor = build_message_rumor(
951 me,
952 &chan(),
953 Epoch(0),
954 "poof",
955 None,
956 &[],
957 vec![Tag::expiration(Timestamp::from_secs(EXP))],
958 AT,
959 );
960 assert_eq!(message_expiration(&rumor), Some(EXP), "inner rumor carries the expiry");
961
962 let wrap = seal(&rumor, &author);
963 let mirrored = wrap.tags.iter().any(|t| {
965 let s = t.as_slice();
966 s.len() >= 2 && s[0] == "expiration" && s[1] == EXP.to_string()
967 });
968 assert!(mirrored, "the outer wrap mirrors the NIP-40 expiration for relays");
969
970 let ChatEvent::Message { opened, reply_to, emoji } = open(&wrap).unwrap() else {
972 panic!("expected a Message");
973 };
974 let msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
975 assert_eq!(msg.expiration, Some(EXP), "the receiver's Message carries the expiry");
976
977 let plain = build_message_rumor(me, &chan(), Epoch(0), "forever", None, &[], vec![], AT);
979 assert_eq!(message_expiration(&plain), None);
980 let plain_wrap = seal(&plain, &author);
981 assert!(!plain_wrap
982 .tags
983 .iter()
984 .any(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false)));
985 let ChatEvent::Message { opened, reply_to, emoji } = open(&plain_wrap).unwrap() else {
986 panic!("expected a Message");
987 };
988 let plain_msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
989 assert_eq!(plain_msg.expiration, None);
990 }
991
992 #[test]
993 fn a_received_message_carries_its_role_mentions() {
994 let (author, me) = (Keys::generate(), Keys::generate().public_key());
995 let role = "ab".repeat(32);
996 let tags = crate::community::mentions::to_tags(std::slice::from_ref(&role)).collect();
997 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "@Raid Team go", None, &[], tags, AT);
998 let ChatEvent::Message { opened, reply_to, emoji } = open(&seal(&rumor, &author)).unwrap() else {
999 panic!("expected a Message");
1000 };
1001 let msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
1002 assert_eq!(msg.role_mentions, vec![role]);
1003 }
1004
1005 #[test]
1006 fn message_without_q_has_no_reply() {
1007 let author = Keys::generate();
1008 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "hi", None, &[], vec![], AT);
1009 let ChatEvent::Message { reply_to, emoji, .. } = open(&seal(&rumor, &author)).unwrap() else {
1010 panic!("expected a Message");
1011 };
1012 assert_eq!(reply_to, None);
1013 assert!(emoji.is_empty());
1014 }
1015
1016 #[test]
1017 fn a_threaded_reply_round_trips_as_a_message_with_its_parent_as_reply_context() {
1018 let author = Keys::generate();
1021 let root_author = Keys::generate();
1022 let root_id = "cd".repeat(32);
1023 let rumor = build_comment_rumor(
1024 author.public_key(),
1025 &chan(),
1026 Epoch(0),
1027 "replying in the thread!",
1028 &root_id,
1029 kind::MESSAGE,
1030 &root_author.public_key().to_hex(),
1031 None, &[],
1033 AT,
1034 );
1035 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["K", "9"]));
1037 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "E" && t.as_slice()[1] == root_id));
1038 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "9"]));
1039
1040 let ChatEvent::Message { opened, reply_to, .. } = open(&seal(&rumor, &author)).unwrap() else {
1041 panic!("a threaded reply parses as a Message");
1042 };
1043 assert_eq!(opened.rumor.kind.as_u16(), kind::COMMENT, "the wire kind is preserved on the rumor");
1044 let reply = reply_to.expect("the immediate parent is the reply context");
1045 assert_eq!(reply.id, [0xcd; 32]);
1046 assert_eq!(reply.author, Some(root_author.public_key()));
1047 }
1048
1049 #[test]
1050 fn an_armada_shaped_threaded_reply_parses_verbatim() {
1051 let author = Keys::generate();
1055 let root_author = Keys::generate();
1056 let parent_author = Keys::generate();
1057 let root_id = "ef".repeat(32);
1058 let parent_id = "12".repeat(32);
1059 let tags = vec![
1060 Tag::custom("channel", [crate::simd::hex::bytes_to_hex_32(&chan().0)]),
1061 Tag::custom("epoch", ["0".to_string()]),
1062 Tag::custom("K", ["9".to_string()]),
1063 Tag::custom(
1064 "E",
1065 [root_id.clone(), String::new(), root_author.public_key().to_hex()],
1066 ),
1067 Tag::custom("P", [root_author.public_key().to_hex()]),
1068 Tag::custom("k", ["1111".to_string()]),
1069 Tag::custom("e", [parent_id.clone(), String::new(), parent_author.public_key().to_hex()]),
1070 Tag::custom("p", [parent_author.public_key().to_hex()]),
1071 ];
1072 let rumor = stream::build_rumor_ms(kind::COMMENT, author.public_key(), "nested reply", tags, AT);
1073 let ChatEvent::Message { reply_to, .. } = open(&seal(&rumor, &author)).unwrap() else {
1074 panic!("expected a Message");
1075 };
1076 let reply = reply_to.expect("parent parses");
1079 assert_eq!(reply.id, [0x12; 32]);
1080 assert_eq!(reply.author, Some(parent_author.public_key()));
1081 }
1082
1083 #[test]
1084 fn a_nested_comment_inherits_its_root_tags_verbatim() {
1085 let author = Keys::generate();
1086 let root_id = "ab".repeat(32);
1087 let root_author_hex = Keys::generate().public_key().to_hex();
1088 let parent_id = "cd".repeat(32);
1089 let parent_author_hex = Keys::generate().public_key().to_hex();
1090 let rumor = build_comment_rumor(
1091 author.public_key(),
1092 &chan(),
1093 Epoch(0),
1094 "deep",
1095 &parent_id,
1096 kind::COMMENT, &parent_author_hex,
1098 Some((&root_id, kind::MESSAGE, &root_author_hex)),
1099 &[],
1100 AT,
1101 );
1102 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "E" && t.as_slice()[1] == root_id));
1105 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["K", "9"]));
1106 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "1111"]));
1107 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "e" && t.as_slice()[1] == parent_id));
1108 }
1109
1110 #[test]
1111 fn a_comment_with_duplicate_parent_tags_is_rejected() {
1112 let author = Keys::generate();
1115 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1116 for id in ["ab", "ff"] {
1117 tags.push(Tag::custom("e", [
1118 id.repeat(32),
1119 String::new(),
1120 Keys::generate().public_key().to_hex(),
1121 ]));
1122 }
1123 let rumor = stream::build_rumor_ms(kind::COMMENT, author.public_key(), "ambiguous", tags, AT);
1124 let got = open(&seal(&rumor, &author));
1125 assert!(matches!(&got, Err(ChatError::DuplicateTag("e"))), "got: {got:?}");
1126 }
1127
1128 #[test]
1129 fn a_reaction_to_a_threaded_reply_carries_k_1111() {
1130 let author = Keys::generate();
1131 let rumor = build_reaction_rumor(
1132 author.public_key(),
1133 &chan(),
1134 Epoch(0),
1135 &"bc".repeat(32),
1136 &Keys::generate().public_key().to_hex(),
1137 kind::COMMENT,
1138 "🔥",
1139 None,
1140 AT,
1141 );
1142 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "1111"]), "the k tag names the target's kind");
1143 assert!(matches!(open(&seal(&rumor, &author)).unwrap(), ChatEvent::Reaction { .. }));
1144 }
1145
1146 #[test]
1147 fn reaction_round_trip_and_nip25_shape() {
1148 let author = Keys::generate();
1149 let target_author = Keys::generate();
1150 let target_id = "bc".repeat(32);
1151 let rumor = build_reaction_rumor(
1152 author.public_key(),
1153 &chan(),
1154 Epoch(0),
1155 &target_id,
1156 &target_author.public_key().to_hex(),
1157 kind::MESSAGE,
1158 "🔥",
1159 None,
1160 AT,
1161 );
1162 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "9"]));
1164
1165 let ChatEvent::Reaction { opened, target, target_author: ta, emoji, emoji_url } =
1166 open(&seal(&rumor, &author)).unwrap()
1167 else {
1168 panic!("expected a Reaction");
1169 };
1170 assert_eq!(opened.author, author.public_key());
1171 assert_eq!(target, [0xbc; 32]);
1172 assert_eq!(ta, target_author.public_key());
1173 assert_eq!(emoji, "🔥");
1174 assert_eq!(emoji_url, None);
1175 assert_eq!(opened.at_ms, AT);
1176 }
1177
1178 #[test]
1179 fn reaction_custom_emoji_carries_the_nip30_url() {
1180 let author = Keys::generate();
1181 let rumor = build_reaction_rumor(
1182 author.public_key(),
1183 &chan(),
1184 Epoch(0),
1185 &"bc".repeat(32),
1186 &Keys::generate().public_key().to_hex(),
1187 kind::MESSAGE,
1188 ":catJAM:",
1189 Some(("catJAM", "https://x/cat.gif")),
1190 AT,
1191 );
1192 let ChatEvent::Reaction { emoji, emoji_url, .. } = open(&seal(&rumor, &author)).unwrap() else {
1193 panic!("expected a Reaction");
1194 };
1195 assert_eq!(emoji, ":catJAM:");
1196 assert_eq!(emoji_url, Some("https://x/cat.gif".to_string()));
1197 }
1198
1199 #[test]
1200 fn a_reaction_takes_only_the_emoji_tag_naming_its_own_shortcode() {
1201 let author = Keys::generate();
1202 let rumor = build_reaction_rumor(
1203 author.public_key(),
1204 &chan(),
1205 Epoch(0),
1206 &"bc".repeat(32),
1207 &Keys::generate().public_key().to_hex(),
1208 kind::MESSAGE,
1209 ":catJAM:",
1210 Some(("dogJAM", "https://x/dog.gif")),
1211 AT,
1212 );
1213 let ChatEvent::Reaction { emoji_url, .. } = open(&seal(&rumor, &author)).unwrap() else {
1214 panic!("expected a Reaction");
1215 };
1216 assert_eq!(emoji_url, None);
1217 }
1218
1219 #[test]
1220 fn delete_round_trip_and_optional_target_kind() {
1221 let author = Keys::generate();
1222 let rumor = build_delete_rumor(author.public_key(), &chan(), Epoch(0), &"cd".repeat(32), kind::MESSAGE, AT, None);
1223 let ChatEvent::Delete { target, target_kind, .. } = open(&seal(&rumor, &author)).unwrap() else {
1224 panic!("expected a Delete");
1225 };
1226 assert_eq!(target, [0xcd; 32]);
1227 assert_eq!(target_kind, Some(kind::MESSAGE));
1228
1229 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1231 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1232 let bare = stream::build_rumor_ms(kind::DELETE, author.public_key(), "", tags, AT);
1233 let ChatEvent::Delete { target_kind, .. } = open(&seal(&bare, &author)).unwrap() else {
1234 panic!("expected a Delete");
1235 };
1236 assert_eq!(target_kind, None);
1237 }
1238
1239 #[test]
1240 fn edit_round_trip_replaces_content() {
1241 let author = Keys::generate();
1242 let rumor = build_edit_rumor(author.public_key(), &chan(), Epoch(0), &"de".repeat(32), "fixed the typo", &[], None, AT);
1243 let ChatEvent::Edit { opened, target, new_content, .. } = open(&seal(&rumor, &author)).unwrap() else {
1244 panic!("expected an Edit");
1245 };
1246 assert_eq!(opened.author, author.public_key());
1247 assert_eq!(target, [0xde; 32]);
1248 assert_eq!(new_content, "fixed the typo");
1249 }
1250
1251 #[test]
1252 fn webxdc_round_trip_is_opaque() {
1253 let author = Keys::generate();
1254 let app_tag = Tag::custom("xdc", ["state-update".to_string()]);
1255 let rumor = build_webxdc_rumor(
1256 author.public_key(),
1257 &chan(),
1258 Epoch(0),
1259 "{\"move\":\"e4\"}",
1260 vec![app_tag.clone()],
1261 AT,
1262 );
1263 let ChatEvent::Webxdc { opened } = open(&seal(&rumor, &author)).unwrap() else {
1264 panic!("expected a Webxdc");
1265 };
1266 assert_eq!(opened.rumor.content, "{\"move\":\"e4\"}");
1267 assert!(opened.rumor.tags.iter().any(|t| t.as_slice() == app_tag.as_slice()));
1268 }
1269
1270 #[test]
1271 fn typing_rides_ephemeral_and_wrap_tier_is_not_content_authority() {
1272 let author = Keys::generate();
1273 let typing = build_typing_rumor(author.public_key(), &chan(), Epoch(0), AT);
1274 let (wrap, _) = seal_chat_rumor(&typing, &group(), &author, WRAP_AT, true).unwrap();
1275 assert_eq!(wrap.kind.as_u16(), stream::KIND_WRAP_EPHEMERAL);
1276 let ChatEvent::Typing { opened } = open(&wrap).unwrap() else {
1277 panic!("expected a Typing");
1278 };
1279 assert_eq!(opened.author, author.public_key());
1280 assert_eq!(opened.rumor.content, "");
1281
1282 let msg = build_message_rumor(author.public_key(), &chan(), Epoch(0), "live", None, &[], vec![], AT);
1285 let (wrap, _) = seal_chat_rumor(&msg, &group(), &author, WRAP_AT, true).unwrap();
1286 assert!(matches!(open(&wrap), Ok(ChatEvent::Message { .. })));
1287 }
1288
1289 #[test]
1290 fn wrong_channel_and_wrong_epoch_are_rejected() {
1291 let author = Keys::generate();
1292 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "x", None, &[], vec![], AT);
1293 let wrap = seal(&rumor, &author);
1294 assert!(matches!(
1296 open_chat_event(&wrap, &group(), &ChannelId([0xcd; 32]), Epoch(0)),
1297 Err(ChatError::Stream(StreamError::ChannelMismatch))
1298 ));
1299 let stale = build_message_rumor(author.public_key(), &chan(), Epoch(1), "x", None, &[], vec![], AT);
1301 let wrap = seal(&stale, &author);
1302 assert!(matches!(open(&wrap), Err(ChatError::Stream(StreamError::EpochMismatch))));
1303 }
1304
1305 #[test]
1306 fn reaction_bound_to_channel_a_under_channel_b_key_is_rejected() {
1307 let author = Keys::generate();
1311 let chan_a = ChannelId([0xaa; 32]);
1312 let chan_b = ChannelId([0xbb; 32]);
1313 let group_b = chat_group_key(&secret(), &chan_b, Epoch(0));
1314 let rumor = build_reaction_rumor(
1315 author.public_key(),
1316 &chan_a,
1317 Epoch(0),
1318 &"bc".repeat(32),
1319 &Keys::generate().public_key().to_hex(),
1320 kind::MESSAGE,
1321 "🔥",
1322 None,
1323 AT,
1324 );
1325 let (wrap, _) = seal_chat_rumor(&rumor, &group_b, &author, WRAP_AT, false).unwrap();
1326 assert!(matches!(
1327 open_chat_event(&wrap, &group_b, &chan_b, Epoch(0)),
1328 Err(ChatError::Stream(StreamError::ChannelMismatch))
1329 ));
1330 }
1331
1332 #[test]
1333 fn multi_epoch_opens_each_wrap_under_its_own_epoch() {
1334 let author = Keys::generate();
1335 let key0 = [1u8; 32];
1336 let key1 = [2u8; 32];
1337 let held = [(Epoch(0), key0), (Epoch(1), key1)];
1338
1339 let m0 = build_message_rumor(author.public_key(), &chan(), Epoch(0), "before the rekey", None, &[], vec![], AT);
1340 let g0 = chat_group_key(&key0, &chan(), Epoch(0));
1341 let (w0, _) = seal_chat_rumor(&m0, &g0, &author, WRAP_AT, false).unwrap();
1342
1343 let m1 = build_message_rumor(author.public_key(), &chan(), Epoch(1), "after the rekey", None, &[], vec![], AT + 1);
1344 let g1 = chat_group_key(&key1, &chan(), Epoch(1));
1345 let (w1, _) = seal_chat_rumor(&m1, &g1, &author, WRAP_AT, false).unwrap();
1346
1347 let (ev0, e0) = open_chat_event_multi(&w0, &held, &chan()).unwrap();
1348 assert_eq!(e0, Epoch(0));
1349 assert_eq!(ev0.opened().rumor.content, "before the rekey");
1350 let (ev1, e1) = open_chat_event_multi(&w1, &held, &chan()).unwrap();
1351 assert_eq!(e1, Epoch(1));
1352 assert_eq!(ev1.opened().rumor.content, "after the rekey");
1353 }
1354
1355 #[test]
1356 fn multi_epoch_unheld_wrap_is_not_ours() {
1357 let author = Keys::generate();
1358 let held = [(Epoch(0), [1u8; 32]), (Epoch(1), [2u8; 32])];
1359 let m2 = build_message_rumor(author.public_key(), &chan(), Epoch(2), "future", None, &[], vec![], AT);
1360 let g2 = chat_group_key(&[3u8; 32], &chan(), Epoch(2));
1361 let (w2, _) = seal_chat_rumor(&m2, &g2, &author, WRAP_AT, false).unwrap();
1362 assert!(matches!(open_chat_event_multi(&w2, &held, &chan()), Err(ChatError::NoHeldEpoch)));
1363 }
1364
1365 #[test]
1366 fn multi_epoch_cross_epoch_splice_is_rejected() {
1367 let author = Keys::generate();
1371 let key0 = [1u8; 32];
1372 let key1 = [2u8; 32];
1373 let held = [(Epoch(0), key0), (Epoch(1), key1)];
1374 let stale = build_message_rumor(author.public_key(), &chan(), Epoch(0), "replay", None, &[], vec![], AT);
1375 let g1 = chat_group_key(&key1, &chan(), Epoch(1));
1376 let (wrap, _) = seal_chat_rumor(&stale, &g1, &author, WRAP_AT, false).unwrap();
1377 assert!(matches!(
1378 open_chat_event_multi(&wrap, &held, &chan()),
1379 Err(ChatError::Stream(StreamError::EpochMismatch))
1380 ));
1381 }
1382
1383 #[test]
1384 fn duplicate_e_tag_on_a_reaction_is_rejected() {
1385 let author = Keys::generate();
1386 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1387 tags.push(Tag::custom("e", ["aa".repeat(32)]));
1388 tags.push(Tag::custom("e", ["bb".repeat(32)]));
1389 tags.push(Tag::custom("p", [Keys::generate().public_key().to_hex()]));
1390 let rumor = stream::build_rumor_ms(kind::REACTION, author.public_key(), "+", tags, AT);
1391 assert!(matches!(
1392 open(&seal(&rumor, &author)),
1393 Err(ChatError::DuplicateTag(TAG_TARGET))
1394 ));
1395 }
1396
1397 #[test]
1398 fn unknown_rumor_kind_is_rejected_on_both_sides() {
1399 let author = Keys::generate();
1400 let tags = stream::channel_binding_tags(&chan(), Epoch(0));
1402 let rumor = stream::build_rumor_ms(3300, author.public_key(), "v1 ghost", tags, AT);
1403 assert!(matches!(
1404 seal_chat_rumor(&rumor, &group(), &author, WRAP_AT, false),
1405 Err(ChatError::UnknownKind(3300))
1406 ));
1407 let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
1409 let (wrap, _) = stream::wrap_seal(&seal, &group(), stream::KIND_WRAP, WRAP_AT).unwrap();
1410 assert!(matches!(open(&wrap), Err(ChatError::UnknownKind(3300))));
1411 }
1412
1413 #[test]
1414 fn plaintext_sealed_chat_event_is_rejected() {
1415 let author = Keys::generate();
1416 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "leaky", None, &[], vec![], AT);
1417 let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group(), &author).unwrap();
1418 let (wrap, _) = stream::wrap_seal(&seal, &group(), stream::KIND_WRAP, WRAP_AT).unwrap();
1419 assert!(matches!(open(&wrap), Err(ChatError::NotEncryptedSealed)));
1420 }
1421
1422 #[test]
1423 fn malformed_targets_are_errors_not_panics() {
1424 let author = Keys::generate();
1425 let rumor = build_reaction_rumor(
1427 author.public_key(),
1428 &chan(),
1429 Epoch(0),
1430 &"zz".repeat(32),
1431 &Keys::generate().public_key().to_hex(),
1432 kind::MESSAGE,
1433 "+",
1434 None,
1435 AT,
1436 );
1437 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_TARGET))));
1438 let rumor = build_message_rumor(
1440 author.public_key(),
1441 &chan(),
1442 Epoch(0),
1443 "x",
1444 Some(("abcd", &Keys::generate().public_key().to_hex())),
1445 &[],
1446 vec![],
1447 AT,
1448 );
1449 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_QUOTE))));
1450 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1452 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1453 tags.push(Tag::custom(
1454 "k",
1455 ["nine".to_string()],
1456 ));
1457 let rumor = stream::build_rumor_ms(kind::DELETE, author.public_key(), "", tags, AT);
1458 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_TARGET_KIND))));
1459 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1461 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1462 let rumor = stream::build_rumor_ms(kind::REACTION, author.public_key(), "+", tags, AT);
1463 assert!(matches!(
1464 open(&seal(&rumor, &author)),
1465 Err(ChatError::MissingTag(TAG_TARGET_AUTHOR))
1466 ));
1467 }
1468}