Skip to main content

vector_core/community/v2/
control.rs

1//! The v2 Control Plane (CORD-04 over CORD-01/02).
2//!
3//! Editions keep v1's exact grammar — the `vsk/eid/ev/ep/vac` tags, the frozen
4//! `edition_hash` (`community::version`, label `vector-community/v1/edition`,
5//! which upstream froze verbatim), and the fold rules — but ride the v2 stream
6//! envelope: a kind-3308 UNSIGNED rumor inside a **plaintext seal** (20014) at
7//! `control_pk`. Authorship moves from the rumor's own signature (v1) to the
8//! seal's (v2): [`super::stream::open_wrap`] Schnorr-verifies the seal and pins
9//! `rumor.pubkey == seal.pubkey`, so by the time an edition is parsed here its
10//! author is already proven. The plaintext seal is load-bearing: a compaction
11//! re-wraps the signed seal into a new epoch byte-verbatim, and the signature
12//! (over the rumor string) survives — an encrypted seal could not.
13//!
14//! Two v1↔v2 wire deltas, both deliberate:
15//!   - v2 editions carry NO `["v","1"]` protocol tag (frozen derivations
16//!     partition protocol revisions by address; version tags are the rejected
17//!     mechanism).
18//!   - the owner is proven by the self-certifying `community_id` commitment
19//!     ([`super::derive::verify_community_id`]), not an attestation event —
20//!     vsk 7 is retired.
21
22use nostr_sdk::prelude::{Event, Keys, PublicKey, Tag, TagKind, 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, 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
36/// Protocol-wide UTF-8 byte cap on names (community, channel, role).
37pub const MAX_NAME_BYTES: usize = 64;
38/// UTF-8 byte cap on a community description.
39pub const MAX_DESCRIPTION_BYTES: usize = 10_000;
40
41/// Errors from the control plane layer (envelope errors ride inside).
42#[derive(Debug)]
43pub enum ControlError {
44    Stream(StreamError),
45    Edition(EditionError),
46    /// The rumor isn't a kind-3308 edition.
47    NotAnEdition(u16),
48    /// A control edition arrived in an encrypted seal — CORD-02 §5 requires the
49    /// plaintext form (compaction must preserve signatures), so a strict reader
50    /// drops it rather than folding a chain a re-wrap would later fork.
51    NotPlaintextSealed,
52    /// A name/description exceeds its protocol byte cap.
53    OverCap(&'static str),
54}
55
56impl std::fmt::Display for ControlError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            ControlError::Stream(e) => write!(f, "stream: {e}"),
60            ControlError::Edition(e) => write!(f, "edition: {e:?}"),
61            ControlError::NotAnEdition(k) => write!(f, "rumor kind {k} is not a control edition"),
62            ControlError::NotPlaintextSealed => write!(f, "control edition must ride a plaintext seal"),
63            ControlError::OverCap(what) => write!(f, "{what} exceeds its byte cap"),
64        }
65    }
66}
67
68impl std::error::Error for ControlError {}
69
70impl From<StreamError> for ControlError {
71    fn from(e: StreamError) -> Self {
72        ControlError::Stream(e)
73    }
74}
75
76// ── Identity ─────────────────────────────────────────────────────────────────
77
78/// A v2 community's self-certifying identity triple. The id IS the owner
79/// commitment — carry all three together and verify before trusting any claim.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct CommunityIdentity {
82    pub community_id: CommunityId,
83    pub owner_xonly: [u8; 32],
84    pub owner_salt: [u8; 32],
85}
86
87impl CommunityIdentity {
88    /// Mint a fresh identity for `owner` (a new random salt ⇒ a new community).
89    pub fn mint(owner: &PublicKey) -> CommunityIdentity {
90        let owner_xonly = owner.to_bytes();
91        let owner_salt = super::super::random_32();
92        CommunityIdentity {
93            community_id: super::derive::community_id_of(&owner_xonly, &owner_salt),
94            owner_xonly,
95            owner_salt,
96        }
97    }
98
99    /// True iff the commitment reproduces the id — the ONLY valid owner proof.
100    pub fn verify(&self) -> bool {
101        verify_community_id(&self.community_id, &self.owner_xonly, &self.owner_salt)
102    }
103
104    /// The proven owner as a `PublicKey` (call only after [`Self::verify`]).
105    pub fn owner(&self) -> Result<PublicKey, String> {
106        PublicKey::from_slice(&self.owner_xonly).map_err(|e| e.to_string())
107    }
108}
109
110// ── Edition rumors (build + parse) ───────────────────────────────────────────
111
112/// Build the unsigned kind-3308 edition rumor — v1's grammar minus the protocol
113/// `v` tag. Control editions carry no `ms` tag: they fold by version, not time.
114#[allow(clippy::too_many_arguments)]
115pub fn build_edition_rumor(
116    author: PublicKey,
117    vsk: &str,
118    entity_id: &[u8; 32],
119    version: u64,
120    prev_hash: Option<&[u8; 32]>,
121    content: &str,
122    created_at_secs: u64,
123    authority: Option<&AuthorityCitation>,
124) -> UnsignedEvent {
125    let mut tags = vec![
126        Tag::custom(TagKind::Custom(TAG_SUBKIND.into()), [vsk.to_string()]),
127        Tag::custom(TagKind::Custom(TAG_ENTITY.into()), [crate::simd::hex::bytes_to_hex_32(entity_id)]),
128        Tag::custom(TagKind::Custom(TAG_EVERSION.into()), [version.to_string()]),
129    ];
130    if let Some(p) = prev_hash {
131        tags.push(Tag::custom(TagKind::Custom(TAG_EPREV.into()), [crate::simd::hex::bytes_to_hex_32(p)]));
132    }
133    if let Some(a) = authority {
134        tags.push(a.to_tag());
135    }
136    stream::build_rumor_secs(kind::CONTROL, author, content, tags, created_at_secs)
137}
138
139/// Parse an edition from an ALREADY-VERIFIED rumor (one produced by
140/// [`stream::open_wrap`], which proved the seal signature, the author binding,
141/// and the rumor id). No signature lives on the rumor itself — never feed this
142/// a rumor that didn't come through the stream verifier.
143pub fn parse_edition_rumor(rumor: &UnsignedEvent) -> Result<ParsedEdition, ControlError> {
144    if rumor.kind.as_u16() != kind::CONTROL {
145        return Err(ControlError::NotAnEdition(rumor.kind.as_u16()));
146    }
147    // Duplicate machinery tags make signed-bytes → canonical-fields ambiguous
148    // (two clients could pick different duplicates and fork on self_hash).
149    for name in [TAG_SUBKIND, TAG_ENTITY, TAG_EVERSION, TAG_EPREV, TAG_AUTHORITY_CITATION] {
150        let count = rumor
151            .tags
152            .iter()
153            .filter(|t| t.as_slice().first().map(|s| s.as_str() == name).unwrap_or(false))
154            .count();
155        if count > 1 {
156            return Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")));
157        }
158    }
159    let get = |name: &str| -> Option<String> {
160        rumor.tags.iter().find_map(|t| {
161            let s = t.as_slice();
162            (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
163        })
164    };
165    let decode_hash = |hex: &str, field: &'static str| -> Result<[u8; 32], ControlError> {
166        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
167            return Err(ControlError::Edition(EditionError::BadField(field)));
168        }
169        Ok(crate::simd::hex::hex_to_bytes_32(hex))
170    };
171    let vsk = get(TAG_SUBKIND).ok_or(ControlError::Edition(EditionError::MissingField("vsk")))?;
172    let entity_id = decode_hash(&get(TAG_ENTITY).ok_or(ControlError::Edition(EditionError::MissingField("eid")))?, "eid")?;
173    // Decimal, no leading zeros (CORD-01 Encoding): `u64::from_str` accepts a leading
174    // `+`, and "007"/"7" are distinct signed rumors that fold to the same version — a
175    // same-version convergence fork a strict peer (which drops the padded form)
176    // resolves differently. Reject any non-canonical decimal, matching the `ms` rule.
177    let ev_raw = get(TAG_EVERSION).ok_or(ControlError::Edition(EditionError::MissingField("ev")))?;
178    if ev_raw.is_empty()
179        || !ev_raw.bytes().all(|b| b.is_ascii_digit())
180        || (ev_raw.len() > 1 && ev_raw.starts_with('0'))
181    {
182        return Err(ControlError::Edition(EditionError::BadField("ev")));
183    }
184    let version: u64 = ev_raw.parse().map_err(|_| ControlError::Edition(EditionError::BadField("ev")))?;
185    let prev_hash = match get(TAG_EPREV) {
186        Some(h) => Some(decode_hash(&h, "ep")?),
187        None => None,
188    };
189    let self_hash = version::edition_hash(&entity_id, version, prev_hash.as_ref(), rumor.content.as_bytes());
190    Ok(ParsedEdition {
191        author: rumor.pubkey,
192        vsk,
193        entity_id,
194        version,
195        prev_hash,
196        content: rumor.content.clone(),
197        self_hash,
198        created_at: rumor.created_at.as_secs(),
199        inner_id: rumor.id.expect("verified rumors carry their id").to_bytes(),
200        authority: AuthorityCitation::from_tags(&rumor.tags),
201    })
202}
203
204// ── Seal / open over the stream ──────────────────────────────────────────────
205
206/// Seal a signed-by-`author_keys` edition rumor into a control-plane wrap.
207/// Local-keys convenience; bunker accounts use [`stream::seal_content`] +
208/// their remote signer + [`stream::wrap_seal`] for identical wire output.
209pub fn seal_control_edition(
210    rumor: &UnsignedEvent,
211    group: &GroupKey,
212    author_keys: &Keys,
213    wrap_at: Timestamp,
214) -> Result<(Event, Keys), ControlError> {
215    let seal = stream::build_seal(rumor, SealForm::Plaintext, group, author_keys)?;
216    Ok(stream::wrap_seal(&seal, group, stream::KIND_WRAP, wrap_at)?)
217}
218
219/// Open a control-plane wrap into a verified, parsed edition. Strict on both
220/// gates: the rumor must be kind 3308, and the seal must be the plaintext form.
221pub fn open_control_edition(wrap: &Event, group: &GroupKey) -> Result<(ParsedEdition, OpenedStream), ControlError> {
222    let opened = stream::open_wrap(wrap, group)?;
223    if opened.seal_form != SealForm::Plaintext {
224        return Err(ControlError::NotPlaintextSealed);
225    }
226    let edition = parse_edition_rumor(&opened.rumor)?;
227    Ok((edition, opened))
228}
229
230// ── Entity payloads (vsk 0 / vsk 2) ──────────────────────────────────────────
231
232/// An encrypted-blob image pointer (icon/banner): the media server sees only an
233/// opaque blob; members fetch, decrypt with `key`/`nonce`, and verify `hash`.
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235pub struct ImageRef {
236    pub url: String,
237    pub key: String,
238    pub nonce: String,
239    pub hash: String,
240    /// Unknown fields round-trip (e.g. Vector's `ext`) — editors MUST preserve
241    /// what they don't understand (CORD-02 §6).
242    #[serde(flatten)]
243    pub extra: serde_json::Map<String, serde_json::Value>,
244}
245
246/// Community metadata — the vsk-0 entity content (CORD-02 §6). `eid` = the
247/// community_id itself; gated by `MANAGE_METADATA`.
248#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
249pub struct CommunityMetadata {
250    pub name: String,
251    #[serde(skip_serializing_if = "Option::is_none")]
252    pub description: Option<String>,
253    #[serde(default, skip_serializing_if = "Vec::is_empty")]
254    pub relays: Vec<String>,
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub icon: Option<ImageRef>,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub banner: Option<ImageRef>,
259    /// Client-extensible opaque object; folds atomically with the entity.
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
262    /// Reserved-for-protocol unknown top-level fields, round-tripped verbatim.
263    #[serde(flatten)]
264    pub extra: serde_json::Map<String, serde_json::Value>,
265}
266
267/// Channel metadata — the vsk-2 entity content (CORD-03 §2). `eid` = the
268/// channel_id; gated by `MANAGE_CHANNELS`. Absent flags mean false; deletion is
269/// terminal.
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
271pub struct ChannelMetadata {
272    pub name: String,
273    pub private: bool,
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub voice: Option<bool>,
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub deleted: Option<bool>,
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
280    #[serde(flatten)]
281    pub extra: serde_json::Map<String, serde_json::Value>,
282}
283
284/// Enforce the protocol byte caps before an edition is built (a strict reader
285/// may drop over-cap state; never publish what peers would refuse).
286pub fn validate_community_metadata(meta: &CommunityMetadata) -> Result<(), ControlError> {
287    if meta.name.len() > MAX_NAME_BYTES {
288        return Err(ControlError::OverCap("name"));
289    }
290    if meta.description.as_ref().is_some_and(|d| d.len() > MAX_DESCRIPTION_BYTES) {
291        return Err(ControlError::OverCap("description"));
292    }
293    Ok(())
294}
295
296pub fn validate_channel_metadata(meta: &ChannelMetadata) -> Result<(), ControlError> {
297    if meta.name.len() > MAX_NAME_BYTES {
298        return Err(ControlError::OverCap("name"));
299    }
300    Ok(())
301}
302
303// ── Genesis (CORD-02 §1) ─────────────────────────────────────────────────────
304
305/// The two wraps of a community genesis — exactly two owner-signed editions:
306/// the community metadata (vsk 0) and one public `#general` channel (vsk 2).
307/// Nothing more — no default roles, no scaffolding.
308pub struct Genesis {
309    pub identity: CommunityIdentity,
310    /// The community_root minted for epoch 0.
311    pub community_root: [u8; 32],
312    pub general_channel_id: ChannelId,
313    /// `[metadata wrap, #general wrap]`, both sealed at the epoch-0 control_pk.
314    pub wraps: [Event; 2],
315}
316
317/// Mint a v2 community: fresh identity (salt-committed to the owner), fresh
318/// community_root, and the two genesis editions sealed at the epoch-0 control
319/// plane. The caller persists the secrets and publishes the wraps.
320pub fn genesis(owner_keys: &Keys, mut metadata: CommunityMetadata, at_secs: u64) -> Result<Genesis, ControlError> {
321    validate_community_metadata(&metadata)?;
322    // Relays ride the metadata entity so they can evolve by edit; cap on write.
323    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);
324
325    let identity = CommunityIdentity::mint(&owner_keys.public_key());
326    let community_root = super::super::random_32();
327    let general_channel_id = ChannelId(super::super::random_32());
328    let group = control_group_key(&community_root, &identity.community_id, Epoch(0));
329
330    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
331    let meta_rumor = build_edition_rumor(
332        owner_keys.public_key(),
333        vsk::COMMUNITY_METADATA,
334        &identity.community_id.0,
335        1,
336        None,
337        &meta_json,
338        at_secs,
339        None,
340    );
341
342    let general = ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
343    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
344    let general_rumor = build_edition_rumor(
345        owner_keys.public_key(),
346        vsk::CHANNEL_METADATA,
347        &general_channel_id.0,
348        1,
349        None,
350        &general_json,
351        at_secs,
352        None,
353    );
354
355    let (meta_wrap, _) = seal_control_edition(&meta_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
356    let (general_wrap, _) = seal_control_edition(&general_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
357
358    Ok(Genesis {
359        identity,
360        community_root,
361        general_channel_id,
362        wraps: [meta_wrap, general_wrap],
363    })
364}
365
366#[cfg(test)]
367mod tests {
368    use super::super::super::edition::build_edition_inner;
369    use super::*;
370
371    fn cid() -> CommunityId {
372        CommunityId([0x33; 32])
373    }
374
375    fn group_at(epoch: u64) -> GroupKey {
376        control_group_key(&[0x44; 32], &cid(), Epoch(epoch))
377    }
378
379    fn simple_edition(author: &Keys, version: u64, prev: Option<&[u8; 32]>) -> UnsignedEvent {
380        build_edition_rumor(
381            author.public_key(),
382            vsk::GRANT,
383            &[0x55; 32],
384            version,
385            prev,
386            "{\"member\":\"aa\",\"role_ids\":[]}",
387            1_700_000_000,
388            None,
389        )
390    }
391
392    #[test]
393    fn edition_round_trips_through_the_control_plane() {
394        let owner = Keys::generate();
395        let group = group_at(0);
396        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
397        let rumor = build_edition_rumor(
398            owner.public_key(),
399            vsk::GRANT,
400            &[0x55; 32],
401            2,
402            Some(&[0x66; 32]),
403            "{\"member\":\"aa\",\"role_ids\":[]}",
404            1_700_000_000,
405            Some(&cite),
406        );
407        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_700_000_001)).unwrap();
408
409        let (edition, opened) = open_control_edition(&wrap, &group).unwrap();
410        assert_eq!(edition.author, owner.public_key());
411        assert_eq!(edition.vsk, vsk::GRANT);
412        assert_eq!(edition.entity_id, [0x55; 32]);
413        assert_eq!(edition.version, 2);
414        assert_eq!(edition.prev_hash, Some([0x66; 32]));
415        assert_eq!(edition.authority.as_ref(), Some(&cite));
416        assert_eq!(opened.seal_form, SealForm::Plaintext);
417        // self_hash matches the canonical recomputation.
418        assert_eq!(
419            edition.self_hash,
420            version::edition_hash(&[0x55; 32], 2, Some(&[0x66; 32]), rumor.content.as_bytes())
421        );
422    }
423
424    #[test]
425    fn v2_edition_tags_carry_no_protocol_version_tag() {
426        // FROZEN: the v2 tag set is exactly vsk/eid/ev(+ep/vac) — a `v` tag is
427        // the rejected versioning mechanism (address partitioning does the job).
428        let owner = Keys::generate();
429        let rumor = simple_edition(&owner, 1, None);
430        assert!(
431            !rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "v").unwrap_or(false)),
432            "v2 editions must not carry a protocol version tag"
433        );
434        // And no ms tag — editions fold by version, not time.
435        assert!(!rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "ms").unwrap_or(false)));
436    }
437
438    #[test]
439    fn edition_hash_is_identical_across_protocols() {
440        // The edition hash is the ONE construction both protocols share (upstream
441        // froze v1's byte layout, label included). The same logical edition must
442        // hash identically whether built as a v1 signed inner or a v2 rumor —
443        // this is what makes the fold engine shareable.
444        let author = Keys::generate();
445        let entity = [0x55; 32];
446        let content = "{\"member\":\"aa\",\"role_ids\":[]}";
447        let v1_inner = build_edition_inner(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None)
448            .sign_with_keys(&author)
449            .unwrap();
450        let v1_parsed = super::super::super::edition::parse_edition_inner(&v1_inner).unwrap();
451
452        let v2_rumor = build_edition_rumor(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None);
453        let v2_parsed = parse_edition_rumor(&v2_rumor).unwrap();
454
455        assert_eq!(v1_parsed.self_hash, v2_parsed.self_hash);
456    }
457
458    #[test]
459    fn encrypted_seal_control_edition_is_rejected() {
460        let owner = Keys::generate();
461        let group = group_at(0);
462        let rumor = simple_edition(&owner, 1, None);
463        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &owner).unwrap();
464        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
465        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotPlaintextSealed)));
466    }
467
468    #[test]
469    fn non_edition_rumor_is_rejected() {
470        let owner = Keys::generate();
471        let group = group_at(0);
472        let rumor = stream::build_rumor_secs(super::kind::MESSAGE, owner.public_key(), "hi", vec![], 100);
473        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &owner).unwrap();
474        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
475        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotAnEdition(k)) if k == super::kind::MESSAGE));
476    }
477
478    #[test]
479    fn duplicate_machinery_tags_are_rejected() {
480        let owner = Keys::generate();
481        let mut rumor = simple_edition(&owner, 1, None);
482        let dup = Tag::custom(TagKind::Custom("eid".into()), [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]);
483        let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
484        tags.push(dup);
485        rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), &rumor.content, tags, 100);
486        assert!(matches!(
487            parse_edition_rumor(&rumor),
488            Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")))
489        ));
490    }
491
492    #[test]
493    fn a_non_canonical_ev_version_is_rejected() {
494        let owner = Keys::generate();
495        // A leading-zero (or `+`-prefixed) version is a distinct rumor that folds to
496        // the same numeric version — a same-version fork a strict peer drops.
497        for bad in ["007", "+5", "01"] {
498            let tags = vec![
499                Tag::custom(TagKind::Custom("vsk".into()), [vsk::GRANT]),
500                Tag::custom(TagKind::Custom("eid".into()), [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]),
501                Tag::custom(TagKind::Custom("ev".into()), [bad]),
502            ];
503            let rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), "{\"member\":\"aa\",\"role_ids\":[]}", tags, 100);
504            assert!(
505                matches!(parse_edition_rumor(&rumor), Err(ControlError::Edition(EditionError::BadField("ev")))),
506                "a non-canonical ev {bad:?} is rejected"
507            );
508        }
509    }
510
511    #[test]
512    fn compaction_rewrap_preserves_the_edition_chain_identity() {
513        // The whole reason control seals are plaintext: carry a signed head into
514        // a new epoch and its self_hash + authorship must be untouched, so a
515        // fresh joiner folds the same chain the old epoch held.
516        let owner = Keys::generate();
517        let e0 = group_at(0);
518        let rumor = simple_edition(&owner, 3, Some(&[0x77; 32]));
519        let (wrap, _) = seal_control_edition(&rumor, &e0, &owner, Timestamp::from_secs(10)).unwrap();
520        let (edition, opened) = open_control_edition(&wrap, &e0).unwrap();
521
522        let e1 = group_at(1);
523        let (rewrapped, _) = stream::rewrap_seal(&opened.seal, &e1, Timestamp::from_secs(20)).unwrap();
524        let (re_edition, _) = open_control_edition(&rewrapped, &e1).unwrap();
525
526        assert_eq!(re_edition.self_hash, edition.self_hash);
527        assert_eq!(re_edition.author, edition.author);
528        assert_eq!(re_edition.inner_id, edition.inner_id, "rumor id survives compaction");
529    }
530
531    #[test]
532    fn editions_opened_from_wraps_fold_to_the_head() {
533        let owner = Keys::generate();
534        let group = group_at(0);
535        let entity = [0x55; 32];
536        let content = |v: u64| format!("{{\"v\":{v}}}");
537
538        // Build a 3-link chain v1 → v2 → v3.
539        let mut prev: Option<[u8; 32]> = None;
540        let mut parsed = Vec::new();
541        for v in 1..=3u64 {
542            let rumor = build_edition_rumor(owner.public_key(), vsk::GRANT, &entity, v, prev.as_ref(), &content(v), 100 + v, None);
543            let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(100 + v)).unwrap();
544            let (edition, _) = open_control_edition(&wrap, &group).unwrap();
545            prev = Some(edition.self_hash);
546            parsed.push(edition);
547        }
548
549        let fold_editions: Vec<version::Edition> = parsed.iter().map(|p| p.to_fold_edition()).collect();
550        let folded = version::fold(&fold_editions, 0, None);
551        assert_eq!(fold_editions[folded.head.expect("chain folds")].version, 3);
552        assert!(!folded.gap);
553
554        // Withhold the middle link: the chain gaps at v1 (fail-closed signal).
555        let partial = [fold_editions[0].clone(), fold_editions[2].clone()];
556        let gapped = version::fold(&partial, 0, None);
557        assert_eq!(partial[gapped.head.expect("genesis edition anchors")].version, 1);
558        assert!(gapped.gap, "a missing middle version is a gap, not a silent skip");
559    }
560
561    #[test]
562    fn genesis_mints_a_verifiable_two_edition_community() {
563        let owner = Keys::generate();
564        let meta = CommunityMetadata {
565            name: "Vector".into(),
566            description: Some("Private messaging, no compromises.".into()),
567            relays: vec!["wss://jskitty.com/nostr".into()],
568            ..Default::default()
569        };
570        let g = genesis(&owner, meta, 1_700_000_000).unwrap();
571
572        // The identity self-certifies and names the owner.
573        assert!(g.identity.verify());
574        assert_eq!(g.identity.owner().unwrap(), owner.public_key());
575
576        // Exactly two editions, both owner-signed, both openable at epoch 0.
577        let group = control_group_key(&g.community_root, &g.identity.community_id, Epoch(0));
578        let (meta_ed, _) = open_control_edition(&g.wraps[0], &group).unwrap();
579        let (chan_ed, _) = open_control_edition(&g.wraps[1], &group).unwrap();
580        assert_eq!(meta_ed.author, owner.public_key());
581        assert_eq!(chan_ed.author, owner.public_key());
582        assert_eq!(meta_ed.vsk, vsk::COMMUNITY_METADATA);
583        assert_eq!(chan_ed.vsk, vsk::CHANNEL_METADATA);
584        // Metadata's coordinate IS the community id; the channel's its channel id.
585        assert_eq!(meta_ed.entity_id, g.identity.community_id.0);
586        assert_eq!(chan_ed.entity_id, g.general_channel_id.0);
587        // Both are genesis editions: version 1, no prev, no citation (owner is supreme).
588        for e in [&meta_ed, &chan_ed] {
589            assert_eq!(e.version, 1);
590            assert_eq!(e.prev_hash, None);
591            assert_eq!(e.authority, None);
592        }
593        let general: ChannelMetadata = serde_json::from_str(&chan_ed.content).unwrap();
594        assert_eq!(general.name, "general");
595        assert!(!general.private);
596    }
597
598    #[test]
599    fn a_forged_identity_fails_the_commitment() {
600        let owner = Keys::generate();
601        let attacker = Keys::generate();
602        let real = CommunityIdentity::mint(&owner.public_key());
603        // An attacker claiming the real community id with their own key + any salt
604        // needs a second preimage — verify() must fail.
605        let forged = CommunityIdentity {
606            community_id: real.community_id,
607            owner_xonly: attacker.public_key().to_bytes(),
608            owner_salt: real.owner_salt,
609        };
610        assert!(!forged.verify());
611    }
612
613    #[test]
614    fn metadata_caps_and_unknown_field_round_trip() {
615        let over_name = CommunityMetadata { name: "x".repeat(MAX_NAME_BYTES + 1), ..Default::default() };
616        assert!(matches!(validate_community_metadata(&over_name), Err(ControlError::OverCap("name"))));
617        let over_desc = CommunityMetadata {
618            name: "ok".into(),
619            description: Some("d".repeat(MAX_DESCRIPTION_BYTES + 1)),
620            ..Default::default()
621        };
622        assert!(matches!(validate_community_metadata(&over_desc), Err(ControlError::OverCap("description"))));
623        // The cap is BYTES, not chars: 22 three-byte chars = 66 bytes > 64.
624        let multibyte = ChannelMetadata { name: "€".repeat(22), private: false, ..Default::default() };
625        assert!(matches!(validate_channel_metadata(&multibyte), Err(ControlError::OverCap("name"))));
626
627        // Round-trip discipline: unknown top-level fields, unknown icon fields,
628        // and the custom object all survive a parse → serialize cycle.
629        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]}}"#;
630        let parsed: CommunityMetadata = serde_json::from_str(wire).unwrap();
631        let out = serde_json::to_string(&parsed).unwrap();
632        let reparsed: serde_json::Value = serde_json::from_str(&out).unwrap();
633        assert_eq!(reparsed["future_field"]["deep"][1], 2);
634        assert_eq!(reparsed["icon"]["ext"], "png");
635        assert_eq!(reparsed["custom"]["rules"], "Be excellent.");
636    }
637}