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
246impl ImageRef {
247    /// Bridge to the v1 image-ref shape so the shared download/decrypt/cache
248    /// plumbing serves both protocols. `ext` rides the flattened extras; fall
249    /// back to the URL's extension, else png.
250    pub fn to_community_image(&self) -> crate::community::CommunityImage {
251        let ext = self
252            .extra
253            .get("ext")
254            .and_then(|v| v.as_str())
255            .filter(|s| !s.is_empty())
256            .map(str::to_string)
257            .or_else(|| {
258                std::path::Path::new(&self.url)
259                    .extension()
260                    .and_then(|e| e.to_str())
261                    .map(|s| s.to_lowercase())
262            })
263            .unwrap_or_else(|| "png".to_string());
264        crate::community::CommunityImage {
265            url: self.url.clone(),
266            key: self.key.clone(),
267            nonce: self.nonce.clone(),
268            hash: self.hash.clone(),
269            ext,
270        }
271    }
272}
273
274/// Community metadata — the vsk-0 entity content (CORD-02 §6). `eid` = the
275/// community_id itself; gated by `MANAGE_METADATA`.
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
277pub struct CommunityMetadata {
278    pub name: String,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub description: Option<String>,
281    #[serde(default, skip_serializing_if = "Vec::is_empty")]
282    pub relays: Vec<String>,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub icon: Option<ImageRef>,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub banner: Option<ImageRef>,
287    /// Client-extensible opaque object; folds atomically with the entity.
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
290    /// Reserved-for-protocol unknown top-level fields, round-tripped verbatim.
291    #[serde(flatten)]
292    pub extra: serde_json::Map<String, serde_json::Value>,
293}
294
295/// Channel metadata — the vsk-2 entity content (CORD-03 §2). `eid` = the
296/// channel_id; gated by `MANAGE_CHANNELS`. Absent flags mean false; deletion is
297/// terminal.
298#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
299pub struct ChannelMetadata {
300    pub name: String,
301    pub private: bool,
302    #[serde(skip_serializing_if = "Option::is_none")]
303    pub voice: Option<bool>,
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub deleted: Option<bool>,
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
308    #[serde(flatten)]
309    pub extra: serde_json::Map<String, serde_json::Value>,
310}
311
312/// Enforce the protocol byte caps before an edition is built (a strict reader
313/// may drop over-cap state; never publish what peers would refuse).
314pub fn validate_community_metadata(meta: &CommunityMetadata) -> Result<(), ControlError> {
315    if meta.name.len() > MAX_NAME_BYTES {
316        return Err(ControlError::OverCap("name"));
317    }
318    if meta.description.as_ref().is_some_and(|d| d.len() > MAX_DESCRIPTION_BYTES) {
319        return Err(ControlError::OverCap("description"));
320    }
321    Ok(())
322}
323
324pub fn validate_channel_metadata(meta: &ChannelMetadata) -> Result<(), ControlError> {
325    if meta.name.len() > MAX_NAME_BYTES {
326        return Err(ControlError::OverCap("name"));
327    }
328    Ok(())
329}
330
331// ── Genesis (CORD-02 §1) ─────────────────────────────────────────────────────
332
333/// The two wraps of a community genesis — exactly two owner-signed editions:
334/// the community metadata (vsk 0) and one public `#general` channel (vsk 2).
335/// Nothing more — no default roles, no scaffolding.
336pub struct Genesis {
337    pub identity: CommunityIdentity,
338    /// The community_root minted for epoch 0.
339    pub community_root: [u8; 32],
340    pub general_channel_id: ChannelId,
341    /// `[metadata wrap, #general wrap]`, both sealed at the epoch-0 control_pk.
342    pub wraps: [Event; 2],
343}
344
345/// Mint a v2 community: fresh identity (salt-committed to the owner), fresh
346/// community_root, and the two genesis editions sealed at the epoch-0 control
347/// plane. The caller persists the secrets and publishes the wraps.
348pub fn genesis(owner_keys: &Keys, mut metadata: CommunityMetadata, at_secs: u64) -> Result<Genesis, ControlError> {
349    validate_community_metadata(&metadata)?;
350    // Relays ride the metadata entity so they can evolve by edit; cap on write.
351    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);
352
353    let identity = CommunityIdentity::mint(&owner_keys.public_key());
354    let community_root = super::super::random_32();
355    let general_channel_id = ChannelId(super::super::random_32());
356    let group = control_group_key(&community_root, &identity.community_id, Epoch(0));
357
358    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
359    let meta_rumor = build_edition_rumor(
360        owner_keys.public_key(),
361        vsk::COMMUNITY_METADATA,
362        &identity.community_id.0,
363        1,
364        None,
365        &meta_json,
366        at_secs,
367        None,
368    );
369
370    let general = ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
371    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
372    let general_rumor = build_edition_rumor(
373        owner_keys.public_key(),
374        vsk::CHANNEL_METADATA,
375        &general_channel_id.0,
376        1,
377        None,
378        &general_json,
379        at_secs,
380        None,
381    );
382
383    let (meta_wrap, _) = seal_control_edition(&meta_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
384    let (general_wrap, _) = seal_control_edition(&general_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
385
386    Ok(Genesis {
387        identity,
388        community_root,
389        general_channel_id,
390        wraps: [meta_wrap, general_wrap],
391    })
392}
393
394#[cfg(test)]
395mod tests {
396    use super::super::super::edition::build_edition_inner;
397    use super::*;
398
399    fn cid() -> CommunityId {
400        CommunityId([0x33; 32])
401    }
402
403    fn group_at(epoch: u64) -> GroupKey {
404        control_group_key(&[0x44; 32], &cid(), Epoch(epoch))
405    }
406
407    fn simple_edition(author: &Keys, version: u64, prev: Option<&[u8; 32]>) -> UnsignedEvent {
408        build_edition_rumor(
409            author.public_key(),
410            vsk::GRANT,
411            &[0x55; 32],
412            version,
413            prev,
414            "{\"member\":\"aa\",\"role_ids\":[]}",
415            1_700_000_000,
416            None,
417        )
418    }
419
420    #[test]
421    fn edition_round_trips_through_the_control_plane() {
422        let owner = Keys::generate();
423        let group = group_at(0);
424        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
425        let rumor = build_edition_rumor(
426            owner.public_key(),
427            vsk::GRANT,
428            &[0x55; 32],
429            2,
430            Some(&[0x66; 32]),
431            "{\"member\":\"aa\",\"role_ids\":[]}",
432            1_700_000_000,
433            Some(&cite),
434        );
435        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_700_000_001)).unwrap();
436
437        let (edition, opened) = open_control_edition(&wrap, &group).unwrap();
438        assert_eq!(edition.author, owner.public_key());
439        assert_eq!(edition.vsk, vsk::GRANT);
440        assert_eq!(edition.entity_id, [0x55; 32]);
441        assert_eq!(edition.version, 2);
442        assert_eq!(edition.prev_hash, Some([0x66; 32]));
443        assert_eq!(edition.authority.as_ref(), Some(&cite));
444        assert_eq!(opened.seal_form, SealForm::Plaintext);
445        // self_hash matches the canonical recomputation.
446        assert_eq!(
447            edition.self_hash,
448            version::edition_hash(&[0x55; 32], 2, Some(&[0x66; 32]), rumor.content.as_bytes())
449        );
450    }
451
452    #[test]
453    fn v2_edition_tags_carry_no_protocol_version_tag() {
454        // FROZEN: the v2 tag set is exactly vsk/eid/ev(+ep/vac) — a `v` tag is
455        // the rejected versioning mechanism (address partitioning does the job).
456        let owner = Keys::generate();
457        let rumor = simple_edition(&owner, 1, None);
458        assert!(
459            !rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "v").unwrap_or(false)),
460            "v2 editions must not carry a protocol version tag"
461        );
462        // And no ms tag — editions fold by version, not time.
463        assert!(!rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "ms").unwrap_or(false)));
464    }
465
466    #[test]
467    fn edition_hash_is_identical_across_protocols() {
468        // The edition hash is the ONE construction both protocols share (upstream
469        // froze v1's byte layout, label included). The same logical edition must
470        // hash identically whether built as a v1 signed inner or a v2 rumor —
471        // this is what makes the fold engine shareable.
472        let author = Keys::generate();
473        let entity = [0x55; 32];
474        let content = "{\"member\":\"aa\",\"role_ids\":[]}";
475        let v1_inner = build_edition_inner(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None)
476            .sign_with_keys(&author)
477            .unwrap();
478        let v1_parsed = super::super::super::edition::parse_edition_inner(&v1_inner).unwrap();
479
480        let v2_rumor = build_edition_rumor(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None);
481        let v2_parsed = parse_edition_rumor(&v2_rumor).unwrap();
482
483        assert_eq!(v1_parsed.self_hash, v2_parsed.self_hash);
484    }
485
486    #[test]
487    fn encrypted_seal_control_edition_is_rejected() {
488        let owner = Keys::generate();
489        let group = group_at(0);
490        let rumor = simple_edition(&owner, 1, None);
491        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &owner).unwrap();
492        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
493        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotPlaintextSealed)));
494    }
495
496    #[test]
497    fn non_edition_rumor_is_rejected() {
498        let owner = Keys::generate();
499        let group = group_at(0);
500        let rumor = stream::build_rumor_secs(super::kind::MESSAGE, owner.public_key(), "hi", vec![], 100);
501        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &owner).unwrap();
502        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
503        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotAnEdition(k)) if k == super::kind::MESSAGE));
504    }
505
506    #[test]
507    fn duplicate_machinery_tags_are_rejected() {
508        let owner = Keys::generate();
509        let mut rumor = simple_edition(&owner, 1, None);
510        let dup = Tag::custom(TagKind::Custom("eid".into()), [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]);
511        let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
512        tags.push(dup);
513        rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), &rumor.content, tags, 100);
514        assert!(matches!(
515            parse_edition_rumor(&rumor),
516            Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")))
517        ));
518    }
519
520    #[test]
521    fn a_non_canonical_ev_version_is_rejected() {
522        let owner = Keys::generate();
523        // A leading-zero (or `+`-prefixed) version is a distinct rumor that folds to
524        // the same numeric version — a same-version fork a strict peer drops.
525        for bad in ["007", "+5", "01"] {
526            let tags = vec![
527                Tag::custom(TagKind::Custom("vsk".into()), [vsk::GRANT]),
528                Tag::custom(TagKind::Custom("eid".into()), [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]),
529                Tag::custom(TagKind::Custom("ev".into()), [bad]),
530            ];
531            let rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), "{\"member\":\"aa\",\"role_ids\":[]}", tags, 100);
532            assert!(
533                matches!(parse_edition_rumor(&rumor), Err(ControlError::Edition(EditionError::BadField("ev")))),
534                "a non-canonical ev {bad:?} is rejected"
535            );
536        }
537    }
538
539    #[test]
540    fn compaction_rewrap_preserves_the_edition_chain_identity() {
541        // The whole reason control seals are plaintext: carry a signed head into
542        // a new epoch and its self_hash + authorship must be untouched, so a
543        // fresh joiner folds the same chain the old epoch held.
544        let owner = Keys::generate();
545        let e0 = group_at(0);
546        let rumor = simple_edition(&owner, 3, Some(&[0x77; 32]));
547        let (wrap, _) = seal_control_edition(&rumor, &e0, &owner, Timestamp::from_secs(10)).unwrap();
548        let (edition, opened) = open_control_edition(&wrap, &e0).unwrap();
549
550        let e1 = group_at(1);
551        let (rewrapped, _) = stream::rewrap_seal(&opened.seal, &e1, Timestamp::from_secs(20)).unwrap();
552        let (re_edition, _) = open_control_edition(&rewrapped, &e1).unwrap();
553
554        assert_eq!(re_edition.self_hash, edition.self_hash);
555        assert_eq!(re_edition.author, edition.author);
556        assert_eq!(re_edition.inner_id, edition.inner_id, "rumor id survives compaction");
557    }
558
559    #[test]
560    fn editions_opened_from_wraps_fold_to_the_head() {
561        let owner = Keys::generate();
562        let group = group_at(0);
563        let entity = [0x55; 32];
564        let content = |v: u64| format!("{{\"v\":{v}}}");
565
566        // Build a 3-link chain v1 → v2 → v3.
567        let mut prev: Option<[u8; 32]> = None;
568        let mut parsed = Vec::new();
569        for v in 1..=3u64 {
570            let rumor = build_edition_rumor(owner.public_key(), vsk::GRANT, &entity, v, prev.as_ref(), &content(v), 100 + v, None);
571            let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(100 + v)).unwrap();
572            let (edition, _) = open_control_edition(&wrap, &group).unwrap();
573            prev = Some(edition.self_hash);
574            parsed.push(edition);
575        }
576
577        let fold_editions: Vec<version::Edition> = parsed.iter().map(|p| p.to_fold_edition()).collect();
578        let folded = version::fold(&fold_editions, 0, None);
579        assert_eq!(fold_editions[folded.head.expect("chain folds")].version, 3);
580        assert!(!folded.gap);
581
582        // Withhold the middle link: the chain gaps at v1 (fail-closed signal).
583        let partial = [fold_editions[0].clone(), fold_editions[2].clone()];
584        let gapped = version::fold(&partial, 0, None);
585        assert_eq!(partial[gapped.head.expect("genesis edition anchors")].version, 1);
586        assert!(gapped.gap, "a missing middle version is a gap, not a silent skip");
587    }
588
589    #[test]
590    fn genesis_mints_a_verifiable_two_edition_community() {
591        let owner = Keys::generate();
592        let meta = CommunityMetadata {
593            name: "Vector".into(),
594            description: Some("Private messaging, no compromises.".into()),
595            relays: vec!["wss://jskitty.com/nostr".into()],
596            ..Default::default()
597        };
598        let g = genesis(&owner, meta, 1_700_000_000).unwrap();
599
600        // The identity self-certifies and names the owner.
601        assert!(g.identity.verify());
602        assert_eq!(g.identity.owner().unwrap(), owner.public_key());
603
604        // Exactly two editions, both owner-signed, both openable at epoch 0.
605        let group = control_group_key(&g.community_root, &g.identity.community_id, Epoch(0));
606        let (meta_ed, _) = open_control_edition(&g.wraps[0], &group).unwrap();
607        let (chan_ed, _) = open_control_edition(&g.wraps[1], &group).unwrap();
608        assert_eq!(meta_ed.author, owner.public_key());
609        assert_eq!(chan_ed.author, owner.public_key());
610        assert_eq!(meta_ed.vsk, vsk::COMMUNITY_METADATA);
611        assert_eq!(chan_ed.vsk, vsk::CHANNEL_METADATA);
612        // Metadata's coordinate IS the community id; the channel's its channel id.
613        assert_eq!(meta_ed.entity_id, g.identity.community_id.0);
614        assert_eq!(chan_ed.entity_id, g.general_channel_id.0);
615        // Both are genesis editions: version 1, no prev, no citation (owner is supreme).
616        for e in [&meta_ed, &chan_ed] {
617            assert_eq!(e.version, 1);
618            assert_eq!(e.prev_hash, None);
619            assert_eq!(e.authority, None);
620        }
621        let general: ChannelMetadata = serde_json::from_str(&chan_ed.content).unwrap();
622        assert_eq!(general.name, "general");
623        assert!(!general.private);
624    }
625
626    #[test]
627    fn a_forged_identity_fails_the_commitment() {
628        let owner = Keys::generate();
629        let attacker = Keys::generate();
630        let real = CommunityIdentity::mint(&owner.public_key());
631        // An attacker claiming the real community id with their own key + any salt
632        // needs a second preimage — verify() must fail.
633        let forged = CommunityIdentity {
634            community_id: real.community_id,
635            owner_xonly: attacker.public_key().to_bytes(),
636            owner_salt: real.owner_salt,
637        };
638        assert!(!forged.verify());
639    }
640
641    #[test]
642    fn metadata_caps_and_unknown_field_round_trip() {
643        let over_name = CommunityMetadata { name: "x".repeat(MAX_NAME_BYTES + 1), ..Default::default() };
644        assert!(matches!(validate_community_metadata(&over_name), Err(ControlError::OverCap("name"))));
645        let over_desc = CommunityMetadata {
646            name: "ok".into(),
647            description: Some("d".repeat(MAX_DESCRIPTION_BYTES + 1)),
648            ..Default::default()
649        };
650        assert!(matches!(validate_community_metadata(&over_desc), Err(ControlError::OverCap("description"))));
651        // The cap is BYTES, not chars: 22 three-byte chars = 66 bytes > 64.
652        let multibyte = ChannelMetadata { name: "€".repeat(22), private: false, ..Default::default() };
653        assert!(matches!(validate_channel_metadata(&multibyte), Err(ControlError::OverCap("name"))));
654
655        // Round-trip discipline: unknown top-level fields, unknown icon fields,
656        // and the custom object all survive a parse → serialize cycle.
657        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]}}"#;
658        let parsed: CommunityMetadata = serde_json::from_str(wire).unwrap();
659        let out = serde_json::to_string(&parsed).unwrap();
660        let reparsed: serde_json::Value = serde_json::from_str(&out).unwrap();
661        assert_eq!(reparsed["future_field"]["deep"][1], 2);
662        assert_eq!(reparsed["icon"]["ext"], "png");
663        assert_eq!(reparsed["custom"]["rules"], "Be excellent.");
664    }
665}