vector_core/community/
mod.rs1pub mod attachments;
5pub mod cache;
6pub mod cipher;
7pub mod mentions;
8pub mod message_delete;
9pub mod policy;
10pub mod moderation;
11pub mod edition;
12pub mod version;
13pub mod raid;
14pub mod rank;
15pub mod roles;
16pub(crate) mod plane_neg;
17pub mod transport;
18pub mod v2;
19
20use rand::RngCore;
21use serde::{Deserialize, Serialize};
22use zeroize::{Zeroize, ZeroizeOnDrop};
23
24pub const REALTIME_FRESH_WINDOW_MS: u64 = 300_000;
28
29pub fn is_realtime_fresh(at_ms: u64) -> bool {
37 at_ms.saturating_add(REALTIME_FRESH_WINDOW_MS) >= crate::clock::now_ms()
38}
39
40pub async fn dispatch_inbound(
42 event: nostr_sdk::prelude::Event,
43 handler: std::sync::Arc<dyn crate::InboundEventHandler>,
44) {
45 v2::realtime::dispatch_event(event, handler).await;
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct CommunityId(pub [u8; 32]);
52
53impl CommunityId {
54 pub fn to_hex(&self) -> String {
56 crate::simd::hex::bytes_to_hex_32(&self.0)
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct ChannelId(pub [u8; 32]);
64
65impl ChannelId {
66 pub fn to_hex(&self) -> String {
68 crate::simd::hex::bytes_to_hex_32(&self.0)
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
76pub struct Epoch(pub u64);
77
78#[derive(Clone, Zeroize, ZeroizeOnDrop)]
81pub struct ChannelKey(pub [u8; 32]);
82
83impl ChannelKey {
84 pub fn as_bytes(&self) -> &[u8; 32] {
85 &self.0
86 }
87}
88
89impl core::fmt::Debug for ChannelKey {
91 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92 f.write_str("ChannelKey(<redacted>)")
93 }
94}
95
96pub const SERVER_ROOT_SCOPE_HEX: &str =
101 "0000000000000000000000000000000000000000000000000000000000000000";
102
103pub const CONTROL_ROOT_SCOPE: &str = "control-root";
108
109pub const CONTROL_PK_SCOPE: &str = "control-pk";
112
113pub(crate) fn id32_from_hex(hex: &str) -> Option<[u8; 32]> {
116 crate::simd::hex::hex_to_bytes_32_checked(hex).filter(|_| !hex.bytes().any(|b| b.is_ascii_uppercase()))
117}
118
119pub(crate) fn random_32() -> [u8; 32] {
121 let mut b = [0u8; 32];
122 rand::rngs::OsRng.fill_bytes(&mut b);
123 b
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132pub struct CommunityImage {
133 pub url: String,
135 pub key: String,
137 pub nonce: String,
139 pub hash: String,
141 #[serde(default)]
143 pub ext: String,
144}
145
146pub const SVG_REFUSED: &str = "SVG isn't supported for community icons or banners";
148
149pub(crate) fn lenient_image<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
152where
153 D: serde::Deserializer<'de>,
154 T: serde::de::DeserializeOwned,
155{
156 let value = Option::<serde_json::Value>::deserialize(d)?;
157 Ok(value.and_then(|v| serde_json::from_value(v).ok()))
158}
159
160pub const MAX_COMMUNITY_RELAYS: usize = 5;
165
166pub fn reached_history_start(channel_id: &str, before_secs: Option<u64>, count: &crate::BackfillCount) -> bool {
173 reached_start(count, before_secs, |b| crate::db::events::newest_message_before(channel_id, b).is_some())
174}
175
176pub fn holds_history_from_start(channel_id: &str) -> bool {
180 let Ok(Some(cid)) = crate::db::community::community_id_for_channel(channel_id) else { return true };
181 let id = CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
182 let Ok(Some(community)) = crate::db::community::load_community_v2(&id) else { return true };
183 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
184 let Some(channel) = community.channel(&ch) else { return true };
185 let scope = if channel.private { channel_id } else { SERVER_ROOT_SCOPE_HEX };
186 let current = (channel.private && channel.key.is_some()).then_some(channel.epoch.0);
187 let oldest = crate::db::community::held_epoch_keys(&cid, scope).unwrap_or_default().into_iter().map(|(e, _)| e.0).chain(current).min();
188 oldest.is_none_or(|e| e == 0)
189}
190
191fn reached_start(count: &crate::BackfillCount, before_secs: Option<u64>, held_below: impl Fn(u64) -> bool) -> bool {
192 if count.unreachable || count.next_before.is_some() || count.new_messages > 0 {
193 return false;
194 }
195 count.fetched == 0 || before_secs.is_some_and(|b| !held_below(b))
196}
197
198#[cfg(test)]
199mod start_tests {
200 use super::reached_start;
201 use crate::BackfillCount;
202
203 #[test]
204 fn a_page_of_only_the_cursors_own_second_is_the_start() {
205 let held_boundary = BackfillCount { fetched: 3, new_messages: 0, next_before: None, unreachable: false };
206 assert!(reached_start(&held_boundary, Some(1000), |_| false), "nothing older held or served");
207 assert!(!reached_start(&held_boundary, Some(1000), |_| true), "held history below: a page that met it, not the start");
208 }
209
210 #[test]
211 fn silence_is_never_the_start() {
212 let silent = BackfillCount { unreachable: true, ..Default::default() };
213 assert!(!reached_start(&silent, Some(1000), |_| false));
214 let answered_empty = BackfillCount::default();
215 assert!(reached_start(&answered_empty, Some(1000), |_| false));
216 }
217
218 #[test]
219 fn more_to_walk_or_new_rows_is_not_the_start() {
220 assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 0, next_before: Some(900), unreachable: false }, Some(1000), |_| false));
221 assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 4, next_before: None, unreachable: false }, Some(1000), |_| false));
222 }
223}
224
225pub fn cap_relays(relays: Vec<String>) -> Vec<String> {
226 let mut seen = std::collections::HashSet::new();
227 let mut out = Vec::with_capacity(relays.len().min(MAX_COMMUNITY_RELAYS));
228 for r in relays {
229 if out.len() >= MAX_COMMUNITY_RELAYS {
230 break;
231 }
232 if seen.insert(r.clone()) {
233 out.push(r);
234 }
235 }
236 out
237}
238
239#[cfg(test)]
240mod freshness_tests {
241 use super::*;
242
243 #[test]
246 fn realtime_freshness_window() {
247 let now_ms = crate::clock::now_ms();
248 assert!(is_realtime_fresh(now_ms), "just-sent is fresh");
249 assert!(is_realtime_fresh(now_ms - REALTIME_FRESH_WINDOW_MS / 2), "modest delay is fresh");
250 assert!(!is_realtime_fresh(now_ms - 3_600_000), "an hour-old replay is not");
251 assert!(!is_realtime_fresh(now_ms.saturating_sub(30 * 24 * 3_600_000)), "a month-old replay is not");
252 assert!(is_realtime_fresh(now_ms + 60_000), "sender clock slightly ahead still fresh");
253 }
254}