use nostr_sdk::prelude::PublicKey;
use super::super::{ChannelId, CommunityId, Epoch};
use super::control::{CommunityIdentity, Genesis, ImageRef};
use super::invite::CommunityInvite;
#[derive(Debug, Clone)]
pub struct ChannelV2 {
pub id: ChannelId,
pub name: String,
pub private: bool,
pub key: Option<[u8; 32]>,
pub epoch: Epoch,
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>,
pub writers: Option<super::writers::Ledger>,
pub sealed: Option<SealedMeta>,
}
pub const SYSTEM_MESSAGES: &str = "system_messages";
pub const LANDING: &str = "landing";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SystemChannel {
Default,
Off,
Named(ChannelId),
}
#[derive(Debug, Clone, Copy)]
pub struct PresenceHome<'a> {
pub channel: &'a ChannelV2,
pub shown: bool,
}
pub fn set_system_channel_in(meta: &mut super::control::CommunityMetadata, channel: Option<&ChannelId>) {
let named = channel.map_or_else(String::new, |c| crate::simd::hex::bytes_to_hex_32(&c.0));
set_custom_channel(meta, SYSTEM_MESSAGES, Some(named));
}
pub fn set_landing_channel_in(meta: &mut super::control::CommunityMetadata, channel: Option<&ChannelId>) {
set_custom_channel(meta, LANDING, channel.map(|c| crate::simd::hex::bytes_to_hex_32(&c.0)));
}
fn set_custom_channel(meta: &mut super::control::CommunityMetadata, key: &str, channel: Option<String>) {
let custom = meta.custom.get_or_insert_with(Default::default);
let entry = custom.entry(key).or_insert_with(|| serde_json::json!({}));
if !entry.is_object() {
*entry = serde_json::json!({});
}
if let Some(fields) = entry.as_object_mut() {
match channel {
Some(c) => {
fields.insert("channel".into(), serde_json::Value::String(c));
}
None => {
fields.remove("channel");
}
}
if fields.is_empty() {
custom.remove(key);
}
}
if custom.is_empty() {
meta.custom = None;
}
}
pub fn can_land_in(c: &ChannelV2) -> bool {
!c.private && c.view() != ChannelView::Voice
}
pub fn takes_system_lines(c: &ChannelV2) -> bool {
c.view() == ChannelView::Chat
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SealedMeta {
pub epoch: u64,
pub raw: String,
pub open: bool,
#[serde(default)]
pub junk: bool,
#[serde(default)]
pub prev: Option<String>,
}
impl ChannelV2 {
pub fn public_until(&self) -> Option<u64> {
self.meta_extra.get("public_until").and_then(|v| v.as_u64()).filter(|_| self.private)
}
pub fn restricted(&self) -> bool {
self.writers.as_ref().is_some_and(|l| l.restricted())
}
pub fn locked(&self) -> bool {
self.writers.as_ref().is_some_and(|l| l.locked())
}
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()
}
}
pub const HISTORY_FIELD: &str = "history";
pub const MAX_HISTORY: usize = 128;
#[derive(Debug, Clone, PartialEq)]
pub struct CategoryV2 {
pub id: [u8; 32],
pub name: String,
pub position: Option<String>,
pub extra: serde_json::Map<String, serde_json::Value>,
}
pub const MAX_CATEGORIES: usize = 100;
pub const MAX_VOICE_RELAYS: usize = 8;
#[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",
}
}
pub fn try_parse(s: &str) -> Option<ChannelView> {
match s {
"chat" => Some(ChannelView::Chat),
"forum" => Some(ChannelView::Forum),
"voice" => Some(ChannelView::Voice),
_ => None,
}
}
pub fn parse(s: &str) -> ChannelView {
match s {
"forum" => ChannelView::Forum,
"voice" => ChannelView::Voice,
_ => ChannelView::Chat,
}
}
}
impl ChannelV2 {
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))
}
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)
}
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)
}
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,
}
}
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(),
}
}
}
#[derive(Debug, Clone)]
pub struct CommunityV2 {
pub identity: CommunityIdentity,
pub community_root: [u8; 32],
pub root_epoch: Epoch,
pub control_pk: Option<PublicKey>,
pub control_root: Option<[u8; 32]>,
pub name: String,
pub description: Option<String>,
pub icon: Option<ImageRef>,
pub banner: Option<ImageRef>,
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 categories: Vec<CategoryV2>,
pub dissolved: bool,
pub created_at_ms: u64,
}
impl CommunityV2 {
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,
}
}
pub fn from_bundle(bundle: &CommunityInvite, created_at_ms: u64) -> Result<CommunityV2, String> {
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,
});
}
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,
control_root: None,
name: bundle.name.clone(),
description: None,
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,
})
}
pub fn id(&self) -> &CommunityId {
&self.identity.community_id
}
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(),
}
}
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)
}
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)
}
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
}
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;
}
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()
}
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())
}
pub fn system_channel(&self) -> SystemChannel {
match self.custom_channel(SYSTEM_MESSAGES) {
None => SystemChannel::Default,
Some("") => SystemChannel::Off,
Some(hex) => crate::simd::hex::hex_to_bytes_32_checked(hex).map_or(SystemChannel::Default, |id| SystemChannel::Named(ChannelId(id))),
}
}
fn custom_channel(&self, key: &str) -> Option<&str> {
self.meta_custom.as_ref().and_then(|c| c.get(key)).and_then(|s| s.get("channel")).and_then(|v| v.as_str())
}
pub fn landing_channel(&self) -> Option<&ChannelV2> {
let id = self.custom_channel(LANDING).and_then(crate::simd::hex::hex_to_bytes_32_checked)?;
self.channel(&ChannelId(id)).filter(|c| can_land_in(c))
}
pub fn default_system_channel(&self) -> Option<&ChannelV2> {
let public = |c: &&ChannelV2| takes_system_lines(c) && !c.private;
let readable = |c: &&ChannelV2| takes_system_lines(c) && !(c.private && c.key.is_none());
self.channels
.iter()
.filter(public)
.find(|c| c.name.eq_ignore_ascii_case("general"))
.or_else(|| self.channels.iter().find(public))
.or_else(|| self.channels.iter().find(readable))
}
pub fn system_lines_target(&self) -> Option<&ChannelV2> {
match self.system_channel() {
SystemChannel::Off => None,
SystemChannel::Named(id) => self.channel(&id).filter(|c| takes_system_lines(c)).or_else(|| self.default_system_channel()),
SystemChannel::Default => self.default_system_channel(),
}
}
pub fn presence_home(&self) -> Option<PresenceHome<'_>> {
let readable = |c: &ChannelV2| !(c.private && c.key.is_none());
let keeper = || self.default_system_channel().or_else(|| self.primary_channel());
match self.system_lines_target() {
Some(channel) if readable(channel) => Some(PresenceHome { channel, shown: true }),
Some(_) => keeper().map(|channel| PresenceHome { channel, shown: false }),
None => {
let on = self.system_channel() != SystemChannel::Off;
keeper().map(|channel| PresenceHome { channel, shown: on && readable(channel) })
}
}
}
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),
}
}
pub fn channel_read_coords(&self, ch: &ChannelV2) -> Vec<([u8; 32], Epoch)> {
if ch.private && ch.key.is_none() {
return Vec::new();
}
vec![self.channel_secret(ch)]
}
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");
assert_eq!(c.channel_secret(ch), (c.community_root, Epoch(0)));
}
fn lines_fixture() -> CommunityV2 {
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();
CommunityV2::from_genesis(&g, "T", None, vec!["wss://r".into()], 0)
}
fn chan(id: u8, name: &str, view: Option<&str>) -> ChannelV2 {
let mut meta_extra = serde_json::Map::new();
if let Some(v) = view {
meta_extra.insert("view".into(), serde_json::json!(v));
}
ChannelV2 { id: ChannelId([id; 32]), name: name.into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra, writers: None, sealed: None }
}
fn lines_to(c: &mut CommunityV2, channel: Option<&ChannelId>) {
let mut meta = c.metadata();
set_system_channel_in(&mut meta, channel);
c.meta_custom = meta.custom;
}
#[test]
fn join_lines_default_to_general_then_the_oldest_public_chat_channel() {
let mut c = lines_fixture();
assert_eq!(c.system_channel(), SystemChannel::Default);
assert_eq!(c.system_lines_target().unwrap().name, "general");
c.channels[0].name = "☕┊General".into();
let mut team = chan(4, "team", None);
team.private = true;
team.key = Some([1; 32]);
c.channels.insert(0, team);
c.channels.insert(1, chan(5, "alpha", Some("voice")));
c.channels.insert(2, chan(6, "beta", Some("forum")));
c.channels.push(chan(8, "chat", None));
assert_eq!(c.default_system_channel().unwrap().name, "☕┊General", "public before private, oldest first, chat only");
c.channels.push(chan(10, "General", None));
assert_eq!(c.default_system_channel().unwrap().name, "General", "a channel named general wins over the oldest");
let home = c.presence_home().unwrap();
assert!(home.shown && home.channel.name == "General");
c.channels.retain(|ch| ch.private || ch.view() != ChannelView::Chat);
assert_eq!(c.default_system_channel().unwrap().name, "team");
}
#[test]
fn join_lines_follow_the_chosen_channel_while_it_takes_them() {
let mut c = lines_fixture();
c.channels.push(chan(5, "welcome", None));
c.channels.push(chan(6, "lounge", Some("voice")));
let welcome = ChannelId([5; 32]);
lines_to(&mut c, Some(&welcome));
assert_eq!(c.system_channel(), SystemChannel::Named(welcome));
let home = c.presence_home().unwrap();
assert!(home.shown && home.channel.name == "welcome");
lines_to(&mut c, Some(&ChannelId([6; 32])));
assert_eq!(c.system_lines_target().unwrap().name, "general", "a voice channel can't take them");
lines_to(&mut c, Some(&ChannelId([42; 32])));
assert_eq!(c.system_lines_target().unwrap().name, "general", "nor a channel that's gone");
lines_to(&mut c, None);
assert_eq!(c.system_channel(), SystemChannel::Off);
assert!(c.system_lines_target().is_none());
let home = c.presence_home().unwrap();
assert!(!home.shown && home.channel.name == "general", "off: kept, unseen, in the default");
}
#[test]
fn join_lines_bound_for_an_unreadable_channel_wait_hidden_in_the_default() {
let mut c = lines_fixture();
let mut staff = chan(5, "staff", None);
staff.private = true;
c.channels.push(staff);
lines_to(&mut c, Some(&ChannelId([5; 32])));
assert_eq!(c.system_lines_target().unwrap().name, "staff", "the setting names it for everyone");
let home = c.presence_home().unwrap();
assert!(!home.shown && home.channel.name == "general");
c.channels[1].key = Some([1; 32]);
let home = c.presence_home().unwrap();
assert!(home.shown && home.channel.name == "staff", "its key arrived");
}
#[test]
fn the_landing_channel_is_the_chosen_one_while_it_can_be_opened() {
let mut c = lines_fixture();
c.channels.push(chan(5, "rules", Some("forum")));
c.channels.push(chan(6, "lounge", Some("voice")));
let mut staff = chan(7, "staff", None);
staff.private = true;
staff.key = Some([1; 32]);
c.channels.push(staff);
let land = |c: &mut CommunityV2, ch: Option<&ChannelId>| {
let mut meta = c.metadata();
set_landing_channel_in(&mut meta, ch);
c.meta_custom = meta.custom;
};
assert!(c.landing_channel().is_none(), "unset: the default");
land(&mut c, Some(&ChannelId([5; 32])));
assert_eq!(c.landing_channel().unwrap().name, "rules", "a forum opens fine");
land(&mut c, Some(&ChannelId([6; 32])));
assert!(c.landing_channel().is_none(), "a voice channel isn't somewhere to land");
land(&mut c, Some(&ChannelId([7; 32])));
assert!(c.landing_channel().is_none(), "nor a private one, readable here or not");
land(&mut c, Some(&ChannelId([42; 32])));
assert!(c.landing_channel().is_none(), "nor a channel that's gone");
land(&mut c, None);
assert!(c.meta_custom.is_none(), "back to the default leaves nothing behind");
}
#[test]
fn clearing_the_landing_channel_keeps_what_else_custom_holds() {
let mut meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
meta.custom = serde_json::json!({ "rules": "be kind", "landing": { "channel": "aa", "note": "hi" } }).as_object().cloned();
set_landing_channel_in(&mut meta, None);
let custom = meta.custom.unwrap();
assert_eq!(custom["rules"], "be kind");
assert_eq!(custom["landing"], serde_json::json!({ "note": "hi" }), "only the channel goes");
}
#[test]
fn setting_the_system_channel_keeps_what_else_custom_holds() {
let mut meta = super::super::control::CommunityMetadata { name: "T".into(), ..Default::default() };
meta.custom = serde_json::json!({ "rules": "be kind", "system_messages": { "channel": "", "welcome": "hi" } }).as_object().cloned();
set_system_channel_in(&mut meta, Some(&ChannelId([5; 32])));
let custom = meta.custom.unwrap();
assert_eq!(custom["rules"], "be kind");
assert_eq!(custom["system_messages"]["welcome"], "hi", "a newer client's field survives");
assert_eq!(custom["system_messages"]["channel"], crate::simd::hex::bytes_to_hex_32(&[5; 32]));
}
#[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);
assert_eq!(c.primary_channel().unwrap().name, "general");
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");
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,
});
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);
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"));
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![
ChannelGrant { id: hex(&[0xa1; 32]), key: hex(&root), epoch: 0, name: "general".into() },
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));
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() {
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;
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());
}
}