Skip to main content

vector_core/community/v2/
community.rs

1//! The v2 in-memory community — the service/DB working type.
2//!
3//! Deliberately v2-native rather than reusing v1's [`crate::community::Community`]:
4//! a v1 `Channel` assumes an independent per-channel key, but a v2 Public Channel
5//! derives its key from the `community_root` (CORD-03), so the two don't share a
6//! shape. Both protocols converge instead at the FACADE, where each produces the
7//! same untyped JSON summary the SDK consumes — so dual-stack costs no SDK type
8//! change (a `version` field is the only tell).
9
10use nostr_sdk::prelude::PublicKey;
11
12use super::super::{ChannelId, CommunityId, Epoch};
13use super::control::{CommunityIdentity, Genesis, ImageRef};
14use super::invite::CommunityInvite;
15
16/// A channel as the v2 service holds it. A Public channel's secret is the
17/// `community_root` (`key == None`); a Private channel carries its own
18/// independent key at its own monotonic epoch.
19#[derive(Debug, Clone)]
20pub struct ChannelV2 {
21    pub id: ChannelId,
22    pub name: String,
23    pub private: bool,
24    /// The independent key of a Private channel; `None` for Public (derive from
25    /// the community_root).
26    pub key: Option<[u8; 32]>,
27    pub epoch: Epoch,
28    /// Folded vsk-2 fields Vector doesn't drive but MUST carry through its own
29    /// editions (CORD-02 §6) — an edition replaces the entity, so dropping these
30    /// on a rename would wipe them for every member.
31    pub voice: Option<bool>,
32    pub meta_custom: Option<serde_json::Map<String, serde_json::Value>>,
33    pub meta_extra: serde_json::Map<String, serde_json::Value>,
34}
35
36impl ChannelV2 {
37    /// The full vsk-2 document rebuilt from held state — the base every local
38    /// channel edit MUST start from (CORD-02 §6 preservation).
39    pub fn metadata(&self) -> super::control::ChannelMetadata {
40        super::control::ChannelMetadata {
41            name: self.name.clone(),
42            private: self.private,
43            voice: self.voice,
44            deleted: None,
45            custom: self.meta_custom.clone(),
46            extra: self.meta_extra.clone(),
47        }
48    }
49}
50
51/// A v2 community in memory: its self-certifying identity, base access key, and
52/// channels. Persisted via [`crate::db::community`]'s v2 helpers into the shared
53/// community tables (with the migration-65 columns).
54#[derive(Debug, Clone)]
55pub struct CommunityV2 {
56    pub identity: CommunityIdentity,
57    /// The base `@everyone` access key at `root_epoch` — holding it IS membership.
58    pub community_root: [u8; 32],
59    pub root_epoch: Epoch,
60    pub name: String,
61    pub description: Option<String>,
62    /// Folded vsk-0 icon/banner. Held so a local edit republishes the FULL
63    /// metadata document — an edition replaces the entity, so an editor that
64    /// doesn't carry these forward wipes them for everyone (CORD-02 §6).
65    pub icon: Option<ImageRef>,
66    pub banner: Option<ImageRef>,
67    /// Folded vsk-0 client-extensible object + unknown top-level fields —
68    /// carried through our own editions verbatim (CORD-02 §6).
69    pub meta_custom: Option<serde_json::Map<String, serde_json::Value>>,
70    pub meta_extra: serde_json::Map<String, serde_json::Value>,
71    pub relays: Vec<String>,
72    pub channels: Vec<ChannelV2>,
73    pub dissolved: bool,
74    /// Local wall-clock of first acquisition (ms), for display ordering.
75    pub created_at_ms: u64,
76}
77
78impl CommunityV2 {
79    /// Build the owner's fresh community from a [`Genesis`] (the two genesis
80    /// editions are the caller's to publish). The `#general` channel is Public.
81    pub fn from_genesis(g: &Genesis, name: &str, description: Option<String>, relays: Vec<String>, created_at_ms: u64) -> CommunityV2 {
82        CommunityV2 {
83            identity: g.identity.clone(),
84            community_root: g.community_root,
85            root_epoch: Epoch(0),
86            name: name.to_string(),
87            description,
88            icon: None,
89            banner: None,
90            meta_custom: None,
91            meta_extra: Default::default(),
92            relays,
93            channels: vec![ChannelV2 {
94                id: g.general_channel_id,
95                name: "general".to_string(),
96                private: false,
97                key: None,
98                epoch: Epoch(0),
99                voice: None,
100                meta_custom: None,
101                meta_extra: Default::default(),
102            }],
103            dissolved: false,
104            created_at_ms,
105        }
106    }
107
108    /// Reconstruct a member's community from an accepted invite bundle. The
109    /// bundle's owner commitment MUST already have been verified
110    /// ([`CommunityInvite::validate`]) — this re-checks it fail-closed anyway.
111    /// A channel is treated as Private iff its bundle key differs from the
112    /// community_root (a Public channel's "key" is the root; a Private one
113    /// carries its own).
114    pub fn from_bundle(bundle: &CommunityInvite, created_at_ms: u64) -> Result<CommunityV2, String> {
115        // A bundle is attacker-crafted input (a fetched link, or a Direct Invite
116        // from any npub), so bound BEFORE allocating: `validate` enforces the
117        // 256-channel cap AND the owner commitment (CORD-05 §1). Never
118        // `Vec::with_capacity(bundle.channels.len())` on unbounded input.
119        bundle.validate().map_err(|e| e.to_string())?;
120        let community_id = CommunityId(parse_hex32(&bundle.community_id, "community_id")?);
121        let owner_xonly = parse_hex32(&bundle.owner, "owner")?;
122        let owner_salt = parse_hex32(&bundle.owner_salt, "owner_salt")?;
123        let identity = CommunityIdentity { community_id, owner_xonly, owner_salt };
124        let community_root = parse_hex32(&bundle.community_root, "community_root")?;
125
126        let mut channels = Vec::with_capacity(bundle.channels.len());
127        for g in &bundle.channels {
128            let id = ChannelId(parse_hex32(&g.id, "channel id")?);
129            let key = parse_hex32(&g.key, "channel key")?;
130            let private = key != community_root;
131            channels.push(ChannelV2 {
132                id,
133                name: g.name.clone(),
134                private,
135                key: private.then_some(key),
136                epoch: Epoch(g.epoch),
137                voice: None,
138                meta_custom: None,
139                meta_extra: Default::default(),
140            });
141        }
142
143        Ok(CommunityV2 {
144            identity,
145            community_root,
146            root_epoch: Epoch(bundle.root_epoch),
147            name: bundle.name.clone(),
148            description: None,
149            // Mint-time snapshot so the community has an icon the moment it's
150            // joined; the Control fold is the authority and overwrites it.
151            icon: bundle.icon.clone(),
152            banner: None,
153            meta_custom: None,
154            meta_extra: Default::default(),
155            relays: bundle.relays.clone(),
156            channels,
157            dissolved: false,
158            created_at_ms,
159        })
160    }
161
162    /// The `community_id` this community is anchored on.
163    pub fn id(&self) -> &CommunityId {
164        &self.identity.community_id
165    }
166
167    /// The full vsk-0 metadata document rebuilt from held state — the base every
168    /// local edit MUST start from, so changing one field can't wipe the rest
169    /// (CORD-02 §6), foreign clients' `custom`/`extra` fields included.
170    pub fn metadata(&self) -> super::control::CommunityMetadata {
171        super::control::CommunityMetadata {
172            name: self.name.clone(),
173            description: self.description.clone(),
174            relays: self.relays.clone(),
175            icon: self.icon.clone(),
176            banner: self.banner.clone(),
177            custom: self.meta_custom.clone(),
178            extra: self.meta_extra.clone(),
179        }
180    }
181
182    /// The proven owner (the identity self-certifies at construction).
183    pub fn owner(&self) -> Result<PublicKey, String> {
184        self.identity.owner()
185    }
186
187    pub fn channel(&self, id: &ChannelId) -> Option<&ChannelV2> {
188        self.channels.iter().find(|c| c.id.0 == id.0)
189    }
190
191    /// The ONE channel the chat list surfaces for this community (multi-channel
192    /// UI is a later cut, mirroring v1's single-channel groups): a readable
193    /// `#general` when present, else the oldest readable channel, else the first.
194    /// A keyless Private channel is skipped — it can't render a single message.
195    pub fn primary_channel(&self) -> Option<&ChannelV2> {
196        let readable = |c: &&ChannelV2| !(c.private && c.key.is_none());
197        self.channels
198            .iter()
199            .filter(readable)
200            .find(|c| c.name.eq_ignore_ascii_case("general"))
201            .or_else(|| self.channels.iter().find(readable))
202            .or_else(|| self.channels.first())
203    }
204
205    /// The encryption secret + epoch that address a channel's Chat Plane: the
206    /// `community_root` at `root_epoch` for a Public channel, the channel's own
207    /// key at its own epoch for a Private one (CORD-03 §1).
208    pub fn channel_secret(&self, ch: &ChannelV2) -> ([u8; 32], Epoch) {
209        match ch.key {
210            Some(k) if ch.private => (k, ch.epoch),
211            _ => (self.community_root, self.root_epoch),
212        }
213    }
214
215    /// Every `(secret, epoch)` pair to query for a channel's history — for the
216    /// first cut this is the single current head; the multi-epoch archive
217    /// (across rekeys) layers on once rotation lands in the service.
218    pub fn channel_read_coords(&self, ch: &ChannelV2) -> Vec<([u8; 32], Epoch)> {
219        // A keyless PRIVATE channel is UNREADABLE — never derive it from the root
220        // (that would address a private channel at the public plane, a leak). Its key
221        // rides the rekey plane; it surfaces only once follow_rekeys delivers it.
222        if ch.private && ch.key.is_none() {
223            return Vec::new();
224        }
225        vec![self.channel_secret(ch)]
226    }
227
228    /// The untyped summary the facade hands the SDK (protocol-agnostic shape +
229    /// a `version` tell). Kept deliberately close to v1's summary keys so a
230    /// consumer treats both uniformly.
231    pub fn to_summary_json(&self) -> serde_json::Value {
232        serde_json::json!({
233            "id": crate::simd::hex::bytes_to_hex_32(&self.identity.community_id.0),
234            "version": 2,
235            "name": self.name,
236            "description": self.description,
237            "relays": self.relays,
238            "owner": crate::simd::hex::bytes_to_hex_32(&self.identity.owner_xonly),
239            "dissolved": self.dissolved,
240            "channels": self.channels.iter().map(|c| serde_json::json!({
241                "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
242                "name": c.name,
243                "private": c.private,
244            })).collect::<Vec<_>>(),
245        })
246    }
247}
248
249fn parse_hex32(hex: &str, field: &str) -> Result<[u8; 32], String> {
250    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
251        return Err(format!("{field} is not 32-byte hex"));
252    }
253    Ok(crate::simd::hex::hex_to_bytes_32(hex))
254}
255
256#[cfg(test)]
257mod tests {
258    use super::super::invite::ChannelGrant;
259    use super::*;
260    use nostr_sdk::prelude::Keys;
261
262    #[test]
263    fn genesis_yields_a_public_general_channel() {
264        let owner = Keys::generate();
265        let meta = super::super::control::CommunityMetadata { name: "Test".into(), ..Default::default() };
266        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
267        let c = CommunityV2::from_genesis(&g, "Test", None, vec!["wss://r".into()], 42);
268
269        assert!(c.identity.verify());
270        assert_eq!(c.owner().unwrap(), owner.public_key());
271        assert_eq!(c.channels.len(), 1);
272        let ch = &c.channels[0];
273        assert!(!ch.private);
274        assert_eq!(ch.key, None, "a public channel stores no key");
275        // A public channel's secret is the community_root at the root epoch.
276        assert_eq!(c.channel_secret(ch), (c.community_root, Epoch(0)));
277    }
278
279    #[test]
280    fn primary_channel_prefers_a_readable_general() {
281        let owner = Keys::generate();
282        let meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
283        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
284        let mut c = CommunityV2::from_genesis(&g, "T", None, vec!["wss://r".into()], 0);
285        // Genesis mints #general — it is the primary.
286        assert_eq!(c.primary_channel().unwrap().name, "general");
287
288        // A renamed general → the first READABLE channel wins; a keyless private
289        // channel (unreadable) is skipped even when it sits first.
290        c.channels[0].name = "lobby".into();
291        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() });
292        assert_eq!(c.primary_channel().unwrap().name, "lobby");
293
294        // A readable channel NAMED general beats position.
295        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() });
296        assert_eq!(c.primary_channel().unwrap().name, "General");
297    }
298
299    #[test]
300    fn metadata_document_rebuilds_the_full_entity() {
301        let owner = Keys::generate();
302        let meta = super::super::control::CommunityMetadata { name: "Test".into(), ..Default::default() };
303        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
304        let mut c = CommunityV2::from_genesis(&g, "Test", Some("desc".into()), vec!["wss://r".into()], 42);
305        let mut extra = serde_json::Map::new();
306        extra.insert("ext".into(), serde_json::Value::String("png".into()));
307        c.icon = Some(ImageRef {
308            url: "https://blossom.example/i".into(),
309            key: "k".into(),
310            nonce: "n".into(),
311            hash: "h".into(),
312            extra,
313        });
314
315        // An edition replaces the entity, so the edit base MUST be the full held
316        // document — a name-only edit built from it keeps the icon (CORD-02 §6).
317        let mut custom = serde_json::Map::new();
318        custom.insert("theme".into(), serde_json::Value::String("solarpunk".into()));
319        c.meta_custom = Some(custom.clone());
320        c.meta_extra.insert("future_field".into(), serde_json::Value::Bool(true));
321        let doc = c.metadata();
322        assert_eq!(doc.name, "Test");
323        assert_eq!(doc.description.as_deref(), Some("desc"));
324        assert_eq!(doc.icon, c.icon);
325        assert_eq!(doc.banner, None);
326        assert_eq!(doc.relays, c.relays);
327        assert_eq!(doc.custom, Some(custom), "client-extensible custom rides the edit base");
328        assert_eq!(doc.extra.get("future_field"), Some(&serde_json::Value::Bool(true)), "unknown fields ride too");
329    }
330
331    #[test]
332    fn channel_metadata_document_preserves_undriven_fields() {
333        let owner = Keys::generate();
334        let meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
335        let g = super::super::control::genesis(&owner, meta, 1_000).unwrap();
336        let mut c = CommunityV2::from_genesis(&g, "T", None, vec!["wss://r".into()], 0);
337        // A foreign client marked #general as a voice channel with custom fields.
338        c.channels[0].voice = Some(true);
339        let mut custom = serde_json::Map::new();
340        custom.insert("bitrate".into(), serde_json::Value::from(64000));
341        c.channels[0].meta_custom = Some(custom.clone());
342        c.channels[0].meta_extra.insert("vnd_field".into(), serde_json::Value::from("x"));
343
344        // Our rename rebuilds from the held document: voice/custom/extra survive.
345        let mut doc = c.channels[0].metadata();
346        doc.name = "lounge".into();
347        assert_eq!(doc.voice, Some(true), "a rename must not wipe the voice flag");
348        assert_eq!(doc.custom, Some(custom));
349        assert_eq!(doc.extra.get("vnd_field"), Some(&serde_json::Value::from("x")));
350        assert_eq!(doc.deleted, None);
351    }
352
353    #[test]
354    fn from_bundle_verifies_owner_and_classifies_channels() {
355        let owner = Keys::generate();
356        let identity = CommunityIdentity::mint(&owner.public_key());
357        let root = [0x11u8; 32];
358        let hex = crate::simd::hex::bytes_to_hex_32;
359
360        let priv_key = [0x22u8; 32];
361        let bundle = CommunityInvite {
362            community_id: hex(&identity.community_id.0),
363            owner: hex(&identity.owner_xonly),
364            owner_salt: hex(&identity.owner_salt),
365            community_root: hex(&root),
366            root_epoch: 0,
367            channels: vec![
368                // Public: key == root.
369                ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() },
370                // Private: key != root.
371                ChannelGrant { id: hex(&[0xa2; 32]), key: hex(&priv_key), epoch: 1, name: "mods".into() },
372            ],
373            relays: vec!["wss://r".into()],
374            name: "Test".into(),
375            icon: None,
376            expires_at: None,
377            creator_npub: None,
378            label: None,
379            extra: Default::default(),
380        };
381
382        let c = CommunityV2::from_bundle(&bundle, 99).unwrap();
383        assert_eq!(c.owner().unwrap(), owner.public_key());
384        assert!(!c.channels[0].private);
385        assert!(c.channels[1].private);
386        assert_eq!(c.channels[1].key, Some(priv_key));
387        // Public channel reads under the root; private under its own key/epoch.
388        assert_eq!(c.channel_secret(&c.channels[0]), (root, Epoch(0)));
389        assert_eq!(c.channel_secret(&c.channels[1]), (priv_key, Epoch(1)));
390    }
391
392    #[test]
393    fn from_bundle_rejects_an_out_of_range_epoch() {
394        // Epochs aren't covered by the owner commitment, so a hostile bundle can set
395        // root_epoch = u64::MAX to push a downstream `epoch + 1` toward overflow. The
396        // validate bound refuses it even though the owner commitment itself verifies.
397        let owner = Keys::generate();
398        let identity = CommunityIdentity::mint(&owner.public_key());
399        let hex = crate::simd::hex::bytes_to_hex_32;
400        let root = [0x11u8; 32];
401        let bundle = CommunityInvite {
402            community_id: hex(&identity.community_id.0),
403            owner: hex(&identity.owner_xonly),
404            owner_salt: hex(&identity.owner_salt),
405            community_root: hex(&root),
406            root_epoch: u64::MAX,
407            channels: vec![ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() }],
408            relays: vec!["wss://r".into()],
409            name: "Overflow".into(),
410            icon: None,
411            expires_at: None,
412            creator_npub: None,
413            label: None,
414            extra: Default::default(),
415        };
416        assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an out-of-range epoch is refused");
417    }
418
419    #[test]
420    fn from_bundle_rejects_a_forged_owner_commitment() {
421        let owner = Keys::generate();
422        let attacker = Keys::generate();
423        let identity = CommunityIdentity::mint(&owner.public_key());
424        let hex = crate::simd::hex::bytes_to_hex_32;
425        // Claim the real id but the attacker's key — the commitment won't reproduce it.
426        let bundle = CommunityInvite {
427            community_id: hex(&identity.community_id.0),
428            owner: hex(&attacker.public_key().to_bytes()),
429            owner_salt: hex(&identity.owner_salt),
430            community_root: hex(&[0x11; 32]),
431            root_epoch: 0,
432            channels: vec![],
433            relays: vec![],
434            name: "X".into(),
435            icon: None,
436            expires_at: None,
437            creator_npub: None,
438            label: None,
439            extra: Default::default(),
440        };
441        assert!(CommunityV2::from_bundle(&bundle, 0).is_err());
442    }
443}