Skip to main content

vector_core/community/v2/
pins.rs

1//! Pins — CORD-04 §7. A pin does not quote a message; it proves one.
2//!
3//! One Pin List per Channel on the Control Plane (vsk 11, coordinate
4//! `pins_locator(community_id, channel_id)`), replaced entire per edit like the
5//! Banlist. Each entry carries the original kind-20013 seal verbatim plus the
6//! message's disclosed NIP-44 keys, so any reader able to open the list's form
7//! verifies author, words, Channel, and signed time — holding no history and no
8//! old keys. Compaction re-wraps the head across rotations, which is the whole
9//! point of the placement.
10//!
11//! Wire format shared with Armada's `pins.ts` — entry JSON, both content forms,
12//! and the caps are cross-client surface. Divergence silently breaks pin
13//! verification between clients.
14
15use nostr_sdk::prelude::*;
16use serde::{Deserialize, Serialize};
17
18use super::kind;
19use super::pin_keys;
20use super::stream::OpenedStream;
21
22/// Structural caps (CORD-04 §7 Limits) — a violating edition reads as EMPTY.
23pub const PIN_MAX_ENTRIES: usize = 25;
24pub const PIN_MAX_CONTENT_BYTES: usize = 32_768;
25
26/// The seal kind a proof requires (an encrypted chat seal).
27const KIND_SEAL_ENCRYPTED: u16 = 20013;
28
29/// An Edit's proof bundle: the same disclosure, for the revision.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct PinEditBundle {
32    pub seal: Event,
33    pub keys: String,
34}
35
36/// One wire entry. Optional fields are omitted when absent (matching the
37/// reference implementation's JSON), and unknown fields are carried through
38/// `extra` so republishing an entry never strips what a newer client added.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct PinEntry {
41    /// The original kind-20013 seal event: fields carried exactly, content
42    /// string unaltered.
43    pub seal: Event,
44    /// 76-byte lowercase hex: `chacha_key[32] || chacha_nonce[12] || hmac_key[32]`.
45    pub keys: String,
46    /// Optional, UNVERIFIED locator hint for jump-to-context.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub wrap: Option<String>,
49    /// The newest provable Edit, for readers who hold no Chat plane (§7 Edits).
50    /// At most one, ever: Edits target the ORIGINAL rumor and never each other,
51    /// so a later Edit REPLACES this rather than appending.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub edit: Option<PinEditBundle>,
54    #[serde(flatten)]
55    pub extra: serde_json::Map<String, serde_json::Value>,
56}
57
58/// A pin that passed the full §7 verification — safe to render.
59#[derive(Debug, Clone, Serialize)]
60pub struct VerifiedPin {
61    /// Recomputed from the decrypted bytes; never the embedded field.
62    pub rumor_id: String,
63    /// The seal's signer == the rumor's author (hex).
64    pub author: String,
65    pub kind: u16,
66    pub content: String,
67    pub tags: Vec<Vec<String>>,
68    /// The message's own epoch tag — derives the plane address for jump-to-context.
69    pub epoch: Option<String>,
70    /// Ordering basis: created_at*1000 + ms tag.
71    pub ms: u64,
72    pub created_at: u64,
73    /// Untrusted locator hint, if the entry carried one.
74    pub wrap_hint: Option<String>,
75    /// Set when a proven Edit superseded the original's words.
76    pub edited: Option<EditedContent>,
77    /// The wire entry, verbatim — for republishing (re-wraps, omissions).
78    #[serde(skip_serializing)]
79    pub entry: PinEntry,
80}
81
82#[derive(Debug, Clone, Serialize)]
83pub struct EditedContent {
84    pub content: String,
85    pub ms: u64,
86}
87
88/// Why a message could not be pinned — each cause needs a different answer.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum PinBuildFailure {
91    /// The seal is not an encrypted chat seal (plaintext seals carry no NIP-44
92    /// payload to disclose).
93    NotEncrypted,
94    /// The conversation key does not open this payload — the message is from an
95    /// epoch this client does not hold, or the payload is malformed.
96    BadPayload,
97    /// The built entry failed its own verification; publishing it would burn
98    /// list budget on a proof no reader accepts.
99    Unverifiable,
100}
101
102fn tag_value<'a>(tags: &'a [Vec<String>], name: &str) -> Option<&'a str> {
103    tags.iter()
104        .find(|t| t.first().map(String::as_str) == Some(name))
105        .and_then(|t| t.get(1))
106        .map(String::as_str)
107}
108
109/// Ordering basis (CORD-02 §4): `created_at * 1000 + ms`, out-of-range ms as 0.
110fn resolve_ms(created_at: u64, tags: &[Vec<String>]) -> u64 {
111    let ms = tag_value(tags, "ms")
112        .and_then(|raw| raw.parse::<u64>().ok())
113        .filter(|ms| *ms <= 999)
114        .unwrap_or(0);
115    created_at * 1000 + ms
116}
117
118/// Build a pin entry from an opened chat message, with the reason attached on
119/// refusal. Requires the Channel's stream conversation key at the message's
120/// epoch — i.e. the pinner can read what they pin. A pinner told "that message
121/// is from an epoch you no longer hold" when the real cause is a non-encrypted
122/// seal would retry forever, so the caller gets the distinction.
123pub fn build_pin_entry(
124    opened: &OpenedStream,
125    conv_key: &[u8; 32],
126    channel_id_hex: &str,
127) -> Result<PinEntry, PinBuildFailure> {
128    let seal = &opened.seal;
129    if seal.kind.as_u16() != KIND_SEAL_ENCRYPTED {
130        return Err(PinBuildFailure::NotEncrypted);
131    }
132    let keys =
133        pin_keys::disclose_keys_for(&seal.content, conv_key).ok_or(PinBuildFailure::BadPayload)?;
134    // Deriving keys is not the same as being able to read: the expansion
135    // succeeds under ANY conversation key, and a message written under an epoch
136    // we no longer hold only fails later, at the MAC. Check here so "you don't
137    // hold these keys" and "this proof doesn't hold up" stay different answers.
138    if pin_keys::decrypt_with_disclosed_keys(&seal.content, &keys).is_none() {
139        return Err(PinBuildFailure::BadPayload);
140    }
141    let entry = PinEntry {
142        seal: seal.clone(),
143        keys: pin_keys::encode_message_keys(&keys),
144        wrap: Some(opened.wrapper_id.to_hex()),
145        edit: None,
146        extra: Default::default(),
147    };
148    // Refuse to build an entry that would not verify — the same gate every
149    // reader applies, run before it costs list budget.
150    if verify_pin_entry(&entry, channel_id_hex).is_none() {
151        return Err(PinBuildFailure::Unverifiable);
152    }
153    Ok(entry)
154}
155
156/// Build an Edit's proof bundle from its opened stream — the same disclosure
157/// as an entry, for the revision (§7 Edits). Verification-mirrored like
158/// [`build_pin_entry`]: refuse to build what `verify_edit_bundle` would drop.
159pub fn build_pin_edit_bundle(
160    edit_opened: &OpenedStream,
161    conv_key: &[u8; 32],
162    original_author: &str,
163    original_rumor_id: &str,
164    channel_id_hex: &str,
165) -> Result<PinEditBundle, PinBuildFailure> {
166    let seal = &edit_opened.seal;
167    if seal.kind.as_u16() != KIND_SEAL_ENCRYPTED {
168        return Err(PinBuildFailure::NotEncrypted);
169    }
170    let keys =
171        pin_keys::disclose_keys_for(&seal.content, conv_key).ok_or(PinBuildFailure::BadPayload)?;
172    if pin_keys::decrypt_with_disclosed_keys(&seal.content, &keys).is_none() {
173        return Err(PinBuildFailure::BadPayload);
174    }
175    let bundle = PinEditBundle { seal: seal.clone(), keys: pin_keys::encode_message_keys(&keys) };
176    if verify_edit_bundle(&bundle, original_author, original_rumor_id, channel_id_hex).is_none() {
177        return Err(PinBuildFailure::Unverifiable);
178    }
179    Ok(bundle)
180}
181
182/// The rumor fields step 4 inspects, parsed strictly from the decrypted bytes.
183#[derive(Deserialize)]
184struct RumorFields {
185    pubkey: String,
186    kind: u16,
187    content: String,
188    created_at: u64,
189    tags: Vec<Vec<String>>,
190}
191
192/// Recompute the rumor's NIP-01 id from its decrypted fields — an embedded
193/// `id` is never trusted.
194fn recompute_rumor_id(r: &RumorFields) -> Option<String> {
195    let pubkey = PublicKey::from_hex(&r.pubkey).ok()?;
196    let tags: Vec<Tag> = r.tags.iter().map(|t| Tag::parse(t.clone()).ok()).collect::<Option<_>>()?;
197    let id = EventId::compute(
198        &pubkey,
199        &Timestamp::from(r.created_at),
200        &Kind::from(r.kind),
201        &Tags::from_list(tags),
202        &r.content,
203    );
204    Some(id.to_hex())
205}
206
207/// The §7 verification, holding nothing but the pin and the list's Channel:
208/// seal kind + signature → MAC → decrypt → rumor checks (author equality, chat
209/// kind, channel binding) → recomputed id. `None` on ANY failure; a failed
210/// entry is dropped alone, its edition folds normally.
211pub fn verify_pin_entry(entry: &PinEntry, channel_id_hex: &str) -> Option<VerifiedPin> {
212    let seal = &entry.seal;
213    // Step 1 — an encrypted chat seal, honestly signed. `verify` checks both
214    // the id-hash and the Schnorr signature.
215    if seal.kind.as_u16() != KIND_SEAL_ENCRYPTED || seal.verify().is_err() {
216        return None;
217    }
218
219    // Steps 2–3 — MAC, then decrypt, under the disclosed keys alone.
220    let keys = pin_keys::decode_message_keys(&entry.keys)?;
221    let plaintext = pin_keys::decrypt_with_disclosed_keys(&seal.content, &keys)?;
222
223    // Step 4 — the rumor's own claims, each strict.
224    let rumor: RumorFields = serde_json::from_str(&plaintext).ok()?;
225    // NIP-59's impersonation check: renderers display rumor fields, so a seal
226    // honestly signed around a rumor claiming another author must fail.
227    if rumor.pubkey != seal.pubkey.to_hex() {
228        return None;
229    }
230    if rumor.kind != kind::MESSAGE && rumor.kind != kind::COMMENT {
231        return None;
232    }
233    // The rumor names its Channel under the author's signature (CORD-01
234    // Binding); strict equality against the list's own Channel, absence
235    // failing — without this, a private Channel's keyholder could pin its
236    // messages into a public list, disclosing them Community-wide with proof.
237    if channel_id_hex.len() != 64
238        || !channel_id_hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
239        || tag_value(&rumor.tags, "channel") != Some(channel_id_hex)
240    {
241        return None;
242    }
243
244    // Step 5 — identity from the bytes, never from a field.
245    let rumor_id = recompute_rumor_id(&rumor)?;
246
247    // The Edit bundle, if the entry carries one. A bad bundle drops the EDIT,
248    // never the pin: the original is still proven, and refusing it outright
249    // would hide a message because someone attached a bad correction.
250    let edited = entry
251        .edit
252        .as_ref()
253        .and_then(|b| verify_edit_bundle(b, &rumor.pubkey, &rumor_id, channel_id_hex));
254
255    Some(VerifiedPin {
256        author: rumor.pubkey,
257        kind: rumor.kind,
258        content: edited.as_ref().map(|e| e.content.clone()).unwrap_or_else(|| rumor.content.clone()),
259        epoch: tag_value(&rumor.tags, "epoch").map(str::to_string),
260        ms: resolve_ms(rumor.created_at, &rumor.tags),
261        created_at: rumor.created_at,
262        tags: rumor.tags,
263        rumor_id,
264        wrap_hint: entry.wrap.clone(),
265        edited,
266        entry: entry.clone(),
267    })
268}
269
270/// An Edit bundle proves the SAME author revised THIS message: the five steps
271/// of [`verify_pin_entry`] with kind `3302` substituted, plus the fold's own
272/// two rules — author equality (nobody else may revise another member's words)
273/// and an `e` tag naming the original's recomputed rumor id.
274fn verify_edit_bundle(
275    bundle: &PinEditBundle,
276    original_author: &str,
277    original_rumor_id: &str,
278    channel_id_hex: &str,
279) -> Option<EditedContent> {
280    let seal = &bundle.seal;
281    if seal.kind.as_u16() != KIND_SEAL_ENCRYPTED {
282        return None;
283    }
284    // Author equality is checkable before any crypto: a bundle sealed by anyone
285    // but the original's author cannot revise it, whatever it decrypts to.
286    if seal.pubkey.to_hex() != original_author {
287        return None;
288    }
289    if seal.verify().is_err() {
290        return None;
291    }
292
293    let keys = pin_keys::decode_message_keys(&bundle.keys)?;
294    let plaintext = pin_keys::decrypt_with_disclosed_keys(&seal.content, &keys)?;
295    let rumor: RumorFields = serde_json::from_str(&plaintext).ok()?;
296    if rumor.pubkey != seal.pubkey.to_hex() {
297        return None;
298    }
299    if rumor.kind != kind::EDIT {
300        return None;
301    }
302    // The Edit binds to this Channel too — the revision path opens no door the
303    // entry path closes.
304    if tag_value(&rumor.tags, "channel") != Some(channel_id_hex) {
305        return None;
306    }
307    if tag_value(&rumor.tags, "e") != Some(original_rumor_id) {
308        return None;
309    }
310    Some(EditedContent {
311        content: rumor.content,
312        ms: resolve_ms(rumor.created_at, &rumor.tags),
313    })
314}
315
316// ── The list's two self-describing content forms ─────────────────────────────
317
318#[derive(Serialize, Deserialize)]
319struct PlainForm {
320    entries: Vec<PinEntry>,
321}
322
323/// Serialize a pin list's `content` for a PUBLIC Channel (plaintext — the
324/// plane's wrap is the gate). Errors on a cap violation: a writer must never
325/// publish an edition every reader would read as empty.
326pub fn serialize_public_pin_list(entries: &[PinEntry]) -> Result<String, String> {
327    let content = serde_json::to_string(&PlainForm { entries: entries.to_vec() })
328        .map_err(|e| e.to_string())?;
329    assert_caps(entries.len(), &content)?;
330    Ok(content)
331}
332
333/// Serialize for a PRIVATE Channel: the entries sealed under the Channel's
334/// group conversation key at `epoch`. Both caps are checked on the final
335/// carried bytes, the sealed envelope living INSIDE the byte cap.
336pub fn serialize_sealed_pin_list(
337    entries: &[PinEntry],
338    conv_key: &nostr_sdk::prelude::nip44::v2::ConversationKey,
339    epoch: u64,
340) -> Result<String, String> {
341    if entries.len() > PIN_MAX_ENTRIES {
342        return Err(format!("pin list exceeds {PIN_MAX_ENTRIES} entries"));
343    }
344    let inner = serde_json::to_string(&PlainForm { entries: entries.to_vec() })
345        .map_err(|e| e.to_string())?;
346    let sealed_raw = crate::community::cipher::encrypt_with_random_nonce(conv_key, inner.as_bytes())?;
347    let sealed = crate::simd::base64::STANDARD.encode_to_string(&sealed_raw);
348    let content = serde_json::json!({ "epoch": epoch.to_string(), "sealed": sealed }).to_string();
349    assert_caps(entries.len(), &content)?;
350    Ok(content)
351}
352
353fn assert_caps(count: usize, content: &str) -> Result<(), String> {
354    if count > PIN_MAX_ENTRIES {
355        return Err(format!("pin list exceeds {PIN_MAX_ENTRIES} entries"));
356    }
357    let bytes = content.len();
358    if bytes > PIN_MAX_CONTENT_BYTES {
359        return Err(format!("pin list content is {bytes} bytes (cap {PIN_MAX_CONTENT_BYTES})"));
360    }
361    Ok(())
362}
363
364/// The entries of a list's `entries` array, each misshapen one dropped alone (CORD-04 §7). `None`
365/// when it isn't an array, or runs past the entry cap, which reads the whole list as empty.
366fn entries_of(entries: Option<&serde_json::Value>) -> Option<Vec<PinEntry>> {
367    let raw = entries?.as_array()?;
368    if raw.len() > PIN_MAX_ENTRIES {
369        return None;
370    }
371    Some(raw.iter().filter_map(|e| serde_json::from_value::<PinEntry>(e.clone()).ok()).collect())
372}
373
374/// A read list: its entries, or the fact it stayed dark.
375pub struct ReadPinList {
376    pub entries: Vec<PinEntry>,
377    /// The sealed form under an epoch key this reader lacks. Darkness, not
378    /// violation — and a WRITER seeing this must withhold, never publish.
379    pub sealed: bool,
380}
381
382/// Read a pin list edition's `content` (§7 Limits): the byte cap judged on the
383/// exact carried bytes by every reader; the entry cap by whoever can open the
384/// form. A violating or unreadable-as-JSON edition reads as an EMPTY list —
385/// never refused from the fold.
386pub fn read_pin_list(
387    content: &str,
388    unseal_key: impl Fn(u64) -> Option<[u8; 32]>,
389) -> ReadPinList {
390    const EMPTY: fn() -> ReadPinList = || ReadPinList { entries: Vec::new(), sealed: false };
391    if content.len() > PIN_MAX_CONTENT_BYTES {
392        return EMPTY();
393    }
394    let Ok(parsed) = serde_json::from_str::<serde_json::Value>(content) else {
395        return EMPTY();
396    };
397
398    // Public form: { "entries": [...] }
399    if parsed.get("entries").is_some() {
400        let Some(entries) = entries_of(parsed.get("entries")) else {
401            return EMPTY();
402        };
403        return ReadPinList { entries, sealed: false };
404    }
405
406    // Sealed form: { "epoch": "<decimal u64>", "sealed": "<base64>" }
407    let (Some(epoch_str), Some(sealed)) = (
408        parsed.get("epoch").and_then(|v| v.as_str()),
409        parsed.get("sealed").and_then(|v| v.as_str()),
410    ) else {
411        return EMPTY();
412    };
413    let canonical = !epoch_str.is_empty() && epoch_str.bytes().all(|b| b.is_ascii_digit()) && (epoch_str == "0" || !epoch_str.starts_with('0'));
414    if !canonical {
415        return EMPTY();
416    }
417    let Ok(epoch) = epoch_str.parse::<u64>() else {
418        return EMPTY();
419    };
420    let Some(key) = unseal_key(epoch) else {
421        return ReadPinList { entries: Vec::new(), sealed: true };
422    };
423    let Some(conv_key) = nostr_sdk::prelude::nip44::v2::ConversationKey::from_slice(&key).ok() else {
424        return EMPTY();
425    };
426    let Ok(raw) = crate::simd::base64::STANDARD.decode_to_vec(sealed.as_bytes()) else {
427        return EMPTY();
428    };
429    let Ok(inner) = crate::crypto::nip44::decrypt(&conv_key, raw) else {
430        return EMPTY();
431    };
432    let Ok(inner) = serde_json::from_slice::<serde_json::Value>(&inner) else {
433        return EMPTY();
434    };
435    let Some(entries) = entries_of(inner.get("entries")) else {
436        return EMPTY();
437    };
438    ReadPinList { entries, sealed: false }
439}
440
441// ── Deletion (§7): self-erasure outranks curation ────────────────────────────
442
443/// Whether a kind-5 kills this pin: matched by the RECOMPUTED rumor id against
444/// the delete's `e` tags, honored only when the delete's author equals the
445/// pin's proven author.
446pub fn pin_killed_by(pin: &VerifiedPin, delete_author_hex: &str, delete_tags: &[Vec<String>]) -> bool {
447    if delete_author_hex != pin.author {
448        return false;
449    }
450    delete_tags
451        .iter()
452        .any(|t| t.first().map(String::as_str) == Some("e") && t.get(1).map(String::as_str) == Some(pin.rumor_id.as_str()))
453}
454
455/// Attach the newest provable Edit to an entry (§7 Edits). Requires the
456/// Channel conversation key of the Edit's own epoch — i.e. the curator can
457/// read it. Returns the entry unchanged when the Edit cannot be proven, so a
458/// refresh never downgrades a good pin into a broken one.
459pub fn with_proven_edit(
460    entry: &PinEntry,
461    edit_opened: &OpenedStream,
462    conv_key: &[u8; 32],
463    channel_id_hex: &str,
464) -> PinEntry {
465    let seal = &edit_opened.seal;
466    if seal.kind.as_u16() != KIND_SEAL_ENCRYPTED {
467        return entry.clone();
468    }
469    let Some(keys) = pin_keys::disclose_keys_for(&seal.content, conv_key) else {
470        return entry.clone();
471    };
472    let mut candidate = entry.clone();
473    candidate.edit = Some(PinEditBundle {
474        seal: seal.clone(),
475        keys: pin_keys::encode_message_keys(&keys),
476    });
477    // Only keep it if it actually verifies against this entry — the same gate a
478    // reader will apply, run before it costs list budget.
479    match verify_pin_entry(&candidate, channel_id_hex) {
480        Some(v) if v.edited.is_some() => candidate,
481        _ => entry.clone(),
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::community::v2::chat::{
489        build_edit_rumor, build_message_rumor, open_chat_event, seal_chat_rumor, ChatEvent,
490    };
491    use crate::community::v2::derive::channel_group_key;
492    use crate::community::{ChannelId, Epoch};
493
494    const AT: u64 = 1_686_840_217_417;
495    const WRAP_AT: Timestamp = Timestamp::from_secs(1_700_000_000);
496
497    fn chan() -> ChannelId {
498        ChannelId([0xab; 32])
499    }
500
501    fn chan_hex() -> String {
502        crate::simd::hex::bytes_to_hex_32(&chan().0)
503    }
504
505    fn group() -> crate::community::v2::derive::GroupKey {
506        channel_group_key(&[7u8; 32], &chan(), Epoch(0))
507    }
508
509    fn conv_bytes() -> [u8; 32] {
510        group().conv_key().as_bytes().try_into().unwrap()
511    }
512
513    /// A real opened chat message, through the production seal/open pipeline.
514    fn opened_message(author: &Keys, text: &str) -> OpenedStream {
515        let rumor = build_message_rumor(author.public_key(), &chan(), Epoch(0), text, None, &[], vec![], AT);
516        let wrap = seal_chat_rumor(&rumor, &group(), author, WRAP_AT, false).unwrap().0;
517        match open_chat_event(&wrap, &group(), &chan(), Epoch(0)).unwrap() {
518            ChatEvent::Message { opened, .. } => opened,
519            other => panic!("expected Message, got {other:?}"),
520        }
521    }
522
523    fn entry_for(author: &Keys, text: &str) -> (PinEntry, OpenedStream) {
524        let opened = opened_message(author, text);
525        let entry = build_pin_entry(&opened, &conv_bytes(), &chan_hex()).unwrap();
526        (entry, opened)
527    }
528
529    #[test]
530    fn a_built_entry_verifies_and_proves_the_author_and_words() {
531        let author = Keys::generate();
532        let (entry, opened) = entry_for(&author, "pin me, I'm important");
533        let v = verify_pin_entry(&entry, &chan_hex()).expect("verifies");
534        assert_eq!(v.author, author.public_key().to_hex());
535        assert_eq!(v.content, "pin me, I'm important");
536        assert_eq!(v.rumor_id, opened.rumor_id.to_hex(), "identity = recomputed rumor id");
537        assert_eq!(v.ms, AT);
538        assert_eq!(v.epoch.as_deref(), Some("0"));
539        assert!(v.edited.is_none());
540    }
541
542    /// The channel binding: a keyholder must not be able to pin channel X's
543    /// message into channel Y's list, proof intact (§7 step 4).
544    #[test]
545    fn a_pin_cannot_cross_channels() {
546        let author = Keys::generate();
547        let (entry, _) = entry_for(&author, "private words");
548        let other = crate::simd::hex::bytes_to_hex_32(&[0xcd; 32]);
549        assert!(verify_pin_entry(&entry, &other).is_none());
550        // And a malformed channel id fails closed.
551        assert!(verify_pin_entry(&entry, "not-hex").is_none());
552        assert!(verify_pin_entry(&entry, "").is_none());
553    }
554
555    #[test]
556    fn tampering_with_the_disclosed_keys_or_seal_fails() {
557        let author = Keys::generate();
558        let (entry, _) = entry_for(&author, "immutable");
559        // Wrong keys: MAC fails.
560        let mut bad = entry.clone();
561        bad.keys = format!("{}{}", &entry.keys[2..], "00");
562        assert!(verify_pin_entry(&bad, &chan_hex()).is_none());
563        // A different author's seal around the same payload: signature check
564        // rejects a re-signed seal (id no longer matches its own content).
565        let mut forged = entry.clone();
566        forged.seal.pubkey = Keys::generate().public_key();
567        assert!(verify_pin_entry(&forged, &chan_hex()).is_none());
568    }
569
570    #[test]
571    fn a_proven_edit_replaces_the_words_and_a_foreign_one_is_refused() {
572        let author = Keys::generate();
573        let (entry, opened) = entry_for(&author, "teh typo");
574
575        // The author's own edit, through the real pipeline.
576        let edit_rumor = build_edit_rumor(author.public_key(), &chan(), Epoch(0), &opened.rumor_id.to_hex(), "the typo, fixed", &[], None, AT + 5_000);
577        let wrap = seal_chat_rumor(&edit_rumor, &group(), &author, WRAP_AT, false).unwrap().0;
578        let edit_opened = match open_chat_event(&wrap, &group(), &chan(), Epoch(0)).unwrap() {
579            ChatEvent::Edit { opened, .. } => opened,
580            other => panic!("expected Edit, got {other:?}"),
581        };
582
583        let refreshed = with_proven_edit(&entry, &edit_opened, &conv_bytes(), &chan_hex());
584        let v = verify_pin_entry(&refreshed, &chan_hex()).unwrap();
585        assert_eq!(v.content, "the typo, fixed", "edited words render as current");
586        assert_eq!(v.edited.as_ref().unwrap().ms, AT + 5_000);
587
588        // A STRANGER's edit of the same message: refused, entry unchanged.
589        let stranger = Keys::generate();
590        let foreign_rumor = build_edit_rumor(stranger.public_key(), &chan(), Epoch(0), &opened.rumor_id.to_hex(), "hijacked", &[], None, AT + 6_000);
591        let wrap = seal_chat_rumor(&foreign_rumor, &group(), &stranger, WRAP_AT, false).unwrap().0;
592        let foreign_opened = match open_chat_event(&wrap, &group(), &chan(), Epoch(0)).unwrap() {
593            ChatEvent::Edit { opened, .. } => opened,
594            other => panic!("expected Edit, got {other:?}"),
595        };
596        let unchanged = with_proven_edit(&entry, &foreign_opened, &conv_bytes(), &chan_hex());
597        assert!(unchanged.edit.is_none(), "a stranger's edit must not attach");
598    }
599
600    #[test]
601    fn public_list_round_trips_and_respects_caps() {
602        let author = Keys::generate();
603        let (entry, _) = entry_for(&author, "hello");
604        let content = serialize_public_pin_list(&[entry.clone()]).unwrap();
605        let read = read_pin_list(&content, |_| None);
606        assert!(!read.sealed);
607        assert_eq!(read.entries.len(), 1);
608        assert!(verify_pin_entry(&read.entries[0], &chan_hex()).is_some(), "survives the round trip");
609
610        // 26 entries: the writer refuses...
611        let many: Vec<PinEntry> = (0..26).map(|_| entry.clone()).collect();
612        assert!(serialize_public_pin_list(&many).is_err());
613        // ...and a reader treats a hand-built violating edition as EMPTY.
614        let violating = serde_json::json!({ "entries": many }).to_string();
615        assert_eq!(read_pin_list(&violating, |_| None).entries.len(), 0);
616    }
617
618    #[test]
619    fn sealed_list_is_dark_without_the_key_and_opens_with_it() {
620        let author = Keys::generate();
621        let (entry, _) = entry_for(&author, "private pin");
622        let content = serialize_sealed_pin_list(&[entry], group().conv_key(), 4).unwrap();
623
624        // No key: darkness, not violation — and NOT an empty public list.
625        let dark = read_pin_list(&content, |_| None);
626        assert!(dark.sealed);
627        assert!(dark.entries.is_empty());
628
629        // The right key at the named epoch opens it.
630        let lit = read_pin_list(&content, |epoch| (epoch == 4).then(conv_bytes));
631        assert!(!lit.sealed);
632        assert_eq!(lit.entries.len(), 1);
633        assert!(verify_pin_entry(&lit.entries[0], &chan_hex()).is_some());
634
635        // A wrong key reads as empty (decrypt fails), never as a panic.
636        let wrong = read_pin_list(&content, |_| Some([9u8; 32]));
637        assert!(wrong.entries.is_empty());
638    }
639
640    #[test]
641    fn garbage_content_reads_as_empty_never_panics() {
642        for bad in ["", "not json", "[]", "42", r#"{"entries": 7}"#, r#"{"epoch":"x","sealed":"y"}"#, r#"{"epoch":"04","sealed":"y"}"#] {
643            let read = read_pin_list(bad, |_| None);
644            assert!(read.entries.is_empty(), "{bad}");
645            assert!(!read.sealed, "{bad}");
646        }
647        // Hostile entries inside a well-formed list drop alone; a good one beside them stands.
648        let (good, _) = entry_for(&Keys::generate(), "kept");
649        let hostile = format!(r#"{{"entries":[null, 42, {{"seal": null}}, {{"keys": "zz"}}, {}]}}"#, serde_json::to_string(&good).unwrap());
650        let read = read_pin_list(&hostile, |_| None);
651        let standing: Vec<_> = read.entries.iter().filter(|e| verify_pin_entry(e, &chan_hex()).is_some()).collect();
652        assert_eq!(standing.len(), 1, "one misshapen entry never empties the list");
653    }
654
655    #[test]
656    fn deletion_matches_by_recomputed_id_and_author_only() {
657        let author = Keys::generate();
658        let (entry, opened) = entry_for(&author, "delete me later");
659        let v = verify_pin_entry(&entry, &chan_hex()).unwrap();
660        let e_tag = vec![vec!["e".to_string(), opened.rumor_id.to_hex()]];
661
662        // The author's own delete kills it.
663        assert!(pin_killed_by(&v, &author.public_key().to_hex(), &e_tag));
664        // Someone else's delete of the same id does not.
665        assert!(!pin_killed_by(&v, &Keys::generate().public_key().to_hex(), &e_tag));
666        // The author's delete of a DIFFERENT message does not.
667        let other_tag = vec![vec!["e".to_string(), "ff".repeat(32)]];
668        assert!(!pin_killed_by(&v, &author.public_key().to_hex(), &other_tag));
669    }
670
671    /// Wire-shape guarantees shared with Armada: optional fields absent when
672    /// unset, unknown fields carried through a round trip.
673    #[test]
674    fn wire_json_matches_the_reference_shape() {
675        let author = Keys::generate();
676        let (mut entry, _) = entry_for(&author, "wire check");
677        entry.wrap = None;
678        let json = serde_json::to_value(&entry).unwrap();
679        assert!(json.get("wrap").is_none(), "unset wrap must be omitted, not null");
680        assert!(json.get("edit").is_none(), "unset edit must be omitted, not null");
681
682        // An unknown field a future client added survives our round trip.
683        let mut with_extra = serde_json::to_value(&entry).unwrap();
684        with_extra["future_field"] = serde_json::json!({"x": 1});
685        let reparsed: PinEntry = serde_json::from_value(with_extra).unwrap();
686        assert_eq!(reparsed.extra.get("future_field").unwrap()["x"], 1);
687        let re_serialized = serde_json::to_value(&reparsed).unwrap();
688        assert_eq!(re_serialized["future_field"]["x"], 1, "republish must not strip it");
689        // And the entry still verifies with the stranger field aboard.
690        assert!(verify_pin_entry(&reparsed, &chan_hex()).is_some());
691    }
692
693    /// The build-refusal reasons stay distinct — the UI answers each differently.
694    #[test]
695    fn build_failures_are_distinguishable() {
696        let author = Keys::generate();
697        let opened = opened_message(&author, "reasons");
698        // A conversation key that doesn't open this message: BadPayload.
699        assert_eq!(
700            build_pin_entry(&opened, &[3u8; 32], &chan_hex()).unwrap_err(),
701            PinBuildFailure::BadPayload
702        );
703        // The right key builds fine.
704        assert!(build_pin_entry(&opened, &conv_bytes(), &chan_hex()).is_ok());
705    }
706}