vector-core 0.12.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
//! The v2 in-memory community — the service/DB working type.
//!
//! A Public Channel derives its key from the `community_root` (CORD-03); only a
//! Private Channel holds its own. The FACADE hands the SDK an untyped JSON summary
//! of it (see [`CommunityV2::to_summary_json`]).

use nostr_sdk::prelude::PublicKey;

use super::super::{ChannelId, CommunityId, Epoch};
use super::control::{CommunityIdentity, Genesis, ImageRef};
use super::invite::CommunityInvite;

/// A channel as the v2 service holds it. A Public channel's secret is the
/// `community_root` (`key == None`); a Private channel carries its own
/// independent key at its own monotonic epoch.
#[derive(Debug, Clone)]
pub struct ChannelV2 {
    pub id: ChannelId,
    pub name: String,
    pub private: bool,
    /// The independent key of a Private channel; `None` for Public (derive from
    /// the community_root).
    pub key: Option<[u8; 32]>,
    pub epoch: Epoch,
    /// Folded vsk-2 fields Vector doesn't drive but MUST carry through its own
    /// editions (CORD-02 §6) — an edition replaces the entity, so dropping these
    /// on a rename would wipe them for every member.
    pub voice: Option<bool>,
    pub meta_custom: Option<serde_json::Map<String, serde_json::Value>>,
    pub meta_extra: serde_json::Map<String, serde_json::Value>,
    /// The folded Writers ledger of a restricted Channel (CORD-03 §1), held in its own table.
    pub writers: Option<super::writers::Ledger>,
    /// A Private Channel's sealed metadata head (CORD-03 §2), kept so it opens once the key
    /// arrives and a deletion can carry it verbatim.
    pub sealed: Option<SealedMeta>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SealedMeta {
    pub epoch: u64,
    /// The edition's content as carried.
    pub raw: String,
    /// The fields above came out of it.
    pub open: bool,
    /// This device holds the key of its epoch and still couldn't open it: the fields above are
    /// the last it read, and a manager seals them again.
    #[serde(default)]
    pub junk: bool,
    /// The carrying edition's predecessor, which the seal must name.
    #[serde(default)]
    pub prev: Option<String>,
}

impl ChannelV2 {
    /// When a Private Channel that was public went private (unix ms): what was sent at its root
    /// planes before then is its history (CORD-03 §2).
    pub fn public_until(&self) -> Option<u64> {
        self.meta_extra.get("public_until").and_then(|v| v.as_u64()).filter(|_| self.private)
    }

    /// Whether posts land at a writer address now (CORD-03 §1).
    pub fn restricted(&self) -> bool {
        self.writers.as_ref().is_some_and(|l| l.restricted())
    }

    /// Whether every write lands at a writer address now: reactions and calls too.
    pub fn locked(&self) -> bool {
        self.writers.as_ref().is_some_and(|l| l.locked())
    }

    /// The earlier planes its metadata hands every member (CORD-03 §2), each by its own secret
    /// at the epoch its messages commit. A malformed entry names nothing.
    pub fn published_history(&self) -> Vec<(Epoch, super::derive::GroupKey)> {
        let Some(entries) = self.meta_extra.get(HISTORY_FIELD).and_then(|v| v.as_array()) else { return Vec::new() };
        entries
            .iter()
            .filter_map(|entry| match entry.as_array()?.as_slice() {
                [epoch, secret] => {
                    let epoch = epoch.as_u64().filter(|e| *e < 1 << 53)?;
                    let secret = crate::simd::hex::hex_to_bytes_32_checked(secret.as_str()?)?;
                    Some((Epoch(epoch), super::derive::GroupKey::from_secret(&secret)?))
                }
                _ => None,
            })
            .take(MAX_HISTORY)
            .collect()
    }
}

/// The ChannelMetadata field that publishes a Channel's earlier planes (CORD-03 §2).
pub const HISTORY_FIELD: &str = "history";

/// At most this many earlier planes in a Channel's published history, so its edition stays well
/// under a relay's 64 KB.
pub const MAX_HISTORY: usize = 128;

/// A Category (CORD-03 §4): a sidebar group Channels file under by their `category`.
#[derive(Debug, Clone, PartialEq)]
pub struct CategoryV2 {
    pub id: [u8; 32],
    pub name: String,
    pub position: Option<String>,
    /// Fields Vector doesn't drive, carried through its own editions (CORD-02 §6).
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// The most Categories a Community folds.
pub const MAX_CATEGORIES: usize = 100;
/// How many voice relays a Community may list.
pub const MAX_VOICE_RELAYS: usize = 8;

/// How a client opens a Channel (CORD-03 §2). It changes nothing on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelView {
    Chat,
    Forum,
    Voice,
}

impl ChannelView {
    pub fn as_str(self) -> &'static str {
        match self {
            ChannelView::Chat => "chat",
            ChannelView::Forum => "forum",
            ChannelView::Voice => "voice",
        }
    }

    /// A view this build knows by name, or `None`.
    pub fn try_parse(s: &str) -> Option<ChannelView> {
        match s {
            "chat" => Some(ChannelView::Chat),
            "forum" => Some(ChannelView::Forum),
            "voice" => Some(ChannelView::Voice),
            _ => None,
        }
    }

    /// An unknown view reads as chat.
    pub fn parse(s: &str) -> ChannelView {
        match s {
            "forum" => ChannelView::Forum,
            "voice" => ChannelView::Voice,
            _ => ChannelView::Chat,
        }
    }
}

impl ChannelV2 {
    /// Its sidebar key, when it carries a well-formed one (CORD-03 §2).
    pub fn position(&self) -> Option<&str> {
        self.meta_extra.get("position").and_then(|v| v.as_str()).filter(|k| crate::community::rank::is_rank_key(k))
    }

    /// The Category it files under, whether or not that Category still stands.
    pub fn category(&self) -> Option<[u8; 32]> {
        self.meta_extra.get("category").and_then(|v| v.as_str()).and_then(crate::simd::hex::hex_to_bytes_32_checked)
    }

    /// Who made this Private Channel, as its sealed metadata says: only a key holder can write that.
    pub fn creator(&self) -> Option<&str> {
        let sealed = self.private && self.sealed.as_ref().is_some_and(|s| s.open && !s.junk);
        self.meta_extra
            .get("creator")
            .and_then(|v| v.as_str())
            .filter(|c| sealed && c.len() == 64 && c.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
    }

    pub fn topic(&self) -> Option<&str> {
        self.meta_extra.get("topic").and_then(|v| v.as_str()).filter(|t| !t.is_empty() && t.len() <= super::control::MAX_TOPIC_BYTES)
    }

    /// The legacy `voice` flag reads as a voice view.
    pub fn view(&self) -> ChannelView {
        match self.meta_extra.get("view").and_then(|v| v.as_str()) {
            Some(v) => ChannelView::parse(v),
            None if self.voice == Some(true) => ChannelView::Voice,
            None => ChannelView::Chat,
        }
    }

    /// The full vsk-2 document rebuilt from held state — the base every local
    /// channel edit MUST start from (CORD-02 §6 preservation).
    pub fn metadata(&self) -> super::control::ChannelMetadata {
        super::control::ChannelMetadata {
            name: self.name.clone(),
            private: self.private,
            voice: self.voice,
            deleted: None,
            custom: self.meta_custom.clone(),
            extra: self.meta_extra.clone(),
        }
    }
}

/// A v2 community in memory: its self-certifying identity, base access key, and
/// channels. Persisted via [`crate::db::community`]'s v2 helpers into the shared
/// community tables (with the migration-65 columns).
#[derive(Debug, Clone)]
pub struct CommunityV2 {
    pub identity: CommunityIdentity,
    /// The base `@everyone` access key at `root_epoch` — holding it IS membership.
    pub community_root: [u8; 32],
    pub root_epoch: Epoch,
    /// The CURRENT epoch's Control Plane signer pubkey (CORD-02 §2) — HELD,
    /// never derived: it derives from a `control_root` only the owner and staff
    /// hold, and arrives in invites, base rekey blobs, and the Community List.
    /// Present = a split epoch (subscribe/verify by this address, decrypt under
    /// the community_root-derived read key); absent = a LEGACY pre-split epoch,
    /// whose Control Plane folds at the member-derivable `concord/control`
    /// address (CORD-02 §5).
    pub control_pk: Option<PublicKey>,
    /// The CURRENT epoch's staff write secret (`control_root`, CORD-02 §2) —
    /// held only by the owner and staff, delivered on promotion inside the
    /// staff-making Grant (CORD-04 §3) or in a 136-byte base rekey blob
    /// (CORD-06 §1). Absent for regular members and on legacy epochs.
    /// Possession gates publishing to the Control Plane, never authority.
    pub control_root: Option<[u8; 32]>,
    pub name: String,
    pub description: Option<String>,
    /// Folded vsk-0 icon/banner. Held so a local edit republishes the FULL
    /// metadata document — an edition replaces the entity, so an editor that
    /// doesn't carry these forward wipes them for everyone (CORD-02 §6).
    pub icon: Option<ImageRef>,
    pub banner: Option<ImageRef>,
    /// Folded vsk-0 client-extensible object + unknown top-level fields —
    /// carried through our own editions verbatim (CORD-02 §6).
    pub meta_custom: Option<serde_json::Map<String, serde_json::Value>>,
    pub meta_extra: serde_json::Map<String, serde_json::Value>,
    pub relays: Vec<String>,
    pub channels: Vec<ChannelV2>,
    /// Folded Categories (CORD-03 §4), unordered: [`CommunityV2::sidebar`] orders them.
    pub categories: Vec<CategoryV2>,
    pub dissolved: bool,
    /// Local wall-clock of first acquisition (ms), for display ordering.
    pub created_at_ms: u64,
}

impl CommunityV2 {
    /// Build the owner's fresh community from a [`Genesis`] (the two genesis
    /// editions are the caller's to publish). The `#general` channel is Public.
    pub fn from_genesis(g: &Genesis, name: &str, description: Option<String>, relays: Vec<String>, created_at_ms: u64) -> CommunityV2 {
        CommunityV2 {
            identity: g.identity.clone(),
            community_root: g.community_root,
            root_epoch: Epoch(0),
            control_pk: Some(g.control_pk()),
            control_root: Some(g.control_root),
            name: name.to_string(),
            description,
            icon: None,
            banner: None,
            meta_custom: None,
            meta_extra: Default::default(),
            relays,
            channels: vec![ChannelV2 {
                id: g.general_channel_id,
                name: "general".to_string(),
                private: false,
                key: None,
                epoch: Epoch(0),
                voice: None,
                meta_custom: None,
                meta_extra: Default::default(),
                writers: None,
                sealed: None,
            }],
            categories: Vec::new(),
            dissolved: false,
            created_at_ms,
        }
    }

    /// Reconstruct a member's community from an accepted invite bundle. The
    /// bundle's owner commitment MUST already have been verified
    /// ([`CommunityInvite::validate`]) — this re-checks it fail-closed anyway.
    /// A channel is treated as Private iff its bundle key differs from the
    /// community_root (a Public channel's "key" is the root; a Private one
    /// carries its own).
    pub fn from_bundle(bundle: &CommunityInvite, created_at_ms: u64) -> Result<CommunityV2, String> {
        // A bundle is attacker-crafted input (a fetched link, or a Direct Invite
        // from any npub), so bound BEFORE allocating: `validate` enforces the
        // 256-channel cap AND the owner commitment (CORD-05 §1). Never
        // `Vec::with_capacity(bundle.channels.len())` on unbounded input.
        bundle.validate().map_err(|e| e.to_string())?;
        let community_id = CommunityId(parse_hex32(&bundle.community_id, "community_id")?);
        let owner_xonly = parse_hex32(&bundle.owner, "owner")?;
        let owner_salt = parse_hex32(&bundle.owner_salt, "owner_salt")?;
        let identity = CommunityIdentity { community_id, owner_xonly, owner_salt };
        let community_root = parse_hex32(&bundle.community_root, "community_root")?;

        let mut channels = Vec::with_capacity(bundle.channels.len());
        for g in &bundle.channels {
            let id = ChannelId(parse_hex32(&g.id, "channel id")?);
            let key = parse_hex32(&g.key, "channel key")?;
            let private = key != community_root;
            channels.push(ChannelV2 {
                id,
                name: g.name.clone(),
                private,
                key: private.then_some(key),
                epoch: Epoch(g.epoch),
                voice: None,
                meta_custom: None,
                meta_extra: Default::default(),
                writers: None,
                sealed: None,
            });
        }

        // The split epoch's Control address, taken on trust (CORD-05 §1: it
        // derives from a secret the joiner never holds, so nothing in the
        // bundle can prove it; a wrong one is eclipse-class self-harm by the
        // inviter, healed by the next verified base rotation). A malformed
        // value degrades to the legacy view rather than refusing the bundle.
        let control_pk = bundle
            .control_pk
            .as_deref()
            .and_then(|h| PublicKey::from_hex(h).ok());

        Ok(CommunityV2 {
            identity,
            community_root,
            root_epoch: Epoch(bundle.root_epoch),
            control_pk,
            // The bundle never carries the staff secret; a staffer's own
            // devices receive it via the Community List, a Grant's
            // control_wrap, or a 136-byte base blob.
            control_root: None,
            name: bundle.name.clone(),
            description: None,
            // Mint-time snapshot so the community has an icon the moment it's
            // joined; the Control fold is the authority and overwrites it.
            icon: bundle.icon.clone(),
            banner: None,
            meta_custom: None,
            meta_extra: Default::default(),
            relays: bundle.relays.clone(),
            channels,
            categories: Vec::new(),
            dissolved: false,
            created_at_ms,
        })
    }

    /// The `community_id` this community is anchored on.
    pub fn id(&self) -> &CommunityId {
        &self.identity.community_id
    }

    /// The full vsk-0 metadata document rebuilt from held state — the base every
    /// local edit MUST start from, so changing one field can't wipe the rest
    /// (CORD-02 §6), foreign clients' `custom`/`extra` fields included.
    pub fn metadata(&self) -> super::control::CommunityMetadata {
        super::control::CommunityMetadata {
            name: self.name.clone(),
            description: self.description.clone(),
            relays: self.relays.clone(),
            icon: self.icon.clone(),
            banner: self.banner.clone(),
            custom: self.meta_custom.clone(),
            extra: self.meta_extra.clone(),
        }
    }

    /// The proven owner (the identity self-certifies at construction).
    pub fn owner(&self) -> Result<PublicKey, String> {
        self.identity.owner()
    }

    pub fn channel(&self, id: &ChannelId) -> Option<&ChannelV2> {
        self.channels.iter().find(|c| c.id.0 == id.0)
    }

    /// What a channel list renders: the Categories in order, and every Channel in order
    /// with the Category it shows under.
    pub fn layout(&self) -> (Vec<&CategoryV2>, Vec<(&ChannelV2, Option<&CategoryV2>)>) {
        let groups = self.sidebar();
        let categories = groups.iter().filter_map(|(c, _)| *c).collect();
        let channels = groups.iter().flat_map(|(c, chans)| chans.iter().map(move |ch| (*ch, *c))).collect();
        (categories, channels)
    }

    /// The sidebar (CORD-03 §2, §4): uncategorized Channels first, then each Category by
    /// position with its Channels by position. A Channel filed under a Category that isn't
    /// held renders uncategorized. A keyless entry sorts after every keyed one, then by
    /// name, then by id.
    pub fn sidebar(&self) -> Vec<(Option<&CategoryV2>, Vec<&ChannelV2>)> {
        fn order<'a>(position: Option<&'a str>, name: &'a str, id: &'a [u8; 32]) -> (bool, &'a [u8], &'a str, &'a [u8; 32]) {
            (position.is_none(), position.map_or(&[][..], str::as_bytes), name, id)
        }
        let mut categories: Vec<&CategoryV2> = self.categories.iter().collect();
        categories.sort_by(|a, b| order(a.position.as_deref(), &a.name, &a.id).cmp(&order(b.position.as_deref(), &b.name, &b.id)));
        let mut groups: Vec<(Option<&CategoryV2>, Vec<&ChannelV2>)> =
            std::iter::once(None).chain(categories.iter().copied().map(Some)).map(|c| (c, Vec::new())).collect();
        for ch in &self.channels {
            let at = ch.category().and_then(|c| categories.iter().position(|x| x.id == c)).map_or(0, |i| i + 1);
            groups[at].1.push(ch);
        }
        for (_, channels) in &mut groups {
            channels.sort_by(|a, b| order(a.position(), &a.name, &a.id.0).cmp(&order(b.position(), &b.name, &b.id.0)));
        }
        groups
    }

    /// The channels an invite bundle may grant to `audience` (CORD-05 §1/§2).
    ///
    /// Public channels always ride (the joiner derives them from the
    /// `community_root` anyway). A Private channel rides only for a MEMBER the
    /// roster shows entitled, and only if we hold its key — a keyless one can't
    /// be granted, and carrying the root placeholder would make the joiner
    /// address a private channel at the public plane.
    ///
    /// A LINK has no recipient, so its audience holds no Role by construction
    /// and is entitled to no Private channel at all.
    /// The iroh relays its voice Channels use (CORD-07 §8), as the Community lists them; none
    /// means iroh's defaults. Only https URLs, at most eight.
    pub fn voice_relays(&self) -> Vec<String> {
        self.meta_extra
            .get("voice_relays")
            .and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|u| u.as_str()).filter(|u| u.starts_with("https://") && u.len() <= 256).map(str::to_string).take(MAX_VOICE_RELAYS).collect())
            .unwrap_or_default()
    }

    pub fn vendable_channels<'a>(
        &'a self,
        roster: &crate::community::roles::CommunityRoles,
        owner_hex: Option<&str>,
        audience: Option<&str>,
        with: &[String],
        without: &[String],
    ) -> Vec<&'a ChannelV2> {
        self.channels
            .iter()
            .filter(|c| {
                if !c.private {
                    return true;
                }
                if c.key.is_none() {
                    return false;
                }
                // Without Read Message History, a key comes only with a fresh epoch (CORD-03 §5).
                match audience {
                    None => false,
                    Some(m) => {
                        let chan = crate::simd::hex::bytes_to_hex_32(&c.id.0);
                        roster.is_entitled(owner_hex, m, &chan, with, without) && roster.reads_history(owner_hex, m, &chan, with, without)
                    }
                }
            })
            .collect()
    }

    /// The ONE channel the chat list surfaces for this community (multi-channel
    /// UI is a later cut): a readable
    /// `#general` when present, else the oldest readable channel, else the first.
    /// A keyless Private channel is skipped — it can't render a single message.
    pub fn primary_channel(&self) -> Option<&ChannelV2> {
        let readable = |c: &&ChannelV2| !(c.private && c.key.is_none());
        self.channels
            .iter()
            .filter(readable)
            .find(|c| c.name.eq_ignore_ascii_case("general"))
            .or_else(|| self.channels.iter().find(readable))
            .or_else(|| self.channels.first())
    }

    /// The encryption secret + epoch that address a channel's Chat Plane: the
    /// `community_root` at `root_epoch` for a Public channel, the channel's own
    /// key at its own epoch for a Private one (CORD-03 §1).
    pub fn channel_secret(&self, ch: &ChannelV2) -> ([u8; 32], Epoch) {
        match ch.key {
            Some(k) if ch.private => (k, ch.epoch),
            _ => (self.community_root, self.root_epoch),
        }
    }

    /// Every `(secret, epoch)` pair to query for a channel's history — for the
    /// first cut this is the single current head; the multi-epoch archive
    /// (across rekeys) layers on once rotation lands in the service.
    pub fn channel_read_coords(&self, ch: &ChannelV2) -> Vec<([u8; 32], Epoch)> {
        // A keyless PRIVATE channel is UNREADABLE — never derive it from the root
        // (that would address a private channel at the public plane, a leak). Its key
        // rides the rekey plane; it surfaces only once follow_rekeys delivers it.
        if ch.private && ch.key.is_none() {
            return Vec::new();
        }
        vec![self.channel_secret(ch)]
    }

    /// The untyped summary the facade hands the SDK (protocol-agnostic shape +
    /// a `version` field).
    pub fn to_summary_json(&self) -> serde_json::Value {
        serde_json::json!({
            "id": crate::simd::hex::bytes_to_hex_32(&self.identity.community_id.0),
            "version": 2,
            "name": self.name,
            "description": self.description,
            "relays": self.relays,
            "owner": crate::simd::hex::bytes_to_hex_32(&self.identity.owner_xonly),
            "dissolved": self.dissolved,
            "channels": self.channels.iter().map(|c| serde_json::json!({
                "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
                "name": c.name,
                "private": c.private,
            })).collect::<Vec<_>>(),
        })
    }
}

fn parse_hex32(hex: &str, field: &str) -> Result<[u8; 32], String> {
    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(format!("{field} is not 32-byte hex"));
    }
    Ok(crate::simd::hex::hex_to_bytes_32(hex))
}

#[cfg(test)]
mod tests {
    use super::super::invite::ChannelGrant;
    use super::*;
    use nostr_sdk::prelude::Keys;

    #[test]
    fn genesis_yields_a_public_general_channel() {
        let owner = Keys::generate();
        let meta = super::super::control::CommunityMetadata { name: "Test".into(), ..Default::default() };
        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
        let c = CommunityV2::from_genesis(&g, "Test", None, vec!["wss://r".into()], 42);

        assert!(c.identity.verify());
        assert_eq!(c.owner().unwrap(), owner.public_key());
        assert_eq!(c.channels.len(), 1);
        let ch = &c.channels[0];
        assert!(!ch.private);
        assert_eq!(ch.key, None, "a public channel stores no key");
        // A public channel's secret is the community_root at the root epoch.
        assert_eq!(c.channel_secret(ch), (c.community_root, Epoch(0)));
    }

    #[test]
    fn primary_channel_prefers_a_readable_general() {
        let owner = Keys::generate();
        let meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
        let mut c = CommunityV2::from_genesis(&g, "T", None, vec!["wss://r".into()], 0);
        // Genesis mints #general — it is the primary.
        assert_eq!(c.primary_channel().unwrap().name, "general");

        // A renamed general → the first READABLE channel wins; a keyless private
        // channel (unreadable) is skipped even when it sits first.
        c.channels[0].name = "lobby".into();
        c.channels.insert(0, ChannelV2 { id: ChannelId([9u8; 32]), name: "sekrit".into(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
        assert_eq!(c.primary_channel().unwrap().name, "lobby");

        // A readable channel NAMED general beats position.
        c.channels.push(ChannelV2 { id: ChannelId([8u8; 32]), name: "General".into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
        assert_eq!(c.primary_channel().unwrap().name, "General");
    }

    #[test]
    fn metadata_document_rebuilds_the_full_entity() {
        let owner = Keys::generate();
        let meta = super::super::control::CommunityMetadata { name: "Test".into(), ..Default::default() };
        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
        let mut c = CommunityV2::from_genesis(&g, "Test", Some("desc".into()), vec!["wss://r".into()], 42);
        let mut extra = serde_json::Map::new();
        extra.insert("ext".into(), serde_json::Value::String("png".into()));
        c.icon = Some(ImageRef {
            url: "https://blossom.example/i".into(),
            key: "k".into(),
            nonce: "n".into(),
            hash: "h".into(),
            extra,
        });

        // An edition replaces the entity, so the edit base MUST be the full held
        // document — a name-only edit built from it keeps the icon (CORD-02 §6).
        let mut custom = serde_json::Map::new();
        custom.insert("theme".into(), serde_json::Value::String("solarpunk".into()));
        c.meta_custom = Some(custom.clone());
        c.meta_extra.insert("future_field".into(), serde_json::Value::Bool(true));
        let doc = c.metadata();
        assert_eq!(doc.name, "Test");
        assert_eq!(doc.description.as_deref(), Some("desc"));
        assert_eq!(doc.icon, c.icon);
        assert_eq!(doc.banner, None);
        assert_eq!(doc.relays, c.relays);
        assert_eq!(doc.custom, Some(custom), "client-extensible custom rides the edit base");
        assert_eq!(doc.extra.get("future_field"), Some(&serde_json::Value::Bool(true)), "unknown fields ride too");
    }

    #[test]
    fn channel_metadata_document_preserves_undriven_fields() {
        let owner = Keys::generate();
        let meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
        let mut c = CommunityV2::from_genesis(&g, "T", None, vec!["wss://r".into()], 0);
        // A foreign client marked #general as a voice channel with custom fields.
        c.channels[0].voice = Some(true);
        let mut custom = serde_json::Map::new();
        custom.insert("bitrate".into(), serde_json::Value::from(64000));
        c.channels[0].meta_custom = Some(custom.clone());
        c.channels[0].meta_extra.insert("vnd_field".into(), serde_json::Value::from("x"));

        // Our rename rebuilds from the held document: voice/custom/extra survive.
        let mut doc = c.channels[0].metadata();
        doc.name = "lounge".into();
        assert_eq!(doc.voice, Some(true), "a rename must not wipe the voice flag");
        assert_eq!(doc.custom, Some(custom));
        assert_eq!(doc.extra.get("vnd_field"), Some(&serde_json::Value::from("x")));
        assert_eq!(doc.deleted, None);
    }

    #[test]
    fn from_bundle_verifies_owner_and_classifies_channels() {
        let owner = Keys::generate();
        let identity = CommunityIdentity::mint(&owner.public_key());
        let root = [0x11u8; 32];
        let hex = crate::simd::hex::bytes_to_hex_32;

        let priv_key = [0x22u8; 32];
        let bundle = CommunityInvite {
            community_id: hex(&identity.community_id.0),
            owner: hex(&identity.owner_xonly),
            owner_salt: hex(&identity.owner_salt),
            community_root: hex(&root),
            root_epoch: 0,
            control_pk: None,
            channels: vec![
                // Public: key == root.
                ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() },
                // Private: key != root.
                ChannelGrant { id: hex(&[0xa2; 32]), key: hex(&priv_key), epoch: 1, name: "mods".into() },
            ],
            relays: vec!["wss://r".into()],
            name: "Test".into(),
            icon: None,
            expires_at: None,
            creator_npub: None,
            label: None,
            extra: Default::default(),
        };

        let c = CommunityV2::from_bundle(&bundle, 99).unwrap();
        assert_eq!(c.owner().unwrap(), owner.public_key());
        assert!(!c.channels[0].private);
        assert!(c.channels[1].private);
        assert_eq!(c.channels[1].key, Some(priv_key));
        // Public channel reads under the root; private under its own key/epoch.
        assert_eq!(c.channel_secret(&c.channels[0]), (root, Epoch(0)));
        assert_eq!(c.channel_secret(&c.channels[1]), (priv_key, Epoch(1)));
    }

    #[test]
    fn from_bundle_rejects_an_out_of_range_epoch() {
        // Epochs aren't covered by the owner commitment, so a hostile bundle can set
        // root_epoch = u64::MAX to push a downstream `epoch + 1` toward overflow. The
        // validate bound refuses it even though the owner commitment itself verifies.
        let owner = Keys::generate();
        let identity = CommunityIdentity::mint(&owner.public_key());
        let hex = crate::simd::hex::bytes_to_hex_32;
        let root = [0x11u8; 32];
        let bundle = CommunityInvite {
            community_id: hex(&identity.community_id.0),
            owner: hex(&identity.owner_xonly),
            owner_salt: hex(&identity.owner_salt),
            community_root: hex(&root),
            root_epoch: u64::MAX,
            control_pk: None,
            channels: vec![ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() }],
            relays: vec!["wss://r".into()],
            name: "Overflow".into(),
            icon: None,
            expires_at: None,
            creator_npub: None,
            label: None,
            extra: Default::default(),
        };
        assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an out-of-range epoch is refused");
    }

    #[test]
    fn from_bundle_rejects_a_forged_owner_commitment() {
        let owner = Keys::generate();
        let attacker = Keys::generate();
        let identity = CommunityIdentity::mint(&owner.public_key());
        let hex = crate::simd::hex::bytes_to_hex_32;
        // Claim the real id but the attacker's key — the commitment won't reproduce it.
        let bundle = CommunityInvite {
            community_id: hex(&identity.community_id.0),
            owner: hex(&attacker.public_key().to_bytes()),
            owner_salt: hex(&identity.owner_salt),
            community_root: hex(&[0x11; 32]),
            root_epoch: 0,
            control_pk: None,
            channels: vec![],
            relays: vec![],
            name: "X".into(),
            icon: None,
            expires_at: None,
            creator_npub: None,
            label: None,
            extra: Default::default(),
        };
        assert!(CommunityV2::from_bundle(&bundle, 0).is_err());
    }
}