Skip to main content

vector_core/community/v2/
stream.rs

1//! CORD-01 Private Streams — the Concord v2 envelope.
2//!
3//! Every durable plane event is the same three-layer shape: a kind-1059 **wrap**
4//! signed by the plane's derived group key (fixed author, random ephemeral `p`
5//! tag — NIP-59 reversed), containing a **seal** signed by the author's real
6//! key, containing the unsigned **rumor** that carries the functional kind.
7//!
8//! Two seal forms, fixed per plane (CORD-02 §5), declared by the seal's kind:
9//!   - **20013 encrypted** (Chat, Guestbook, rekey planes): the rumor is
10//!     NIP-44-encrypted *again* inside the already-encrypted wrap, so no layer
11//!     can ever be lifted out as a standalone public event.
12//!   - **20014 plaintext** (Control Plane ONLY): the seal's content is the
13//!     rumor's serialized JSON string byte-verbatim, which is what lets a
14//!     compaction re-wrap a signed edition into a new epoch with the signature
15//!     intact. A re-wrap MUST carry those exact bytes forward, never
16//!     re-serialize.
17//!
18//! Ephemeral actions (typing, voice presence) ride the identical structure at
19//! kind 21059 — relays MUST NOT store it.
20//!
21//! NIP-44 hard-caps plaintext at 65,535 bytes and libraries are lenient, so the
22//! cap is enforced HERE at every nesting layer — a lenient publisher mints
23//! events a strict reader cannot decrypt.
24
25use crate::event_ext::FinalizeUnsignedWithId;
26use crate::event_ext::FinalizeOnClock;
27#[cfg(test)]
28use nostr_sdk::prelude::FinalizeEvent;
29use nostr_sdk::prelude::nip44::v2::ConversationKey;
30use nostr_sdk::prelude::{Event, EventBuilder, EventId, Keys, Kind, PublicKey, Tag, Timestamp, UnsignedEvent};
31
32use super::super::{ChannelId, Epoch};
33use super::derive::GroupKey;
34
35/// Durable stream wrap.
36pub const KIND_WRAP: u16 = 1059;
37/// Ephemeral stream wrap — identical structure, relays MUST NOT store it.
38pub const KIND_WRAP_EPHEMERAL: u16 = 21059;
39/// Encrypted seal (Chat / Guestbook / rekey planes).
40pub const KIND_SEAL_ENCRYPTED: u16 = 20013;
41/// Plaintext seal (Control Plane only).
42pub const KIND_SEAL_PLAINTEXT: u16 = 20014;
43
44/// NIP-44 v2 plaintext hard cap, enforced at every nesting layer.
45pub const NIP44_MAX_PLAINTEXT: usize = 65_535;
46
47const TAG_MS: &str = "ms";
48const TAG_CHANNEL: &str = "channel";
49const TAG_EPOCH: &str = "epoch";
50
51/// Which seal form a plane uses (CORD-02 §5) — a fixed property of the plane,
52/// never a per-message choice.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SealForm {
55    Encrypted,
56    Plaintext,
57}
58
59impl SealForm {
60    pub fn kind(self) -> u16 {
61        match self {
62            SealForm::Encrypted => KIND_SEAL_ENCRYPTED,
63            SealForm::Plaintext => KIND_SEAL_PLAINTEXT,
64        }
65    }
66
67    fn from_kind(kind: u16) -> Option<Self> {
68        match kind {
69            KIND_SEAL_ENCRYPTED => Some(SealForm::Encrypted),
70            KIND_SEAL_PLAINTEXT => Some(SealForm::Plaintext),
71            _ => None,
72        }
73    }
74}
75
76/// Errors from building or opening a v2 stream event.
77#[derive(Debug)]
78pub enum StreamError {
79    Sign(String),
80    Encrypt(String),
81    Decrypt(String),
82    Parse(String),
83    /// A plaintext (wrap/seal/rumor JSON) exceeds the NIP-44 65,535-byte cap.
84    Oversize(usize),
85    /// The encoded wrap exceeds the 65,536-byte relay ceiling.
86    TooLarge(usize),
87    /// Outer kind is neither 1059 nor 21059.
88    BadWrapKind(u16),
89    /// Wrap author isn't this plane's group key — not this stream's event.
90    WrongStream,
91    /// A write-restricted stream's wrap signature failed to verify (CORD-01):
92    /// the signer set is narrower than the readership there, so the signature
93    /// IS the write gate and a reader MUST check it.
94    BadWrapSignature,
95    /// Seal kind is neither 20013 nor 20014.
96    BadSealKind(u16),
97    /// The seal's Schnorr signature (or id) failed to verify.
98    BadSealSignature,
99    /// Rumor pubkey ≠ seal pubkey — the seal doesn't vouch for this author.
100    AuthorMismatch,
101    /// Rumor's claimed id ≠ the hash of its serialized form.
102    BadRumorId,
103    /// `ms` tag present but not an integer in 0..=999 — the event is malformed
104    /// and MUST be dropped, never clamped or interpreted.
105    BadMs,
106    /// Inner channel id ≠ the channel whose key decrypted this (cross-channel splice).
107    ChannelMismatch,
108    /// Inner epoch ≠ the epoch whose key decrypted this (cross-epoch splice/replay).
109    EpochMismatch,
110    MissingTag(&'static str),
111    /// A binding tag appears more than once — ambiguous, rejected.
112    DuplicateTag(&'static str),
113    /// `rewrap` was handed a non-plaintext seal — only 20014 survives re-wrapping
114    /// (a signature over ciphertext binds the old key).
115    NotRewrappable,
116}
117
118impl std::fmt::Display for StreamError {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        match self {
121            StreamError::Sign(e) => write!(f, "sign: {e}"),
122            StreamError::Encrypt(e) => write!(f, "encrypt: {e}"),
123            StreamError::Decrypt(e) => write!(f, "decrypt: {e}"),
124            StreamError::Parse(e) => write!(f, "parse: {e}"),
125            StreamError::Oversize(n) => write!(f, "plaintext {n} bytes exceeds NIP-44 cap"),
126            StreamError::TooLarge(n) => f.write_str(&crate::event_size::too_large(*n)),
127            StreamError::BadWrapKind(k) => write!(f, "not a stream wrap kind: {k}"),
128            StreamError::WrongStream => write!(f, "wrap author is not this stream"),
129            StreamError::BadWrapSignature => write!(f, "write-restricted wrap signature invalid"),
130            StreamError::BadSealKind(k) => write!(f, "not a seal kind: {k}"),
131            StreamError::BadSealSignature => write!(f, "seal signature invalid"),
132            StreamError::AuthorMismatch => write!(f, "rumor pubkey != seal pubkey"),
133            StreamError::BadRumorId => write!(f, "rumor id != computed hash"),
134            StreamError::BadMs => write!(f, "ms tag outside 0..=999"),
135            StreamError::ChannelMismatch => write!(f, "channel-binding mismatch (splice)"),
136            StreamError::EpochMismatch => write!(f, "epoch-binding mismatch (splice/replay)"),
137            StreamError::MissingTag(t) => write!(f, "missing rumor tag: {t}"),
138            StreamError::DuplicateTag(t) => write!(f, "duplicate rumor tag: {t}"),
139            StreamError::NotRewrappable => write!(f, "only plaintext seals survive re-wrapping"),
140        }
141    }
142}
143
144impl std::error::Error for StreamError {}
145
146/// A fully verified, opened stream event.
147#[derive(Debug, Clone)]
148pub struct OpenedStream {
149    /// The unsigned rumor, id-verified against its serialized form.
150    pub rumor: UnsignedEvent,
151    /// The rumor's verified id (content-derived — the protocol's message id).
152    pub rumor_id: EventId,
153    /// The real author: the seal's Schnorr-verified pubkey (== rumor pubkey).
154    pub author: PublicKey,
155    /// Which seal form carried it.
156    pub seal_form: SealForm,
157    /// The verified seal, retained so a compaction can re-wrap a plaintext seal
158    /// byte-verbatim (its content string carries the signed rumor bytes).
159    pub seal: Event,
160    /// The outer wrap's id (per-transport identity; differs per re-wrap).
161    pub wrapper_id: EventId,
162    /// True event time in ms: `created_at * 1000 + ms-tag` (tag absent = 0).
163    pub at_ms: u64,
164    /// Its Channel's writers' rules don't stand behind it (CORD-03 §1): kept for managers, marked.
165    pub held: bool,
166}
167
168// ── millisecond ordering (CORD-02 §4) ────────────────────────────────────────
169
170/// Split a full epoch-ms send time into (`created_at` seconds, `ms` remainder).
171pub fn split_ms(at_ms: u64) -> (u64, u16) {
172    (at_ms / 1000, (at_ms % 1000) as u16)
173}
174
175/// Resolve a rumor's true millisecond time — STRICT per CORD-02 §5: an absent
176/// `ms` tag is offset 0; ANY present `ms` tag that isn't a lone integer in
177/// 0..=999 makes the event malformed (`BadMs` — drop it, never clamp), or the
178/// excess would smuggle arbitrary "future" past the coalesce clock checks.
179///
180/// A present-but-valueless `["ms"]` and a duplicated `ms` tag both count as
181/// malformed here — the generic `unique_tag_unsigned` treats a valueless tag as
182/// absent (correct for the binding path, which then rejects true absence as
183/// MissingTag), but for `ms` "present yet uninterpretable" must be BadMs, not a
184/// silent default, so this scans every occurrence of the tag name directly.
185pub fn resolve_ms_strict(rumor: &UnsignedEvent) -> Result<u64, StreamError> {
186    let secs = rumor.created_at.as_secs();
187    // FIRST occurrence wins, matching Armada (and NIP-01's usual convention for
188    // a repeated tag). Rejecting a duplicate outright is defensible in
189    // isolation, but it made the two clients disagree on whether the EVENT
190    // EXISTS — one folding it, the other dropping it — and `ms` is the ordering
191    // basis for message order, Guestbook recency and List tiebreaks, so that
192    // divergence reached membership. It costs nothing to concede: `ms` is the
193    // publisher's own value, so a second tag grants an attacker no reach they
194    // did not already have with a single one.
195    let Some(raw) = rumor.tags.iter().find_map(|t| {
196        let s = t.as_slice();
197        (s.first().map(|k| k.as_str()) == Some(TAG_MS)).then(|| s.get(1).cloned())
198    }) else {
199        return Ok(secs.saturating_mul(1000));
200    };
201    // Present but valueless, or not a lone 0..=999 decimal without leading
202    // zeros — malformed. Digit-only FIRST: `u64::from_str` would otherwise
203    // accept a leading `+` ("+5", "+000"), a second byte-encoding a strict peer
204    // rejects — the exact cross-impl divergence this gate exists to prevent.
205    let raw = raw.ok_or(StreamError::BadMs)?;
206    if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
207        return Err(StreamError::BadMs);
208    }
209    let n: u64 = raw.parse().map_err(|_| StreamError::BadMs)?;
210    if n > 999 || (raw.len() > 1 && raw.starts_with('0')) {
211        return Err(StreamError::BadMs);
212    }
213    Ok(secs.saturating_mul(1000).saturating_add(n))
214}
215
216// ── build side ───────────────────────────────────────────────────────────────
217
218/// Build an unsigned rumor carrying a full epoch-ms timestamp: `created_at`
219/// takes the seconds, an `["ms", <0..999>]` tag the remainder.
220pub fn build_rumor_ms(
221    kind: u16,
222    author: PublicKey,
223    content: &str,
224    mut tags: Vec<Tag>,
225    at_ms: u64,
226) -> UnsignedEvent {
227    let (secs, offset) = split_ms(at_ms);
228    tags.push(Tag::custom(TAG_MS, [offset.to_string()]));
229    build_rumor_secs(kind, author, content, tags, secs)
230}
231
232/// Build an unsigned rumor with a plain seconds timestamp and NO `ms` tag —
233/// the Control Plane shape (editions fold by version, not time).
234pub fn build_rumor_secs(
235    kind: u16,
236    author: PublicKey,
237    content: &str,
238    tags: Vec<Tag>,
239    at_secs: u64,
240) -> UnsignedEvent {
241    // allow_self_tagging: EventBuilder silently strips a `p` naming the author,
242    // which would break a self-reaction's NIP-25 shape. Rumor tags are the
243    // builder's byte-verbatim contract — no hidden normalization.
244    let mut rumor = EventBuilder::new(Kind::Custom(kind), content)
245        .tags(tags)
246        .custom_created_at(Timestamp::from_secs(at_secs))
247        .finalize_unsigned_with_id(author);
248    rumor.ensure_id();
249    rumor
250}
251
252/// The seal's `content` for a rumor: NIP-44 ciphertext under the stream's
253/// conversation key (encrypted form) or the rumor's serialized JSON string
254/// verbatim (plaintext form). Split from signing so the caller can sign with
255/// local keys OR a NIP-46 bunker — the seal is `(seal_form.kind(), content,
256/// created_at = rumor.created_at)` signed by the author's real key.
257pub fn seal_content(rumor: &UnsignedEvent, form: SealForm, group: &GroupKey) -> Result<String, StreamError> {
258    let json = rumor.as_json();
259    cap(json.len())?;
260    match form {
261        SealForm::Plaintext => Ok(json),
262        SealForm::Encrypted => {
263            let ct = crate::community::cipher::encrypt_with_random_nonce(group.conv_key(), json.as_bytes()).map_err(|e| StreamError::Encrypt(e.to_string()))?;
264            Ok(crate::simd::base64::STANDARD.encode_to_string(&ct))
265        }
266    }
267}
268
269/// Local-keys convenience: build + sign the seal in one step. Wire-identical to
270/// the split path (`seal_content` + caller-side signing), which bunker accounts
271/// use instead.
272pub fn build_seal(rumor: &UnsignedEvent, form: SealForm, group: &GroupKey, author_keys: &Keys) -> Result<Event, StreamError> {
273    let content = seal_content(rumor, form, group)?;
274    EventBuilder::new(Kind::Custom(form.kind()), content)
275        .custom_created_at(rumor.created_at)
276        .finalize_on_clock(author_keys)
277        .map_err(|e| StreamError::Sign(e.to_string()))
278}
279
280/// Wrap a signed seal into the outer stream event: content = NIP-44 under the
281/// stream conversation key, signed by the group key, one random ephemeral `p`
282/// tag (NIP-59 reversed). Returns the wrap and the ephemeral `p` keypair — a
283/// client MAY retain the latter to best-effort NIP-09-scrub the wrap later.
284///
285/// `wrap_kind` is [`KIND_WRAP`] or [`KIND_WRAP_EPHEMERAL`]; `wrap_at` is the
286/// wrap's `created_at` (untweaked wall clock — CORD-01 forbids NIP-59's
287/// timestamp tweak on stream events).
288pub fn wrap_seal(seal: &Event, group: &GroupKey, wrap_kind: u16, wrap_at: Timestamp) -> Result<(Event, Keys), StreamError> {
289    wrap_seal_with_tags(seal, group, wrap_kind, wrap_at, &[])
290}
291
292/// [`wrap_seal`] plus caller-supplied `extra_tags` on the outer wrap. The chat
293/// plane uses this to mirror a message's NIP-40 `expiration` (Self-Destruct
294/// Timer) onto the wrap so relays drop the stored event on schedule; every other
295/// plane wraps with none.
296pub fn wrap_seal_with_tags(
297    seal: &Event,
298    group: &GroupKey,
299    wrap_kind: u16,
300    wrap_at: Timestamp,
301    extra_tags: &[Tag],
302) -> Result<(Event, Keys), StreamError> {
303    let ephemeral = Keys::generate();
304    let wrap = wrap_seal_for(seal, group, wrap_kind, wrap_at, extra_tags, &ephemeral.public_key())?;
305    Ok((wrap, ephemeral))
306}
307
308/// [`wrap_seal_with_tags`] `p`-tagged to `owner`, the key that may later delete the wrap
309/// (CORD-01 §Deletions).
310pub fn wrap_seal_for(
311    seal: &Event,
312    group: &GroupKey,
313    wrap_kind: u16,
314    wrap_at: Timestamp,
315    extra_tags: &[Tag],
316    owner: &PublicKey,
317) -> Result<Event, StreamError> {
318    if wrap_kind != KIND_WRAP && wrap_kind != KIND_WRAP_EPHEMERAL {
319        return Err(StreamError::BadWrapKind(wrap_kind));
320    }
321    let seal_json = seal.as_json();
322    cap(seal_json.len())?;
323    let ct = crate::community::cipher::encrypt_with_random_nonce(group.conv_key(), seal_json.as_bytes()).map_err(|e| StreamError::Encrypt(e.to_string()))?;
324    let mut tags = vec![Tag::public_key(*owner)];
325    tags.extend_from_slice(extra_tags);
326    let wrap = EventBuilder::new(Kind::Custom(wrap_kind), crate::simd::base64::STANDARD.encode_to_string(&ct))
327        .tags(tags)
328        .custom_created_at(wrap_at)
329        .finalize_on_clock(group.keys())
330        .map_err(|e| StreamError::Sign(e.to_string()))?;
331    let len = wrap.as_json().len();
332    if len > crate::event_size::MAX_EVENT_BYTES {
333        return Err(StreamError::TooLarge(len));
334    }
335    Ok(wrap)
336}
337
338/// The `p` key a wrap names: whoever holds its secret may delete the wrap.
339pub fn wrap_owner(wrap: &Event) -> Option<PublicKey> {
340    wrap.tags.iter().find_map(|t| {
341        let s = t.as_slice();
342        (s.len() >= 2 && s[0] == "p").then(|| PublicKey::from_hex(&s[1]).ok()).flatten()
343    })
344}
345
346/// Signer-driven twin of [`build_seal`] + [`wrap_seal_with_tags`]: seal a rumor
347/// into its wrap using a [`VectorSigner`](crate::signer::VectorSigner) for the author signature, so a NIP-46
348/// bunker (or NIP-55) account yields wire-identical output to the local-keys
349/// path. Only the seal signature needs the identity key; the seal content
350/// (symmetric group-key encrypt, or plaintext) and the group-key wrap do not.
351#[allow(clippy::too_many_arguments)]
352pub async fn seal_and_wrap_signed<S: crate::signer::VectorSigner + ?Sized>(
353    signer: &S,
354    author: PublicKey,
355    rumor: &UnsignedEvent,
356    form: SealForm,
357    group: &GroupKey,
358    wrap_kind: u16,
359    wrap_at: Timestamp,
360    extra_tags: &[Tag],
361) -> Result<(Event, Keys), StreamError> {
362    let seal = sign_seal(signer, author, rumor, form, group).await?;
363    wrap_seal_with_tags(&seal, group, wrap_kind, wrap_at, extra_tags)
364}
365
366async fn sign_seal<S: crate::signer::VectorSigner + ?Sized>(
367    signer: &S,
368    author: PublicKey,
369    rumor: &UnsignedEvent,
370    form: SealForm,
371    group: &GroupKey,
372) -> Result<Event, StreamError> {
373    let content = seal_content(rumor, form, group)?;
374    let unsigned = EventBuilder::new(Kind::Custom(form.kind()), content)
375        .custom_created_at(rumor.created_at)
376        .finalize_unsigned_with_id(author);
377    signer
378        .sign_event_async(unsigned)
379        .await
380        .map_err(|e| StreamError::Sign(e.to_string()))
381}
382
383/// [`seal_and_wrap_signed`] `p`-tagged to `owner` (see [`wrap_seal_for`]).
384#[allow(clippy::too_many_arguments)]
385pub async fn seal_and_wrap_signed_for<S: crate::signer::VectorSigner + ?Sized>(
386    signer: &S,
387    author: PublicKey,
388    rumor: &UnsignedEvent,
389    form: SealForm,
390    group: &GroupKey,
391    wrap_kind: u16,
392    wrap_at: Timestamp,
393    extra_tags: &[Tag],
394    owner: &PublicKey,
395) -> Result<Event, StreamError> {
396    let seal = sign_seal(signer, author, rumor, form, group).await?;
397    wrap_seal_for(&seal, group, wrap_kind, wrap_at, extra_tags, owner)
398}
399
400/// Re-wrap an already-verified PLAINTEXT seal into another stream (a compaction
401/// carrying a signed edition into a new epoch). The seal event is carried
402/// whole — its content string holds the rumor bytes verbatim, so the rumor id
403/// and the author's signature survive.
404pub fn rewrap_seal(seal: &Event, new_group: &GroupKey, wrap_at: Timestamp) -> Result<(Event, Keys), StreamError> {
405    if seal.kind.as_u16() != KIND_SEAL_PLAINTEXT {
406        return Err(StreamError::NotRewrappable);
407    }
408    wrap_seal(seal, new_group, KIND_WRAP, wrap_at)
409}
410
411// ── open side ────────────────────────────────────────────────────────────────
412
413/// Open and fully verify a stream wrap against the plane's group key.
414///
415/// Verification chain: wrap kind → wrap author == stream address → decrypt
416/// (the NIP-44 MAC under the members-only conversation key is the envelope
417/// gate — the wrap's own signature adds nothing an outsider couldn't also
418/// forge-or-not, so it isn't re-checked) → seal kind → seal Schnorr verify →
419/// rumor recover → rumor.pubkey == seal.pubkey → rumor.id == computed hash
420/// (never trust a claimed id) → strict ms resolve.
421pub fn open_wrap(wrap: &Event, group: &GroupKey) -> Result<OpenedStream, StreamError> {
422    open_wrap_at(wrap, &group.pk(), group.conv_key(), false)
423}
424
425/// [`open_wrap`] against a stream READ VIEW: the address to verify by and the
426/// conversation key that opens the wraps — no signing secret needed. With
427/// `verify_wrap_sig` (a Write-Restricted Stream, CORD-01), the wrap's own
428/// signature is additionally checked: there the signer set is narrower than the
429/// readership, so unlike an ordinary stream wrap (signed with a key every
430/// reader holds — proves nothing) it proves a write-keyholder published this,
431/// and a reader MUST check it rather than lean on the relays having done so.
432pub fn open_wrap_at(
433    wrap: &Event,
434    address: &PublicKey,
435    conv_key: &nostr_sdk::prelude::nip44::v2::ConversationKey,
436    verify_wrap_sig: bool,
437) -> Result<OpenedStream, StreamError> {
438    let wrap_kind = wrap.kind.as_u16();
439    if wrap_kind != KIND_WRAP && wrap_kind != KIND_WRAP_EPHEMERAL {
440        return Err(StreamError::BadWrapKind(wrap_kind));
441    }
442    if wrap.pubkey != *address {
443        return Err(StreamError::WrongStream);
444    }
445    if verify_wrap_sig && !verified(wrap) {
446        return Err(StreamError::BadWrapSignature);
447    }
448
449    let seal = match batch_seal(wrap, conv_key) {
450        Some(seal) => seal,
451        None => crate::event_json::event(&open_nip44(conv_key, &wrap.content)?).map_err(|e| StreamError::Parse(e.to_string()))?,
452    };
453    let seal_form = SealForm::from_kind(seal.kind.as_u16()).ok_or(StreamError::BadSealKind(seal.kind.as_u16()))?;
454    if !verified(&seal) {
455        return Err(StreamError::BadSealSignature);
456    }
457
458    let rumor_json = match seal_form {
459        SealForm::Plaintext => seal.content.clone(),
460        SealForm::Encrypted => open_nip44(conv_key, &seal.content)?,
461    };
462    let mut rumor: UnsignedEvent = crate::event_json::unsigned(&rumor_json).map_err(|e| StreamError::Parse(e.to_string()))?;
463
464    if rumor.pubkey != seal.pubkey {
465        return Err(StreamError::AuthorMismatch);
466    }
467    // Never trust a claimed id: recompute from the serialized fields
468    // unconditionally (`ensure_id` is a no-op when an id is present, so it
469    // would wave a forged one through). An absent id just takes the computed one.
470    let computed = EventId::compute(&rumor.pubkey, &rumor.created_at, &rumor.kind, &rumor.tags, &rumor.content);
471    if let Some(claimed) = rumor.id {
472        if claimed != computed {
473            return Err(StreamError::BadRumorId);
474        }
475    }
476    rumor.id = Some(computed);
477    let at_ms = resolve_ms_strict(&rumor)?;
478
479    Ok(OpenedStream {
480        rumor_id: computed,
481        author: seal.pubkey,
482        seal_form,
483        seal,
484        wrapper_id: wrap.id,
485        at_ms,
486        rumor,
487        held: false,
488    })
489}
490
491/// An event's (author, id, signature).
492type CheckedSig = ([u8; 32], [u8; 32], [u8; 64]);
493
494fn checked_sig(e: &Event) -> CheckedSig {
495    (*e.pubkey.as_bytes(), *e.id.as_bytes(), *e.sig.as_bytes())
496}
497
498/// Signatures this session has found valid, so a plane read again (every follow re-reads its
499/// Control Plane) confirms only each event's id. Keyed by a salted digest of the whole
500/// (author, id, signature), in two generations: a full `cur` ages into `prev`.
501struct VerifiedSigs {
502    salt: [u8; 16],
503    cur: std::collections::HashSet<u128>,
504    prev: std::collections::HashSet<u128>,
505}
506
507const VERIFIED_SIGS_GEN: usize = 16_384;
508
509impl Default for VerifiedSigs {
510    fn default() -> Self {
511        let mut salt = [0u8; 16];
512        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut salt);
513        VerifiedSigs { salt, cur: Default::default(), prev: Default::default() }
514    }
515}
516
517impl VerifiedSigs {
518    fn key(&self, sig: &CheckedSig) -> u128 {
519        let mut h = crate::crypto::sha256::Sha256::new();
520        h.update(self.salt);
521        h.update(sig.0);
522        h.update(sig.1);
523        h.update(sig.2);
524        u128::from_le_bytes(h.finalize()[..16].try_into().expect("16 of 32 bytes"))
525    }
526
527    fn contains(&mut self, key: u128) -> bool {
528        if self.cur.contains(&key) {
529            return true;
530        }
531        if self.prev.remove(&key) {
532            self.insert(key);
533            return true;
534        }
535        false
536    }
537
538    fn insert(&mut self, key: u128) {
539        if self.cur.len() >= VERIFIED_SIGS_GEN {
540            self.prev = std::mem::take(&mut self.cur);
541        }
542        self.cur.insert(key);
543    }
544}
545
546fn verified_sigs() -> std::sync::Arc<std::sync::Mutex<VerifiedSigs>> {
547    struct Key;
548    crate::db::current_session().scoped::<Key, std::sync::Mutex<VerifiedSigs>>()
549}
550
551#[cfg(test)]
552fn forget_verified() {
553    *verified_sigs().lock().unwrap() = VerifiedSigs::default();
554}
555
556/// `Event::verify`. A signature this session already found valid needs only its id confirmed
557/// against the content, which is all `verify` adds to it.
558fn verified(e: &Event) -> bool {
559    let sigs = verified_sigs();
560    let key = {
561        let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
562        let key = known.key(&checked_sig(e));
563        if known.contains(key) {
564            drop(known);
565            return e.verify_id();
566        }
567        key
568    };
569    let ok = e.verify_id() && crate::crypto::batch_verify::signature(e);
570    if ok {
571        sigs.lock().unwrap_or_else(|p| p.into_inner()).insert(key);
572    }
573    ok
574}
575
576thread_local! {
577    /// The seals [`check_signatures_together`] decrypted for the page being opened on this
578    /// thread, by wrap id with the key that opened each, so [`open_wrap_at`] needn't again.
579    static BATCH_SEALS: std::cell::RefCell<std::collections::HashMap<EventId, (ConversationKey, Event)>> = Default::default();
580}
581
582/// The seal the current page's batch already opened from `wrap` under `conv_key`.
583fn batch_seal(wrap: &Event, conv_key: &ConversationKey) -> Option<Event> {
584    BATCH_SEALS.with_borrow_mut(|seals| match seals.get(&wrap.id) {
585        Some((ck, _)) if ck == conv_key => seals.remove(&wrap.id).map(|(_, seal)| seal),
586        _ => None,
587    })
588}
589
590/// A page's batch-opened seals, held for [`open_wrap_at`] on this thread until it drops. Hold
591/// it only across the page's synchronous opens.
592pub struct BatchChecked(());
593
594impl Drop for BatchChecked {
595    fn drop(&mut self) {
596        BATCH_SEALS.with_borrow_mut(std::collections::HashMap::clear);
597    }
598}
599
600/// Checks a page of wraps' signatures in one BIP-340 batch (nostr-verify) before they are
601/// opened one by one: every seal's, found by opening the wrap under the first of its
602/// conversation keys that fits, and with `true` the wrap's own (a Write-Restricted Stream).
603/// What verifies joins the session's checked signatures, so the opens confirm only ids, and
604/// while the guard lives they take each seal from here rather than decrypting it again.
605/// Anything the batch rejected or never saw is verified in full as before.
606pub fn check_signatures_together(wraps: &[(&Event, Vec<&ConversationKey>, bool)]) -> BatchChecked {
607    let guard = BatchChecked(());
608    let mut seals: Vec<Event> = Vec::with_capacity(wraps.len());
609    BATCH_SEALS.with_borrow_mut(|kept| {
610        kept.clear();
611        for (wrap, keys, _) in wraps {
612            let opened = keys.iter().find_map(|ck| Some((**ck, crate::event_json::event(&open_nip44(ck, &wrap.content).ok()?).ok()?)));
613            if let Some((ck, seal)) = opened {
614                seals.push(seal.clone());
615                kept.insert(wrap.id, (ck, seal));
616            }
617        }
618    });
619    let sigs = verified_sigs();
620    let unchecked: Vec<(&Event, u128)> = {
621        let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
622        wraps
623            .iter()
624            .filter(|(.., own)| *own)
625            .map(|(wrap, ..)| *wrap)
626            .chain(&seals)
627            .filter_map(|e| {
628                let key = known.key(&checked_sig(e));
629                (!known.contains(key)).then_some((e, key))
630            })
631            .collect()
632    };
633    if unchecked.len() >= nostr_verify::MIN_BATCH {
634        let events: Vec<&Event> = unchecked.iter().map(|(e, _)| *e).collect();
635        let ok = crate::crypto::batch_verify::signatures(&events);
636        let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
637        for ((_, key), ok) in unchecked.iter().zip(ok) {
638            if ok {
639                known.insert(*key);
640            }
641        }
642    }
643    guard
644}
645
646/// [`check_signatures_together`] for a page whose wraps all open under `group`.
647pub fn check_page(wraps: &[&Event], group: &GroupKey) -> BatchChecked {
648    let page: Vec<_> = wraps.iter().map(|w| (*w, vec![group.conv_key()], false)).collect();
649    check_signatures_together(&page)
650}
651
652/// Enforce the Chat-plane binding (CORD-03 §3): the rumor MUST commit
653/// `["channel", id]` + `["epoch", n]`, strict-equal to the coordinate whose key
654/// decrypted the wrap; a mismatch (or duplicate/absent tag) is a splice — drop.
655pub fn check_channel_binding(rumor: &UnsignedEvent, channel_id: &ChannelId, epoch: Epoch) -> Result<(), StreamError> {
656    match unique_tag_unsigned(rumor, TAG_CHANNEL)? {
657        Some(c) if c == channel_id.to_hex() => {}
658        Some(_) => return Err(StreamError::ChannelMismatch),
659        None => return Err(StreamError::MissingTag(TAG_CHANNEL)),
660    }
661    match unique_tag_unsigned(rumor, TAG_EPOCH)? {
662        Some(e) if e == epoch.0.to_string() => {}
663        Some(_) => return Err(StreamError::EpochMismatch),
664        None => return Err(StreamError::MissingTag(TAG_EPOCH)),
665    }
666    Ok(())
667}
668
669/// The standard chat binding tags for a rumor: `["channel", id]` + `["epoch", n]`.
670pub fn channel_binding_tags(channel_id: &ChannelId, epoch: Epoch) -> Vec<Tag> {
671    vec![
672        Tag::custom(TAG_CHANNEL, [channel_id.to_hex()]),
673        Tag::custom(TAG_EPOCH, [epoch.0.to_string()]),
674    ]
675}
676
677// ── helpers ──────────────────────────────────────────────────────────────────
678
679fn cap(len: usize) -> Result<(), StreamError> {
680    if len > NIP44_MAX_PLAINTEXT {
681        return Err(StreamError::Oversize(len));
682    }
683    Ok(())
684}
685
686fn open_nip44(conv_key: &ConversationKey, content_b64: &str) -> Result<String, StreamError> {
687    let ct = crate::simd::base64::STANDARD
688        .decode_to_vec(content_b64.as_bytes())
689        .map_err(|e| StreamError::Decrypt(e.to_string()))?;
690    let pt = crate::crypto::nip44::decrypt(conv_key, ct).map_err(|e| StreamError::Decrypt(e.to_string()))?;
691    String::from_utf8(pt).map_err(|e| StreamError::Parse(e.to_string()))
692}
693
694/// Value of the tag named `name` on an unsigned rumor, requiring it to appear
695/// AT MOST ONCE (any keyholder can craft a rumor; a duplicated binding tag
696/// makes first-match nondeterministic — reject).
697fn unique_tag_unsigned(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, StreamError> {
698    let mut found: Option<String> = None;
699    for t in rumor.tags.iter() {
700        let s = t.as_slice();
701        if s.len() >= 2 && s[0] == name {
702            if found.is_some() {
703                return Err(StreamError::DuplicateTag(name));
704            }
705            found = Some(s[1].clone());
706        }
707    }
708    Ok(found)
709}
710
711#[cfg(test)]
712mod tests {
713
714    /// Wrap raw `Keys` as the polymorphic signer. `VectorSigner` pins its error to
715    /// `SignerError`, which bare `Keys` doesn't satisfy, so tests go through the
716    /// same enum the app uses.
717    fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
718        crate::signer::ActiveSigner::Keys(k.clone())
719    }
720    use super::super::super::{ChannelId, Epoch};
721    use super::super::derive::channel_group_key;
722    use super::super::kind;
723    use super::*;
724
725    fn group() -> GroupKey {
726        channel_group_key(&[7u8; 32], &chan(), Epoch(0))
727    }
728
729    fn chan() -> ChannelId {
730        ChannelId([0xabu8; 32])
731    }
732
733    fn send(author: &Keys, group: &GroupKey, form: SealForm, content: &str, at_ms: u64) -> Event {
734        let tags = channel_binding_tags(&chan(), Epoch(0));
735        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), content, tags, at_ms);
736        let seal = build_seal(&rumor, form, group, author).unwrap();
737        wrap_seal(&seal, group, KIND_WRAP, Timestamp::from_secs(1_700_000_000)).unwrap().0
738    }
739
740    #[test]
741    fn encrypted_round_trip_preserves_author_content_and_ms() {
742        let author = Keys::generate();
743        let wrap = send(&author, &group(), SealForm::Encrypted, "Hey chat!", 1_686_840_217_417);
744        assert_eq!(wrap.kind.as_u16(), KIND_WRAP);
745        assert_eq!(wrap.pubkey, group().pk(), "wrap is signed by the stream key");
746
747        let opened = open_wrap(&wrap, &group()).unwrap();
748        assert_eq!(opened.author, author.public_key());
749        assert_eq!(opened.rumor.content, "Hey chat!");
750        assert_eq!(opened.at_ms, 1_686_840_217_417);
751        assert_eq!(opened.seal_form, SealForm::Encrypted);
752        check_channel_binding(&opened.rumor, &chan(), Epoch(0)).unwrap();
753    }
754
755    #[tokio::test]
756    async fn signer_seal_opens_identically_to_local_seal() {
757        // A signer that is a plain Keys (NOT the vault) must produce a wrap that
758        // opens to the same rumor + author as the local build_seal path — the seal
759        // half of the wire-identity guarantee the bunker/NIP-55 integration rests on.
760        let author = Keys::generate();
761        let g = group();
762        let tags = channel_binding_tags(&chan(), Epoch(0));
763        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "parity", tags, 1_686_840_217_000);
764        let wrap_at = Timestamp::from_secs(1_686_840_217);
765
766        let seal_l = build_seal(&rumor, SealForm::Encrypted, &g, &author).unwrap();
767        let (wrap_l, _) = wrap_seal(&seal_l, &g, KIND_WRAP, wrap_at).unwrap();
768        let (wrap_s, _) = seal_and_wrap_signed(&as_signer(&author), author.public_key(), &rumor, SealForm::Encrypted, &g, KIND_WRAP, wrap_at, &[])
769            .await
770            .unwrap();
771
772        let opened_l = open_wrap(&wrap_l, &g).unwrap();
773        let opened_s = open_wrap(&wrap_s, &g).unwrap();
774        assert_eq!(opened_l.rumor_id, opened_s.rumor_id, "same inner rumor id via either seal path");
775        assert_eq!(opened_s.author, author.public_key(), "signer seal carries the author identity");
776        assert_eq!(opened_l.seal_form, opened_s.seal_form);
777        assert_eq!(opened_s.rumor.content, "parity");
778    }
779
780    #[test]
781    fn plaintext_seal_round_trip_carries_rumor_verbatim() {
782        let author = Keys::generate();
783        let wrap = send(&author, &group(), SealForm::Plaintext, "an edition", 1_686_840_217_000);
784        let opened = open_wrap(&wrap, &group()).unwrap();
785        assert_eq!(opened.seal_form, SealForm::Plaintext);
786        // The seal's content IS the rumor's JSON — the compaction contract.
787        assert_eq!(opened.seal.content, opened.rumor.as_json());
788    }
789
790    #[test]
791    fn wrong_stream_key_cannot_open() {
792        let author = Keys::generate();
793        let wrap = send(&author, &group(), SealForm::Encrypted, "secret", 1_000);
794        let other = channel_group_key(&[8u8; 32], &chan(), Epoch(0));
795        // Different address entirely → WrongStream before any decrypt attempt.
796        assert!(matches!(open_wrap(&wrap, &other), Err(StreamError::WrongStream)));
797    }
798
799    #[test]
800    fn tampered_wrap_content_fails_the_mac() {
801        let author = Keys::generate();
802        let mut wrap = send(&author, &group(), SealForm::Encrypted, "x", 1_000);
803        let mut json: serde_json::Value = serde_json::from_str(&wrap.as_json()).unwrap();
804        let ct = json["content"].as_str().unwrap().to_string();
805        // Flip a mid-payload character (the first char of a NIP-44 base64 payload
806        // is always 'A' — the 0x02 version byte — so tampering there is a no-op).
807        let mut bytes = ct.into_bytes();
808        bytes[20] = if bytes[20] == b'B' { b'C' } else { b'B' };
809        json["content"] = serde_json::Value::String(String::from_utf8(bytes).unwrap());
810        wrap = Event::from_json(json.to_string()).unwrap();
811        assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::Decrypt(_))));
812    }
813
814    #[test]
815    fn forged_seal_signature_is_rejected() {
816        let author = Keys::generate();
817        let impostor = Keys::generate();
818        let tags = channel_binding_tags(&chan(), Epoch(0));
819        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "hi", tags, 1_000);
820        // Seal signed by the impostor but CLAIMING the author's pubkey: rebuild
821        // the seal event JSON with a swapped pubkey — the sig no longer matches.
822        let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &impostor).unwrap();
823        let mut json: serde_json::Value = serde_json::from_str(&seal.as_json()).unwrap();
824        json["pubkey"] = serde_json::Value::String(author.public_key().to_hex());
825        // (id also changes with pubkey — recompute is not attempted; both id and
826        // sig checks are downstream of Event::from_json/verify.)
827        let forged = Event::from_json(json.to_string());
828        let Ok(forged) = forged else { return }; // strict parsers may reject outright — equally a pass
829        let (wrap, _) = wrap_seal(&forged, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
830        assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::BadSealSignature)));
831    }
832
833    /// A page checked in one batch opens exactly as each wrap opened alone: valid wraps the
834    /// same, every forgery refused with the same error. That includes a seal whose content
835    /// changed under its valid (id, signature) pair, which only the id check can catch.
836    #[test]
837    fn a_page_checked_together_opens_as_one_at_a_time() {
838        let g = group();
839        let authors: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
840        let mut page: Vec<Event> =
841            (0..12).map(|i| send(&authors[i % 3], &g, SealForm::Encrypted, &format!("message {i}"), 1_000 + i as u64)).collect();
842        let seal_of = |w: &Event| crate::event_json::event(&open_nip44(g.conv_key(), &w.content).unwrap()).unwrap();
843        let (mut swapped, mut edited) = (seal_of(&page[0]), seal_of(&page[1]));
844        swapped.sig = seal_of(&page[2]).sig;
845        edited.content = seal_of(&page[3]).content;
846        for seal in [swapped, edited] {
847            page.push(wrap_seal(&seal, &g, KIND_WRAP, Timestamp::from_secs(1)).unwrap().0);
848        }
849        let open = |w: &Event, own: bool| open_wrap_at(w, &g.pk(), g.conv_key(), own).map(|o| o.rumor_id).map_err(|e| e.to_string());
850
851        forget_verified();
852        let alone: Vec<_> = page.iter().map(|w| open(w, false)).collect();
853        forget_verified();
854        let before = crate::crypto::batch_verify::stats();
855        let batch = check_signatures_together(&page.iter().map(|w| (w, vec![g.conv_key()], false)).collect::<Vec<_>>());
856        assert!(crate::crypto::batch_verify::stats().batches > before.batches, "the page went through a batch");
857        let together: Vec<_> = page.iter().map(|w| open(w, false)).collect();
858        drop(batch);
859        assert_eq!(together, alone);
860        assert_eq!(alone.iter().filter(|r| r.is_ok()).count(), 12);
861        assert!(alone[12..].iter().all(|r| *r == Err(StreamError::BadSealSignature.to_string())));
862        // Read again with every honest signature remembered: the forgeries still fail.
863        let again: Vec<_> = page.iter().map(|w| open(w, false)).collect();
864        assert_eq!(again, alone);
865
866        // A Write-Restricted Stream checks each wrap's own signature as well.
867        let mut forged = page[4].clone();
868        forged.sig = page[5].sig;
869        let restricted = [&page[4], &page[5], &page[6], &forged];
870        forget_verified();
871        let alone: Vec<_> = restricted.iter().map(|w| open(w, true)).collect();
872        forget_verified();
873        let batch = check_signatures_together(&restricted.iter().map(|w| (*w, vec![g.conv_key()], true)).collect::<Vec<_>>());
874        let together: Vec<_> = restricted.iter().map(|w| open(w, true)).collect();
875        drop(batch);
876        assert_eq!(together, alone);
877        assert_eq!(alone[3], Err(StreamError::BadWrapSignature.to_string()));
878        assert!(alone[..3].iter().all(Result::is_ok));
879    }
880
881    #[test]
882    fn rumor_author_must_match_seal_author() {
883        let author = Keys::generate();
884        let other = Keys::generate();
885        let tags = channel_binding_tags(&chan(), Epoch(0));
886        // Rumor claims `other` as its author, but the seal is signed by `author`.
887        let rumor = build_rumor_ms(kind::MESSAGE, other.public_key(), "spoof", tags, 1_000);
888        let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
889        let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
890        assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::AuthorMismatch)));
891    }
892
893    #[test]
894    fn forged_rumor_id_is_rejected() {
895        let author = Keys::generate();
896        let tags = channel_binding_tags(&chan(), Epoch(0));
897        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "real", tags, 1_000);
898        let mut json: serde_json::Value = serde_json::from_str(&rumor.as_json()).unwrap();
899        json["id"] = serde_json::Value::String("00".repeat(32));
900        let forged_json = json.to_string();
901        // Hand-build a seal around the forged rumor bytes (plaintext form so the
902        // bytes ride verbatim).
903        let seal = EventBuilder::new(Kind::Custom(KIND_SEAL_PLAINTEXT), forged_json)
904            .custom_created_at(rumor.created_at)
905            .finalize(&author)
906            .unwrap();
907        let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
908        assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::BadRumorId)));
909    }
910
911    #[test]
912    fn ms_is_strict_absent_is_zero_invalid_is_dropped() {
913        let author = Keys::generate();
914        // Absent ms = offset 0.
915        let rumor = build_rumor_secs(kind::MESSAGE, author.public_key(), "x", vec![], 1_000);
916        assert_eq!(resolve_ms_strict(&rumor).unwrap(), 1_000_000);
917        // 999 is the max valid offset.
918        let ok = build_rumor_secs(
919            kind::MESSAGE,
920            author.public_key(),
921            "x",
922            vec![Tag::custom("ms", ["999".to_string()])],
923            1_000,
924        );
925        assert_eq!(resolve_ms_strict(&ok).unwrap(), 1_000_999);
926        // 1000, negatives, non-integers, leading zeros, and a leading '+' (which
927        // `u64::from_str` would otherwise accept as a second byte-encoding):
928        // malformed — DROP, never clamp.
929        for bad in ["1000", "-1", "12.5", "abc", "007", "", "+5", "+0", "+000", "+999"] {
930            let r = build_rumor_secs(
931                kind::MESSAGE,
932                author.public_key(),
933                "x",
934                vec![Tag::custom("ms", [bad.to_string()])],
935                1_000,
936            );
937            assert!(
938                matches!(resolve_ms_strict(&r), Err(StreamError::BadMs)),
939                "ms={bad:?} must be malformed"
940            );
941        }
942    }
943
944    #[test]
945    fn a_valueless_ms_tag_is_malformed_and_a_duplicate_takes_the_first() {
946        // A present-but-valueless ["ms"] must be BadMs, not treated as absent (a
947        // silent offset-0 default would honor a rumor a spec-strict peer drops).
948        let author = Keys::generate();
949        let bare = build_rumor_secs(
950            kind::MESSAGE,
951            author.public_key(),
952            "x",
953            vec![Tag::custom("ms", Vec::<String>::new())],
954            1_000,
955        );
956        assert!(matches!(resolve_ms_strict(&bare), Err(StreamError::BadMs)));
957        // A valueless FIRST occurrence is still malformed: first-wins picks it,
958        // and it carries no value to interpret. A later valued tag can't rescue it.
959        let two = build_rumor_secs(
960            kind::MESSAGE,
961            author.public_key(),
962            "x",
963            vec![
964                Tag::custom("ms", Vec::<String>::new()),
965                Tag::custom("ms", ["5".to_string()]),
966            ],
967            1_000,
968        );
969        assert!(matches!(resolve_ms_strict(&two), Err(StreamError::BadMs)));
970        // Two VALUED ms tags: the first wins, matching Armada. Rejecting the
971        // rumor instead made the two clients disagree on whether the event
972        // exists — and `ms` orders messages, Guestbook recency and List
973        // tiebreaks, so that reached membership. Conceding costs nothing: `ms`
974        // is the publisher's own value, so a second tag buys an attacker no
975        // reach a single one didn't already give them.
976        let two_valued = build_rumor_secs(
977            kind::MESSAGE,
978            author.public_key(),
979            "x",
980            vec![
981                Tag::custom("ms", ["1".to_string()]),
982                Tag::custom("ms", ["2".to_string()]),
983            ],
984            1_000,
985        );
986        assert_eq!(resolve_ms_strict(&two_valued).unwrap(), 1_000_001, "the FIRST ms wins");
987    }
988
989    #[test]
990    fn tag_numbers_are_spec_shaped_decimals() {
991        use crate::community::edition::is_tag_decimal;
992        // CORD-01 §5: "its decimal form with no leading zeros".
993        for good in ["4", "0", "1099511627776"] {
994            assert!(is_tag_decimal(good), "{good:?} is decimal form");
995        }
996        for bad in ["04", "007", "00", "+4", "-4", "0x4", "1e2", " 4", "4 ", "", "4.0"] {
997            assert!(!is_tag_decimal(bad), "{bad:?} is NOT decimal form");
998        }
999    }
1000
1001    #[test]
1002    fn a_citation_version_must_be_plain_digits() {
1003        // CORD-01 §5: a tag number rides as its decimal form. `u64::from_str`
1004        // accepts a leading `+`, which Armada's digit check rejects — so an
1005        // action citing "+5" would be honored by one client and parked by the
1006        // other. Same guard `resolve_ms_strict` already applies to `ms`.
1007        let eid = "ab".repeat(32);
1008        let hash = "cd".repeat(32);
1009        let cite = |v: &str| {
1010            let tags = nostr_sdk::prelude::Tags::from_list(vec![Tag::custom(
1011                "vac",
1012                [eid.clone(), v.to_string(), hash.clone()],
1013            )]);
1014            crate::community::edition::AuthorityCitation::from_tags(&tags)
1015        };
1016        assert!(cite("5").is_some(), "a plain decimal is the shape the spec names");
1017        assert!(cite("+5").is_none(), "a leading plus is not decimal form");
1018        assert!(cite("").is_none());
1019        assert!(cite("5x").is_none());
1020        assert!(cite("05").is_none(), "no leading zeros (CORD-01 §5)");
1021    }
1022
1023    #[test]
1024    fn binding_rejects_splices_and_duplicates() {
1025        let author = Keys::generate();
1026        let tags = channel_binding_tags(&chan(), Epoch(0));
1027        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1028        // Wrong channel and wrong epoch both reject.
1029        assert!(matches!(
1030            check_channel_binding(&rumor, &ChannelId([0xcd; 32]), Epoch(0)),
1031            Err(StreamError::ChannelMismatch)
1032        ));
1033        assert!(matches!(
1034            check_channel_binding(&rumor, &chan(), Epoch(1)),
1035            Err(StreamError::EpochMismatch)
1036        ));
1037        // A duplicated binding tag is ambiguous — rejected outright.
1038        let mut tags = channel_binding_tags(&chan(), Epoch(0));
1039        tags.extend(channel_binding_tags(&chan(), Epoch(0)));
1040        let dup = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1041        assert!(matches!(
1042            check_channel_binding(&dup, &chan(), Epoch(0)),
1043            Err(StreamError::DuplicateTag(_))
1044        ));
1045        // Missing binding tags reject too.
1046        let bare = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", vec![], 1_000);
1047        assert!(matches!(
1048            check_channel_binding(&bare, &chan(), Epoch(0)),
1049            Err(StreamError::MissingTag(_))
1050        ));
1051    }
1052
1053    #[test]
1054    fn oversize_plaintext_is_refused_at_build_time() {
1055        let author = Keys::generate();
1056        let big = "x".repeat(NIP44_MAX_PLAINTEXT + 1);
1057        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), &big, vec![], 1_000);
1058        assert!(matches!(
1059            seal_content(&rumor, SealForm::Encrypted, &group()),
1060            Err(StreamError::Oversize(_))
1061        ));
1062    }
1063
1064    #[test]
1065    fn ephemeral_wrap_round_trips_and_bad_wrap_kind_rejects() {
1066        let author = Keys::generate();
1067        let tags = channel_binding_tags(&chan(), Epoch(0));
1068        let rumor = build_rumor_ms(kind::TYPING, author.public_key(), "", tags, 5_000);
1069        let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
1070        let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP_EPHEMERAL, Timestamp::from_secs(5)).unwrap();
1071        assert_eq!(wrap.kind.as_u16(), KIND_WRAP_EPHEMERAL);
1072        assert_eq!(open_wrap(&wrap, &group()).unwrap().rumor.kind.as_u16(), kind::TYPING);
1073        assert!(matches!(
1074            wrap_seal(&seal, &group(), 1058, Timestamp::from_secs(5)),
1075            Err(StreamError::BadWrapKind(1058))
1076        ));
1077    }
1078
1079    #[test]
1080    fn rewrap_preserves_rumor_id_and_signature_across_epochs() {
1081        let author = Keys::generate();
1082        let wrap = send(&author, &group(), SealForm::Plaintext, "the head edition", 9_000);
1083        let opened = open_wrap(&wrap, &group()).unwrap();
1084
1085        // Compaction: carry the verified seal into the next epoch's stream.
1086        let next = channel_group_key(&[7u8; 32], &chan(), Epoch(1));
1087        let (rewrapped, _) = rewrap_seal(&opened.seal, &next, Timestamp::from_secs(2_000)).unwrap();
1088        let reopened = open_wrap(&rewrapped, &next).unwrap();
1089
1090        assert_eq!(reopened.rumor_id, opened.rumor_id, "rumor id survives the re-wrap");
1091        assert_eq!(reopened.author, author.public_key(), "authorship survives");
1092        assert_eq!(reopened.seal.sig, opened.seal.sig, "the original signature rides verbatim");
1093        assert_ne!(reopened.wrapper_id, opened.wrapper_id, "outer identity differs per wrap");
1094
1095        // Encrypted seals must refuse to re-wrap (sig binds the old key's ciphertext).
1096        let enc = send(&author, &group(), SealForm::Encrypted, "no", 9_000);
1097        let enc_opened = open_wrap(&enc, &group()).unwrap();
1098        assert!(matches!(
1099            rewrap_seal(&enc_opened.seal, &next, Timestamp::from_secs(2_000)),
1100            Err(StreamError::NotRewrappable)
1101        ));
1102    }
1103
1104    #[test]
1105    fn wrap_p_tag_is_ephemeral_not_the_stream_or_author() {
1106        let author = Keys::generate();
1107        let g = group();
1108        let tags = channel_binding_tags(&chan(), Epoch(0));
1109        let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1110        let seal = build_seal(&rumor, SealForm::Encrypted, &g, &author).unwrap();
1111        let (wrap, ephemeral) = wrap_seal(&seal, &g, KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1112        let p = wrap
1113            .tags
1114            .iter()
1115            .find_map(|t| {
1116                let s = t.as_slice();
1117                (s.len() >= 2 && s[0] == "p").then(|| s[1].clone())
1118            })
1119            .expect("wrap carries a p tag");
1120        assert_eq!(p, ephemeral.public_key().to_hex());
1121        assert_ne!(p, g.pk_hex());
1122        assert_ne!(p, author.public_key().to_hex());
1123    }
1124}