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";
618const TAG_RCERT: &str = "rcert";
619
620/// A writer's proof of place at one writer epoch: whole, or for only some writes.
621#[derive(Debug, Clone, Copy, PartialEq, Eq)]
622pub enum WriterCert {
623    Full([u8; 64]),
624    /// `rights`: the CORD-04 bits of the writes it covers.
625    Scoped([u8; 64], u64),
626}
627
628/// The writer certificate a rumor carries, if a well-formed one.
629pub 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
634/// The scoped writer certificate a rumor carries, `["rcert", <sig hex>, <rights decimal>]`, if
635/// its first one is well-formed.
636pub 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
643/// The CORD-04 bit a write of `kind` needs at a writer address, `None` for a deletion, which is
644/// judged on its signer's authority wherever it lands.
645pub 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
655/// Whether a scoped certificate for `rights` covers a write of `kind`: never a post.
656pub 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
663/// `rumor` committing writer epoch `wepoch` (CORD-03 §3), its id recomputed.
664pub fn with_writer_epoch(rumor: UnsignedEvent, wepoch: Epoch) -> UnsignedEvent {
665    with_writer(rumor, wepoch, None)
666}
667
668/// [`with_writer_epoch`], carrying the author's writer certificate for that epoch.
669pub 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
673/// [`with_writer_epoch`], carrying `cert`, whole or scoped.
674pub 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
687/// Whether a rumor kind moves to a restricted Channel's writer address. Reactions and deletions
688/// stay at the read address: a restricted Channel gates posting, not reacting, and a deletion is
689/// judged by its signer's authority wherever it lands. Typing signals posting, so it moves too.
690/// Voice presence stays: being in a call is CONNECT, not posting. In a Locked window everything
691/// moves, so the read address carries nothing anyone needs.
692pub 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
696/// Open a chat wrap against every `(epoch, secret)` a client holds for one
697/// Channel — the CORD-03 §3 read path, where history spanning a rekey is
698/// queried across all held epoch pubkeys. Selection is by the wrap's author
699/// (each epoch's derived address), NEVER trial decryption, and the binding is
700/// then enforced against the epoch that actually matched — so an epoch-N rumor
701/// re-sealed under epoch M's key still dies as a splice.
702///
703/// `secret` per entry is whatever feeds the Channel at that epoch (CORD-03 §1:
704/// `community_root` for Public epochs, the channel key for Private ones).
705/// Derivation costs an HKDF + keypair per entry per call — batch readers
706/// should derive their [`GroupKey`]s once and match `wrap.pubkey` themselves.
707pub 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
721// ── Parse (rumor → typed event) ──────────────────────────────────────────────
722
723fn 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
730/// Type an ALREADY-VERIFIED rumor (one produced by [`stream::open_wrap`] and
731/// binding-checked). Target ids come from UNIQUE tags — a duplicated `e`/`p`/
732/// `q` is ambiguous (which target did the author sign off on?) and rejected.
733fn 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                    // NIP-C7 q tag: [q, id, relay-hint, pubkey] — the author
741                    // slot is a SHOULD; absent or empty parses as unknown.
742                    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            // A threaded reply (NIP-22, CORD-03 §3). Vector's timeline renders it
754            // INLINE: the immediate parent (the lowercase `e`) becomes the reply
755            // context, exactly like a kind-9 quote — never dropped. The uppercase
756            // root tags stay on the rumor for a future thread view.
757            let reply_to = match unique_tag(&opened.rumor, TAG_TARGET)? {
758                None => None, // a parentless comment still renders as plain text.
759                Some(s) => {
760                    let id = decode_id32(value_of(s, TAG_TARGET)?, TAG_TARGET)?;
761                    // NIP-22 e tag: [e, id, relay-hint, pubkey] — author optional.
762                    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            // NIP-30: only the tag naming this reaction's own `:shortcode:` is its image.
778            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
841// ── Tag helpers ──────────────────────────────────────────────────────────────
842
843fn emoji_tag(shortcode: &str, url: &str) -> Tag {
844    Tag::custom(TAG_EMOJI, [shortcode.to_string(), url.to_string()])
845}
846
847/// The unique tag named `name`, or None. More than one match = ambiguous,
848/// rejected (any keyholder can craft a rumor; first-match is nondeterministic).
849fn 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
863/// The unique tag's value, requiring the tag to be present.
864fn 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
880/// All well-formed NIP-30 `(shortcode, url)` pairs; malformed emoji tags are
881/// skipped, not fatal (worst case the raw `:shortcode:` text renders).
882fn 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        // The imeta tag rides the signed rumor byte-verbatim.
982        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        // NIP-40 Self-Destruct Timer: the expiry rides the inner rumor (drives
988        // every client's local purge + survives restart) AND is mirrored onto the
989        // outer wrap (so relays drop the stored event). Without a timer, neither
990        // layer carries a tag.
991        const EXP: u64 = 1_700_000_500;
992        let author = Keys::generate();
993        let me = author.public_key();
994
995        // Sender stamps the expiry as an extra tag (exactly how the send command does).
996        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        // Relay-drop half: the outer wrap mirrors the expiration tag.
1010        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        // Local-purge half: the receiver's opened Message carries the expiry.
1017        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        // Control: no timer → clean rumor, clean wrap, no Message expiry.
1024        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        // CORD-03 §3 kind-1111: Vector renders a thread reply inline — the
1065        // immediate parent (lowercase e) is the reply context, never dropped.
1066        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, // the parent IS the root
1078            &[],
1079            AT,
1080        );
1081        // The wire shape matches the spec example: K/E/P root + k/e/p parent.
1082        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        // The EXACT tag shape from the spec example (examples.md §2.2) built by
1098        // hand — proving we parse the cross-client wire form, not just our own
1099        // builder's output.
1100        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        // A NESTED reply: the immediate parent (lowercase e), not the root, is
1123        // the inline context.
1124        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, // the parent is itself a reply
1143            &parent_author_hex,
1144            Some((&root_id, kind::MESSAGE, &root_author_hex)),
1145            &[],
1146            AT,
1147        );
1148        // Root pinned to the ORIGINAL root (stable at any depth), parent to the
1149        // immediate reply.
1150        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        // Two lowercase `e` tags = ambiguous parent (which did the author sign
1159        // off on?) — same discipline as every target-bearing tag.
1160        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        // NIP-25 shape: the k tag names the reacted-to kind.
1209        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        // A k-less delete (the tag is optional in NIP-09) parses with None.
1276        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        // A kind-9 on a 21059 wrap still opens: the wrap kind is a transport
1329        // tier (storage policy), the rumor-kind allowlist governs content.
1330        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        // Same key, wrong claimed coordinate: the strict-equal binding gates it.
1341        assert!(matches!(
1342            open_chat_event(&wrap, &group(), &ChannelId([0xcd; 32]), Epoch(0)),
1343            Err(ChatError::Stream(StreamError::ChannelMismatch))
1344        ));
1345        // A rumor bound to epoch 1 sealed under epoch 0's key (replay shape).
1346        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        // Cross-channel splice: a keyholder of both channels re-seals a rumor
1354        // bound to A under B's key — the binding must be judged against the
1355        // key that decrypted, never the rumor's own claim.
1356        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        // A rumor bound to epoch 0 re-sealed under epoch 1's key: selection by
1414        // wrap author picks epoch 1, and the binding must then fail — held-key
1415        // selection can never launder a stale-epoch rumor.
1416        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        // 3300 is a RETIRED number — burned forever, never a v2 chat kind.
1447        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        // And a wrap hand-built around it (bypassing the send gate) dies on open.
1454        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        // Reaction: 64 chars but not hex.
1472        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        // Message: truncated q id.
1485        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        // Delete: a k tag that isn't an integer kind.
1497        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        // Reaction missing its p target author entirely.
1506        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}