Skip to main content

vector_core/community/v2/
chat.rs

1//! CORD-03 Chat Plane — a Channel's messages over the v2 stream envelope.
2//!
3//! Every chat action is an unsigned rumor in an **encrypted seal** (CORD-02 §5
4//! makes 20013 mandatory here — chat content must never be liftable as a
5//! standalone public event) inside a wrap at the Channel's stream address.
6//! The rumor kinds reuse standard Nostr shapes wherever one fits:
7//!   - kind 9 message (NIP-C7: content = text, replies via a `q` tag naming
8//!     the parent RUMOR id — never the outer wrap's, which differs per re-wrap)
9//!   - kind 7 reaction (NIP-25: `e`/`p`/`k` name the target)
10//!   - kind 5 delete (NIP-09: `e` = the author's own rumor id, `k` its kind)
11//!   - kind 3302 edit (`e` = own message rumor id, content = replacement text)
12//!   - kind 3310 WebXDC peer signal (payload opaque to the protocol)
13//!   - kind 23311 typing (ephemeral tier — rides the 21059 wrap)
14//!
15//! Two Vector inner-tag conventions: NIP-30
16//! `["emoji", shortcode, url]` tags and verbatim extra tags (NIP-92 `imeta`
17//! attachments) ride inside the signed rumor, so they are author-committed.
18//!
19//! Every rumor MUST commit `["channel", id]` + `["epoch", n]`, checked
20//! strict-equal against the coordinate whose key decrypted the wrap (CORD-03
21//! §3) — the rumor's own claim is never trusted, so a keyholder of two planes
22//! cannot re-seal a rumor across Channels or replay it across epochs.
23//!
24//! The wrap kind (1059/21059) is a transport tier, not a content authority:
25//! the open side admits any allowlisted rumor kind on either wrap and lets the
26//! rumor kind govern meaning. Publishers still MUST put typing on 21059
27//! (relays MUST NOT store it) — that is a send-side duty, not a read gate.
28
29use 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";
48/// `["video", "screen"]` or `["video", "camera"]` on a `joined`: what its author is sending.
49const TAG_VIDEO: &str = "video";
50const VIDEO_SCREEN: &str = "screen";
51const VIDEO_CAMERA: &str = "camera";
52const TAG_DO: &str = "do";
53const TAG_TO: &str = "to";
54/// The transport a peer-to-peer call names (CORD-07 §8).
55pub const TRANSPORT_IROH: &str = "iroh";
56
57/// Errors from the chat plane layer (envelope errors ride inside).
58#[derive(Debug)]
59pub enum ChatError {
60    Stream(StreamError),
61    /// A chat rumor arrived in a plaintext seal — CORD-02 §5 requires the
62    /// encrypted form on this plane, a strict reader drops the violation.
63    NotEncryptedSealed,
64    /// The rumor kind isn't in the chat-plane registry (retired numbers stay
65    /// burned — a 3300 is never a v2 message).
66    UnknownKind(u16),
67    MissingTag(&'static str),
68    /// A target-bearing tag appears more than once — ambiguous, rejected
69    /// (same discipline as the stream module's binding tags).
70    DuplicateTag(&'static str),
71    /// A tag value failed its shape check (64-hex id, pubkey, or integer kind).
72    BadTag(&'static str),
73    /// The wrap's author matches no held `(epoch, key)` — not ours to open.
74    NoHeldEpoch,
75    /// The rumor's writer epoch isn't the one whose address served it (CORD-03 §3).
76    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
102// ── Keying (CORD-03 §1) ──────────────────────────────────────────────────────
103
104/// A Channel's Chat Plane group key. `secret` is whatever feeds the Channel at
105/// this epoch: the `community_root` for a Public Channel (at the root epoch),
106/// or the Channel's independent key for a Private one (at its own channel
107/// epoch). The channel id inside the derivation gives every Channel a distinct
108/// address regardless of which secret feeds it.
109pub fn chat_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
110    channel_group_key(secret, channel_id, epoch)
111}
112
113// ── Rumor builders ───────────────────────────────────────────────────────────
114//
115// All builders take the author's pubkey (not keys) so bunker accounts build
116// identical rumors — signing happens at the seal, not here. `at_ms` is the
117// full epoch-ms send time (CORD-02 §4); the binding tags are always attached.
118
119/// Build a kind-9 message rumor. `reply_to` is the parent's
120/// `(rumor_id_hex, author_hex)` — the NIP-C7 `q` tag; `emoji` the NIP-30
121/// `(shortcode, url)` pairs for any `:shortcode:` in the content; `extra_tags`
122/// ride verbatim (NIP-92 `imeta` attachments), author-committed by the seal.
123#[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
148/// Parse the NIP-40 `["expiration", <unix secs>]` tag off a chat rumor
149/// (Self-Destruct Timer). The inner twin of the wrap tag relays act on: this is
150/// what drives a receiver's local countdown + purge, and the only copy that
151/// survives a restart (the wrap is a discarded transport artifact).
152pub(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/// Build a kind-1111 threaded-reply rumor (NIP-22, CORD-03 §3). Uppercase
164/// `K`/`E`/`P` pin the immutable thread ROOT, lowercase `k`/`e`/`p` the
165/// immediate PARENT — all rumor ids. `parent_root` names the parent's own root
166/// when the parent is itself a reply (inherited verbatim, so the root stays
167/// stable at any depth — the exact shape Armada builds); `None` means the
168/// parent IS the root.
169#[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/// Build a kind-7 reaction rumor (NIP-25): `e` = the target rumor id, `p` its
203/// author, `k` = the target's kind (`9` for a message, `1111` for a threaded
204/// reply). `emoji_content` is the reaction itself (`"+"`, an emoji, or a
205/// `:shortcode:`); `emoji` carries the NIP-30 pair when the content is a
206/// custom-emoji shortcode.
207#[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
232/// Build a kind-5 delete rumor (NIP-09): `e` = the target rumor id, `k` = its
233/// kind. Semantic within the plane only — members stop rendering; the wrap
234/// ciphertext on relays needs a separate NIP-09 scrub by its `p` tag.
235///
236/// `citation` is the moderator's `vac` (CORD-04 §5) when this deletes SOMEONE
237/// ELSE's message: peers resolve the removal against that exact Grant version.
238/// A self-delete carries none, and neither does the owner (supreme, no grant to
239/// cite) — so an absent `vac` never widens what a delete may reach.
240pub 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/// [`build_delete_rumor`] that relays drop at `expiration` (unix seconds).
253#[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/// Build a kind-3302 edit rumor: `e` = the author's own message rumor id,
280/// content = the replacement text (fields unpinned upstream; this shape
281/// matches the CORD examples). `emoji` carries the NIP-30 pairs for any
282/// `:shortcode:` in the replacement — the edit is what peers render from, so
283/// it must be as self-describing as the message it replaces. `expiration` is
284/// the target's own NIP-40 expiry, so the edit dies with the message it edits.
285#[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/// [`build_edit_rumor`] carrying extra tags verbatim (the edit's colour spans).
300#[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
324/// Build a kind-3310 WebXDC peer-signal rumor: `content` and `extra_tags` are
325/// the app payload, opaque to the protocol, carried verbatim.
326pub 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
339/// Build a kind-23311 typing rumor — presence of the event is the signal, it
340/// carries nothing. Seal it with `ephemeral: true` so relays never store it.
341/// A voice presence heartbeat (CORD-07 §4): `Some` is `joined` over iroh, naming the endpoint and
342/// the relay it's reached through (a relay names no IP), and whether we're muted or deafened;
343/// None is `left`.
344pub 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/// A moderator's voice directive (CORD-07 §7), citing the signer's standing.
369#[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
397// ── Seal / open over the stream ──────────────────────────────────────────────
398
399/// Seal a chat rumor into its wrap: encrypted seal (mandatory on this plane),
400/// then the durable 1059 wrap — or the ephemeral 21059 when `ephemeral` (the
401/// typing tier). Refuses non-chat rumor kinds so a control edition can never
402/// be published onto a Channel's stream by mistake. Returns the wrap plus the
403/// ephemeral `p` keypair (retain it to best-effort NIP-09-scrub the wrap
404/// later). Local-keys convenience; bunker accounts use [`stream::seal_content`]
405/// + their remote signer + [`stream::wrap_seal`] for identical wire output.
406pub 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    // Mirror a NIP-40 expiration (Self-Destruct Timer) from the inner rumor onto
420    // the outer wrap so relays drop the stored event on schedule; the inner copy
421    // drives each client's local purge. Only chat messages ever carry one.
422    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
431/// Signer-driven twin of [`seal_chat_rumor`] for bunker / NIP-55 accounts: the
432/// author seal signs through a [`VectorSigner`](crate::signer::VectorSigner); the group-key wrap is unchanged.
433/// `author` is the identity the signer signs as (must equal `my_public_key()`); the wrap is
434/// `p`-tagged to `owner`, the key that may delete it.
435pub 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/// A parsed reply reference — the NIP-C7 `q` tag's parent rumor id and (when
459/// carried, a SHOULD upstream) its author.
460#[derive(Debug, Clone, PartialEq, Eq)]
461pub struct ReplyRef {
462    pub id: [u8; 32],
463    pub author: Option<PublicKey>,
464}
465
466/// A fully verified, typed chat event. Every variant keeps its
467/// [`OpenedStream`] — the proven author, rumor id, and ms time live there.
468#[derive(Debug, Clone)]
469pub enum ChatEvent {
470    /// Kind 9 (message; `reply_to` = its `q` inline quote) or kind 1111
471    /// (threaded reply; `reply_to` = its immediate parent, the lowercase `e`).
472    /// Text lives in `opened.rumor.content`; `emoji` is the NIP-30
473    /// `(shortcode, url)` pairs (attachments ride the rumor's `imeta` tags).
474    /// `opened.rumor.kind` distinguishes the two when a caller needs to.
475    Message {
476        opened: OpenedStream,
477        reply_to: Option<ReplyRef>,
478        emoji: Vec<(String, String)>,
479    },
480    /// Kind 7 — `emoji` is the reaction content; `emoji_url` the NIP-30 image
481    /// when the content is a custom `:shortcode:`.
482    Reaction {
483        opened: OpenedStream,
484        target: [u8; 32],
485        target_author: PublicKey,
486        emoji: String,
487        emoji_url: Option<String>,
488    },
489    /// Kind 5 — authorization (self, or a moderator) is the fold's job, not
490    /// the envelope's.
491    Delete {
492        opened: OpenedStream,
493        target: [u8; 32],
494        target_kind: Option<u16>,
495    },
496    /// Kind 3302 — author-only validity is likewise judged at fold time.
497    /// `emoji` is the NIP-30 pairs for the REPLACEMENT text; the fold adopts
498    /// them wholesale, so an edit that drops a shortcode retires its image.
499    Edit {
500        opened: OpenedStream,
501        target: [u8; 32],
502        new_content: String,
503        emoji: Vec<(String, String)>,
504    },
505    /// Kind 3310 — payload opaque, read `opened.rumor` directly.
506    Webxdc { opened: OpenedStream },
507    /// Kind 23311 — the event's presence is the whole signal.
508    Typing { opened: OpenedStream },
509    /// Kind 23313 (CORD-07 §4): in a Channel's call, or out of it. A `joined` names how it's
510    /// reached: on iroh, `endpoint`; any other transport leaves it None but still counts.
511    VoicePresence { opened: OpenedStream, heard: super::voice::Heard },
512    /// Kind 23314 (CORD-07 §7): a moderator mutes, deafens, moves or disconnects `target`;
513    /// `to` is a move's destination Channel.
514    VoiceDirective { opened: OpenedStream, target: PublicKey, directive: super::voice::Directive, to: Option<[u8; 32]> },
515}
516
517impl ChatEvent {
518    /// Mark a post its Channel's writers' rules don't stand behind.
519    pub fn mark_held(&mut self) {
520        if let ChatEvent::Message { opened, .. } = self {
521            opened.held = true;
522        }
523    }
524
525    /// The verified envelope facts (author, ms, rumor id) behind any variant.
526    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
540/// Open and fully verify one chat wrap against the `(channel, epoch)` whose
541/// key is being tried: envelope verification ([`stream::open_wrap`]), the
542/// encrypted-seal gate, the strict channel/epoch binding, the kind allowlist,
543/// then the typed parse. Malformed targets are errors, never panics.
544pub 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
553/// [`open_chat_event`] with a read view only: the epoch's address and conversation key.
554pub 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
572/// Open a post at a restricted Channel's writer address (CORD-03 §1): the wrap must verify as
573/// signed by writer epoch `wepoch`'s key, open under read epoch `epoch`'s conversation key, and
574/// its rumor commit the Channel and both epochs.
575pub 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
596/// The writer epoch a rumor commits, if any.
597pub(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
612/// Whether a rumor commits a writer epoch.
613pub 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
619/// The writer certificate a rumor carries, if a well-formed one.
620pub 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
625/// `rumor` committing writer epoch `wepoch` (CORD-03 §3), its id recomputed.
626pub fn with_writer_epoch(rumor: UnsignedEvent, wepoch: Epoch) -> UnsignedEvent {
627    with_writer(rumor, wepoch, None)
628}
629
630/// [`with_writer_epoch`], carrying the author's writer certificate for that epoch.
631pub 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
642/// Whether a rumor kind moves to a restricted Channel's writer address. Reactions and deletions
643/// stay at the read address: a restricted Channel gates posting, not reacting, and a deletion is
644/// judged by its signer's authority wherever it lands. Typing signals posting, so it moves too.
645/// Voice presence stays: being in a call is CONNECT, not posting.
646pub fn rides_writer_address(kind: u16) -> bool {
647    !matches!(kind, kind::REACTION | kind::DELETE | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE)
648}
649
650/// Open a chat wrap against every `(epoch, secret)` a client holds for one
651/// Channel — the CORD-03 §3 read path, where history spanning a rekey is
652/// queried across all held epoch pubkeys. Selection is by the wrap's author
653/// (each epoch's derived address), NEVER trial decryption, and the binding is
654/// then enforced against the epoch that actually matched — so an epoch-N rumor
655/// re-sealed under epoch M's key still dies as a splice.
656///
657/// `secret` per entry is whatever feeds the Channel at that epoch (CORD-03 §1:
658/// `community_root` for Public epochs, the channel key for Private ones).
659/// Derivation costs an HKDF + keypair per entry per call — batch readers
660/// should derive their [`GroupKey`]s once and match `wrap.pubkey` themselves.
661pub 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
675// ── Parse (rumor → typed event) ──────────────────────────────────────────────
676
677fn 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
684/// Type an ALREADY-VERIFIED rumor (one produced by [`stream::open_wrap`] and
685/// binding-checked). Target ids come from UNIQUE tags — a duplicated `e`/`p`/
686/// `q` is ambiguous (which target did the author sign off on?) and rejected.
687fn 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                    // NIP-C7 q tag: [q, id, relay-hint, pubkey] — the author
695                    // slot is a SHOULD; absent or empty parses as unknown.
696                    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            // A threaded reply (NIP-22, CORD-03 §3). Vector's timeline renders it
708            // INLINE: the immediate parent (the lowercase `e`) becomes the reply
709            // context, exactly like a kind-9 quote — never dropped. The uppercase
710            // root tags stay on the rumor for a future thread view.
711            let reply_to = match unique_tag(&opened.rumor, TAG_TARGET)? {
712                None => None, // a parentless comment still renders as plain text.
713                Some(s) => {
714                    let id = decode_id32(value_of(s, TAG_TARGET)?, TAG_TARGET)?;
715                    // NIP-22 e tag: [e, id, relay-hint, pubkey] — author optional.
716                    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            // NIP-30: only the tag naming this reaction's own `:shortcode:` is its image.
732            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
795// ── Tag helpers ──────────────────────────────────────────────────────────────
796
797fn emoji_tag(shortcode: &str, url: &str) -> Tag {
798    Tag::custom(TAG_EMOJI, [shortcode.to_string(), url.to_string()])
799}
800
801/// The unique tag named `name`, or None. More than one match = ambiguous,
802/// rejected (any keyholder can craft a rumor; first-match is nondeterministic).
803fn 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
817/// The unique tag's value, requiring the tag to be present.
818fn 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
834/// All well-formed NIP-30 `(shortcode, url)` pairs; malformed emoji tags are
835/// skipped, not fatal (worst case the raw `:shortcode:` text renders).
836fn 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        // The imeta tag rides the signed rumor byte-verbatim.
936        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        // NIP-40 Self-Destruct Timer: the expiry rides the inner rumor (drives
942        // every client's local purge + survives restart) AND is mirrored onto the
943        // outer wrap (so relays drop the stored event). Without a timer, neither
944        // layer carries a tag.
945        const EXP: u64 = 1_700_000_500;
946        let author = Keys::generate();
947        let me = author.public_key();
948
949        // Sender stamps the expiry as an extra tag (exactly how the send command does).
950        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        // Relay-drop half: the outer wrap mirrors the expiration tag.
964        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        // Local-purge half: the receiver's opened Message carries the expiry.
971        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        // Control: no timer → clean rumor, clean wrap, no Message expiry.
978        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        // CORD-03 §3 kind-1111: Vector renders a thread reply inline — the
1019        // immediate parent (lowercase e) is the reply context, never dropped.
1020        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, // the parent IS the root
1032            &[],
1033            AT,
1034        );
1035        // The wire shape matches the spec example: K/E/P root + k/e/p parent.
1036        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        // The EXACT tag shape from the spec example (examples.md §2.2) built by
1052        // hand — proving we parse the cross-client wire form, not just our own
1053        // builder's output.
1054        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        // A NESTED reply: the immediate parent (lowercase e), not the root, is
1077        // the inline context.
1078        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, // the parent is itself a reply
1097            &parent_author_hex,
1098            Some((&root_id, kind::MESSAGE, &root_author_hex)),
1099            &[],
1100            AT,
1101        );
1102        // Root pinned to the ORIGINAL root (stable at any depth), parent to the
1103        // immediate reply.
1104        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        // Two lowercase `e` tags = ambiguous parent (which did the author sign
1113        // off on?) — same discipline as every target-bearing tag.
1114        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        // NIP-25 shape: the k tag names the reacted-to kind.
1163        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        // A k-less delete (the tag is optional in NIP-09) parses with None.
1230        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        // A kind-9 on a 21059 wrap still opens: the wrap kind is a transport
1283        // tier (storage policy), the rumor-kind allowlist governs content.
1284        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        // Same key, wrong claimed coordinate: the strict-equal binding gates it.
1295        assert!(matches!(
1296            open_chat_event(&wrap, &group(), &ChannelId([0xcd; 32]), Epoch(0)),
1297            Err(ChatError::Stream(StreamError::ChannelMismatch))
1298        ));
1299        // A rumor bound to epoch 1 sealed under epoch 0's key (replay shape).
1300        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        // Cross-channel splice: a keyholder of both channels re-seals a rumor
1308        // bound to A under B's key — the binding must be judged against the
1309        // key that decrypted, never the rumor's own claim.
1310        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        // A rumor bound to epoch 0 re-sealed under epoch 1's key: selection by
1368        // wrap author picks epoch 1, and the binding must then fail — held-key
1369        // selection can never launder a stale-epoch rumor.
1370        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        // 3300 is a RETIRED number — burned forever, never a v2 chat kind.
1401        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        // And a wrap hand-built around it (bypassing the send gate) dies on open.
1408        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        // Reaction: 64 chars but not hex.
1426        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        // Message: truncated q id.
1439        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        // Delete: a k tag that isn't an integer kind.
1451        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        // Reaction missing its p target author entirely.
1460        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}