Skip to main content

vector_core/community/v2/
control.rs

1//! The v2 Control Plane (CORD-04 over CORD-01/02).
2//!
3//! Editions use the `vsk/eid/ev/ep/vac` tags, the frozen `edition_hash`
4//! (`community::version`, label `vector-community/v1/edition`, which upstream froze
5//! verbatim), and the shared fold rules, riding the stream envelope: a kind-3308
6//! UNSIGNED rumor inside a **plaintext seal** (20014) at `control_pk`. Authorship is
7//! the seal's signature: [`super::stream::open_wrap`] Schnorr-verifies the seal and pins
8//! `rumor.pubkey == seal.pubkey`, so by the time an edition is parsed here its
9//! author is already proven. The plaintext seal is load-bearing: a compaction
10//! re-wraps the signed seal into a new epoch byte-verbatim, and the signature
11//! (over the rumor string) survives — an encrypted seal could not.
12//!
13//! Two deliberate wire choices:
14//!   - editions carry NO `["v","1"]` protocol tag (frozen derivations
15//!     partition protocol revisions by address; version tags are the rejected
16//!     mechanism).
17//!   - the owner is proven by the self-certifying `community_id` commitment
18//!     ([`super::derive::verify_community_id`]), not an attestation event —
19//!     vsk 7 is retired.
20
21use nostr_sdk::prelude::nip44::v2::ConversationKey;
22use nostr_sdk::prelude::{Event, Keys, PublicKey, Tag, Timestamp, UnsignedEvent};
23use serde::{Deserialize, Serialize};
24
25use super::super::edition::{AuthorityCitation, EditionError, ParsedEdition, TAG_AUTHORITY_CITATION};
26use super::super::{version, ChannelId, CommunityId, Epoch};
27use super::derive::{control_group_key, control_signer_group_key, verify_community_id, GroupKey};
28use super::stream::{self, OpenedStream, SealForm, StreamError};
29use super::{kind, vsk};
30
31const TAG_SUBKIND: &str = "vsk";
32const TAG_ENTITY: &str = "eid";
33const TAG_EVERSION: &str = "ev";
34const TAG_EPREV: &str = "ep";
35/// Marks an edition whose hash covers its signer (CORD-04 §1); the only value is "2".
36const TAG_EHASH: &str = "eh";
37/// A marked edition's Community binding (CORD-02): `community_binding(community_id)`.
38const TAG_EBIND: &str = "eb";
39
40/// Protocol-wide UTF-8 byte cap on names (community, channel, role).
41pub const MAX_NAME_BYTES: usize = 64;
42/// UTF-8 byte cap on a community description.
43pub const MAX_DESCRIPTION_BYTES: usize = 10_000;
44
45/// Errors from the control plane layer (envelope errors ride inside).
46#[derive(Debug)]
47pub enum ControlError {
48    Stream(StreamError),
49    Edition(EditionError),
50    /// The rumor isn't a kind-3308 edition.
51    NotAnEdition(u16),
52    /// A control edition arrived in an encrypted seal — CORD-02 §5 requires the
53    /// plaintext form (compaction must preserve signatures), so a strict reader
54    /// drops it rather than folding a chain a re-wrap would later fork.
55    NotPlaintextSealed,
56    /// A name/description exceeds its protocol byte cap.
57    OverCap(&'static str),
58}
59
60impl std::fmt::Display for ControlError {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            ControlError::Stream(e) => write!(f, "stream: {e}"),
64            ControlError::Edition(e) => write!(f, "edition: {e:?}"),
65            ControlError::NotAnEdition(k) => write!(f, "rumor kind {k} is not a control edition"),
66            ControlError::NotPlaintextSealed => write!(f, "control edition must ride a plaintext seal"),
67            ControlError::OverCap(what) => write!(f, "{what} exceeds its byte cap"),
68        }
69    }
70}
71
72impl std::error::Error for ControlError {}
73
74impl From<StreamError> for ControlError {
75    fn from(e: StreamError) -> Self {
76        ControlError::Stream(e)
77    }
78}
79
80// ── Identity ─────────────────────────────────────────────────────────────────
81
82/// A v2 community's self-certifying identity triple. The id IS the owner
83/// commitment — carry all three together and verify before trusting any claim.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CommunityIdentity {
86    pub community_id: CommunityId,
87    pub owner_xonly: [u8; 32],
88    pub owner_salt: [u8; 32],
89}
90
91impl CommunityIdentity {
92    /// Mint a fresh identity for `owner` (a new random salt ⇒ a new community).
93    pub fn mint(owner: &PublicKey) -> CommunityIdentity {
94        let owner_xonly = owner.to_bytes();
95        let owner_salt = super::super::random_32();
96        CommunityIdentity {
97            community_id: super::derive::community_id_of(&owner_xonly, &owner_salt),
98            owner_xonly,
99            owner_salt,
100        }
101    }
102
103    /// True iff the commitment reproduces the id — the ONLY valid owner proof.
104    pub fn verify(&self) -> bool {
105        verify_community_id(&self.community_id, &self.owner_xonly, &self.owner_salt)
106    }
107
108    /// The proven owner as a `PublicKey` (call only after [`Self::verify`]).
109    pub fn owner(&self) -> Result<PublicKey, String> {
110        PublicKey::from_slice(&self.owner_xonly).map_err(|e| e.to_string())
111    }
112}
113
114// ── Edition rumors (build + parse) ───────────────────────────────────────────
115
116/// Build the unsigned kind-3308 edition rumor (no protocol `v` tag). Control
117/// editions carry no `ms` tag: they fold by version, not time.
118#[allow(clippy::too_many_arguments)]
119pub fn build_edition_rumor(
120    author: PublicKey,
121    vsk: &str,
122    entity_id: &[u8; 32],
123    version: u64,
124    prev_hash: Option<&[u8; 32]>,
125    content: &str,
126    created_at_secs: u64,
127    authority: Option<&AuthorityCitation>,
128) -> UnsignedEvent {
129    build_edition_rumor_bound(author, vsk, entity_id, version, prev_hash, content, created_at_secs, authority, None)
130}
131
132/// [`build_edition_rumor`], marked and bound to a Community (`binding`) when one is given:
133/// what every edition of a Community on Roles v2 carries.
134#[allow(clippy::too_many_arguments)]
135pub fn build_edition_rumor_bound(
136    author: PublicKey,
137    vsk: &str,
138    entity_id: &[u8; 32],
139    version: u64,
140    prev_hash: Option<&[u8; 32]>,
141    content: &str,
142    created_at_secs: u64,
143    authority: Option<&AuthorityCitation>,
144    binding: Option<[u8; 32]>,
145) -> UnsignedEvent {
146    let mut tags = vec![
147        Tag::custom(TAG_SUBKIND, [vsk.to_string()]),
148        Tag::custom(TAG_ENTITY, [crate::simd::hex::bytes_to_hex_32(entity_id)]),
149        Tag::custom(TAG_EVERSION, [version.to_string()]),
150    ];
151    if let Some(p) = prev_hash {
152        tags.push(Tag::custom(TAG_EPREV, [crate::simd::hex::bytes_to_hex_32(p)]));
153    }
154    if let Some(a) = authority {
155        tags.push(a.to_tag());
156    }
157    if let Some(b) = binding {
158        tags.push(Tag::custom(TAG_EHASH, ["2".to_string()]));
159        tags.push(Tag::custom(TAG_EBIND, [crate::simd::hex::bytes_to_hex_32(&b)]));
160    }
161    stream::build_rumor_secs(kind::CONTROL, author, content, tags, created_at_secs)
162}
163
164/// Parse an edition from an ALREADY-VERIFIED rumor (one produced by
165/// [`stream::open_wrap`], which proved the seal signature, the author binding,
166/// and the rumor id). No signature lives on the rumor itself — never feed this
167/// a rumor that didn't come through the stream verifier.
168pub fn parse_edition_rumor(rumor: &UnsignedEvent) -> Result<ParsedEdition, ControlError> {
169    if rumor.kind.as_u16() != kind::CONTROL {
170        return Err(ControlError::NotAnEdition(rumor.kind.as_u16()));
171    }
172    // Duplicate machinery tags make signed-bytes → canonical-fields ambiguous
173    // (two clients could pick different duplicates and fork on self_hash).
174    for name in [TAG_SUBKIND, TAG_ENTITY, TAG_EVERSION, TAG_EPREV, TAG_AUTHORITY_CITATION, TAG_EHASH, TAG_EBIND] {
175        let count = rumor
176            .tags
177            .iter()
178            .filter(|t| t.as_slice().first().map(|s| s.as_str() == name).unwrap_or(false))
179            .count();
180        if count > 1 {
181            return Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")));
182        }
183    }
184    let get = |name: &str| -> Option<String> {
185        rumor.tags.iter().find_map(|t| {
186            let s = t.as_slice();
187            (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
188        })
189    };
190    let decode_hash = |hex: &str, field: &'static str| -> Result<[u8; 32], ControlError> {
191        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
192            return Err(ControlError::Edition(EditionError::BadField(field)));
193        }
194        Ok(crate::simd::hex::hex_to_bytes_32(hex))
195    };
196    let vsk = get(TAG_SUBKIND).ok_or(ControlError::Edition(EditionError::MissingField("vsk")))?;
197    let entity_id = decode_hash(&get(TAG_ENTITY).ok_or(ControlError::Edition(EditionError::MissingField("eid")))?, "eid")?;
198    // Decimal, no leading zeros (CORD-01 Encoding): `u64::from_str` accepts a leading
199    // `+`, and "007"/"7" are distinct signed rumors that fold to the same version — a
200    // same-version convergence fork a strict peer (which drops the padded form)
201    // resolves differently. Reject any non-canonical decimal, matching the `ms` rule.
202    let ev_raw = get(TAG_EVERSION).ok_or(ControlError::Edition(EditionError::MissingField("ev")))?;
203    if !crate::community::edition::is_tag_decimal(&ev_raw) {
204        return Err(ControlError::Edition(EditionError::BadField("ev")));
205    }
206    let version: u64 = ev_raw.parse().map_err(|_| ControlError::Edition(EditionError::BadField("ev")))?;
207    let prev_hash = match get(TAG_EPREV) {
208        Some(h) => Some(decode_hash(&h, "ep")?),
209        None => None,
210    };
211    // A marked edition is bound to its Community and its hash covers its signer; anything
212    // else in the marker is a form this reader doesn't know, and refused.
213    let binding = match get(TAG_EHASH) {
214        None => None,
215        Some(v) if v == "2" => Some(decode_hash(&get(TAG_EBIND).ok_or(ControlError::Edition(EditionError::MissingField("eb")))?, "eb")?),
216        Some(_) => return Err(ControlError::Edition(EditionError::BadField("eh"))),
217    };
218    let self_hash = match binding {
219        Some(_) => version::edition_hash_signed(&entity_id, version, prev_hash.as_ref(), rumor.content.as_bytes(), &rumor.pubkey.to_bytes()),
220        None => version::edition_hash(&entity_id, version, prev_hash.as_ref(), rumor.content.as_bytes()),
221    };
222    Ok(ParsedEdition {
223        author: rumor.pubkey,
224        vsk,
225        entity_id,
226        version,
227        prev_hash,
228        content: rumor.content.clone(),
229        self_hash,
230        created_at: rumor.created_at.as_secs(),
231        inner_id: rumor.id.expect("verified rumors carry their id").to_bytes(),
232        authority: AuthorityCitation::from_tags(&rumor.tags),
233        binding,
234    })
235}
236
237// ── The Control Plane view (CORD-02 §2/§5) ───────────────────────────────────
238
239/// The Control Plane as this member holds it for one epoch.
240///
241/// A SPLIT epoch (the community carries a held `control_pk`) subscribes and
242/// verifies by that address while decrypting under the community_root-derived
243/// read key; its signer is present only when this member holds the epoch's
244/// `control_root` AND it derives to the held address (staff, fail-closed on a
245/// corrupt secret). A LEGACY epoch is the `concord/control` derivation whole —
246/// address, signer, and encryption in one key every member holds.
247#[derive(Clone)]
248pub struct ControlPlane {
249    pk: PublicKey,
250    conv_key: ConversationKey,
251    signer: Option<Keys>,
252    restricted: bool,
253    /// What a marked edition here must be bound to (`None`: a bare group view, unchecked).
254    binding: Option<[u8; 32]>,
255}
256
257impl ControlPlane {
258    /// The CURRENT epoch's view of `community`'s Control Plane.
259    pub fn of(community: &super::community::CommunityV2) -> ControlPlane {
260        let read = control_group_key(&community.community_root, community.id(), community.root_epoch);
261        match community.control_pk {
262            None => ControlPlane {
263                pk: read.pk(),
264                conv_key: *read.conv_key(),
265                signer: Some(read.keys().clone()),
266                restricted: false,
267                binding: Some(super::derive::edition_binding(community.id())),
268            },
269            Some(pk) => {
270                // A held secret that does not derive to the held address is
271                // corrupt state, not a signer: fail closed to read-only rather
272                // than mint wraps at an address nobody subscribes to.
273                let signer = community.control_root.and_then(|cr| {
274                    let s = control_signer_group_key(&cr, community.id(), community.root_epoch);
275                    (s.pk() == pk).then(|| s.keys().clone())
276                });
277                ControlPlane { pk, conv_key: *read.conv_key(), signer, restricted: true, binding: Some(super::derive::edition_binding(community.id())) }
278            }
279        }
280    }
281
282    /// A whole legacy plane view from its single group key (tests, migrations).
283    pub fn legacy(group: &GroupKey) -> ControlPlane {
284        ControlPlane {
285            pk: group.pk(),
286            conv_key: *group.conv_key(),
287            signer: Some(group.keys().clone()),
288            restricted: false,
289            binding: None,
290        }
291    }
292
293    /// The plane address — what `authors` filters and wrap-author checks match.
294    pub fn pk(&self) -> PublicKey {
295        self.pk
296    }
297
298    pub fn pk_hex(&self) -> String {
299        self.pk.to_hex()
300    }
301
302    /// Whether this member can PUBLISH to the plane (CORD-02 §2).
303    pub fn can_write(&self) -> bool {
304        self.signer.is_some()
305    }
306
307    /// The signer Keys when held (NIP-42 auth as the plane, staff only on a
308    /// split epoch).
309    pub fn signer_keys(&self) -> Option<&Keys> {
310        self.signer.as_ref()
311    }
312
313    /// The WRITE group: address, signing secret, and read conv_key composed for
314    /// the seal/wrap builders. Errs when the epoch is split and this member does
315    /// not hold its `control_root` — publishing there would mint a wrap that
316    /// fails the plane's signature check at every reader and relay.
317    pub fn write_group(&self) -> Result<GroupKey, String> {
318        match &self.signer {
319            Some(keys) => Ok(GroupKey::from_parts(keys.clone(), self.conv_key)),
320            None => Err("only community staff hold this community's write key; ask an admin to re-send your promotion".to_string()),
321        }
322    }
323
324    /// Check a page's signatures together before it is opened (see
325    /// [`stream::check_signatures_together`]); hold the guard across the page's opens. A wrap
326    /// this view already opened is left out: its open needs no signature.
327    pub fn check_page(&self, wraps: &[&Event]) -> stream::BatchChecked {
328        let page: Vec<_> = {
329            let memo = opened_memo();
330            let memo = memo.lock().unwrap_or_else(|e| e.into_inner());
331            wraps.iter().filter(|w| !memo.contains(&self.opened_key(w))).map(|w| (*w, vec![&self.conv_key], self.restricted)).collect()
332        };
333        stream::check_signatures_together(&page)
334    }
335
336    /// This view, by what an open here depends on: its address, read key and restriction.
337    /// Hashed, so no key sits where it is stored.
338    pub(crate) fn view_id(&self) -> [u8; 32] {
339        let mut h = crate::crypto::sha256::Sha256::new();
340        h.update(b"concord/control-store");
341        h.update(self.pk.to_bytes());
342        h.update(self.conv_key.as_bytes());
343        h.update([self.restricted as u8]);
344        h.finalize()
345    }
346
347    /// What this view's open of `wrap` is memoized under: an open is a pure function of the
348    /// wrap, which its id and signature pin (the id leaves the signature out), and of the view's
349    /// address, read key and restriction. Hashed, so no key sits in the map.
350    fn opened_key(&self, wrap: &Event) -> [u8; 32] {
351        let mut h = crate::crypto::sha256::Sha256::new();
352        h.update(b"concord/opened-control-wrap");
353        h.update(wrap.id.as_bytes());
354        h.update(wrap.sig.as_bytes());
355        h.update(self.pk.to_bytes());
356        h.update(self.conv_key.as_bytes());
357        h.update([self.restricted as u8]);
358        h.finalize()
359    }
360
361    /// Open a control wrap under this view — [`open_control_edition`] with the
362    /// split's mandatory wrap-signature check on a restricted plane (CORD-01
363    /// Write-Restricted Streams: the signature IS the write gate there).
364    pub fn open(&self, wrap: &Event) -> Result<(ParsedEdition, OpenedStream), ControlError> {
365        let opened = self.opened(wrap)?;
366        Ok((opened.0.clone(), opened.1.clone()))
367    }
368
369    /// [`Self::open`] for a reader that needs only the edition.
370    pub fn open_edition(&self, wrap: &Event) -> Result<ParsedEdition, ControlError> {
371        Ok(self.opened(wrap)?.0.clone())
372    }
373
374    fn opened(&self, wrap: &Event) -> Result<Opened, ControlError> {
375        let memo_key = self.opened_key(wrap);
376        let memo = opened_memo();
377        let hit = memo.lock().unwrap_or_else(|e| e.into_inner()).get(&memo_key);
378        let opened = match hit {
379            Some(hit) => hit,
380            None => {
381                let opened = stream::open_wrap_at(wrap, &self.pk, &self.conv_key, self.restricted)?;
382                if opened.seal_form != SealForm::Plaintext {
383                    return Err(ControlError::NotPlaintextSealed);
384                }
385                let edition = parse_edition_rumor(&opened.rumor)?;
386                let bytes = wrap.content.len() * 2 + edition.content.len() + 512;
387                let opened = std::sync::Arc::new((edition, opened));
388                memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, opened.clone(), bytes);
389                opened
390            }
391        };
392        // A marked edition from another Community, re-wrapped here, is not this Community's.
393        if opened.0.binding.is_some_and(|b| self.binding.is_some_and(|mine| mine != b)) {
394            return Err(ControlError::Edition(EditionError::BadField("eb")));
395        }
396        Ok(opened)
397    }
398}
399
400/// Bytes per generation of the session's [`OpenedMemo`]: a follow re-reads every edition the
401/// plane serves, and a large plane runs to a few thousand of them.
402const OPENED_MEMO_BYTES: usize = 8 << 20;
403
404type Opened = std::sync::Arc<(ParsedEdition, OpenedStream)>;
405
406/// Control wraps already opened, in two generations: a full `cur` ages into `prev`, and a hit
407/// in `prev` moves back, so a working set within the bound never goes cold all at once.
408#[derive(Default)]
409struct OpenedMemo {
410    cur: std::collections::HashMap<[u8; 32], (Opened, usize)>,
411    prev: std::collections::HashMap<[u8; 32], (Opened, usize)>,
412    cur_bytes: usize,
413}
414
415impl OpenedMemo {
416    fn contains(&self, key: &[u8; 32]) -> bool {
417        self.cur.contains_key(key) || self.prev.contains_key(key)
418    }
419
420    fn get(&mut self, key: &[u8; 32]) -> Option<Opened> {
421        if let Some((hit, _)) = self.cur.get(key) {
422            return Some(hit.clone());
423        }
424        let (hit, bytes) = self.prev.remove(key)?;
425        self.insert(*key, hit.clone(), bytes);
426        Some(hit)
427    }
428
429    fn insert(&mut self, key: [u8; 32], value: Opened, bytes: usize) {
430        if self.cur_bytes + bytes > OPENED_MEMO_BYTES && !self.cur.is_empty() {
431            self.prev = std::mem::take(&mut self.cur);
432            self.cur_bytes = 0;
433        }
434        if self.cur.insert(key, (value, bytes)).is_none() {
435            self.cur_bytes += bytes;
436        }
437    }
438}
439
440/// The session's [`OpenedMemo`]: an account's opened editions go with its session.
441fn opened_memo() -> std::sync::Arc<std::sync::Mutex<OpenedMemo>> {
442    struct Key;
443    crate::db::current_session().scoped::<Key, std::sync::Mutex<OpenedMemo>>()
444}
445
446/// Empty this session's [`OpenedMemo`], so the next opens run whole.
447#[cfg(any(test, feature = "bench"))]
448pub(crate) fn forget_opened() {
449    *opened_memo().lock().unwrap() = OpenedMemo::default();
450}
451
452/// Whether this session holds `view`'s open of `wrap`.
453#[cfg(test)]
454pub(crate) fn opened_held(view: &ControlPlane, wrap: &Event) -> bool {
455    opened_memo().lock().unwrap().contains(&view.opened_key(wrap))
456}
457
458impl std::fmt::Debug for ControlPlane {
459    // No key material in logs — address only.
460    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
461        f.debug_struct("ControlPlane")
462            .field("pk", &self.pk_hex())
463            .field("restricted", &self.restricted)
464            .field("writable", &self.can_write())
465            .finish()
466    }
467}
468
469/// The SPLIT write group for a freshly minted epoch (genesis / a Refounding's
470/// new plane): the `control_root`-derived signer with the `community_root`-
471/// derived read key (CORD-02 §5).
472pub fn split_write_group(control_root: &[u8; 32], community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
473    let signer = control_signer_group_key(control_root, community_id, epoch);
474    let read = control_group_key(community_root, community_id, epoch);
475    GroupKey::from_parts(signer.keys().clone(), *read.conv_key())
476}
477
478// ── Seal / open over the stream ──────────────────────────────────────────────
479
480/// Seal a signed-by-`author_keys` edition rumor into a control-plane wrap.
481/// Local-keys convenience; bunker accounts use [`stream::seal_content`] +
482/// their remote signer + [`stream::wrap_seal`] for identical wire output.
483pub fn seal_control_edition(
484    rumor: &UnsignedEvent,
485    group: &GroupKey,
486    author_keys: &Keys,
487    wrap_at: Timestamp,
488) -> Result<(Event, Keys), ControlError> {
489    let seal = stream::build_seal(rumor, SealForm::Plaintext, group, author_keys)?;
490    Ok(stream::wrap_seal(&seal, group, stream::KIND_WRAP, wrap_at)?)
491}
492
493/// Signer-driven twin of [`seal_control_edition`] for bunker / NIP-55 accounts:
494/// the plaintext seal signs through a [`VectorSigner`](crate::signer::VectorSigner). `author` is the identity
495/// the signer signs as (must equal `my_public_key()`). Wire-identical output.
496pub async fn seal_control_edition_signed<S: crate::signer::VectorSigner + ?Sized>(
497    signer: &S,
498    author: PublicKey,
499    rumor: &UnsignedEvent,
500    group: &GroupKey,
501    wrap_at: Timestamp,
502) -> Result<(Event, Keys), ControlError> {
503    Ok(stream::seal_and_wrap_signed(signer, author, rumor, SealForm::Plaintext, group, stream::KIND_WRAP, wrap_at, &[]).await?)
504}
505
506/// Open a control-plane wrap into a verified, parsed edition. Strict on both
507/// gates: the rumor must be kind 3308, and the seal must be the plaintext form.
508pub fn open_control_edition(wrap: &Event, group: &GroupKey) -> Result<(ParsedEdition, OpenedStream), ControlError> {
509    let opened = stream::open_wrap(wrap, group)?;
510    if opened.seal_form != SealForm::Plaintext {
511        return Err(ControlError::NotPlaintextSealed);
512    }
513    let edition = parse_edition_rumor(&opened.rumor)?;
514    Ok((edition, opened))
515}
516
517// ── Entity payloads (vsk 0 / vsk 2) ──────────────────────────────────────────
518
519/// An encrypted-blob image pointer (icon/banner): the media server sees only an
520/// opaque blob; members fetch, decrypt with `key`/`nonce`, and verify `hash`.
521#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
522pub struct ImageRef {
523    pub url: String,
524    pub key: String,
525    pub nonce: String,
526    pub hash: String,
527    /// Unknown fields round-trip (e.g. Vector's `ext`) — editors MUST preserve
528    /// what they don't understand (CORD-02 §6).
529    #[serde(flatten)]
530    pub extra: serde_json::Map<String, serde_json::Value>,
531}
532
533impl ImageRef {
534    /// Convert to the [`CommunityImage`](crate::community::CommunityImage) shape the
535    /// shared download/decrypt/cache plumbing takes. `ext` rides the flattened
536    /// extras; fall back to the URL's extension, else png.
537    pub fn to_community_image(&self) -> crate::community::CommunityImage {
538        let ext = self
539            .extra
540            .get("ext")
541            .and_then(|v| v.as_str())
542            .filter(|s| !s.is_empty())
543            .map(str::to_string)
544            .or_else(|| {
545                std::path::Path::new(&self.url)
546                    .extension()
547                    .and_then(|e| e.to_str())
548                    .map(|s| s.to_lowercase())
549            })
550            .unwrap_or_else(|| "png".to_string());
551        crate::community::CommunityImage {
552            url: self.url.clone(),
553            key: self.key.clone(),
554            nonce: self.nonce.clone(),
555            hash: self.hash.clone(),
556            ext,
557        }
558    }
559}
560
561/// Community metadata — the vsk-0 entity content (CORD-02 §6). `eid` = the
562/// community_id itself; gated by `MANAGE_METADATA`.
563#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
564pub struct CommunityMetadata {
565    pub name: String,
566    #[serde(skip_serializing_if = "Option::is_none")]
567    pub description: Option<String>,
568    #[serde(default, skip_serializing_if = "Vec::is_empty")]
569    pub relays: Vec<String>,
570    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::community::lenient_image")]
571    pub icon: Option<ImageRef>,
572    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::community::lenient_image")]
573    pub banner: Option<ImageRef>,
574    /// Client-extensible opaque object; folds atomically with the entity.
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
577    /// Reserved-for-protocol unknown top-level fields, round-tripped verbatim.
578    #[serde(flatten)]
579    pub extra: serde_json::Map<String, serde_json::Value>,
580}
581
582/// Channel metadata — the vsk-2 entity content (CORD-03 §2). `eid` = the
583/// channel_id; gated by `MANAGE_CHANNELS`. Absent flags mean false; deletion is
584/// terminal.
585#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
586pub struct ChannelMetadata {
587    pub name: String,
588    pub private: bool,
589    #[serde(skip_serializing_if = "Option::is_none")]
590    pub voice: Option<bool>,
591    #[serde(skip_serializing_if = "Option::is_none")]
592    pub deleted: Option<bool>,
593    #[serde(skip_serializing_if = "Option::is_none")]
594    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
595    #[serde(flatten)]
596    pub extra: serde_json::Map<String, serde_json::Value>,
597}
598
599/// A Private Channel's sealed metadata edition (CORD-03 §2): what every member needs to resolve
600/// access stays plain; the rest is sealed under the Channel's key at `epoch`.
601#[derive(Debug, Clone, PartialEq, Eq)]
602pub struct SealedChannelMeta {
603    pub epoch: u64,
604    pub sealed: String,
605    pub deleted: bool,
606}
607
608/// The sealed form of a channel edition, `None` for the plain form or a malformed one.
609pub fn parse_sealed_channel_meta(content: &str) -> Option<SealedChannelMeta> {
610    let serde_json::Value::Object(o) = serde_json::from_str(content).ok()? else { return None };
611    let sealed = o.get("sealed")?.as_str()?.to_string();
612    let epoch = o.get("epoch")?.as_str()?;
613    let canonical = !epoch.is_empty() && epoch.bytes().all(|b| b.is_ascii_digit()) && (epoch == "0" || !epoch.starts_with('0'));
614    if !o.get("private")?.as_bool()? || !canonical {
615        return None;
616    }
617    Some(SealedChannelMeta { epoch: epoch.parse().ok()?, sealed, deleted: o.get("deleted").and_then(|d| d.as_bool()).unwrap_or(false) })
618}
619
620/// Seal a Private Channel's metadata under its conversation key at `epoch`, naming the edition's
621/// predecessor so the seal can't be replayed as a newer edition.
622pub fn seal_channel_metadata(meta: &ChannelMetadata, conv_key: &ConversationKey, epoch: u64, prev: Option<&[u8; 32]>) -> Result<String, String> {
623    validate_channel_metadata(meta).map_err(|e| e.to_string())?;
624    let serde_json::Value::Object(mut inner) = serde_json::to_value(meta).map_err(|e| e.to_string())? else {
625        return Err("channel metadata isn't an object".to_string());
626    };
627    inner.remove("private");
628    inner.remove("deleted");
629    inner.insert(SEALED_PREV.into(), prev.map(crate::simd::hex::bytes_to_hex_32).into());
630    let raw = crate::community::cipher::encrypt_with_random_nonce(conv_key, serde_json::Value::Object(inner).to_string().as_bytes())?;
631    let mut out = serde_json::json!({ "private": true, "epoch": epoch.to_string(), "sealed": crate::simd::base64::STANDARD.encode_to_string(&raw) });
632    if meta.deleted == Some(true) {
633        out["deleted"] = true.into();
634    }
635    Ok(out.to_string())
636}
637
638/// What a seal names as its edition's predecessor.
639const SEALED_PREV: &str = "prev";
640
641/// Open sealed channel metadata with the conversation key of its epoch. `prev` is the carrying
642/// edition's predecessor, which the seal must name; a deletion carries an older seal verbatim
643/// and is exempt.
644pub fn open_sealed_channel_meta(s: &SealedChannelMeta, conv_key: &[u8; 32], prev: Option<&[u8; 32]>) -> Option<ChannelMetadata> {
645    let conv = ConversationKey::from_slice(conv_key).ok()?;
646    let raw = crate::simd::base64::STANDARD.decode_to_vec(s.sealed.as_bytes()).ok()?;
647    let inner = crate::crypto::nip44::decrypt(&conv, raw).ok()?;
648    let serde_json::Value::Object(mut o) = serde_json::from_slice(&inner).ok()? else { return None };
649    let named = o.remove(SEALED_PREV).and_then(|v| v.as_str().and_then(crate::simd::hex::hex_to_bytes_32_checked));
650    if !s.deleted && named.as_ref() != prev {
651        return None;
652    }
653    o.insert("private".into(), true.into());
654    o.remove("deleted");
655    let mut meta: ChannelMetadata = serde_json::from_value(serde_json::Value::Object(o)).ok()?;
656    meta.deleted = s.deleted.then_some(true);
657    Some(meta)
658}
659
660/// A sealed edition's content republished verbatim beside `"deleted": true`: deleting a Private
661/// Channel takes only the bit, never the key.
662pub fn sealed_tombstone(content: &str) -> Option<String> {
663    let serde_json::Value::Object(mut o) = serde_json::from_str(content).ok()? else { return None };
664    o.insert("deleted".into(), true.into());
665    Some(serde_json::Value::Object(o).to_string())
666}
667
668/// `meta` with whatever breaks the protocol caps dropped, the name cut to fit: what folds is
669/// shown, and what a writer re-seals must validate.
670pub fn sanitize_channel_metadata(mut meta: ChannelMetadata) -> ChannelMetadata {
671    cut_name(&mut meta.name);
672    let text = |m: &ChannelMetadata, k: &str| m.extra.get(k).map(|v| v.as_str().map(str::to_string));
673    if text(&meta, "topic").is_some_and(|t| t.is_none_or(|t| t.is_empty() || t.len() > MAX_TOPIC_BYTES)) {
674        meta.extra.remove("topic");
675    }
676    if text(&meta, "position").is_some_and(|k| k.is_none_or(|k| !crate::community::rank::is_rank_key(&k))) {
677        meta.extra.remove("position");
678    }
679    if text(&meta, "category").is_some_and(|c| c.is_none_or(|c| crate::simd::hex::hex_to_bytes_32_checked(&c).is_none())) {
680        meta.extra.remove("category");
681    }
682    meta
683}
684
685/// Enforce the protocol byte caps before an edition is built (a strict reader
686/// may drop over-cap state; never publish what peers would refuse).
687pub fn validate_community_metadata(meta: &CommunityMetadata) -> Result<(), ControlError> {
688    if meta.name.len() > MAX_NAME_BYTES {
689        return Err(ControlError::OverCap("name"));
690    }
691    if meta.description.as_ref().is_some_and(|d| d.len() > MAX_DESCRIPTION_BYTES) {
692        return Err(ControlError::OverCap("description"));
693    }
694    Ok(())
695}
696
697pub fn validate_channel_metadata(meta: &ChannelMetadata) -> Result<(), ControlError> {
698    if meta.name.len() > MAX_NAME_BYTES {
699        return Err(ControlError::OverCap("name"));
700    }
701    let text = |k: &str| meta.extra.get(k).and_then(|v| v.as_str());
702    if text("topic").is_some_and(|t| t.len() > MAX_TOPIC_BYTES) {
703        return Err(ControlError::OverCap("topic"));
704    }
705    if text("position").is_some_and(|k| !crate::community::rank::is_rank_key(k)) {
706        return Err(ControlError::OverCap("position"));
707    }
708    if text("category").is_some_and(|c| crate::simd::hex::hex_to_bytes_32_checked(c).is_none()) {
709        return Err(ControlError::OverCap("category"));
710    }
711    Ok(())
712}
713
714/// A name past the 64-byte cap, cut to the last whole character within it: what a reader shows.
715pub fn cut_name(name: &mut String) {
716    if name.len() > MAX_NAME_BYTES {
717        let mut end = MAX_NAME_BYTES;
718        while !name.is_char_boundary(end) {
719            end -= 1;
720        }
721        name.truncate(end);
722    }
723}
724
725/// An optional string field of another type reads as absent, never sinking the edition.
726fn lenient_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
727    Ok(match serde_json::Value::deserialize(d)? {
728        serde_json::Value::String(s) => Some(s),
729        _ => None,
730    })
731}
732
733fn lenient_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
734    lenient_string(d).map(Option::unwrap_or_default)
735}
736
737/// A Channel's topic cap (CORD-03 §2).
738pub const MAX_TOPIC_BYTES: usize = 1024;
739
740/// A Category (vsk 15, CORD-03 §4), `eid == category_id`, gated by `MANAGE_CHANNELS`.
741/// Deletion is terminal.
742#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
743pub struct CategoryMetadata {
744    #[serde(default, skip_serializing_if = "String::is_empty", deserialize_with = "lenient_name")]
745    pub name: String,
746    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "lenient_string")]
747    pub position: Option<String>,
748    #[serde(default, skip_serializing_if = "Option::is_none")]
749    pub deleted: Option<bool>,
750    #[serde(flatten)]
751    pub extra: serde_json::Map<String, serde_json::Value>,
752}
753
754pub fn validate_category_metadata(meta: &CategoryMetadata) -> Result<(), ControlError> {
755    if meta.name.len() > MAX_NAME_BYTES {
756        return Err(ControlError::OverCap("name"));
757    }
758    if meta.position.as_deref().is_some_and(|k| !crate::community::rank::is_rank_key(k)) {
759        return Err(ControlError::OverCap("position"));
760    }
761    Ok(())
762}
763
764// ── Genesis (CORD-02 §1) ─────────────────────────────────────────────────────
765
766/// The two wraps of a community genesis — exactly two owner-signed editions:
767/// the community metadata (vsk 0) and one public `#general` channel (vsk 2).
768/// Nothing more — no default roles, no scaffolding.
769pub struct Genesis {
770    pub identity: CommunityIdentity,
771    /// The community_root minted for epoch 0.
772    pub community_root: [u8; 32],
773    /// The staff write key minted beside it (CORD-02 §2) — held by the owner
774    /// alone until staff are promoted. Its derived pk is the plane's address.
775    pub control_root: [u8; 32],
776    pub general_channel_id: ChannelId,
777    /// `[metadata wrap, #general wrap]`, both sealed at the epoch-0 control_pk.
778    pub wraps: [Event; 2],
779}
780
781impl Genesis {
782    /// The epoch-0 Control Plane address the split minted (CORD-02 §5).
783    pub fn control_pk(&self) -> PublicKey {
784        control_signer_group_key(&self.control_root, &self.identity.community_id, Epoch(0)).pk()
785    }
786}
787
788/// Mint a v2 community: fresh identity (salt-committed to the owner), fresh
789/// community_root + control_root (the split, CORD-02 §2), and the two genesis
790/// editions sealed at the epoch-0 control plane — signed by the control_root-
791/// derived signer, readable under the community_root-derived read key. The
792/// caller persists the secrets and publishes the wraps.
793pub fn genesis(owner_keys: &Keys, mut metadata: CommunityMetadata, at_secs: u64) -> Result<Genesis, ControlError> {
794    validate_community_metadata(&metadata)?;
795    // Relays ride the metadata entity so they can evolve by edit; cap on write.
796    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);
797
798    let identity = CommunityIdentity::mint(&owner_keys.public_key());
799    let community_root = super::super::random_32();
800    let control_root = super::super::random_32();
801    let general_channel_id = ChannelId(super::super::random_32());
802    let group = split_write_group(&control_root, &community_root, &identity.community_id, Epoch(0));
803
804    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
805    let meta_rumor = build_edition_rumor(
806        owner_keys.public_key(),
807        vsk::COMMUNITY_METADATA,
808        &identity.community_id.0,
809        1,
810        None,
811        &meta_json,
812        at_secs,
813        None,
814    );
815
816    let general = ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
817    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
818    let general_rumor = build_edition_rumor(
819        owner_keys.public_key(),
820        vsk::CHANNEL_METADATA,
821        &general_channel_id.0,
822        1,
823        None,
824        &general_json,
825        at_secs,
826        None,
827    );
828
829    let (meta_wrap, _) = seal_control_edition(&meta_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
830    let (general_wrap, _) = seal_control_edition(&general_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
831
832    Ok(Genesis {
833        identity,
834        community_root,
835        control_root,
836        general_channel_id,
837        wraps: [meta_wrap, general_wrap],
838    })
839}
840
841/// Signer-driven twin of [`genesis`] for bunker / NIP-55 accounts: mints from the
842/// owner's public key and seals the two genesis editions through a [`VectorSigner`](crate::signer::VectorSigner).
843/// `owner_pk` must equal `my_public_key()` (the identity the signer signs as).
844pub async fn genesis_signed<S: crate::signer::VectorSigner + ?Sized>(
845    owner_pk: PublicKey,
846    signer: &S,
847    mut metadata: CommunityMetadata,
848    at_secs: u64,
849) -> Result<Genesis, ControlError> {
850    validate_community_metadata(&metadata)?;
851    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);
852
853    let identity = CommunityIdentity::mint(&owner_pk);
854    let community_root = super::super::random_32();
855    let control_root = super::super::random_32();
856    let (general_channel_id, general_name) = (ChannelId(super::super::random_32()), "general".to_string());
857    let group = split_write_group(&control_root, &community_root, &identity.community_id, Epoch(0));
858
859    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
860    let meta_rumor = build_edition_rumor(owner_pk, vsk::COMMUNITY_METADATA, &identity.community_id.0, 1, None, &meta_json, at_secs, None);
861
862    let general = ChannelMetadata { name: general_name, private: false, ..Default::default() };
863    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
864    let general_rumor = build_edition_rumor(owner_pk, vsk::CHANNEL_METADATA, &general_channel_id.0, 1, None, &general_json, at_secs, None);
865
866    let (meta_wrap, _) = seal_control_edition_signed(signer, owner_pk, &meta_rumor, &group, Timestamp::from_secs(at_secs)).await?;
867    let (general_wrap, _) = seal_control_edition_signed(signer, owner_pk, &general_rumor, &group, Timestamp::from_secs(at_secs)).await?;
868
869    Ok(Genesis {
870        identity,
871        community_root,
872        control_root,
873        general_channel_id,
874        wraps: [meta_wrap, general_wrap],
875    })
876}
877
878#[cfg(test)]
879mod tests {
880    fn shown(r: Result<(ParsedEdition, OpenedStream), ControlError>) -> String {
881        format!("{r:?}")
882    }
883
884    #[test]
885    fn an_open_served_from_the_memo_is_exactly_a_fresh_open() {
886        let owner = Keys::generate();
887        let g = genesis(&owner, CommunityMetadata { name: "Memo".into(), ..Default::default() }, 1_000).unwrap();
888        let held = super::super::community::CommunityV2::from_genesis(&g, "Memo", None, vec![], 0);
889        let view = ControlPlane::of(&held);
890        assert!(!g.wraps.is_empty());
891        for wrap in &g.wraps {
892            forget_opened();
893            let fresh = shown(view.open(wrap));
894            assert!(fresh.starts_with("Ok"), "{fresh}");
895            assert!(opened_held(&view, wrap), "the open is kept");
896            assert_eq!(shown(view.open(wrap)), fresh, "and served again as it was");
897            assert_eq!(format!("{:?}", view.open_edition(wrap)), format!("{:?}", view.open(wrap).map(|(e, _)| e)));
898        }
899    }
900
901    #[test]
902    fn the_memo_serves_no_view_what_its_own_open_would_refuse() {
903        let owner = Keys::generate();
904        let g = genesis(&owner, CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
905        let other = genesis(&owner, CommunityMetadata { name: "B".into(), ..Default::default() }, 1_000).unwrap();
906        let a = super::super::community::CommunityV2::from_genesis(&g, "A", None, vec![], 0);
907        let b = super::super::community::CommunityV2::from_genesis(&other, "B", None, vec![], 0);
908        forget_opened();
909        assert!(ControlPlane::of(&a).open(&g.wraps[0]).is_ok());
910        assert!(ControlPlane::of(&b).open(&g.wraps[0]).is_err(), "another Community's view opens nothing of A's");
911
912        // A bare group view checks no binding; this Community's view still does, cached or not.
913        let mut legacy = a.clone();
914        legacy.control_pk = None;
915        let group = control_group_key(&legacy.community_root, legacy.id(), legacy.root_epoch);
916        let elsewhere = super::super::derive::edition_binding(&CommunityId([0x42; 32]));
917        let rumor = build_edition_rumor_bound(owner.public_key(), vsk::ROLE_V2, &[0x51; 32], 1, None, "{}", 1_000, None, Some(elsewhere));
918        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
919        assert!(ControlPlane::legacy(&group).open(&wrap).is_ok());
920        assert!(opened_held(&ControlPlane::of(&legacy), &wrap), "the same address and key: one memo entry");
921        assert!(
922            matches!(ControlPlane::of(&legacy).open(&wrap), Err(ControlError::Edition(EditionError::BadField("eb")))),
923            "an edition bound to another Community is refused whoever filled the memo"
924        );
925    }
926
927    #[test]
928    fn the_open_memo_ages_a_generation_at_a_time() {
929        let owner = Keys::generate();
930        let g = genesis(&owner, CommunityMetadata { name: "Ages".into(), ..Default::default() }, 1_000).unwrap();
931        let held = super::super::community::CommunityV2::from_genesis(&g, "Ages", None, vec![], 0);
932        let value: Opened = std::sync::Arc::new(ControlPlane::of(&held).open(&g.wraps[0]).unwrap());
933        let half = OPENED_MEMO_BYTES / 2 + 1;
934        let mut memo = OpenedMemo::default();
935        memo.insert([1; 32], value.clone(), half);
936        memo.insert([2; 32], value.clone(), half);
937        assert!(memo.prev.contains_key(&[1; 32]) && memo.cur.contains_key(&[2; 32]), "a full generation ages into the previous one");
938        assert!(memo.get(&[1; 32]).is_some() && memo.cur.contains_key(&[1; 32]), "and a hit there moves back");
939        memo.insert([3; 32], value.clone(), half);
940        memo.insert([4; 32], value.clone(), half);
941        assert!(!memo.contains(&[2; 32]), "two generations on, what nothing touched is gone");
942        assert!(memo.contains(&[4; 32]));
943        let big = OPENED_MEMO_BYTES * 2;
944        memo.insert([5; 32], value, big);
945        assert!(memo.cur.contains_key(&[5; 32]), "one larger than a generation still keeps a generation of its own");
946    }
947
948    #[test]
949    fn sealed_channel_metadata_round_trips_and_hides_everything_but_access() {
950        let mut meta = ChannelMetadata { name: "war room".into(), private: true, voice: None, deleted: None, custom: Some(serde_json::Map::from_iter([("x".to_string(), 1.into())])), extra: Default::default() };
951        meta.extra.insert("topic".into(), "plans".into());
952        meta.extra.insert("category".into(), "11".repeat(32).into());
953        let key = [7u8; 32];
954        let conv = ConversationKey::from_slice(&key).unwrap();
955        let prev = [0x0f; 32];
956        let content = seal_channel_metadata(&meta, &conv, 4, Some(&prev)).unwrap();
957        for leak in ["war room", "plans", &"11".repeat(32)] {
958            assert!(!content.contains(leak), "{leak} must not show");
959        }
960        let s = parse_sealed_channel_meta(&content).unwrap();
961        assert_eq!((s.epoch, s.deleted), (4, false));
962        assert_eq!(open_sealed_channel_meta(&s, &key, Some(&prev)), Some(meta.clone()));
963        assert_eq!(open_sealed_channel_meta(&s, &[8u8; 32], Some(&prev)), None, "another epoch's key opens nothing");
964        assert_eq!(open_sealed_channel_meta(&s, &key, Some(&[0x10; 32])), None, "nor does a seal replayed under another predecessor");
965        assert_eq!(open_sealed_channel_meta(&s, &key, None), None);
966        let gone = parse_sealed_channel_meta(&sealed_tombstone(&content).unwrap()).unwrap();
967        assert_eq!((gone.sealed.as_str(), gone.deleted), (s.sealed.as_str(), true), "the tombstone carries the seal verbatim");
968        assert_eq!(open_sealed_channel_meta(&gone, &key, Some(&[0x11; 32])).unwrap().deleted, Some(true), "a deletion carries an older seal");
969        assert!(parse_sealed_channel_meta(r#"{"name":"general","private":false}"#).is_none());
970        assert!(parse_sealed_channel_meta(&content.replace("\"epoch\":\"4\"", "\"epoch\":\"04\"")).is_none(), "a non-canonical epoch");
971        assert!(parse_sealed_channel_meta(&content.replace("\"epoch\":\"4\"", "\"epoch\":\"+4\"")).is_none());
972        let mut wild = meta.clone();
973        wild.name = "é".repeat(MAX_NAME_BYTES);
974        wild.extra.insert("position".into(), "!!".into());
975        wild.extra.insert("topic".into(), "x".repeat(MAX_TOPIC_BYTES + 1).into());
976        let tame = sanitize_channel_metadata(wild);
977        assert!(validate_channel_metadata(&tame).is_ok() && tame.extra.get("position").is_none() && tame.extra.get("topic").is_none() && tame.extra.get("category").is_some());
978        assert!(parse_sealed_channel_meta(&content.replace("\"private\":true", "\"private\":false")).is_none());
979    }
980
981    use nostr_sdk::prelude::FinalizeEvent;
982    use super::super::super::edition::build_edition_inner;
983    use super::*;
984
985    fn cid() -> CommunityId {
986        CommunityId([0x33; 32])
987    }
988
989    #[test]
990    fn a_malformed_image_drops_alone() {
991        let doc = r#"{"name":"Club","description":"hi","icon":{"url":"u","key":"k","nonce":"n","hash":"h"},"banner":{"url":"only"}}"#;
992        let meta: CommunityMetadata = serde_json::from_str(doc).unwrap();
993        assert_eq!(meta.name, "Club");
994        assert_eq!(meta.description.as_deref(), Some("hi"));
995        assert_eq!(meta.icon.as_ref().map(|i| i.url.as_str()), Some("u"));
996        assert!(meta.banner.is_none());
997
998        let meta: CommunityMetadata = serde_json::from_str(r#"{"name":"Club","banner":"not an object"}"#).unwrap();
999        assert!(meta.banner.is_none() && meta.icon.is_none());
1000    }
1001
1002    #[test]
1003    fn an_image_round_trips_with_its_extras() {
1004        let doc = r#"{"name":"Club","banner":{"url":"u","key":"k","nonce":"n","hash":"h","ext":"webp"}}"#;
1005        let meta: CommunityMetadata = serde_json::from_str(doc).unwrap();
1006        let again: CommunityMetadata = serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap();
1007        assert_eq!(again, meta);
1008        assert_eq!(meta.banner.unwrap().to_community_image().ext, "webp");
1009    }
1010
1011    fn group_at(epoch: u64) -> GroupKey {
1012        control_group_key(&[0x44; 32], &cid(), Epoch(epoch))
1013    }
1014
1015    fn simple_edition(author: &Keys, version: u64, prev: Option<&[u8; 32]>) -> UnsignedEvent {
1016        build_edition_rumor(
1017            author.public_key(),
1018            vsk::GRANT,
1019            &[0x55; 32],
1020            version,
1021            prev,
1022            "{\"member\":\"aa\",\"role_ids\":[]}",
1023            1_700_000_000,
1024            None,
1025        )
1026    }
1027
1028    #[test]
1029    fn edition_round_trips_through_the_control_plane() {
1030        let owner = Keys::generate();
1031        let group = group_at(0);
1032        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
1033        let rumor = build_edition_rumor(
1034            owner.public_key(),
1035            vsk::GRANT,
1036            &[0x55; 32],
1037            2,
1038            Some(&[0x66; 32]),
1039            "{\"member\":\"aa\",\"role_ids\":[]}",
1040            1_700_000_000,
1041            Some(&cite),
1042        );
1043        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_700_000_001)).unwrap();
1044
1045        let (edition, opened) = open_control_edition(&wrap, &group).unwrap();
1046        assert_eq!(edition.author, owner.public_key());
1047        assert_eq!(edition.vsk, vsk::GRANT);
1048        assert_eq!(edition.entity_id, [0x55; 32]);
1049        assert_eq!(edition.version, 2);
1050        assert_eq!(edition.prev_hash, Some([0x66; 32]));
1051        assert_eq!(edition.authority.as_ref(), Some(&cite));
1052        assert_eq!(opened.seal_form, SealForm::Plaintext);
1053        // self_hash matches the canonical recomputation.
1054        assert_eq!(
1055            edition.self_hash,
1056            version::edition_hash(&[0x55; 32], 2, Some(&[0x66; 32]), rumor.content.as_bytes())
1057        );
1058    }
1059
1060    #[test]
1061    fn v2_edition_tags_carry_no_protocol_version_tag() {
1062        // FROZEN: the v2 tag set is exactly vsk/eid/ev(+ep/vac) — a `v` tag is
1063        // the rejected versioning mechanism (address partitioning does the job).
1064        let owner = Keys::generate();
1065        let rumor = simple_edition(&owner, 1, None);
1066        assert!(
1067            !rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "v").unwrap_or(false)),
1068            "v2 editions must not carry a protocol version tag"
1069        );
1070        // And no ms tag — editions fold by version, not time.
1071        assert!(!rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "ms").unwrap_or(false)));
1072    }
1073
1074    #[test]
1075    fn edition_hash_is_identical_across_protocols() {
1076        // The edition hash is frozen (byte layout and label). The same logical
1077        // edition must hash identically whether built as a signed inner or a rumor.
1078        let author = Keys::generate();
1079        let entity = [0x55; 32];
1080        let content = "{\"member\":\"aa\",\"role_ids\":[]}";
1081        let v1_inner = build_edition_inner(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None)
1082            .finalize(&author)
1083            .unwrap();
1084        let v1_parsed = super::super::super::edition::parse_edition_inner(&v1_inner).unwrap();
1085
1086        let v2_rumor = build_edition_rumor(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None);
1087        let v2_parsed = parse_edition_rumor(&v2_rumor).unwrap();
1088
1089        assert_eq!(v1_parsed.self_hash, v2_parsed.self_hash);
1090    }
1091
1092    #[test]
1093    fn encrypted_seal_control_edition_is_rejected() {
1094        let owner = Keys::generate();
1095        let group = group_at(0);
1096        let rumor = simple_edition(&owner, 1, None);
1097        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &owner).unwrap();
1098        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1099        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotPlaintextSealed)));
1100    }
1101
1102    #[test]
1103    fn non_edition_rumor_is_rejected() {
1104        let owner = Keys::generate();
1105        let group = group_at(0);
1106        let rumor = stream::build_rumor_secs(super::kind::MESSAGE, owner.public_key(), "hi", vec![], 100);
1107        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &owner).unwrap();
1108        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1109        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotAnEdition(k)) if k == super::kind::MESSAGE));
1110    }
1111
1112    #[test]
1113    fn duplicate_machinery_tags_are_rejected() {
1114        let owner = Keys::generate();
1115        let mut rumor = simple_edition(&owner, 1, None);
1116        let dup = Tag::custom("eid", [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]);
1117        let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
1118        tags.push(dup);
1119        rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), &rumor.content, tags, 100);
1120        assert!(matches!(
1121            parse_edition_rumor(&rumor),
1122            Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")))
1123        ));
1124    }
1125
1126    #[test]
1127    fn a_non_canonical_ev_version_is_rejected() {
1128        let owner = Keys::generate();
1129        // A leading-zero (or `+`-prefixed) version is a distinct rumor that folds to
1130        // the same numeric version — a same-version fork a strict peer drops.
1131        for bad in ["007", "+5", "01"] {
1132            let tags = vec![
1133                Tag::custom("vsk", [vsk::GRANT]),
1134                Tag::custom("eid", [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]),
1135                Tag::custom("ev", [bad]),
1136            ];
1137            let rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), "{\"member\":\"aa\",\"role_ids\":[]}", tags, 100);
1138            assert!(
1139                matches!(parse_edition_rumor(&rumor), Err(ControlError::Edition(EditionError::BadField("ev")))),
1140                "a non-canonical ev {bad:?} is rejected"
1141            );
1142        }
1143    }
1144
1145    #[test]
1146    fn compaction_rewrap_preserves_the_edition_chain_identity() {
1147        // The whole reason control seals are plaintext: carry a signed head into
1148        // a new epoch and its self_hash + authorship must be untouched, so a
1149        // fresh joiner folds the same chain the old epoch held.
1150        let owner = Keys::generate();
1151        let e0 = group_at(0);
1152        let rumor = simple_edition(&owner, 3, Some(&[0x77; 32]));
1153        let (wrap, _) = seal_control_edition(&rumor, &e0, &owner, Timestamp::from_secs(10)).unwrap();
1154        let (edition, opened) = open_control_edition(&wrap, &e0).unwrap();
1155
1156        let e1 = group_at(1);
1157        let (rewrapped, _) = stream::rewrap_seal(&opened.seal, &e1, Timestamp::from_secs(20)).unwrap();
1158        let (re_edition, _) = open_control_edition(&rewrapped, &e1).unwrap();
1159
1160        assert_eq!(re_edition.self_hash, edition.self_hash);
1161        assert_eq!(re_edition.author, edition.author);
1162        assert_eq!(re_edition.inner_id, edition.inner_id, "rumor id survives compaction");
1163    }
1164
1165    #[test]
1166    fn editions_opened_from_wraps_fold_to_the_head() {
1167        let owner = Keys::generate();
1168        let group = group_at(0);
1169        let entity = [0x55; 32];
1170        let content = |v: u64| format!("{{\"v\":{v}}}");
1171
1172        // Build a 3-link chain v1 → v2 → v3.
1173        let mut prev: Option<[u8; 32]> = None;
1174        let mut parsed = Vec::new();
1175        for v in 1..=3u64 {
1176            let rumor = build_edition_rumor(owner.public_key(), vsk::GRANT, &entity, v, prev.as_ref(), &content(v), 100 + v, None);
1177            let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(100 + v)).unwrap();
1178            let (edition, _) = open_control_edition(&wrap, &group).unwrap();
1179            prev = Some(edition.self_hash);
1180            parsed.push(edition);
1181        }
1182
1183        let fold_editions: Vec<version::Edition> = parsed.iter().map(|p| p.to_fold_edition()).collect();
1184        let folded = version::fold(&fold_editions, 0, None);
1185        assert_eq!(fold_editions[folded.head.expect("chain folds")].version, 3);
1186        assert!(!folded.gap);
1187
1188        // Withhold the middle link: the chain gaps at v1 (fail-closed signal).
1189        let partial = [fold_editions[0].clone(), fold_editions[2].clone()];
1190        let gapped = version::fold(&partial, 0, None);
1191        assert_eq!(partial[gapped.head.expect("genesis edition anchors")].version, 1);
1192        assert!(gapped.gap, "a missing middle version is a gap, not a silent skip");
1193    }
1194
1195    #[test]
1196    fn genesis_mints_a_verifiable_two_edition_community() {
1197        let owner = Keys::generate();
1198        let meta = CommunityMetadata {
1199            name: "Vector".into(),
1200            description: Some("Private messaging, no compromises.".into()),
1201            relays: vec!["wss://jskitty.com/nostr".into()],
1202            ..Default::default()
1203        };
1204        let g = genesis(&owner, meta, 1_700_000_000).unwrap();
1205
1206        // The identity self-certifies and names the owner.
1207        assert!(g.identity.verify());
1208        assert_eq!(g.identity.owner().unwrap(), owner.public_key());
1209
1210        // Exactly two editions, both owner-signed, both openable at epoch 0 —
1211        // at the SPLIT address (the control_root-derived signer, CORD-02 §2).
1212        let group = split_write_group(&g.control_root, &g.community_root, &g.identity.community_id, Epoch(0));
1213        assert_eq!(group.pk(), g.control_pk(), "the plane address is the signer's pk");
1214        assert_ne!(group.pk(), control_group_key(&g.community_root, &g.identity.community_id, Epoch(0)).pk(), "never the legacy address");
1215        let (meta_ed, _) = open_control_edition(&g.wraps[0], &group).unwrap();
1216        let (chan_ed, _) = open_control_edition(&g.wraps[1], &group).unwrap();
1217        assert_eq!(meta_ed.author, owner.public_key());
1218        assert_eq!(chan_ed.author, owner.public_key());
1219        assert_eq!(meta_ed.vsk, vsk::COMMUNITY_METADATA);
1220        assert_eq!(chan_ed.vsk, vsk::CHANNEL_METADATA);
1221        // Metadata's coordinate IS the community id; the channel's its channel id.
1222        assert_eq!(meta_ed.entity_id, g.identity.community_id.0);
1223        assert_eq!(chan_ed.entity_id, g.general_channel_id.0);
1224        // Both are genesis editions: version 1, no prev, no citation (owner is supreme).
1225        for e in [&meta_ed, &chan_ed] {
1226            assert_eq!(e.version, 1);
1227            assert_eq!(e.prev_hash, None);
1228            assert_eq!(e.authority, None);
1229        }
1230        let general: ChannelMetadata = serde_json::from_str(&chan_ed.content).unwrap();
1231        assert_eq!(general.name, "general");
1232        assert!(!general.private);
1233    }
1234
1235    #[test]
1236    fn a_member_view_reads_the_split_plane_but_cannot_write_and_a_bad_wrap_sig_is_refused() {
1237        // CORD-01 Write-Restricted Streams / CORD-02 §2: every member holds the
1238        // address + read key; only a control_root holder can mint a wrap that
1239        // verifies there — and on a restricted view the wrap signature is the
1240        // write gate, so the reader MUST check it.
1241        let owner = Keys::generate();
1242        let g = genesis(&owner, CommunityMetadata { name: "Gate".into(), ..Default::default() }, 1_000).unwrap();
1243        let mut member = super::super::community::CommunityV2::from_genesis(&g, "Gate", None, vec![], 0);
1244        member.control_root = None; // a member holds the address, never the secret
1245        let view = ControlPlane::of(&member);
1246        assert!(!view.can_write());
1247        let err = view.write_group().unwrap_err();
1248        assert!(err.contains("staff"), "a readable refusal, not a panic: {err}");
1249
1250        // The member READS a staff wrap fine…
1251        let (ed, _) = view.open(&g.wraps[0]).unwrap();
1252        assert_eq!(ed.author, owner.public_key());
1253
1254        // …and a corrupt secret fails closed to the same read-only view.
1255        member.control_root = Some([0x77u8; 32]);
1256        assert!(!ControlPlane::of(&member).can_write(), "a non-deriving secret is corrupt state, not a signer");
1257
1258        // A wrap whose signature doesn't verify is refused on the restricted
1259        // view — the best a read-key holder can do is claim the address with a
1260        // signature that cannot check out.
1261        let mut json: serde_json::Value = serde_json::from_str(&g.wraps[0].as_json()).unwrap();
1262        json["sig"] = serde_json::Value::String("aa".repeat(64));
1263        let tampered = Event::from_json(json.to_string()).unwrap();
1264        member.control_root = None;
1265        assert!(
1266            matches!(ControlPlane::of(&member).open(&tampered), Err(ControlError::Stream(StreamError::BadWrapSignature))),
1267            "the wrap signature IS the write gate on a restricted stream"
1268        );
1269    }
1270
1271    #[test]
1272    fn a_forged_identity_fails_the_commitment() {
1273        let owner = Keys::generate();
1274        let attacker = Keys::generate();
1275        let real = CommunityIdentity::mint(&owner.public_key());
1276        // An attacker claiming the real community id with their own key + any salt
1277        // needs a second preimage — verify() must fail.
1278        let forged = CommunityIdentity {
1279            community_id: real.community_id,
1280            owner_xonly: attacker.public_key().to_bytes(),
1281            owner_salt: real.owner_salt,
1282        };
1283        assert!(!forged.verify());
1284    }
1285
1286    #[test]
1287    fn metadata_caps_and_unknown_field_round_trip() {
1288        let over_name = CommunityMetadata { name: "x".repeat(MAX_NAME_BYTES + 1), ..Default::default() };
1289        assert!(matches!(validate_community_metadata(&over_name), Err(ControlError::OverCap("name"))));
1290        let over_desc = CommunityMetadata {
1291            name: "ok".into(),
1292            description: Some("d".repeat(MAX_DESCRIPTION_BYTES + 1)),
1293            ..Default::default()
1294        };
1295        assert!(matches!(validate_community_metadata(&over_desc), Err(ControlError::OverCap("description"))));
1296        // The cap is BYTES, not chars: 22 three-byte chars = 66 bytes > 64.
1297        let multibyte = ChannelMetadata { name: "€".repeat(22), private: false, ..Default::default() };
1298        assert!(matches!(validate_channel_metadata(&multibyte), Err(ControlError::OverCap("name"))));
1299
1300        // Round-trip discipline: unknown top-level fields, unknown icon fields,
1301        // and the custom object all survive a parse → serialize cycle.
1302        let wire = r#"{"name":"Vector","relays":["wss://a"],"icon":{"url":"u","key":"k","nonce":"n","hash":"h","ext":"png"},"custom":{"rules":"Be excellent."},"future_field":{"deep":[1,2]}}"#;
1303        let parsed: CommunityMetadata = serde_json::from_str(wire).unwrap();
1304        let out = serde_json::to_string(&parsed).unwrap();
1305        let reparsed: serde_json::Value = serde_json::from_str(&out).unwrap();
1306        assert_eq!(reparsed["future_field"]["deep"][1], 2);
1307        assert_eq!(reparsed["icon"]["ext"], "png");
1308        assert_eq!(reparsed["custom"]["rules"], "Be excellent.");
1309    }
1310}