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";
618const TAG_RCERT: &str = "rcert";
619
620#[derive(Debug, Clone, Copy, PartialEq, Eq)]
622pub enum WriterCert {
623 Full([u8; 64]),
624 Scoped([u8; 64], u64),
626}
627
628pub fn writer_cert_of(rumor: &UnsignedEvent) -> Option<[u8; 64]> {
630 let s = rumor.tags.iter().map(|t| t.as_slice()).find(|s| s.first().map(String::as_str) == Some(TAG_WCERT))?;
631 crate::simd::hex::hex_string_to_bytes_checked(s.get(1)?)?.try_into().ok()
632}
633
634pub fn scoped_cert_of(rumor: &UnsignedEvent) -> Option<([u8; 64], u64)> {
637 let s = rumor.tags.iter().map(|t| t.as_slice()).find(|s| s.first().map(String::as_str) == Some(TAG_RCERT))?;
638 let sig = crate::simd::hex::hex_string_to_bytes_checked(s.get(1)?)?.try_into().ok()?;
639 let rights = s.get(2).and_then(|v| v.parse::<u64>().ok().filter(|n| n.to_string() == *v))?;
640 Some((sig, rights))
641}
642
643pub fn writer_bit(kind: u16) -> Option<u64> {
646 use crate::community::roles::Permissions;
647 match kind {
648 kind::REACTION => Some(Permissions::ADD_REACTIONS),
649 kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE => Some(Permissions::CONNECT),
650 kind::DELETE => None,
651 _ => Some(Permissions::SEND_MESSAGES),
652 }
653}
654
655pub fn scope_covers(rights: u64, kind: u16) -> bool {
657 match writer_bit(kind) {
658 None => true,
659 Some(bit) => bit != crate::community::roles::Permissions::SEND_MESSAGES && rights & bit != 0,
660 }
661}
662
663pub fn with_writer_epoch(rumor: UnsignedEvent, wepoch: Epoch) -> UnsignedEvent {
665 with_writer(rumor, wepoch, None)
666}
667
668pub fn with_writer(rumor: UnsignedEvent, wepoch: Epoch, cert: Option<&[u8; 64]>) -> UnsignedEvent {
670 with_writer_cert(rumor, wepoch, cert.map(|c| WriterCert::Full(*c)))
671}
672
673pub fn with_writer_cert(rumor: UnsignedEvent, wepoch: Epoch, cert: Option<WriterCert>) -> UnsignedEvent {
675 let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
676 tags.push(Tag::custom(TAG_WEPOCH, [wepoch.0.to_string()]));
677 match cert {
678 Some(WriterCert::Full(cert)) => tags.push(Tag::custom(TAG_WCERT, [crate::simd::hex::bytes_to_hex_string(&cert)])),
679 Some(WriterCert::Scoped(cert, rights)) => tags.push(Tag::custom(TAG_RCERT, [crate::simd::hex::bytes_to_hex_string(&cert), rights.to_string()])),
680 None => {}
681 }
682 let mut out = EventBuilder::new(rumor.kind, rumor.content).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
683 out.ensure_id();
684 out
685}
686
687pub fn rides_writer_address(kind: u16, locked: bool) -> bool {
693 locked || !matches!(kind, kind::REACTION | kind::DELETE | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE)
694}
695
696pub fn open_chat_event_multi(
708 wrap: &Event,
709 held: &[(Epoch, [u8; 32])],
710 channel_id: &ChannelId,
711) -> Result<(ChatEvent, Epoch), ChatError> {
712 for (epoch, secret) in held {
713 let group = channel_group_key(secret, channel_id, *epoch);
714 if wrap.pubkey == group.pk() {
715 return open_chat_event(wrap, &group, channel_id, *epoch).map(|ev| (ev, *epoch));
716 }
717 }
718 Err(ChatError::NoHeldEpoch)
719}
720
721fn is_chat_kind(k: u16) -> bool {
724 matches!(
725 k,
726 kind::MESSAGE | kind::COMMENT | kind::REACTION | kind::DELETE | kind::EDIT | kind::WEBXDC | kind::TYPING | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE
727 )
728}
729
730fn parse_chat_rumor(opened: OpenedStream) -> Result<ChatEvent, ChatError> {
734 match opened.rumor.kind.as_u16() {
735 kind::MESSAGE => {
736 let reply_to = match unique_tag(&opened.rumor, TAG_QUOTE)? {
737 None => None,
738 Some(s) => {
739 let id = decode_id32(value_of(s, TAG_QUOTE)?, TAG_QUOTE)?;
740 let author = match s.get(3).map(String::as_str).filter(|a| !a.is_empty()) {
743 Some(hex) => Some(PublicKey::from_hex(hex).map_err(|_| ChatError::BadTag(TAG_QUOTE))?),
744 None => None,
745 };
746 Some(ReplyRef { id, author })
747 }
748 };
749 let emoji = collect_emoji(&opened.rumor);
750 Ok(ChatEvent::Message { opened, reply_to, emoji })
751 }
752 kind::COMMENT => {
753 let reply_to = match unique_tag(&opened.rumor, TAG_TARGET)? {
758 None => None, Some(s) => {
760 let id = decode_id32(value_of(s, TAG_TARGET)?, TAG_TARGET)?;
761 let author = match s.get(3).map(String::as_str).filter(|a| !a.is_empty()) {
763 Some(hex) => Some(PublicKey::from_hex(hex).map_err(|_| ChatError::BadTag(TAG_TARGET))?),
764 None => None,
765 };
766 Some(ReplyRef { id, author })
767 }
768 };
769 let emoji = collect_emoji(&opened.rumor);
770 Ok(ChatEvent::Message { opened, reply_to, emoji })
771 }
772 kind::REACTION => {
773 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
774 let target_author = PublicKey::from_hex(required_tag(&opened.rumor, TAG_TARGET_AUTHOR)?)
775 .map_err(|_| ChatError::BadTag(TAG_TARGET_AUTHOR))?;
776 let emoji = opened.rumor.content.clone();
777 let code = emoji.strip_prefix(':').and_then(|s| s.strip_suffix(':'));
779 let emoji_url = code
780 .and_then(|code| collect_emoji(&opened.rumor).into_iter().find(|(c, _)| c == code))
781 .map(|(_, url)| url);
782 Ok(ChatEvent::Reaction { opened, target, target_author, emoji, emoji_url })
783 }
784 kind::DELETE => {
785 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
786 let target_kind = match unique_tag(&opened.rumor, TAG_TARGET_KIND)? {
787 None => None,
788 Some(s) => Some(
789 value_of(s, TAG_TARGET_KIND)?
790 .parse::<u16>()
791 .map_err(|_| ChatError::BadTag(TAG_TARGET_KIND))?,
792 ),
793 };
794 Ok(ChatEvent::Delete { opened, target, target_kind })
795 }
796 kind::EDIT => {
797 let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?;
798 let new_content = opened.rumor.content.clone();
799 let emoji = collect_emoji(&opened.rumor);
800 Ok(ChatEvent::Edit { opened, target, new_content, emoji })
801 }
802 kind::WEBXDC => Ok(ChatEvent::Webxdc { opened }),
803 kind::TYPING => Ok(ChatEvent::Typing { opened }),
804 kind::VOICE_PRESENCE => {
805 let joined = match opened.rumor.content.as_str() {
806 "joined" => true,
807 "left" => false,
808 _ => return Err(ChatError::BadTag("content")),
809 };
810 let transport = unique_tag(&opened.rumor, TAG_TRANSPORT)?.map(|t| value_of(t, TAG_TRANSPORT).map(str::to_string)).transpose()?;
811 let endpoint = match (joined, transport.as_deref()) {
812 (true, Some(TRANSPORT_IROH)) => Some(decode_id32(required_tag(&opened.rumor, TAG_ENDPOINT)?, TAG_ENDPOINT)?),
813 _ => None,
814 };
815 let relay = match endpoint {
816 Some(_) => unique_tag(&opened.rumor, TAG_RELAY)?.map(|t| value_of(t, TAG_RELAY).map(str::to_string)).transpose()?,
817 None => None,
818 };
819 let flag = |name: &str| opened.rumor.tags.iter().any(|t| t.as_slice().first().map(String::as_str) == Some(name));
820 let (muted, deafened) = (joined && flag(TAG_MUTED), joined && flag(TAG_DEAFENED));
821 let video = |what: &str| joined && opened.rumor.tags.iter().any(|t| matches!(t.as_slice(), [k, v, ..] if k == TAG_VIDEO && v == what));
822 let (screen, camera) = (video(VIDEO_SCREEN), video(VIDEO_CAMERA));
823 Ok(ChatEvent::VoicePresence { opened, heard: super::voice::Heard { joined, transport, endpoint, relay, muted, deafened, screen, camera } })
824 }
825 kind::VOICE_DIRECTIVE => {
826 let target = PublicKey::from_hex(required_tag(&opened.rumor, TAG_TARGET_AUTHOR)?).map_err(|_| ChatError::BadTag(TAG_TARGET_AUTHOR))?;
827 let directive = super::voice::Directive::parse(required_tag(&opened.rumor, TAG_DO)?).ok_or(ChatError::BadTag(TAG_DO))?;
828 let to = match unique_tag(&opened.rumor, TAG_TO)? {
829 Some(t) => Some(decode_id32(value_of(t, TAG_TO)?, TAG_TO)?),
830 None => None,
831 };
832 if directive == super::voice::Directive::Move && to.is_none() {
833 return Err(ChatError::MissingTag(TAG_TO));
834 }
835 Ok(ChatEvent::VoiceDirective { opened, target, directive, to })
836 }
837 k => Err(ChatError::UnknownKind(k)),
838 }
839}
840
841fn emoji_tag(shortcode: &str, url: &str) -> Tag {
844 Tag::custom(TAG_EMOJI, [shortcode.to_string(), url.to_string()])
845}
846
847fn unique_tag<'a>(rumor: &'a UnsignedEvent, name: &'static str) -> Result<Option<&'a [String]>, ChatError> {
850 let mut found: Option<&[String]> = None;
851 for t in rumor.tags.iter() {
852 let s = t.as_slice();
853 if s.first().map(|n| n == name).unwrap_or(false) {
854 if found.is_some() {
855 return Err(ChatError::DuplicateTag(name));
856 }
857 found = Some(s);
858 }
859 }
860 Ok(found)
861}
862
863fn required_tag<'a>(rumor: &'a UnsignedEvent, name: &'static str) -> Result<&'a str, ChatError> {
865 let s = unique_tag(rumor, name)?.ok_or(ChatError::MissingTag(name))?;
866 value_of(s, name)
867}
868
869fn value_of<'a>(slice: &'a [String], name: &'static str) -> Result<&'a str, ChatError> {
870 slice.get(1).map(String::as_str).ok_or(ChatError::BadTag(name))
871}
872
873fn decode_id32(hex: &str, field: &'static str) -> Result<[u8; 32], ChatError> {
874 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
875 return Err(ChatError::BadTag(field));
876 }
877 Ok(crate::simd::hex::hex_to_bytes_32(hex))
878}
879
880fn collect_emoji(rumor: &UnsignedEvent) -> Vec<(String, String)> {
883 rumor
884 .tags
885 .iter()
886 .filter_map(|t| {
887 let s = t.as_slice();
888 (s.len() >= 3 && s[0] == TAG_EMOJI).then(|| (s[1].clone(), s[2].clone()))
889 })
890 .collect()
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896
897 const AT: u64 = 1_686_840_217_417;
898 const WRAP_AT: Timestamp = Timestamp::from_secs(1_700_000_000);
899
900 fn chan() -> ChannelId {
901 ChannelId([0xab; 32])
902 }
903
904 fn secret() -> [u8; 32] {
905 [7u8; 32]
906 }
907
908 fn group() -> GroupKey {
909 chat_group_key(&secret(), &chan(), Epoch(0))
910 }
911
912 fn open(wrap: &Event) -> Result<ChatEvent, ChatError> {
913 open_chat_event(wrap, &group(), &chan(), Epoch(0))
914 }
915
916 #[test]
917 fn a_post_carries_its_first_writer_certificate_and_a_malformed_one_is_none() {
918 let author = Keys::generate();
919 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "hi", None, &[], vec![], AT);
920 let first = with_writer(rumor.clone(), Epoch(1), Some(&[0x11; 64]));
921 let both = with_writer(first.clone(), Epoch(1), Some(&[0x22; 64]));
922 assert_eq!(writer_cert_of(&both), Some([0x11; 64]), "the first one");
923 let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
924 tags.push(Tag::custom(TAG_WCERT, ["zz"]));
925 tags.push(Tag::custom(TAG_WCERT, [crate::simd::hex::bytes_to_hex_string(&[0x33; 64])]));
926 let bad = EventBuilder::new(rumor.kind, rumor.content.clone()).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
927 assert_eq!(writer_cert_of(&bad), None, "a malformed first one hides nothing behind it");
928 assert_eq!(writer_cert_of(&rumor), None);
929 }
930
931 fn seal(rumor: &UnsignedEvent, author: &Keys) -> Event {
932 seal_chat_rumor(rumor, &group(), author, WRAP_AT, false).unwrap().0
933 }
934
935 #[test]
936 fn a_joined_presence_carries_what_its_author_shows_and_a_left_carries_nothing() {
937 use super::super::voice::Showing;
938 let author = Keys::generate();
939 let ep = [0x5a; 32];
940 let showing = Showing { muted: true, deafened: false, screen: true, camera: true };
941 let joined = build_voice_presence_rumor(author.public_key(), &chan(), Epoch(0), Some((&ep, Some("https://relay.example/"))), showing, AT);
942 let ChatEvent::VoicePresence { heard, .. } = open(&seal(&joined, &author)).unwrap() else { panic!("presence expected") };
943 assert!(heard.joined && heard.muted && !heard.deafened && heard.screen && heard.camera);
944 assert_eq!((heard.endpoint, heard.relay.as_deref()), (Some(ep), Some("https://relay.example/")));
945 let left = build_voice_presence_rumor(author.public_key(), &chan(), Epoch(0), None, showing, AT + 1);
946 let ChatEvent::VoicePresence { heard, .. } = open(&seal(&left, &author)).unwrap() else { panic!("presence expected") };
947 assert!(!heard.joined && !heard.muted && !heard.screen && !heard.camera && heard.endpoint.is_none(), "a left says nothing of what it showed");
948 }
949
950 #[test]
951 fn message_round_trip_carries_reply_emoji_and_extra_tags_verbatim() {
952 let author = Keys::generate();
953 let parent = Keys::generate();
954 let parent_id = "aa".repeat(32);
955 let imeta = Tag::custom(
956 "imeta",
957 ["url https://x/f.png".to_string(), "m image/png".to_string()],
958 );
959 let rumor = build_message_rumor(
960 author.public_key(),
961 &chan(),
962 Epoch(0),
963 "welcome :catJAM:",
964 Some((&parent_id, &parent.public_key().to_hex())),
965 &[("catJAM", "https://x/cat.gif")],
966 vec![imeta.clone()],
967 AT,
968 );
969 let wrap = seal(&rumor, &author);
970
971 let ChatEvent::Message { opened, reply_to, emoji } = open(&wrap).unwrap() else {
972 panic!("expected a Message");
973 };
974 assert_eq!(opened.author, author.public_key());
975 assert_eq!(opened.rumor.content, "welcome :catJAM:");
976 assert_eq!(opened.at_ms, AT);
977 let reply = reply_to.expect("reply parses back");
978 assert_eq!(reply.id, [0xaa; 32]);
979 assert_eq!(reply.author, Some(parent.public_key()));
980 assert_eq!(emoji, vec![("catJAM".to_string(), "https://x/cat.gif".to_string())]);
981 assert!(opened.rumor.tags.iter().any(|t| t.as_slice() == imeta.as_slice()));
983 }
984
985 #[test]
986 fn self_destruct_expiration_mirrors_onto_the_wrap_and_round_trips_into_the_message() {
987 const EXP: u64 = 1_700_000_500;
992 let author = Keys::generate();
993 let me = author.public_key();
994
995 let rumor = build_message_rumor(
997 me,
998 &chan(),
999 Epoch(0),
1000 "poof",
1001 None,
1002 &[],
1003 vec![Tag::expiration(Timestamp::from_secs(EXP))],
1004 AT,
1005 );
1006 assert_eq!(message_expiration(&rumor), Some(EXP), "inner rumor carries the expiry");
1007
1008 let wrap = seal(&rumor, &author);
1009 let mirrored = wrap.tags.iter().any(|t| {
1011 let s = t.as_slice();
1012 s.len() >= 2 && s[0] == "expiration" && s[1] == EXP.to_string()
1013 });
1014 assert!(mirrored, "the outer wrap mirrors the NIP-40 expiration for relays");
1015
1016 let ChatEvent::Message { opened, reply_to, emoji } = open(&wrap).unwrap() else {
1018 panic!("expected a Message");
1019 };
1020 let msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
1021 assert_eq!(msg.expiration, Some(EXP), "the receiver's Message carries the expiry");
1022
1023 let plain = build_message_rumor(me, &chan(), Epoch(0), "forever", None, &[], vec![], AT);
1025 assert_eq!(message_expiration(&plain), None);
1026 let plain_wrap = seal(&plain, &author);
1027 assert!(!plain_wrap
1028 .tags
1029 .iter()
1030 .any(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false)));
1031 let ChatEvent::Message { opened, reply_to, emoji } = open(&plain_wrap).unwrap() else {
1032 panic!("expected a Message");
1033 };
1034 let plain_msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
1035 assert_eq!(plain_msg.expiration, None);
1036 }
1037
1038 #[test]
1039 fn a_received_message_carries_its_role_mentions() {
1040 let (author, me) = (Keys::generate(), Keys::generate().public_key());
1041 let role = "ab".repeat(32);
1042 let tags = crate::community::mentions::to_tags(std::slice::from_ref(&role)).collect();
1043 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "@Raid Team go", None, &[], tags, AT);
1044 let ChatEvent::Message { opened, reply_to, emoji } = open(&seal(&rumor, &author)).unwrap() else {
1045 panic!("expected a Message");
1046 };
1047 let msg = crate::community::v2::inbound::chat_message_to_message(&opened, &reply_to, &emoji, &me);
1048 assert_eq!(msg.role_mentions, vec![role]);
1049 }
1050
1051 #[test]
1052 fn message_without_q_has_no_reply() {
1053 let author = Keys::generate();
1054 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "hi", None, &[], vec![], AT);
1055 let ChatEvent::Message { reply_to, emoji, .. } = open(&seal(&rumor, &author)).unwrap() else {
1056 panic!("expected a Message");
1057 };
1058 assert_eq!(reply_to, None);
1059 assert!(emoji.is_empty());
1060 }
1061
1062 #[test]
1063 fn a_threaded_reply_round_trips_as_a_message_with_its_parent_as_reply_context() {
1064 let author = Keys::generate();
1067 let root_author = Keys::generate();
1068 let root_id = "cd".repeat(32);
1069 let rumor = build_comment_rumor(
1070 author.public_key(),
1071 &chan(),
1072 Epoch(0),
1073 "replying in the thread!",
1074 &root_id,
1075 kind::MESSAGE,
1076 &root_author.public_key().to_hex(),
1077 None, &[],
1079 AT,
1080 );
1081 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["K", "9"]));
1083 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "E" && t.as_slice()[1] == root_id));
1084 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "9"]));
1085
1086 let ChatEvent::Message { opened, reply_to, .. } = open(&seal(&rumor, &author)).unwrap() else {
1087 panic!("a threaded reply parses as a Message");
1088 };
1089 assert_eq!(opened.rumor.kind.as_u16(), kind::COMMENT, "the wire kind is preserved on the rumor");
1090 let reply = reply_to.expect("the immediate parent is the reply context");
1091 assert_eq!(reply.id, [0xcd; 32]);
1092 assert_eq!(reply.author, Some(root_author.public_key()));
1093 }
1094
1095 #[test]
1096 fn an_armada_shaped_threaded_reply_parses_verbatim() {
1097 let author = Keys::generate();
1101 let root_author = Keys::generate();
1102 let parent_author = Keys::generate();
1103 let root_id = "ef".repeat(32);
1104 let parent_id = "12".repeat(32);
1105 let tags = vec![
1106 Tag::custom("channel", [crate::simd::hex::bytes_to_hex_32(&chan().0)]),
1107 Tag::custom("epoch", ["0".to_string()]),
1108 Tag::custom("K", ["9".to_string()]),
1109 Tag::custom(
1110 "E",
1111 [root_id.clone(), String::new(), root_author.public_key().to_hex()],
1112 ),
1113 Tag::custom("P", [root_author.public_key().to_hex()]),
1114 Tag::custom("k", ["1111".to_string()]),
1115 Tag::custom("e", [parent_id.clone(), String::new(), parent_author.public_key().to_hex()]),
1116 Tag::custom("p", [parent_author.public_key().to_hex()]),
1117 ];
1118 let rumor = stream::build_rumor_ms(kind::COMMENT, author.public_key(), "nested reply", tags, AT);
1119 let ChatEvent::Message { reply_to, .. } = open(&seal(&rumor, &author)).unwrap() else {
1120 panic!("expected a Message");
1121 };
1122 let reply = reply_to.expect("parent parses");
1125 assert_eq!(reply.id, [0x12; 32]);
1126 assert_eq!(reply.author, Some(parent_author.public_key()));
1127 }
1128
1129 #[test]
1130 fn a_nested_comment_inherits_its_root_tags_verbatim() {
1131 let author = Keys::generate();
1132 let root_id = "ab".repeat(32);
1133 let root_author_hex = Keys::generate().public_key().to_hex();
1134 let parent_id = "cd".repeat(32);
1135 let parent_author_hex = Keys::generate().public_key().to_hex();
1136 let rumor = build_comment_rumor(
1137 author.public_key(),
1138 &chan(),
1139 Epoch(0),
1140 "deep",
1141 &parent_id,
1142 kind::COMMENT, &parent_author_hex,
1144 Some((&root_id, kind::MESSAGE, &root_author_hex)),
1145 &[],
1146 AT,
1147 );
1148 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "E" && t.as_slice()[1] == root_id));
1151 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["K", "9"]));
1152 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "1111"]));
1153 assert!(rumor.tags.iter().any(|t| t.as_slice()[0] == "e" && t.as_slice()[1] == parent_id));
1154 }
1155
1156 #[test]
1157 fn a_comment_with_duplicate_parent_tags_is_rejected() {
1158 let author = Keys::generate();
1161 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1162 for id in ["ab", "ff"] {
1163 tags.push(Tag::custom("e", [
1164 id.repeat(32),
1165 String::new(),
1166 Keys::generate().public_key().to_hex(),
1167 ]));
1168 }
1169 let rumor = stream::build_rumor_ms(kind::COMMENT, author.public_key(), "ambiguous", tags, AT);
1170 let got = open(&seal(&rumor, &author));
1171 assert!(matches!(&got, Err(ChatError::DuplicateTag("e"))), "got: {got:?}");
1172 }
1173
1174 #[test]
1175 fn a_reaction_to_a_threaded_reply_carries_k_1111() {
1176 let author = Keys::generate();
1177 let rumor = build_reaction_rumor(
1178 author.public_key(),
1179 &chan(),
1180 Epoch(0),
1181 &"bc".repeat(32),
1182 &Keys::generate().public_key().to_hex(),
1183 kind::COMMENT,
1184 "🔥",
1185 None,
1186 AT,
1187 );
1188 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "1111"]), "the k tag names the target's kind");
1189 assert!(matches!(open(&seal(&rumor, &author)).unwrap(), ChatEvent::Reaction { .. }));
1190 }
1191
1192 #[test]
1193 fn reaction_round_trip_and_nip25_shape() {
1194 let author = Keys::generate();
1195 let target_author = Keys::generate();
1196 let target_id = "bc".repeat(32);
1197 let rumor = build_reaction_rumor(
1198 author.public_key(),
1199 &chan(),
1200 Epoch(0),
1201 &target_id,
1202 &target_author.public_key().to_hex(),
1203 kind::MESSAGE,
1204 "🔥",
1205 None,
1206 AT,
1207 );
1208 assert!(rumor.tags.iter().any(|t| t.as_slice() == ["k", "9"]));
1210
1211 let ChatEvent::Reaction { opened, target, target_author: ta, emoji, emoji_url } =
1212 open(&seal(&rumor, &author)).unwrap()
1213 else {
1214 panic!("expected a Reaction");
1215 };
1216 assert_eq!(opened.author, author.public_key());
1217 assert_eq!(target, [0xbc; 32]);
1218 assert_eq!(ta, target_author.public_key());
1219 assert_eq!(emoji, "🔥");
1220 assert_eq!(emoji_url, None);
1221 assert_eq!(opened.at_ms, AT);
1222 }
1223
1224 #[test]
1225 fn reaction_custom_emoji_carries_the_nip30_url() {
1226 let author = Keys::generate();
1227 let rumor = build_reaction_rumor(
1228 author.public_key(),
1229 &chan(),
1230 Epoch(0),
1231 &"bc".repeat(32),
1232 &Keys::generate().public_key().to_hex(),
1233 kind::MESSAGE,
1234 ":catJAM:",
1235 Some(("catJAM", "https://x/cat.gif")),
1236 AT,
1237 );
1238 let ChatEvent::Reaction { emoji, emoji_url, .. } = open(&seal(&rumor, &author)).unwrap() else {
1239 panic!("expected a Reaction");
1240 };
1241 assert_eq!(emoji, ":catJAM:");
1242 assert_eq!(emoji_url, Some("https://x/cat.gif".to_string()));
1243 }
1244
1245 #[test]
1246 fn a_reaction_takes_only_the_emoji_tag_naming_its_own_shortcode() {
1247 let author = Keys::generate();
1248 let rumor = build_reaction_rumor(
1249 author.public_key(),
1250 &chan(),
1251 Epoch(0),
1252 &"bc".repeat(32),
1253 &Keys::generate().public_key().to_hex(),
1254 kind::MESSAGE,
1255 ":catJAM:",
1256 Some(("dogJAM", "https://x/dog.gif")),
1257 AT,
1258 );
1259 let ChatEvent::Reaction { emoji_url, .. } = open(&seal(&rumor, &author)).unwrap() else {
1260 panic!("expected a Reaction");
1261 };
1262 assert_eq!(emoji_url, None);
1263 }
1264
1265 #[test]
1266 fn delete_round_trip_and_optional_target_kind() {
1267 let author = Keys::generate();
1268 let rumor = build_delete_rumor(author.public_key(), &chan(), Epoch(0), &"cd".repeat(32), kind::MESSAGE, AT, None);
1269 let ChatEvent::Delete { target, target_kind, .. } = open(&seal(&rumor, &author)).unwrap() else {
1270 panic!("expected a Delete");
1271 };
1272 assert_eq!(target, [0xcd; 32]);
1273 assert_eq!(target_kind, Some(kind::MESSAGE));
1274
1275 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1277 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1278 let bare = stream::build_rumor_ms(kind::DELETE, author.public_key(), "", tags, AT);
1279 let ChatEvent::Delete { target_kind, .. } = open(&seal(&bare, &author)).unwrap() else {
1280 panic!("expected a Delete");
1281 };
1282 assert_eq!(target_kind, None);
1283 }
1284
1285 #[test]
1286 fn edit_round_trip_replaces_content() {
1287 let author = Keys::generate();
1288 let rumor = build_edit_rumor(author.public_key(), &chan(), Epoch(0), &"de".repeat(32), "fixed the typo", &[], None, AT);
1289 let ChatEvent::Edit { opened, target, new_content, .. } = open(&seal(&rumor, &author)).unwrap() else {
1290 panic!("expected an Edit");
1291 };
1292 assert_eq!(opened.author, author.public_key());
1293 assert_eq!(target, [0xde; 32]);
1294 assert_eq!(new_content, "fixed the typo");
1295 }
1296
1297 #[test]
1298 fn webxdc_round_trip_is_opaque() {
1299 let author = Keys::generate();
1300 let app_tag = Tag::custom("xdc", ["state-update".to_string()]);
1301 let rumor = build_webxdc_rumor(
1302 author.public_key(),
1303 &chan(),
1304 Epoch(0),
1305 "{\"move\":\"e4\"}",
1306 vec![app_tag.clone()],
1307 AT,
1308 );
1309 let ChatEvent::Webxdc { opened } = open(&seal(&rumor, &author)).unwrap() else {
1310 panic!("expected a Webxdc");
1311 };
1312 assert_eq!(opened.rumor.content, "{\"move\":\"e4\"}");
1313 assert!(opened.rumor.tags.iter().any(|t| t.as_slice() == app_tag.as_slice()));
1314 }
1315
1316 #[test]
1317 fn typing_rides_ephemeral_and_wrap_tier_is_not_content_authority() {
1318 let author = Keys::generate();
1319 let typing = build_typing_rumor(author.public_key(), &chan(), Epoch(0), AT);
1320 let (wrap, _) = seal_chat_rumor(&typing, &group(), &author, WRAP_AT, true).unwrap();
1321 assert_eq!(wrap.kind.as_u16(), stream::KIND_WRAP_EPHEMERAL);
1322 let ChatEvent::Typing { opened } = open(&wrap).unwrap() else {
1323 panic!("expected a Typing");
1324 };
1325 assert_eq!(opened.author, author.public_key());
1326 assert_eq!(opened.rumor.content, "");
1327
1328 let msg = build_message_rumor(author.public_key(), &chan(), Epoch(0), "live", None, &[], vec![], AT);
1331 let (wrap, _) = seal_chat_rumor(&msg, &group(), &author, WRAP_AT, true).unwrap();
1332 assert!(matches!(open(&wrap), Ok(ChatEvent::Message { .. })));
1333 }
1334
1335 #[test]
1336 fn wrong_channel_and_wrong_epoch_are_rejected() {
1337 let author = Keys::generate();
1338 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "x", None, &[], vec![], AT);
1339 let wrap = seal(&rumor, &author);
1340 assert!(matches!(
1342 open_chat_event(&wrap, &group(), &ChannelId([0xcd; 32]), Epoch(0)),
1343 Err(ChatError::Stream(StreamError::ChannelMismatch))
1344 ));
1345 let stale = build_message_rumor(author.public_key(), &chan(), Epoch(1), "x", None, &[], vec![], AT);
1347 let wrap = seal(&stale, &author);
1348 assert!(matches!(open(&wrap), Err(ChatError::Stream(StreamError::EpochMismatch))));
1349 }
1350
1351 #[test]
1352 fn reaction_bound_to_channel_a_under_channel_b_key_is_rejected() {
1353 let author = Keys::generate();
1357 let chan_a = ChannelId([0xaa; 32]);
1358 let chan_b = ChannelId([0xbb; 32]);
1359 let group_b = chat_group_key(&secret(), &chan_b, Epoch(0));
1360 let rumor = build_reaction_rumor(
1361 author.public_key(),
1362 &chan_a,
1363 Epoch(0),
1364 &"bc".repeat(32),
1365 &Keys::generate().public_key().to_hex(),
1366 kind::MESSAGE,
1367 "🔥",
1368 None,
1369 AT,
1370 );
1371 let (wrap, _) = seal_chat_rumor(&rumor, &group_b, &author, WRAP_AT, false).unwrap();
1372 assert!(matches!(
1373 open_chat_event(&wrap, &group_b, &chan_b, Epoch(0)),
1374 Err(ChatError::Stream(StreamError::ChannelMismatch))
1375 ));
1376 }
1377
1378 #[test]
1379 fn multi_epoch_opens_each_wrap_under_its_own_epoch() {
1380 let author = Keys::generate();
1381 let key0 = [1u8; 32];
1382 let key1 = [2u8; 32];
1383 let held = [(Epoch(0), key0), (Epoch(1), key1)];
1384
1385 let m0 = build_message_rumor(author.public_key(), &chan(), Epoch(0), "before the rekey", None, &[], vec![], AT);
1386 let g0 = chat_group_key(&key0, &chan(), Epoch(0));
1387 let (w0, _) = seal_chat_rumor(&m0, &g0, &author, WRAP_AT, false).unwrap();
1388
1389 let m1 = build_message_rumor(author.public_key(), &chan(), Epoch(1), "after the rekey", None, &[], vec![], AT + 1);
1390 let g1 = chat_group_key(&key1, &chan(), Epoch(1));
1391 let (w1, _) = seal_chat_rumor(&m1, &g1, &author, WRAP_AT, false).unwrap();
1392
1393 let (ev0, e0) = open_chat_event_multi(&w0, &held, &chan()).unwrap();
1394 assert_eq!(e0, Epoch(0));
1395 assert_eq!(ev0.opened().rumor.content, "before the rekey");
1396 let (ev1, e1) = open_chat_event_multi(&w1, &held, &chan()).unwrap();
1397 assert_eq!(e1, Epoch(1));
1398 assert_eq!(ev1.opened().rumor.content, "after the rekey");
1399 }
1400
1401 #[test]
1402 fn multi_epoch_unheld_wrap_is_not_ours() {
1403 let author = Keys::generate();
1404 let held = [(Epoch(0), [1u8; 32]), (Epoch(1), [2u8; 32])];
1405 let m2 = build_message_rumor(author.public_key(), &chan(), Epoch(2), "future", None, &[], vec![], AT);
1406 let g2 = chat_group_key(&[3u8; 32], &chan(), Epoch(2));
1407 let (w2, _) = seal_chat_rumor(&m2, &g2, &author, WRAP_AT, false).unwrap();
1408 assert!(matches!(open_chat_event_multi(&w2, &held, &chan()), Err(ChatError::NoHeldEpoch)));
1409 }
1410
1411 #[test]
1412 fn multi_epoch_cross_epoch_splice_is_rejected() {
1413 let author = Keys::generate();
1417 let key0 = [1u8; 32];
1418 let key1 = [2u8; 32];
1419 let held = [(Epoch(0), key0), (Epoch(1), key1)];
1420 let stale = build_message_rumor(author.public_key(), &chan(), Epoch(0), "replay", None, &[], vec![], AT);
1421 let g1 = chat_group_key(&key1, &chan(), Epoch(1));
1422 let (wrap, _) = seal_chat_rumor(&stale, &g1, &author, WRAP_AT, false).unwrap();
1423 assert!(matches!(
1424 open_chat_event_multi(&wrap, &held, &chan()),
1425 Err(ChatError::Stream(StreamError::EpochMismatch))
1426 ));
1427 }
1428
1429 #[test]
1430 fn duplicate_e_tag_on_a_reaction_is_rejected() {
1431 let author = Keys::generate();
1432 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1433 tags.push(Tag::custom("e", ["aa".repeat(32)]));
1434 tags.push(Tag::custom("e", ["bb".repeat(32)]));
1435 tags.push(Tag::custom("p", [Keys::generate().public_key().to_hex()]));
1436 let rumor = stream::build_rumor_ms(kind::REACTION, author.public_key(), "+", tags, AT);
1437 assert!(matches!(
1438 open(&seal(&rumor, &author)),
1439 Err(ChatError::DuplicateTag(TAG_TARGET))
1440 ));
1441 }
1442
1443 #[test]
1444 fn unknown_rumor_kind_is_rejected_on_both_sides() {
1445 let author = Keys::generate();
1446 let tags = stream::channel_binding_tags(&chan(), Epoch(0));
1448 let rumor = stream::build_rumor_ms(3300, author.public_key(), "v1 ghost", tags, AT);
1449 assert!(matches!(
1450 seal_chat_rumor(&rumor, &group(), &author, WRAP_AT, false),
1451 Err(ChatError::UnknownKind(3300))
1452 ));
1453 let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
1455 let (wrap, _) = stream::wrap_seal(&seal, &group(), stream::KIND_WRAP, WRAP_AT).unwrap();
1456 assert!(matches!(open(&wrap), Err(ChatError::UnknownKind(3300))));
1457 }
1458
1459 #[test]
1460 fn plaintext_sealed_chat_event_is_rejected() {
1461 let author = Keys::generate();
1462 let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), "leaky", None, &[], vec![], AT);
1463 let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group(), &author).unwrap();
1464 let (wrap, _) = stream::wrap_seal(&seal, &group(), stream::KIND_WRAP, WRAP_AT).unwrap();
1465 assert!(matches!(open(&wrap), Err(ChatError::NotEncryptedSealed)));
1466 }
1467
1468 #[test]
1469 fn malformed_targets_are_errors_not_panics() {
1470 let author = Keys::generate();
1471 let rumor = build_reaction_rumor(
1473 author.public_key(),
1474 &chan(),
1475 Epoch(0),
1476 &"zz".repeat(32),
1477 &Keys::generate().public_key().to_hex(),
1478 kind::MESSAGE,
1479 "+",
1480 None,
1481 AT,
1482 );
1483 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_TARGET))));
1484 let rumor = build_message_rumor(
1486 author.public_key(),
1487 &chan(),
1488 Epoch(0),
1489 "x",
1490 Some(("abcd", &Keys::generate().public_key().to_hex())),
1491 &[],
1492 vec![],
1493 AT,
1494 );
1495 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_QUOTE))));
1496 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1498 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1499 tags.push(Tag::custom(
1500 "k",
1501 ["nine".to_string()],
1502 ));
1503 let rumor = stream::build_rumor_ms(kind::DELETE, author.public_key(), "", tags, AT);
1504 assert!(matches!(open(&seal(&rumor, &author)), Err(ChatError::BadTag(TAG_TARGET_KIND))));
1505 let mut tags = stream::channel_binding_tags(&chan(), Epoch(0));
1507 tags.push(Tag::custom("e", ["cd".repeat(32)]));
1508 let rumor = stream::build_rumor_ms(kind::REACTION, author.public_key(), "+", tags, AT);
1509 assert!(matches!(
1510 open(&seal(&rumor, &author)),
1511 Err(ChatError::MissingTag(TAG_TARGET_AUTHOR))
1512 ));
1513 }
1514}