vector-core 0.8.0

Core library for Vector — the single source of truth for all Vector clients, SDKs, and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! The v2 Control Plane (CORD-04 over CORD-01/02).
//!
//! Editions keep v1's exact grammar — the `vsk/eid/ev/ep/vac` tags, the frozen
//! `edition_hash` (`community::version`, label `vector-community/v1/edition`,
//! which upstream froze verbatim), and the fold rules — but ride the v2 stream
//! envelope: a kind-3308 UNSIGNED rumor inside a **plaintext seal** (20014) at
//! `control_pk`. Authorship moves from the rumor's own signature (v1) to the
//! seal's (v2): [`super::stream::open_wrap`] Schnorr-verifies the seal and pins
//! `rumor.pubkey == seal.pubkey`, so by the time an edition is parsed here its
//! author is already proven. The plaintext seal is load-bearing: a compaction
//! re-wraps the signed seal into a new epoch byte-verbatim, and the signature
//! (over the rumor string) survives — an encrypted seal could not.
//!
//! Two v1↔v2 wire deltas, both deliberate:
//!   - v2 editions carry NO `["v","1"]` protocol tag (frozen derivations
//!     partition protocol revisions by address; version tags are the rejected
//!     mechanism).
//!   - the owner is proven by the self-certifying `community_id` commitment
//!     ([`super::derive::verify_community_id`]), not an attestation event —
//!     vsk 7 is retired.

use nostr_sdk::prelude::nip44::v2::ConversationKey;
use nostr_sdk::prelude::{Event, Keys, PublicKey, Tag, Timestamp, UnsignedEvent};
use serde::{Deserialize, Serialize};

use super::super::edition::{AuthorityCitation, EditionError, ParsedEdition, TAG_AUTHORITY_CITATION};
use super::super::{version, ChannelId, CommunityId, Epoch};
use super::derive::{control_group_key, control_signer_group_key, verify_community_id, GroupKey};
use super::stream::{self, OpenedStream, SealForm, StreamError};
use super::{kind, vsk};

const TAG_SUBKIND: &str = "vsk";
const TAG_ENTITY: &str = "eid";
const TAG_EVERSION: &str = "ev";
const TAG_EPREV: &str = "ep";

/// Protocol-wide UTF-8 byte cap on names (community, channel, role).
pub const MAX_NAME_BYTES: usize = 64;
/// UTF-8 byte cap on a community description.
pub const MAX_DESCRIPTION_BYTES: usize = 10_000;

/// Errors from the control plane layer (envelope errors ride inside).
#[derive(Debug)]
pub enum ControlError {
    Stream(StreamError),
    Edition(EditionError),
    /// The rumor isn't a kind-3308 edition.
    NotAnEdition(u16),
    /// A control edition arrived in an encrypted seal — CORD-02 §5 requires the
    /// plaintext form (compaction must preserve signatures), so a strict reader
    /// drops it rather than folding a chain a re-wrap would later fork.
    NotPlaintextSealed,
    /// A name/description exceeds its protocol byte cap.
    OverCap(&'static str),
}

impl std::fmt::Display for ControlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ControlError::Stream(e) => write!(f, "stream: {e}"),
            ControlError::Edition(e) => write!(f, "edition: {e:?}"),
            ControlError::NotAnEdition(k) => write!(f, "rumor kind {k} is not a control edition"),
            ControlError::NotPlaintextSealed => write!(f, "control edition must ride a plaintext seal"),
            ControlError::OverCap(what) => write!(f, "{what} exceeds its byte cap"),
        }
    }
}

impl std::error::Error for ControlError {}

impl From<StreamError> for ControlError {
    fn from(e: StreamError) -> Self {
        ControlError::Stream(e)
    }
}

// ── Identity ─────────────────────────────────────────────────────────────────

/// A v2 community's self-certifying identity triple. The id IS the owner
/// commitment — carry all three together and verify before trusting any claim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommunityIdentity {
    pub community_id: CommunityId,
    pub owner_xonly: [u8; 32],
    pub owner_salt: [u8; 32],
}

impl CommunityIdentity {
    /// Mint a fresh identity for `owner` (a new random salt ⇒ a new community).
    pub fn mint(owner: &PublicKey) -> CommunityIdentity {
        let owner_xonly = owner.to_bytes();
        let owner_salt = super::super::random_32();
        CommunityIdentity {
            community_id: super::derive::community_id_of(&owner_xonly, &owner_salt),
            owner_xonly,
            owner_salt,
        }
    }

    /// True iff the commitment reproduces the id — the ONLY valid owner proof.
    pub fn verify(&self) -> bool {
        verify_community_id(&self.community_id, &self.owner_xonly, &self.owner_salt)
    }

    /// The proven owner as a `PublicKey` (call only after [`Self::verify`]).
    pub fn owner(&self) -> Result<PublicKey, String> {
        PublicKey::from_slice(&self.owner_xonly).map_err(|e| e.to_string())
    }
}

// ── Edition rumors (build + parse) ───────────────────────────────────────────

/// Build the unsigned kind-3308 edition rumor — v1's grammar minus the protocol
/// `v` tag. Control editions carry no `ms` tag: they fold by version, not time.
#[allow(clippy::too_many_arguments)]
pub fn build_edition_rumor(
    author: PublicKey,
    vsk: &str,
    entity_id: &[u8; 32],
    version: u64,
    prev_hash: Option<&[u8; 32]>,
    content: &str,
    created_at_secs: u64,
    authority: Option<&AuthorityCitation>,
) -> UnsignedEvent {
    let mut tags = vec![
        Tag::custom(TAG_SUBKIND, [vsk.to_string()]),
        Tag::custom(TAG_ENTITY, [crate::simd::hex::bytes_to_hex_32(entity_id)]),
        Tag::custom(TAG_EVERSION, [version.to_string()]),
    ];
    if let Some(p) = prev_hash {
        tags.push(Tag::custom(TAG_EPREV, [crate::simd::hex::bytes_to_hex_32(p)]));
    }
    if let Some(a) = authority {
        tags.push(a.to_tag());
    }
    stream::build_rumor_secs(kind::CONTROL, author, content, tags, created_at_secs)
}

/// Parse an edition from an ALREADY-VERIFIED rumor (one produced by
/// [`stream::open_wrap`], which proved the seal signature, the author binding,
/// and the rumor id). No signature lives on the rumor itself — never feed this
/// a rumor that didn't come through the stream verifier.
pub fn parse_edition_rumor(rumor: &UnsignedEvent) -> Result<ParsedEdition, ControlError> {
    if rumor.kind.as_u16() != kind::CONTROL {
        return Err(ControlError::NotAnEdition(rumor.kind.as_u16()));
    }
    // Duplicate machinery tags make signed-bytes → canonical-fields ambiguous
    // (two clients could pick different duplicates and fork on self_hash).
    for name in [TAG_SUBKIND, TAG_ENTITY, TAG_EVERSION, TAG_EPREV, TAG_AUTHORITY_CITATION] {
        let count = rumor
            .tags
            .iter()
            .filter(|t| t.as_slice().first().map(|s| s.as_str() == name).unwrap_or(false))
            .count();
        if count > 1 {
            return Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")));
        }
    }
    let get = |name: &str| -> Option<String> {
        rumor.tags.iter().find_map(|t| {
            let s = t.as_slice();
            (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
        })
    };
    let decode_hash = |hex: &str, field: &'static str| -> Result<[u8; 32], ControlError> {
        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Err(ControlError::Edition(EditionError::BadField(field)));
        }
        Ok(crate::simd::hex::hex_to_bytes_32(hex))
    };
    let vsk = get(TAG_SUBKIND).ok_or(ControlError::Edition(EditionError::MissingField("vsk")))?;
    let entity_id = decode_hash(&get(TAG_ENTITY).ok_or(ControlError::Edition(EditionError::MissingField("eid")))?, "eid")?;
    // Decimal, no leading zeros (CORD-01 Encoding): `u64::from_str` accepts a leading
    // `+`, and "007"/"7" are distinct signed rumors that fold to the same version — a
    // same-version convergence fork a strict peer (which drops the padded form)
    // resolves differently. Reject any non-canonical decimal, matching the `ms` rule.
    let ev_raw = get(TAG_EVERSION).ok_or(ControlError::Edition(EditionError::MissingField("ev")))?;
    if !crate::community::edition::is_tag_decimal(&ev_raw) {
        return Err(ControlError::Edition(EditionError::BadField("ev")));
    }
    let version: u64 = ev_raw.parse().map_err(|_| ControlError::Edition(EditionError::BadField("ev")))?;
    let prev_hash = match get(TAG_EPREV) {
        Some(h) => Some(decode_hash(&h, "ep")?),
        None => None,
    };
    let self_hash = version::edition_hash(&entity_id, version, prev_hash.as_ref(), rumor.content.as_bytes());
    Ok(ParsedEdition {
        author: rumor.pubkey,
        vsk,
        entity_id,
        version,
        prev_hash,
        content: rumor.content.clone(),
        self_hash,
        created_at: rumor.created_at.as_secs(),
        inner_id: rumor.id.expect("verified rumors carry their id").to_bytes(),
        authority: AuthorityCitation::from_tags(&rumor.tags),
    })
}

// ── The Control Plane view (CORD-02 §2/§5) ───────────────────────────────────

/// The Control Plane as this member holds it for one epoch.
///
/// A SPLIT epoch (the community carries a held `control_pk`) subscribes and
/// verifies by that address while decrypting under the community_root-derived
/// read key; its signer is present only when this member holds the epoch's
/// `control_root` AND it derives to the held address (staff, fail-closed on a
/// corrupt secret). A LEGACY epoch is the `concord/control` derivation whole —
/// address, signer, and encryption in one key every member holds.
#[derive(Clone)]
pub struct ControlPlane {
    pk: PublicKey,
    conv_key: ConversationKey,
    signer: Option<Keys>,
    restricted: bool,
}

impl ControlPlane {
    /// The CURRENT epoch's view of `community`'s Control Plane.
    pub fn of(community: &super::community::CommunityV2) -> ControlPlane {
        let read = control_group_key(&community.community_root, community.id(), community.root_epoch);
        match community.control_pk {
            None => ControlPlane {
                pk: read.pk(),
                conv_key: read.conv_key().clone(),
                signer: Some(read.keys().clone()),
                restricted: false,
            },
            Some(pk) => {
                // A held secret that does not derive to the held address is
                // corrupt state, not a signer: fail closed to read-only rather
                // than mint wraps at an address nobody subscribes to.
                let signer = community.control_root.and_then(|cr| {
                    let s = control_signer_group_key(&cr, community.id(), community.root_epoch);
                    (s.pk() == pk).then(|| s.keys().clone())
                });
                ControlPlane { pk, conv_key: read.conv_key().clone(), signer, restricted: true }
            }
        }
    }

    /// A whole legacy plane view from its single group key (tests, migrations).
    pub fn legacy(group: &GroupKey) -> ControlPlane {
        ControlPlane {
            pk: group.pk(),
            conv_key: group.conv_key().clone(),
            signer: Some(group.keys().clone()),
            restricted: false,
        }
    }

    /// The plane address — what `authors` filters and wrap-author checks match.
    pub fn pk(&self) -> PublicKey {
        self.pk
    }

    pub fn pk_hex(&self) -> String {
        self.pk.to_hex()
    }

    /// Whether this member can PUBLISH to the plane (CORD-02 §2).
    pub fn can_write(&self) -> bool {
        self.signer.is_some()
    }

    /// The signer Keys when held (NIP-42 auth as the plane, staff only on a
    /// split epoch).
    pub fn signer_keys(&self) -> Option<&Keys> {
        self.signer.as_ref()
    }

    /// The WRITE group: address, signing secret, and read conv_key composed for
    /// the seal/wrap builders. Errs when the epoch is split and this member does
    /// not hold its `control_root` — publishing there would mint a wrap that
    /// fails the plane's signature check at every reader and relay.
    pub fn write_group(&self) -> Result<GroupKey, String> {
        match &self.signer {
            Some(keys) => Ok(GroupKey::from_parts(keys.clone(), self.conv_key.clone())),
            None => Err("only community staff hold this community's write key; ask an admin to re-send your promotion".to_string()),
        }
    }

    /// Open a control wrap under this view — [`open_control_edition`] with the
    /// split's mandatory wrap-signature check on a restricted plane (CORD-01
    /// Write-Restricted Streams: the signature IS the write gate there).
    pub fn open(&self, wrap: &Event) -> Result<(ParsedEdition, OpenedStream), ControlError> {
        let opened = stream::open_wrap_at(wrap, &self.pk, &self.conv_key, self.restricted)?;
        if opened.seal_form != SealForm::Plaintext {
            return Err(ControlError::NotPlaintextSealed);
        }
        let edition = parse_edition_rumor(&opened.rumor)?;
        Ok((edition, opened))
    }
}

impl std::fmt::Debug for ControlPlane {
    // No key material in logs — address only.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ControlPlane")
            .field("pk", &self.pk_hex())
            .field("restricted", &self.restricted)
            .field("writable", &self.can_write())
            .finish()
    }
}

/// The SPLIT write group for a freshly minted epoch (genesis / a Refounding's
/// new plane): the `control_root`-derived signer with the `community_root`-
/// derived read key (CORD-02 §5).
pub fn split_write_group(control_root: &[u8; 32], community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
    let signer = control_signer_group_key(control_root, community_id, epoch);
    let read = control_group_key(community_root, community_id, epoch);
    GroupKey::from_parts(signer.keys().clone(), read.conv_key().clone())
}

// ── Seal / open over the stream ──────────────────────────────────────────────

/// Seal a signed-by-`author_keys` edition rumor into a control-plane wrap.
/// Local-keys convenience; bunker accounts use [`stream::seal_content`] +
/// their remote signer + [`stream::wrap_seal`] for identical wire output.
pub fn seal_control_edition(
    rumor: &UnsignedEvent,
    group: &GroupKey,
    author_keys: &Keys,
    wrap_at: Timestamp,
) -> Result<(Event, Keys), ControlError> {
    let seal = stream::build_seal(rumor, SealForm::Plaintext, group, author_keys)?;
    Ok(stream::wrap_seal(&seal, group, stream::KIND_WRAP, wrap_at)?)
}

/// Signer-driven twin of [`seal_control_edition`] for bunker / NIP-55 accounts:
/// the plaintext seal signs through a [`VectorSigner`]. `author` is the identity
/// the signer signs as (must equal `my_public_key()`). Wire-identical output.
pub async fn seal_control_edition_signed<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    author: PublicKey,
    rumor: &UnsignedEvent,
    group: &GroupKey,
    wrap_at: Timestamp,
) -> Result<(Event, Keys), ControlError> {
    Ok(stream::seal_and_wrap_signed(signer, author, rumor, SealForm::Plaintext, group, stream::KIND_WRAP, wrap_at, &[]).await?)
}

/// Open a control-plane wrap into a verified, parsed edition. Strict on both
/// gates: the rumor must be kind 3308, and the seal must be the plaintext form.
pub fn open_control_edition(wrap: &Event, group: &GroupKey) -> Result<(ParsedEdition, OpenedStream), ControlError> {
    let opened = stream::open_wrap(wrap, group)?;
    if opened.seal_form != SealForm::Plaintext {
        return Err(ControlError::NotPlaintextSealed);
    }
    let edition = parse_edition_rumor(&opened.rumor)?;
    Ok((edition, opened))
}

// ── Entity payloads (vsk 0 / vsk 2) ──────────────────────────────────────────

/// An encrypted-blob image pointer (icon/banner): the media server sees only an
/// opaque blob; members fetch, decrypt with `key`/`nonce`, and verify `hash`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageRef {
    pub url: String,
    pub key: String,
    pub nonce: String,
    pub hash: String,
    /// Unknown fields round-trip (e.g. Vector's `ext`) — editors MUST preserve
    /// what they don't understand (CORD-02 §6).
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl ImageRef {
    /// Bridge to the v1 image-ref shape so the shared download/decrypt/cache
    /// plumbing serves both protocols. `ext` rides the flattened extras; fall
    /// back to the URL's extension, else png.
    pub fn to_community_image(&self) -> crate::community::CommunityImage {
        let ext = self
            .extra
            .get("ext")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .or_else(|| {
                std::path::Path::new(&self.url)
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|s| s.to_lowercase())
            })
            .unwrap_or_else(|| "png".to_string());
        crate::community::CommunityImage {
            url: self.url.clone(),
            key: self.key.clone(),
            nonce: self.nonce.clone(),
            hash: self.hash.clone(),
            ext,
        }
    }
}

/// Community metadata — the vsk-0 entity content (CORD-02 §6). `eid` = the
/// community_id itself; gated by `MANAGE_METADATA`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CommunityMetadata {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relays: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<ImageRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub banner: Option<ImageRef>,
    /// Client-extensible opaque object; folds atomically with the entity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
    /// Reserved-for-protocol unknown top-level fields, round-tripped verbatim.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Channel metadata — the vsk-2 entity content (CORD-03 §2). `eid` = the
/// channel_id; gated by `MANAGE_CHANNELS`. Absent flags mean false; deletion is
/// terminal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ChannelMetadata {
    pub name: String,
    pub private: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Enforce the protocol byte caps before an edition is built (a strict reader
/// may drop over-cap state; never publish what peers would refuse).
pub fn validate_community_metadata(meta: &CommunityMetadata) -> Result<(), ControlError> {
    if meta.name.len() > MAX_NAME_BYTES {
        return Err(ControlError::OverCap("name"));
    }
    if meta.description.as_ref().is_some_and(|d| d.len() > MAX_DESCRIPTION_BYTES) {
        return Err(ControlError::OverCap("description"));
    }
    Ok(())
}

pub fn validate_channel_metadata(meta: &ChannelMetadata) -> Result<(), ControlError> {
    if meta.name.len() > MAX_NAME_BYTES {
        return Err(ControlError::OverCap("name"));
    }
    Ok(())
}

// ── Genesis (CORD-02 §1) ─────────────────────────────────────────────────────

/// The two wraps of a community genesis — exactly two owner-signed editions:
/// the community metadata (vsk 0) and one public `#general` channel (vsk 2).
/// Nothing more — no default roles, no scaffolding.
pub struct Genesis {
    pub identity: CommunityIdentity,
    /// The community_root minted for epoch 0.
    pub community_root: [u8; 32],
    /// The staff write key minted beside it (CORD-02 §2) — held by the owner
    /// alone until staff are promoted. Its derived pk is the plane's address.
    pub control_root: [u8; 32],
    pub general_channel_id: ChannelId,
    /// `[metadata wrap, #general wrap]`, both sealed at the epoch-0 control_pk.
    pub wraps: [Event; 2],
}

impl Genesis {
    /// The epoch-0 Control Plane address the split minted (CORD-02 §5).
    pub fn control_pk(&self) -> PublicKey {
        control_signer_group_key(&self.control_root, &self.identity.community_id, Epoch(0)).pk()
    }
}

/// Mint a v2 community: fresh identity (salt-committed to the owner), fresh
/// community_root + control_root (the split, CORD-02 §2), and the two genesis
/// editions sealed at the epoch-0 control plane — signed by the control_root-
/// derived signer, readable under the community_root-derived read key. The
/// caller persists the secrets and publishes the wraps.
pub fn genesis(owner_keys: &Keys, mut metadata: CommunityMetadata, at_secs: u64) -> Result<Genesis, ControlError> {
    validate_community_metadata(&metadata)?;
    // Relays ride the metadata entity so they can evolve by edit; cap on write.
    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);

    let identity = CommunityIdentity::mint(&owner_keys.public_key());
    let community_root = super::super::random_32();
    let control_root = super::super::random_32();
    let general_channel_id = ChannelId(super::super::random_32());
    let group = split_write_group(&control_root, &community_root, &identity.community_id, Epoch(0));

    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
    let meta_rumor = build_edition_rumor(
        owner_keys.public_key(),
        vsk::COMMUNITY_METADATA,
        &identity.community_id.0,
        1,
        None,
        &meta_json,
        at_secs,
        None,
    );

    let general = ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
    let general_rumor = build_edition_rumor(
        owner_keys.public_key(),
        vsk::CHANNEL_METADATA,
        &general_channel_id.0,
        1,
        None,
        &general_json,
        at_secs,
        None,
    );

    let (meta_wrap, _) = seal_control_edition(&meta_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;
    let (general_wrap, _) = seal_control_edition(&general_rumor, &group, owner_keys, Timestamp::from_secs(at_secs))?;

    Ok(Genesis {
        identity,
        community_root,
        control_root,
        general_channel_id,
        wraps: [meta_wrap, general_wrap],
    })
}

/// Signer-driven twin of [`genesis`] for bunker / NIP-55 accounts: mints from the
/// owner's public key and seals the two genesis editions through a [`VectorSigner`].
/// `owner_pk` must equal `my_public_key()` (the identity the signer signs as).
pub async fn genesis_signed<S: crate::signer::VectorSigner + ?Sized>(
    owner_pk: PublicKey,
    signer: &S,
    metadata: CommunityMetadata,
    at_secs: u64,
) -> Result<Genesis, ControlError> {
    genesis_signed_with_primary(owner_pk, signer, metadata, at_secs, None).await
}

/// [`genesis_signed`] with an OPTIONAL explicit primary-channel id + name — the
/// migration-only path (§migration) so the v2 twin's #general reuses the v1 primary
/// channel id and history stitches through the flip. `None` mints a fresh id (the
/// ordinary create path).
pub async fn genesis_signed_with_primary<S: crate::signer::VectorSigner + ?Sized>(
    owner_pk: PublicKey,
    signer: &S,
    mut metadata: CommunityMetadata,
    at_secs: u64,
    primary: Option<(ChannelId, String)>,
) -> Result<Genesis, ControlError> {
    validate_community_metadata(&metadata)?;
    metadata.relays.truncate(super::super::MAX_COMMUNITY_RELAYS);

    let identity = CommunityIdentity::mint(&owner_pk);
    let community_root = super::super::random_32();
    let control_root = super::super::random_32();
    let (general_channel_id, general_name) = match primary {
        Some((id, name)) => (id, name),
        None => (ChannelId(super::super::random_32()), "general".to_string()),
    };
    let group = split_write_group(&control_root, &community_root, &identity.community_id, Epoch(0));

    let meta_json = serde_json::to_string(&metadata).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
    let meta_rumor = build_edition_rumor(owner_pk, vsk::COMMUNITY_METADATA, &identity.community_id.0, 1, None, &meta_json, at_secs, None);

    let general = ChannelMetadata { name: general_name, private: false, ..Default::default() };
    let general_json = serde_json::to_string(&general).map_err(|e| ControlError::Stream(StreamError::Parse(e.to_string())))?;
    let general_rumor = build_edition_rumor(owner_pk, vsk::CHANNEL_METADATA, &general_channel_id.0, 1, None, &general_json, at_secs, None);

    let (meta_wrap, _) = seal_control_edition_signed(signer, owner_pk, &meta_rumor, &group, Timestamp::from_secs(at_secs)).await?;
    let (general_wrap, _) = seal_control_edition_signed(signer, owner_pk, &general_rumor, &group, Timestamp::from_secs(at_secs)).await?;

    Ok(Genesis {
        identity,
        community_root,
        control_root,
        general_channel_id,
        wraps: [meta_wrap, general_wrap],
    })
}

#[cfg(test)]
mod tests {
    use nostr_sdk::prelude::FinalizeEvent;
    use super::super::super::edition::build_edition_inner;
    use super::*;

    fn cid() -> CommunityId {
        CommunityId([0x33; 32])
    }

    fn group_at(epoch: u64) -> GroupKey {
        control_group_key(&[0x44; 32], &cid(), Epoch(epoch))
    }

    fn simple_edition(author: &Keys, version: u64, prev: Option<&[u8; 32]>) -> UnsignedEvent {
        build_edition_rumor(
            author.public_key(),
            vsk::GRANT,
            &[0x55; 32],
            version,
            prev,
            "{\"member\":\"aa\",\"role_ids\":[]}",
            1_700_000_000,
            None,
        )
    }

    #[test]
    fn edition_round_trips_through_the_control_plane() {
        let owner = Keys::generate();
        let group = group_at(0);
        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
        let rumor = build_edition_rumor(
            owner.public_key(),
            vsk::GRANT,
            &[0x55; 32],
            2,
            Some(&[0x66; 32]),
            "{\"member\":\"aa\",\"role_ids\":[]}",
            1_700_000_000,
            Some(&cite),
        );
        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_700_000_001)).unwrap();

        let (edition, opened) = open_control_edition(&wrap, &group).unwrap();
        assert_eq!(edition.author, owner.public_key());
        assert_eq!(edition.vsk, vsk::GRANT);
        assert_eq!(edition.entity_id, [0x55; 32]);
        assert_eq!(edition.version, 2);
        assert_eq!(edition.prev_hash, Some([0x66; 32]));
        assert_eq!(edition.authority.as_ref(), Some(&cite));
        assert_eq!(opened.seal_form, SealForm::Plaintext);
        // self_hash matches the canonical recomputation.
        assert_eq!(
            edition.self_hash,
            version::edition_hash(&[0x55; 32], 2, Some(&[0x66; 32]), rumor.content.as_bytes())
        );
    }

    #[test]
    fn v2_edition_tags_carry_no_protocol_version_tag() {
        // FROZEN: the v2 tag set is exactly vsk/eid/ev(+ep/vac) — a `v` tag is
        // the rejected versioning mechanism (address partitioning does the job).
        let owner = Keys::generate();
        let rumor = simple_edition(&owner, 1, None);
        assert!(
            !rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "v").unwrap_or(false)),
            "v2 editions must not carry a protocol version tag"
        );
        // And no ms tag — editions fold by version, not time.
        assert!(!rumor.tags.iter().any(|t| t.as_slice().first().map(|s| s == "ms").unwrap_or(false)));
    }

    #[test]
    fn edition_hash_is_identical_across_protocols() {
        // The edition hash is the ONE construction both protocols share (upstream
        // froze v1's byte layout, label included). The same logical edition must
        // hash identically whether built as a v1 signed inner or a v2 rumor —
        // this is what makes the fold engine shareable.
        let author = Keys::generate();
        let entity = [0x55; 32];
        let content = "{\"member\":\"aa\",\"role_ids\":[]}";
        let v1_inner = build_edition_inner(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None)
            .finalize(&author)
            .unwrap();
        let v1_parsed = super::super::super::edition::parse_edition_inner(&v1_inner).unwrap();

        let v2_rumor = build_edition_rumor(author.public_key(), "3", &entity, 2, Some(&[0x66; 32]), content, 100, None);
        let v2_parsed = parse_edition_rumor(&v2_rumor).unwrap();

        assert_eq!(v1_parsed.self_hash, v2_parsed.self_hash);
    }

    #[test]
    fn encrypted_seal_control_edition_is_rejected() {
        let owner = Keys::generate();
        let group = group_at(0);
        let rumor = simple_edition(&owner, 1, None);
        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &owner).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotPlaintextSealed)));
    }

    #[test]
    fn non_edition_rumor_is_rejected() {
        let owner = Keys::generate();
        let group = group_at(0);
        let rumor = stream::build_rumor_secs(super::kind::MESSAGE, owner.public_key(), "hi", vec![], 100);
        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &owner).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
        assert!(matches!(open_control_edition(&wrap, &group), Err(ControlError::NotAnEdition(k)) if k == super::kind::MESSAGE));
    }

    #[test]
    fn duplicate_machinery_tags_are_rejected() {
        let owner = Keys::generate();
        let mut rumor = simple_edition(&owner, 1, None);
        let dup = Tag::custom("eid", [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]);
        let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
        tags.push(dup);
        rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), &rumor.content, tags, 100);
        assert!(matches!(
            parse_edition_rumor(&rumor),
            Err(ControlError::Edition(EditionError::BadField("duplicate authority tag")))
        ));
    }

    #[test]
    fn a_non_canonical_ev_version_is_rejected() {
        let owner = Keys::generate();
        // A leading-zero (or `+`-prefixed) version is a distinct rumor that folds to
        // the same numeric version — a same-version fork a strict peer drops.
        for bad in ["007", "+5", "01"] {
            let tags = vec![
                Tag::custom("vsk", [vsk::GRANT]),
                Tag::custom("eid", [crate::simd::hex::bytes_to_hex_32(&[0x55; 32])]),
                Tag::custom("ev", [bad]),
            ];
            let rumor = stream::build_rumor_secs(kind::CONTROL, owner.public_key(), "{\"member\":\"aa\",\"role_ids\":[]}", tags, 100);
            assert!(
                matches!(parse_edition_rumor(&rumor), Err(ControlError::Edition(EditionError::BadField("ev")))),
                "a non-canonical ev {bad:?} is rejected"
            );
        }
    }

    #[test]
    fn compaction_rewrap_preserves_the_edition_chain_identity() {
        // The whole reason control seals are plaintext: carry a signed head into
        // a new epoch and its self_hash + authorship must be untouched, so a
        // fresh joiner folds the same chain the old epoch held.
        let owner = Keys::generate();
        let e0 = group_at(0);
        let rumor = simple_edition(&owner, 3, Some(&[0x77; 32]));
        let (wrap, _) = seal_control_edition(&rumor, &e0, &owner, Timestamp::from_secs(10)).unwrap();
        let (edition, opened) = open_control_edition(&wrap, &e0).unwrap();

        let e1 = group_at(1);
        let (rewrapped, _) = stream::rewrap_seal(&opened.seal, &e1, Timestamp::from_secs(20)).unwrap();
        let (re_edition, _) = open_control_edition(&rewrapped, &e1).unwrap();

        assert_eq!(re_edition.self_hash, edition.self_hash);
        assert_eq!(re_edition.author, edition.author);
        assert_eq!(re_edition.inner_id, edition.inner_id, "rumor id survives compaction");
    }

    #[test]
    fn editions_opened_from_wraps_fold_to_the_head() {
        let owner = Keys::generate();
        let group = group_at(0);
        let entity = [0x55; 32];
        let content = |v: u64| format!("{{\"v\":{v}}}");

        // Build a 3-link chain v1 → v2 → v3.
        let mut prev: Option<[u8; 32]> = None;
        let mut parsed = Vec::new();
        for v in 1..=3u64 {
            let rumor = build_edition_rumor(owner.public_key(), vsk::GRANT, &entity, v, prev.as_ref(), &content(v), 100 + v, None);
            let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(100 + v)).unwrap();
            let (edition, _) = open_control_edition(&wrap, &group).unwrap();
            prev = Some(edition.self_hash);
            parsed.push(edition);
        }

        let fold_editions: Vec<version::Edition> = parsed.iter().map(|p| p.to_fold_edition()).collect();
        let folded = version::fold(&fold_editions, 0, None);
        assert_eq!(fold_editions[folded.head.expect("chain folds")].version, 3);
        assert!(!folded.gap);

        // Withhold the middle link: the chain gaps at v1 (fail-closed signal).
        let partial = [fold_editions[0].clone(), fold_editions[2].clone()];
        let gapped = version::fold(&partial, 0, None);
        assert_eq!(partial[gapped.head.expect("genesis edition anchors")].version, 1);
        assert!(gapped.gap, "a missing middle version is a gap, not a silent skip");
    }

    #[test]
    fn genesis_mints_a_verifiable_two_edition_community() {
        let owner = Keys::generate();
        let meta = CommunityMetadata {
            name: "Vector".into(),
            description: Some("Private messaging, no compromises.".into()),
            relays: vec!["wss://jskitty.com/nostr".into()],
            ..Default::default()
        };
        let g = genesis(&owner, meta, 1_700_000_000).unwrap();

        // The identity self-certifies and names the owner.
        assert!(g.identity.verify());
        assert_eq!(g.identity.owner().unwrap(), owner.public_key());

        // Exactly two editions, both owner-signed, both openable at epoch 0 —
        // at the SPLIT address (the control_root-derived signer, CORD-02 §2).
        let group = split_write_group(&g.control_root, &g.community_root, &g.identity.community_id, Epoch(0));
        assert_eq!(group.pk(), g.control_pk(), "the plane address is the signer's pk");
        assert_ne!(group.pk(), control_group_key(&g.community_root, &g.identity.community_id, Epoch(0)).pk(), "never the legacy address");
        let (meta_ed, _) = open_control_edition(&g.wraps[0], &group).unwrap();
        let (chan_ed, _) = open_control_edition(&g.wraps[1], &group).unwrap();
        assert_eq!(meta_ed.author, owner.public_key());
        assert_eq!(chan_ed.author, owner.public_key());
        assert_eq!(meta_ed.vsk, vsk::COMMUNITY_METADATA);
        assert_eq!(chan_ed.vsk, vsk::CHANNEL_METADATA);
        // Metadata's coordinate IS the community id; the channel's its channel id.
        assert_eq!(meta_ed.entity_id, g.identity.community_id.0);
        assert_eq!(chan_ed.entity_id, g.general_channel_id.0);
        // Both are genesis editions: version 1, no prev, no citation (owner is supreme).
        for e in [&meta_ed, &chan_ed] {
            assert_eq!(e.version, 1);
            assert_eq!(e.prev_hash, None);
            assert_eq!(e.authority, None);
        }
        let general: ChannelMetadata = serde_json::from_str(&chan_ed.content).unwrap();
        assert_eq!(general.name, "general");
        assert!(!general.private);
    }

    #[test]
    fn a_member_view_reads_the_split_plane_but_cannot_write_and_a_bad_wrap_sig_is_refused() {
        // CORD-01 Write-Restricted Streams / CORD-02 §2: every member holds the
        // address + read key; only a control_root holder can mint a wrap that
        // verifies there — and on a restricted view the wrap signature is the
        // write gate, so the reader MUST check it.
        let owner = Keys::generate();
        let g = genesis(&owner, CommunityMetadata { name: "Gate".into(), ..Default::default() }, 1_000).unwrap();
        let mut member = super::super::community::CommunityV2::from_genesis(&g, "Gate", None, vec![], 0);
        member.control_root = None; // a member holds the address, never the secret
        let view = ControlPlane::of(&member);
        assert!(!view.can_write());
        let err = view.write_group().unwrap_err();
        assert!(err.contains("staff"), "a readable refusal, not a panic: {err}");

        // The member READS a staff wrap fine…
        let (ed, _) = view.open(&g.wraps[0]).unwrap();
        assert_eq!(ed.author, owner.public_key());

        // …and a corrupt secret fails closed to the same read-only view.
        member.control_root = Some([0x77u8; 32]);
        assert!(!ControlPlane::of(&member).can_write(), "a non-deriving secret is corrupt state, not a signer");

        // A wrap whose signature doesn't verify is refused on the restricted
        // view — the best a read-key holder can do is claim the address with a
        // signature that cannot check out.
        let mut json: serde_json::Value = serde_json::from_str(&g.wraps[0].as_json()).unwrap();
        json["sig"] = serde_json::Value::String("aa".repeat(64));
        let tampered = Event::from_json(json.to_string()).unwrap();
        member.control_root = None;
        assert!(
            matches!(ControlPlane::of(&member).open(&tampered), Err(ControlError::Stream(StreamError::BadWrapSignature))),
            "the wrap signature IS the write gate on a restricted stream"
        );
    }

    #[test]
    fn a_forged_identity_fails_the_commitment() {
        let owner = Keys::generate();
        let attacker = Keys::generate();
        let real = CommunityIdentity::mint(&owner.public_key());
        // An attacker claiming the real community id with their own key + any salt
        // needs a second preimage — verify() must fail.
        let forged = CommunityIdentity {
            community_id: real.community_id,
            owner_xonly: attacker.public_key().to_bytes(),
            owner_salt: real.owner_salt,
        };
        assert!(!forged.verify());
    }

    #[test]
    fn metadata_caps_and_unknown_field_round_trip() {
        let over_name = CommunityMetadata { name: "x".repeat(MAX_NAME_BYTES + 1), ..Default::default() };
        assert!(matches!(validate_community_metadata(&over_name), Err(ControlError::OverCap("name"))));
        let over_desc = CommunityMetadata {
            name: "ok".into(),
            description: Some("d".repeat(MAX_DESCRIPTION_BYTES + 1)),
            ..Default::default()
        };
        assert!(matches!(validate_community_metadata(&over_desc), Err(ControlError::OverCap("description"))));
        // The cap is BYTES, not chars: 22 three-byte chars = 66 bytes > 64.
        let multibyte = ChannelMetadata { name: "".repeat(22), private: false, ..Default::default() };
        assert!(matches!(validate_channel_metadata(&multibyte), Err(ControlError::OverCap("name"))));

        // Round-trip discipline: unknown top-level fields, unknown icon fields,
        // and the custom object all survive a parse → serialize cycle.
        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]}}"#;
        let parsed: CommunityMetadata = serde_json::from_str(wire).unwrap();
        let out = serde_json::to_string(&parsed).unwrap();
        let reparsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(reparsed["future_field"]["deep"][1], 2);
        assert_eq!(reparsed["icon"]["ext"], "png");
        assert_eq!(reparsed["custom"]["rules"], "Be excellent.");
    }
}