vector-core 0.13.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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
//! The v2 Control Plane (CORD-04 over CORD-01/02).
//!
//! Editions use the `vsk/eid/ev/ep/vac` tags, the frozen `edition_hash`
//! (`community::version`, label `vector-community/v1/edition`, which upstream froze
//! verbatim), and the shared fold rules, riding the stream envelope: a kind-3308
//! UNSIGNED rumor inside a **plaintext seal** (20014) at `control_pk`. Authorship is
//! the seal's signature: [`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 deliberate wire choices:
//!   - 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";
/// Marks an edition whose hash covers its signer (CORD-04 §1); the only value is "2".
const TAG_EHASH: &str = "eh";
/// A marked edition's Community binding (CORD-02): `community_binding(community_id)`.
const TAG_EBIND: &str = "eb";

/// 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 (no 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 {
    build_edition_rumor_bound(author, vsk, entity_id, version, prev_hash, content, created_at_secs, authority, None)
}

/// [`build_edition_rumor`], marked and bound to a Community (`binding`) when one is given:
/// what every edition of a Community on Roles v2 carries.
#[allow(clippy::too_many_arguments)]
pub fn build_edition_rumor_bound(
    author: PublicKey,
    vsk: &str,
    entity_id: &[u8; 32],
    version: u64,
    prev_hash: Option<&[u8; 32]>,
    content: &str,
    created_at_secs: u64,
    authority: Option<&AuthorityCitation>,
    binding: Option<[u8; 32]>,
) -> 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());
    }
    if let Some(b) = binding {
        tags.push(Tag::custom(TAG_EHASH, ["2".to_string()]));
        tags.push(Tag::custom(TAG_EBIND, [crate::simd::hex::bytes_to_hex_32(&b)]));
    }
    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, TAG_EHASH, TAG_EBIND] {
        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,
    };
    // A marked edition is bound to its Community and its hash covers its signer; anything
    // else in the marker is a form this reader doesn't know, and refused.
    let binding = match get(TAG_EHASH) {
        None => None,
        Some(v) if v == "2" => Some(decode_hash(&get(TAG_EBIND).ok_or(ControlError::Edition(EditionError::MissingField("eb")))?, "eb")?),
        Some(_) => return Err(ControlError::Edition(EditionError::BadField("eh"))),
    };
    let self_hash = match binding {
        Some(_) => version::edition_hash_signed(&entity_id, version, prev_hash.as_ref(), rumor.content.as_bytes(), &rumor.pubkey.to_bytes()),
        None => 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),
        binding,
    })
}

// ── 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,
    /// What a marked edition here must be bound to (`None`: a bare group view, unchecked).
    binding: Option<[u8; 32]>,
}

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(),
                signer: Some(read.keys().clone()),
                restricted: false,
                binding: Some(super::derive::edition_binding(community.id())),
            },
            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(), signer, restricted: true, binding: Some(super::derive::edition_binding(community.id())) }
            }
        }
    }

    /// 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(),
            signer: Some(group.keys().clone()),
            restricted: false,
            binding: None,
        }
    }

    /// 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)),
            None => Err("only community staff hold this community's write key; ask an admin to re-send your promotion".to_string()),
        }
    }

    /// Check a page's signatures together before it is opened (see
    /// [`stream::check_signatures_together`]); hold the guard across the page's opens. A wrap
    /// this view already opened is left out: its open needs no signature.
    pub fn check_page(&self, wraps: &[&Event]) -> stream::BatchChecked {
        let page: Vec<_> = {
            let memo = opened_memo();
            let memo = memo.lock().unwrap_or_else(|e| e.into_inner());
            wraps.iter().filter(|w| !memo.contains(&self.opened_key(w))).map(|w| (*w, vec![&self.conv_key], self.restricted)).collect()
        };
        stream::check_signatures_together(&page)
    }

    /// This view, by what an open here depends on: its address, read key and restriction.
    /// Hashed, so no key sits where it is stored.
    pub(crate) fn view_id(&self) -> [u8; 32] {
        let mut h = crate::crypto::sha256::Sha256::new();
        h.update(b"concord/control-store");
        h.update(self.pk.to_bytes());
        h.update(self.conv_key.as_bytes());
        h.update([self.restricted as u8]);
        h.finalize()
    }

    /// What this view's open of `wrap` is memoized under: an open is a pure function of the
    /// wrap, which its id and signature pin (the id leaves the signature out), and of the view's
    /// address, read key and restriction. Hashed, so no key sits in the map.
    fn opened_key(&self, wrap: &Event) -> [u8; 32] {
        let mut h = crate::crypto::sha256::Sha256::new();
        h.update(b"concord/opened-control-wrap");
        h.update(wrap.id.as_bytes());
        h.update(wrap.sig.as_bytes());
        h.update(self.pk.to_bytes());
        h.update(self.conv_key.as_bytes());
        h.update([self.restricted as u8]);
        h.finalize()
    }

    /// 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 = self.opened(wrap)?;
        Ok((opened.0.clone(), opened.1.clone()))
    }

    /// [`Self::open`] for a reader that needs only the edition.
    pub fn open_edition(&self, wrap: &Event) -> Result<ParsedEdition, ControlError> {
        Ok(self.opened(wrap)?.0.clone())
    }

    fn opened(&self, wrap: &Event) -> Result<Opened, ControlError> {
        let memo_key = self.opened_key(wrap);
        let memo = opened_memo();
        let hit = memo.lock().unwrap_or_else(|e| e.into_inner()).get(&memo_key);
        let opened = match hit {
            Some(hit) => hit,
            None => {
                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)?;
                let bytes = wrap.content.len() * 2 + edition.content.len() + 512;
                let opened = std::sync::Arc::new((edition, opened));
                memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, opened.clone(), bytes);
                opened
            }
        };
        // A marked edition from another Community, re-wrapped here, is not this Community's.
        if opened.0.binding.is_some_and(|b| self.binding.is_some_and(|mine| mine != b)) {
            return Err(ControlError::Edition(EditionError::BadField("eb")));
        }
        Ok(opened)
    }
}

/// Bytes per generation of the session's [`OpenedMemo`]: a follow re-reads every edition the
/// plane serves, and a large plane runs to a few thousand of them.
const OPENED_MEMO_BYTES: usize = 8 << 20;

type Opened = std::sync::Arc<(ParsedEdition, OpenedStream)>;

/// Control wraps already opened, in two generations: a full `cur` ages into `prev`, and a hit
/// in `prev` moves back, so a working set within the bound never goes cold all at once.
#[derive(Default)]
struct OpenedMemo {
    cur: std::collections::HashMap<[u8; 32], (Opened, usize)>,
    prev: std::collections::HashMap<[u8; 32], (Opened, usize)>,
    cur_bytes: usize,
}

impl OpenedMemo {
    fn contains(&self, key: &[u8; 32]) -> bool {
        self.cur.contains_key(key) || self.prev.contains_key(key)
    }

    fn get(&mut self, key: &[u8; 32]) -> Option<Opened> {
        if let Some((hit, _)) = self.cur.get(key) {
            return Some(hit.clone());
        }
        let (hit, bytes) = self.prev.remove(key)?;
        self.insert(*key, hit.clone(), bytes);
        Some(hit)
    }

    fn insert(&mut self, key: [u8; 32], value: Opened, bytes: usize) {
        if self.cur_bytes + bytes > OPENED_MEMO_BYTES && !self.cur.is_empty() {
            self.prev = std::mem::take(&mut self.cur);
            self.cur_bytes = 0;
        }
        if self.cur.insert(key, (value, bytes)).is_none() {
            self.cur_bytes += bytes;
        }
    }
}

/// The session's [`OpenedMemo`]: an account's opened editions go with its session.
fn opened_memo() -> std::sync::Arc<std::sync::Mutex<OpenedMemo>> {
    struct Key;
    crate::db::current_session().scoped::<Key, std::sync::Mutex<OpenedMemo>>()
}

/// Empty this session's [`OpenedMemo`], so the next opens run whole.
#[cfg(any(test, feature = "bench"))]
pub(crate) fn forget_opened() {
    *opened_memo().lock().unwrap() = OpenedMemo::default();
}

/// Whether this session holds `view`'s open of `wrap`.
#[cfg(test)]
pub(crate) fn opened_held(view: &ControlPlane, wrap: &Event) -> bool {
    opened_memo().lock().unwrap().contains(&view.opened_key(wrap))
}

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())
}

// ── 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`](crate::signer::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 {
    /// Convert to the [`CommunityImage`](crate::community::CommunityImage) shape the
    /// shared download/decrypt/cache plumbing takes. `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(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::community::lenient_image")]
    pub icon: Option<ImageRef>,
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::community::lenient_image")]
    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>,
}

/// A Private Channel's sealed metadata edition (CORD-03 §2): what every member needs to resolve
/// access stays plain; the rest is sealed under the Channel's key at `epoch`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SealedChannelMeta {
    pub epoch: u64,
    pub sealed: String,
    pub deleted: bool,
}

/// The sealed form of a channel edition, `None` for the plain form or a malformed one.
pub fn parse_sealed_channel_meta(content: &str) -> Option<SealedChannelMeta> {
    let serde_json::Value::Object(o) = serde_json::from_str(content).ok()? else { return None };
    let sealed = o.get("sealed")?.as_str()?.to_string();
    let epoch = o.get("epoch")?.as_str()?;
    let canonical = !epoch.is_empty() && epoch.bytes().all(|b| b.is_ascii_digit()) && (epoch == "0" || !epoch.starts_with('0'));
    if !o.get("private")?.as_bool()? || !canonical {
        return None;
    }
    Some(SealedChannelMeta { epoch: epoch.parse().ok()?, sealed, deleted: o.get("deleted").and_then(|d| d.as_bool()).unwrap_or(false) })
}

/// Seal a Private Channel's metadata under its conversation key at `epoch`, naming the edition's
/// predecessor so the seal can't be replayed as a newer edition.
pub fn seal_channel_metadata(meta: &ChannelMetadata, conv_key: &ConversationKey, epoch: u64, prev: Option<&[u8; 32]>) -> Result<String, String> {
    validate_channel_metadata(meta).map_err(|e| e.to_string())?;
    let serde_json::Value::Object(mut inner) = serde_json::to_value(meta).map_err(|e| e.to_string())? else {
        return Err("channel metadata isn't an object".to_string());
    };
    inner.remove("private");
    inner.remove("deleted");
    inner.insert(SEALED_PREV.into(), prev.map(crate::simd::hex::bytes_to_hex_32).into());
    let raw = crate::community::cipher::encrypt_with_random_nonce(conv_key, serde_json::Value::Object(inner).to_string().as_bytes())?;
    let mut out = serde_json::json!({ "private": true, "epoch": epoch.to_string(), "sealed": crate::simd::base64::STANDARD.encode_to_string(&raw) });
    if meta.deleted == Some(true) {
        out["deleted"] = true.into();
    }
    Ok(out.to_string())
}

/// What a seal names as its edition's predecessor.
const SEALED_PREV: &str = "prev";

/// Open sealed channel metadata with the conversation key of its epoch. `prev` is the carrying
/// edition's predecessor, which the seal must name; a deletion carries an older seal verbatim
/// and is exempt.
pub fn open_sealed_channel_meta(s: &SealedChannelMeta, conv_key: &[u8; 32], prev: Option<&[u8; 32]>) -> Option<ChannelMetadata> {
    let conv = ConversationKey::from_slice(conv_key).ok()?;
    let raw = crate::simd::base64::STANDARD.decode_to_vec(s.sealed.as_bytes()).ok()?;
    let inner = crate::crypto::nip44::decrypt(&conv, raw).ok()?;
    let serde_json::Value::Object(mut o) = serde_json::from_slice(&inner).ok()? else { return None };
    let named = o.remove(SEALED_PREV).and_then(|v| v.as_str().and_then(crate::simd::hex::hex_to_bytes_32_checked));
    if !s.deleted && named.as_ref() != prev {
        return None;
    }
    o.insert("private".into(), true.into());
    o.remove("deleted");
    let mut meta: ChannelMetadata = serde_json::from_value(serde_json::Value::Object(o)).ok()?;
    meta.deleted = s.deleted.then_some(true);
    Some(meta)
}

/// A sealed edition's content republished verbatim beside `"deleted": true`: deleting a Private
/// Channel takes only the bit, never the key.
pub fn sealed_tombstone(content: &str) -> Option<String> {
    let serde_json::Value::Object(mut o) = serde_json::from_str(content).ok()? else { return None };
    o.insert("deleted".into(), true.into());
    Some(serde_json::Value::Object(o).to_string())
}

/// `meta` with whatever breaks the protocol caps dropped, the name cut to fit: what folds is
/// shown, and what a writer re-seals must validate.
pub fn sanitize_channel_metadata(mut meta: ChannelMetadata) -> ChannelMetadata {
    cut_name(&mut meta.name);
    let text = |m: &ChannelMetadata, k: &str| m.extra.get(k).map(|v| v.as_str().map(str::to_string));
    if text(&meta, "topic").is_some_and(|t| t.is_none_or(|t| t.is_empty() || t.len() > MAX_TOPIC_BYTES)) {
        meta.extra.remove("topic");
    }
    if text(&meta, "position").is_some_and(|k| k.is_none_or(|k| !crate::community::rank::is_rank_key(&k))) {
        meta.extra.remove("position");
    }
    if text(&meta, "category").is_some_and(|c| c.is_none_or(|c| crate::simd::hex::hex_to_bytes_32_checked(&c).is_none())) {
        meta.extra.remove("category");
    }
    meta
}

/// 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"));
    }
    let text = |k: &str| meta.extra.get(k).and_then(|v| v.as_str());
    if text("topic").is_some_and(|t| t.len() > MAX_TOPIC_BYTES) {
        return Err(ControlError::OverCap("topic"));
    }
    if text("position").is_some_and(|k| !crate::community::rank::is_rank_key(k)) {
        return Err(ControlError::OverCap("position"));
    }
    if text("category").is_some_and(|c| crate::simd::hex::hex_to_bytes_32_checked(c).is_none()) {
        return Err(ControlError::OverCap("category"));
    }
    Ok(())
}

/// A name past the 64-byte cap, cut to the last whole character within it: what a reader shows.
pub fn cut_name(name: &mut String) {
    if name.len() > MAX_NAME_BYTES {
        let mut end = MAX_NAME_BYTES;
        while !name.is_char_boundary(end) {
            end -= 1;
        }
        name.truncate(end);
    }
}

/// An optional string field of another type reads as absent, never sinking the edition.
fn lenient_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
    Ok(match serde_json::Value::deserialize(d)? {
        serde_json::Value::String(s) => Some(s),
        _ => None,
    })
}

fn lenient_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    lenient_string(d).map(Option::unwrap_or_default)
}

/// A Channel's topic cap (CORD-03 §2).
pub const MAX_TOPIC_BYTES: usize = 1024;

/// A Category (vsk 15, CORD-03 §4), `eid == category_id`, gated by `MANAGE_CHANNELS`.
/// Deletion is terminal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CategoryMetadata {
    #[serde(default, skip_serializing_if = "String::is_empty", deserialize_with = "lenient_name")]
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "lenient_string")]
    pub position: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted: Option<bool>,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

pub fn validate_category_metadata(meta: &CategoryMetadata) -> Result<(), ControlError> {
    if meta.name.len() > MAX_NAME_BYTES {
        return Err(ControlError::OverCap("name"));
    }
    if meta.position.as_deref().is_some_and(|k| !crate::community::rank::is_rank_key(k)) {
        return Err(ControlError::OverCap("position"));
    }
    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`](crate::signer::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,
    mut metadata: CommunityMetadata,
    at_secs: u64,
) -> 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) = (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 {
    fn shown(r: Result<(ParsedEdition, OpenedStream), ControlError>) -> String {
        format!("{r:?}")
    }

    #[test]
    fn an_open_served_from_the_memo_is_exactly_a_fresh_open() {
        let owner = Keys::generate();
        let g = genesis(&owner, CommunityMetadata { name: "Memo".into(), ..Default::default() }, 1_000).unwrap();
        let held = super::super::community::CommunityV2::from_genesis(&g, "Memo", None, vec![], 0);
        let view = ControlPlane::of(&held);
        assert!(!g.wraps.is_empty());
        for wrap in &g.wraps {
            forget_opened();
            let fresh = shown(view.open(wrap));
            assert!(fresh.starts_with("Ok"), "{fresh}");
            assert!(opened_held(&view, wrap), "the open is kept");
            assert_eq!(shown(view.open(wrap)), fresh, "and served again as it was");
            assert_eq!(format!("{:?}", view.open_edition(wrap)), format!("{:?}", view.open(wrap).map(|(e, _)| e)));
        }
    }

    #[test]
    fn the_memo_serves_no_view_what_its_own_open_would_refuse() {
        let owner = Keys::generate();
        let g = genesis(&owner, CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
        let other = genesis(&owner, CommunityMetadata { name: "B".into(), ..Default::default() }, 1_000).unwrap();
        let a = super::super::community::CommunityV2::from_genesis(&g, "A", None, vec![], 0);
        let b = super::super::community::CommunityV2::from_genesis(&other, "B", None, vec![], 0);
        forget_opened();
        assert!(ControlPlane::of(&a).open(&g.wraps[0]).is_ok());
        assert!(ControlPlane::of(&b).open(&g.wraps[0]).is_err(), "another Community's view opens nothing of A's");

        // A bare group view checks no binding; this Community's view still does, cached or not.
        let mut legacy = a.clone();
        legacy.control_pk = None;
        let group = control_group_key(&legacy.community_root, legacy.id(), legacy.root_epoch);
        let elsewhere = super::super::derive::edition_binding(&CommunityId([0x42; 32]));
        let rumor = build_edition_rumor_bound(owner.public_key(), vsk::ROLE_V2, &[0x51; 32], 1, None, "{}", 1_000, None, Some(elsewhere));
        let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
        assert!(ControlPlane::legacy(&group).open(&wrap).is_ok());
        assert!(opened_held(&ControlPlane::of(&legacy), &wrap), "the same address and key: one memo entry");
        assert!(
            matches!(ControlPlane::of(&legacy).open(&wrap), Err(ControlError::Edition(EditionError::BadField("eb")))),
            "an edition bound to another Community is refused whoever filled the memo"
        );
    }

    #[test]
    fn the_open_memo_ages_a_generation_at_a_time() {
        let owner = Keys::generate();
        let g = genesis(&owner, CommunityMetadata { name: "Ages".into(), ..Default::default() }, 1_000).unwrap();
        let held = super::super::community::CommunityV2::from_genesis(&g, "Ages", None, vec![], 0);
        let value: Opened = std::sync::Arc::new(ControlPlane::of(&held).open(&g.wraps[0]).unwrap());
        let half = OPENED_MEMO_BYTES / 2 + 1;
        let mut memo = OpenedMemo::default();
        memo.insert([1; 32], value.clone(), half);
        memo.insert([2; 32], value.clone(), half);
        assert!(memo.prev.contains_key(&[1; 32]) && memo.cur.contains_key(&[2; 32]), "a full generation ages into the previous one");
        assert!(memo.get(&[1; 32]).is_some() && memo.cur.contains_key(&[1; 32]), "and a hit there moves back");
        memo.insert([3; 32], value.clone(), half);
        memo.insert([4; 32], value.clone(), half);
        assert!(!memo.contains(&[2; 32]), "two generations on, what nothing touched is gone");
        assert!(memo.contains(&[4; 32]));
        let big = OPENED_MEMO_BYTES * 2;
        memo.insert([5; 32], value, big);
        assert!(memo.cur.contains_key(&[5; 32]), "one larger than a generation still keeps a generation of its own");
    }

    #[test]
    fn sealed_channel_metadata_round_trips_and_hides_everything_but_access() {
        let mut meta = ChannelMetadata { name: "war room".into(), private: true, voice: None, deleted: None, custom: Some(serde_json::Map::from_iter([("x".to_string(), 1.into())])), extra: Default::default() };
        meta.extra.insert("topic".into(), "plans".into());
        meta.extra.insert("category".into(), "11".repeat(32).into());
        let key = [7u8; 32];
        let conv = ConversationKey::from_slice(&key).unwrap();
        let prev = [0x0f; 32];
        let content = seal_channel_metadata(&meta, &conv, 4, Some(&prev)).unwrap();
        for leak in ["war room", "plans", &"11".repeat(32)] {
            assert!(!content.contains(leak), "{leak} must not show");
        }
        let s = parse_sealed_channel_meta(&content).unwrap();
        assert_eq!((s.epoch, s.deleted), (4, false));
        assert_eq!(open_sealed_channel_meta(&s, &key, Some(&prev)), Some(meta.clone()));
        assert_eq!(open_sealed_channel_meta(&s, &[8u8; 32], Some(&prev)), None, "another epoch's key opens nothing");
        assert_eq!(open_sealed_channel_meta(&s, &key, Some(&[0x10; 32])), None, "nor does a seal replayed under another predecessor");
        assert_eq!(open_sealed_channel_meta(&s, &key, None), None);
        let gone = parse_sealed_channel_meta(&sealed_tombstone(&content).unwrap()).unwrap();
        assert_eq!((gone.sealed.as_str(), gone.deleted), (s.sealed.as_str(), true), "the tombstone carries the seal verbatim");
        assert_eq!(open_sealed_channel_meta(&gone, &key, Some(&[0x11; 32])).unwrap().deleted, Some(true), "a deletion carries an older seal");
        assert!(parse_sealed_channel_meta(r#"{"name":"general","private":false}"#).is_none());
        assert!(parse_sealed_channel_meta(&content.replace("\"epoch\":\"4\"", "\"epoch\":\"04\"")).is_none(), "a non-canonical epoch");
        assert!(parse_sealed_channel_meta(&content.replace("\"epoch\":\"4\"", "\"epoch\":\"+4\"")).is_none());
        let mut wild = meta.clone();
        wild.name = "é".repeat(MAX_NAME_BYTES);
        wild.extra.insert("position".into(), "!!".into());
        wild.extra.insert("topic".into(), "x".repeat(MAX_TOPIC_BYTES + 1).into());
        let tame = sanitize_channel_metadata(wild);
        assert!(validate_channel_metadata(&tame).is_ok() && tame.extra.get("position").is_none() && tame.extra.get("topic").is_none() && tame.extra.get("category").is_some());
        assert!(parse_sealed_channel_meta(&content.replace("\"private\":true", "\"private\":false")).is_none());
    }

    use nostr_sdk::prelude::FinalizeEvent;
    use super::super::super::edition::build_edition_inner;
    use super::*;

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

    #[test]
    fn a_malformed_image_drops_alone() {
        let doc = r#"{"name":"Club","description":"hi","icon":{"url":"u","key":"k","nonce":"n","hash":"h"},"banner":{"url":"only"}}"#;
        let meta: CommunityMetadata = serde_json::from_str(doc).unwrap();
        assert_eq!(meta.name, "Club");
        assert_eq!(meta.description.as_deref(), Some("hi"));
        assert_eq!(meta.icon.as_ref().map(|i| i.url.as_str()), Some("u"));
        assert!(meta.banner.is_none());

        let meta: CommunityMetadata = serde_json::from_str(r#"{"name":"Club","banner":"not an object"}"#).unwrap();
        assert!(meta.banner.is_none() && meta.icon.is_none());
    }

    #[test]
    fn an_image_round_trips_with_its_extras() {
        let doc = r#"{"name":"Club","banner":{"url":"u","key":"k","nonce":"n","hash":"h","ext":"webp"}}"#;
        let meta: CommunityMetadata = serde_json::from_str(doc).unwrap();
        let again: CommunityMetadata = serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap();
        assert_eq!(again, meta);
        assert_eq!(meta.banner.unwrap().to_community_image().ext, "webp");
    }

    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 frozen (byte layout and label). The same logical
        // edition must hash identically whether built as a signed inner or a rumor.
        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.");
    }
}