pub mod attachments;
pub mod cache;
pub mod cipher;
pub mod mentions;
pub mod message_delete;
pub mod policy;
pub mod moderation;
pub mod edition;
pub mod version;
pub mod raid;
pub mod rank;
pub mod roles;
pub(crate) mod plane_neg;
pub mod transport;
pub mod v2;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};
pub const REALTIME_FRESH_WINDOW_MS: u64 = 300_000;
pub fn is_realtime_fresh(at_ms: u64) -> bool {
at_ms.saturating_add(REALTIME_FRESH_WINDOW_MS) >= crate::clock::now_ms()
}
pub async fn dispatch_inbound(
event: nostr_sdk::prelude::Event,
handler: std::sync::Arc<dyn crate::InboundEventHandler>,
) {
v2::realtime::dispatch_event(event, handler).await;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CommunityId(pub [u8; 32]);
impl CommunityId {
pub fn to_hex(&self) -> String {
crate::simd::hex::bytes_to_hex_32(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChannelId(pub [u8; 32]);
impl ChannelId {
pub fn to_hex(&self) -> String {
crate::simd::hex::bytes_to_hex_32(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Epoch(pub u64);
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct ChannelKey(pub [u8; 32]);
impl ChannelKey {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl core::fmt::Debug for ChannelKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("ChannelKey(<redacted>)")
}
}
pub const SERVER_ROOT_SCOPE_HEX: &str =
"0000000000000000000000000000000000000000000000000000000000000000";
pub const CONTROL_ROOT_SCOPE: &str = "control-root";
pub const CONTROL_PK_SCOPE: &str = "control-pk";
pub(crate) fn id32_from_hex(hex: &str) -> Option<[u8; 32]> {
crate::simd::hex::hex_to_bytes_32_checked(hex).filter(|_| !hex.bytes().any(|b| b.is_ascii_uppercase()))
}
pub(crate) fn random_32() -> [u8; 32] {
let mut b = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut b);
b
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommunityImage {
pub url: String,
pub key: String,
pub nonce: String,
pub hash: String,
#[serde(default)]
pub ext: String,
}
pub const SVG_REFUSED: &str = "SVG isn't supported for community icons or banners";
pub(crate) fn lenient_image<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::de::DeserializeOwned,
{
let value = Option::<serde_json::Value>::deserialize(d)?;
Ok(value.and_then(|v| serde_json::from_value(v).ok()))
}
pub const MAX_COMMUNITY_RELAYS: usize = 5;
pub fn reached_history_start(channel_id: &str, before_secs: Option<u64>, count: &crate::BackfillCount) -> bool {
reached_start(count, before_secs, |b| crate::db::events::newest_message_before(channel_id, b).is_some())
}
pub fn holds_history_from_start(channel_id: &str) -> bool {
let Ok(Some(cid)) = crate::db::community::community_id_for_channel(channel_id) else { return true };
let id = CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
let Ok(Some(community)) = crate::db::community::load_community_v2(&id) else { return true };
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let Some(channel) = community.channel(&ch) else { return true };
let scope = if channel.private { channel_id } else { SERVER_ROOT_SCOPE_HEX };
let current = (channel.private && channel.key.is_some()).then_some(channel.epoch.0);
let oldest = crate::db::community::held_epoch_keys(&cid, scope).unwrap_or_default().into_iter().map(|(e, _)| e.0).chain(current).min();
oldest.is_none_or(|e| e == 0)
}
fn reached_start(count: &crate::BackfillCount, before_secs: Option<u64>, held_below: impl Fn(u64) -> bool) -> bool {
if count.unreachable || count.next_before.is_some() || count.new_messages > 0 {
return false;
}
count.fetched == 0 || before_secs.is_some_and(|b| !held_below(b))
}
#[cfg(test)]
mod start_tests {
use super::reached_start;
use crate::BackfillCount;
#[test]
fn a_page_of_only_the_cursors_own_second_is_the_start() {
let held_boundary = BackfillCount { fetched: 3, new_messages: 0, next_before: None, unreachable: false };
assert!(reached_start(&held_boundary, Some(1000), |_| false), "nothing older held or served");
assert!(!reached_start(&held_boundary, Some(1000), |_| true), "held history below: a page that met it, not the start");
}
#[test]
fn silence_is_never_the_start() {
let silent = BackfillCount { unreachable: true, ..Default::default() };
assert!(!reached_start(&silent, Some(1000), |_| false));
let answered_empty = BackfillCount::default();
assert!(reached_start(&answered_empty, Some(1000), |_| false));
}
#[test]
fn more_to_walk_or_new_rows_is_not_the_start() {
assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 0, next_before: Some(900), unreachable: false }, Some(1000), |_| false));
assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 4, next_before: None, unreachable: false }, Some(1000), |_| false));
}
}
pub fn inviter_npub(creator: &str) -> Option<String> {
use nostr_sdk::prelude::{PublicKey, ToBech32};
PublicKey::parse(creator).ok().and_then(|pk| pk.to_bech32().ok())
}
pub fn cap_relays(relays: Vec<String>) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::with_capacity(relays.len().min(MAX_COMMUNITY_RELAYS));
for r in relays {
if out.len() >= MAX_COMMUNITY_RELAYS {
break;
}
if seen.insert(r.clone()) {
out.push(r);
}
}
out
}
#[cfg(test)]
mod freshness_tests {
use super::*;
#[test]
fn realtime_freshness_window() {
let now_ms = crate::clock::now_ms();
assert!(is_realtime_fresh(now_ms), "just-sent is fresh");
assert!(is_realtime_fresh(now_ms - REALTIME_FRESH_WINDOW_MS / 2), "modest delay is fresh");
assert!(!is_realtime_fresh(now_ms - 3_600_000), "an hour-old replay is not");
assert!(!is_realtime_fresh(now_ms.saturating_sub(30 * 24 * 3_600_000)), "a month-old replay is not");
assert!(is_realtime_fresh(now_ms + 60_000), "sender clock slightly ahead still fresh");
}
}