Skip to main content

vector_core/xdc/
signal.rs

1//! Peer signals over Nostr: how players find each other's nodes. An
2//! advertisement says "my node is on this topic, dial it"; a departure says
3//! "I left". DMs carry them as gift-wrapped rumors, Community channels as
4//! sealed kind-3310 events, exactly as the app sends them.
5
6use nostr_sdk::prelude::*;
7
8use crate::event_ext::FinalizeUnsignedWithId;
9use crate::stored_event::{event_kind, StoredEvent};
10
11/// A peer signal as it arrived, already persisted.
12#[derive(Debug, Clone)]
13pub struct Signal {
14    /// The DM npub or Community channel id it arrived in.
15    pub chat_id: String,
16    pub npub: String,
17    pub topic: String,
18    /// `Some` for an advertisement, `None` for a departure.
19    pub node_addr: Option<iroh::EndpointAddr>,
20    pub created_at: u64,
21    /// False when a newer signal from the same peer already superseded this one
22    /// (a replayed or out-of-order event): history, not the present.
23    pub current: bool,
24}
25
26/// Advertise our node on `topic` to `chat_id`, or announce we left (`node_addr: None`).
27pub async fn send(chat_id: &str, topic: &str, node_addr: Option<&str>) -> Result<(), String> {
28    let session = crate::db::current_session();
29    let client = crate::state::nostr_client().ok_or("Not logged in")?;
30    let me = crate::state::my_public_key().ok_or("Not logged in")?;
31    match PublicKey::from_bech32(chat_id) {
32        Ok(pk) => {
33            let content = if node_addr.is_some() { "peer-advertisement" } else { "peer-left" };
34            let mut b = EventBuilder::new(Kind::ApplicationSpecificData, content)
35                .tag(Tag::public_key(pk))
36                .tag(Tag::custom("d", vec!["vector-webxdc-peer"]))
37                .tag(Tag::custom("webxdc-topic", vec![topic.to_string()]));
38            if let Some(addr) = node_addr {
39                b = b.tag(Tag::custom("webxdc-node-addr", vec![addr.to_string()]));
40            }
41            let rumor = b.finalize_unsigned_with_id(me);
42            let relays = crate::state::active_trusted_relays().await;
43            // The signer is process-wide: after a swap it would seal this as another account.
44            if !session.is_live() {
45                return Err("account changed before the signal was sent".into());
46            }
47            crate::send_gift_wrap(&client, relays, &pk, rumor, []).await.map(|_| ()).map_err(|e| e.to_string())
48        }
49        Err(_) => {
50            if !session.is_live() {
51                return Err("account changed before the signal was sent".into());
52            }
53            send_to_channel(chat_id, topic, node_addr).await
54        }
55    }
56}
57
58async fn send_to_channel(channel_id: &str, topic: &str, node_addr: Option<&str>) -> Result<(), String> {
59    use crate::community::{v2, ChannelId, CommunityId};
60    use crate::simd::hex::hex_to_bytes_32;
61    let cid = crate::db::community::community_id_for_channel(channel_id)?.ok_or("Not a Community channel")?;
62    let community_id = CommunityId(hex_to_bytes_32(&cid));
63    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
64    let community = crate::db::community::load_community_v2(&community_id)?.ok_or("Community not found")?;
65    let channel = ChannelId(hex_to_bytes_32(channel_id));
66    v2::service::send_webxdc_signal(&transport, &community, &channel, topic, node_addr).await
67}
68
69/// Take in a peer signal from a DM (`chat_id` = the contact's npub) or a
70/// Community channel: validate, persist it for later joins, and say whether
71/// it is still that peer's latest word on the topic. `None` drops garbage.
72pub async fn ingest(
73    chat_id: &str,
74    npub: &str,
75    topic: &str,
76    node_addr: Option<&str>,
77    event_id: &str,
78    created_at: u64,
79) -> Option<Signal> {
80    // One spelling, so every lookup and lobby keyed on it agrees.
81    let topic = &super::wire::encode_topic(&super::wire::decode_topic(topic).ok()?);
82    let addr = match node_addr.map(super::wire::decode_node_addr) {
83        Some(Ok(a)) => Some(a),
84        Some(Err(_)) => return None,
85        None => None,
86    };
87    let now = crate::clock::now_secs();
88    // Sender-claimed: a forged far-future signal must not outrank every later genuine one.
89    let created_at = created_at.min(now + 300);
90    persist(chat_id, npub, topic, node_addr, event_id, created_at).await;
91    let current = crate::db::miniapps::peer_signal_is_current(topic, npub, created_at, addr.is_some()).unwrap_or(false);
92    Some(Signal { chat_id: chat_id.to_string(), npub: npub.to_string(), topic: topic.to_string(), node_addr: addr, created_at, current })
93}
94
95async fn persist(chat_id: &str, npub: &str, topic: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) {
96    if crate::db::events::event_exists(event_id).unwrap_or(true) {
97        return;
98    }
99    let Ok(chat) = crate::db::id_cache::get_or_create_chat_id(chat_id) else { return };
100    let mut tags = vec![
101        vec!["webxdc-topic".to_string(), topic.to_string()],
102        vec!["d".to_string(), "vector-webxdc-peer".to_string()],
103    ];
104    if let Some(addr) = node_addr {
105        tags.push(vec!["webxdc-node-addr".to_string(), addr.to_string()]);
106    }
107    let event = StoredEvent {
108        id: event_id.to_string(),
109        kind: event_kind::APPLICATION_SPECIFIC,
110        chat_id: chat,
111        user_id: None,
112        content: if node_addr.is_some() { "peer-advertisement" } else { "peer-left" }.to_string(),
113        tags,
114        reference_id: Some(topic.to_string()),
115        created_at,
116        received_at: crate::clock::now_ms(),
117        mine: false,
118        pending: false,
119        failed: false,
120        wrapper_event_id: None,
121        npub: Some(npub.to_string()),
122        preview_metadata: None,
123    };
124    if let Err(e) = crate::db::events::save_event(&event).await {
125        crate::log_warn!("[xdc] could not persist peer signal: {e}");
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
134        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
135        crate::db::close_database();
136        crate::db::clear_id_caches();
137        let tmp = tempfile::tempdir().unwrap();
138        let account = Keys::generate().public_key().to_bech32().unwrap();
139        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
140        crate::db::set_current_account(account.clone()).unwrap();
141        crate::db::init_database(&account).unwrap();
142        (tmp, guard)
143    }
144
145    fn addr_with_direct_ip() -> String {
146        let id = iroh::SecretKey::from([9u8; 32]).public();
147        let relay: iroh::RelayUrl = "https://relay.example./".parse().unwrap();
148        let addr = iroh::EndpointAddr::new(id)
149            .with_relay_url(relay)
150            .with_ip_addr("203.0.113.7:4433".parse().unwrap());
151        super::super::wire::encode_node_addr(&addr).unwrap()
152    }
153
154    #[tokio::test]
155    async fn a_signal_persists_and_only_the_latest_word_is_current() {
156        let (_tmp, _guard) = init_test_db();
157        let topic = crate::webxdc::mint_topic_id("h", "s");
158        let npub = Keys::generate().public_key().to_bech32().unwrap();
159        let addr = addr_with_direct_ip();
160        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
161
162        let ad = ingest("npub1chat", &npub, &topic, Some(&addr), "ev_ad", now - 20).await.expect("valid ad");
163        assert!(ad.current);
164        let node = ad.node_addr.expect("an advertisement carries a node");
165        assert!(node.addrs.iter().all(|a| matches!(a, iroh::TransportAddr::Relay(_))), "a peer-nominated direct IP is never kept");
166
167        let left = ingest("npub1chat", &npub, &topic, None, "ev_left", now - 10).await.expect("valid departure");
168        assert!(left.current && left.node_addr.is_none());
169
170        // An older advertisement replayed by a sync is history, not presence.
171        let stale = ingest("npub1chat", &npub, &topic, Some(&addr), "ev_old_ad", now - 30).await.unwrap();
172        assert!(!stale.current);
173
174        // Only the departure-free latest ads are offered to a joiner.
175        assert!(crate::db::miniapps::get_active_peer_advertisements(&topic, "npub1me").unwrap().is_empty());
176        ingest("npub1chat", &npub, &topic, Some(&addr), "ev_back", now).await.unwrap();
177        assert_eq!(crate::db::miniapps::get_active_peer_advertisements(&topic, "npub1me").unwrap().len(), 1);
178    }
179
180    #[tokio::test]
181    async fn a_joiner_bootstraps_only_from_its_own_chat() {
182        let (_tmp, _guard) = init_test_db();
183        let topic = crate::webxdc::mint_topic_id("h", "s");
184        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
185        let (player, stranger) = (Keys::generate().public_key().to_bech32().unwrap(), Keys::generate().public_key().to_bech32().unwrap());
186        ingest("npub1channel", &player, &topic, Some(&addr_with_direct_ip()), "ev_in", now).await.unwrap();
187        // The same topic advertised to us through a stranger's DM.
188        ingest(&stranger, &stranger, &topic, Some(&addr_with_direct_ip()), "ev_out", now).await.unwrap();
189
190        let here = crate::db::miniapps::get_active_peer_advertisements_in(&topic, "npub1channel", "npub1me", 32).unwrap();
191        assert_eq!(here.iter().map(|r| r.npub.as_str()).collect::<Vec<_>>(), vec![player.as_str()]);
192        assert!(crate::db::miniapps::get_active_peer_advertisements_in(&topic, "npub1unknown", "npub1me", 32).unwrap().is_empty());
193
194        // The same player's later word through another chat neither hides them
195        // here nor adds that chat's node.
196        let other_node = {
197            let id = iroh::SecretKey::from([8u8; 32]).public();
198            let relay: iroh::RelayUrl = "https://relay.example./".parse().unwrap();
199            super::super::wire::encode_node_addr(&iroh::EndpointAddr::new(id).with_relay_url(relay)).unwrap()
200        };
201        ingest(&player, &player, &topic, Some(&other_node), "ev_dm_later", now + 5).await.unwrap();
202        ingest(&player, &player, &topic, Some(&other_node), "ev_dm_same", now).await.unwrap();
203        let here = crate::db::miniapps::get_active_peer_advertisements_in(&topic, "npub1channel", "npub1me", 32).unwrap();
204        assert_eq!(here.len(), 1, "one row, from this chat");
205        assert_eq!(here[0].node_addr_encoded, addr_with_direct_ip());
206    }
207
208    #[tokio::test]
209    async fn garbage_signals_are_dropped_before_they_persist() {
210        let (_tmp, _guard) = init_test_db();
211        let topic = crate::webxdc::mint_topic_id("h", "s");
212        assert!(ingest("npub1chat", "npub1x", "not-a-topic", None, "ev1", 1).await.is_none());
213        assert!(ingest("npub1chat", "npub1x", &topic, Some("!!"), "ev2", 1).await.is_none());
214        assert!(!crate::db::events::event_exists("ev1").unwrap());
215        assert!(!crate::db::events::event_exists("ev2").unwrap());
216    }
217
218    #[tokio::test]
219    async fn a_topic_is_kept_in_its_one_spelling() {
220        let (_tmp, _guard) = init_test_db();
221        let topic = crate::webxdc::mint_topic_id("h", "s");
222        let sig = ingest("npub1chat", "npub1x", &topic.to_lowercase(), Some(&addr_with_direct_ip()), "ev_case", 1).await.unwrap();
223        assert_eq!(sig.topic, topic);
224        let here = crate::db::miniapps::get_active_peer_advertisements_in(&topic, "npub1chat", "npub1me", 32).unwrap();
225        assert_eq!(here.len(), 1);
226    }
227
228    #[tokio::test]
229    async fn a_far_future_timestamp_is_clamped() {
230        let (_tmp, _guard) = init_test_db();
231        let topic = crate::webxdc::mint_topic_id("h", "s");
232        let sig = ingest("npub1chat", "npub1x", &topic, None, "ev_future", u64::MAX / 2).await.unwrap();
233        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
234        assert!(sig.created_at <= now + 300);
235    }
236}