vector-core 0.3.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
//! The v2 in-memory community — the service/DB working type.
//!
//! Deliberately v2-native rather than reusing v1's [`crate::community::Community`]:
//! a v1 `Channel` assumes an independent per-channel key, but a v2 Public Channel
//! derives its key from the `community_root` (CORD-03), so the two don't share a
//! shape. Both protocols converge instead at the FACADE, where each produces the
//! same untyped JSON summary the SDK consumes — so dual-stack costs no SDK type
//! change (a `version` field is the only tell).

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>,
}

impl ChannelV2 {
    /// 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,
    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>,
    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),
            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(),
            }],
            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(),
            });
        }

        Ok(CommunityV2 {
            identity,
            community_root,
            root_epoch: Epoch(bundle.root_epoch),
            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,
            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)
    }

    /// The ONE channel the chat list surfaces for this community (multi-channel
    /// UI is a later cut, mirroring v1's single-channel groups): 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` tell). Kept deliberately close to v1's summary keys so a
    /// consumer treats both uniformly.
    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() });
        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() });
        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,
            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,
            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,
            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());
    }
}