1use nostr_sdk::prelude::PublicKey;
11
12use super::super::{ChannelId, CommunityId, Epoch};
13use super::control::{CommunityIdentity, Genesis, ImageRef};
14use super::invite::CommunityInvite;
15
16#[derive(Debug, Clone)]
20pub struct ChannelV2 {
21 pub id: ChannelId,
22 pub name: String,
23 pub private: bool,
24 pub key: Option<[u8; 32]>,
27 pub epoch: Epoch,
28 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 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#[derive(Debug, Clone)]
55pub struct CommunityV2 {
56 pub identity: CommunityIdentity,
57 pub community_root: [u8; 32],
59 pub root_epoch: Epoch,
60 pub name: String,
61 pub description: Option<String>,
62 pub icon: Option<ImageRef>,
66 pub banner: Option<ImageRef>,
67 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 pub created_at_ms: u64,
76}
77
78impl CommunityV2 {
79 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 pub fn from_bundle(bundle: &CommunityInvite, created_at_ms: u64) -> Result<CommunityV2, String> {
115 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 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 pub fn id(&self) -> &CommunityId {
164 &self.identity.community_id
165 }
166
167 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 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 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 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 pub fn channel_read_coords(&self, ch: &ChannelV2) -> Vec<([u8; 32], Epoch)> {
219 if ch.private && ch.key.is_none() {
223 return Vec::new();
224 }
225 vec![self.channel_secret(ch)]
226 }
227
228 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 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 assert_eq!(c.primary_channel().unwrap().name, "general");
287
288 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 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 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 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 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 ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() },
370 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 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 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 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}