Skip to main content

vector_core/
negentropy.rs

1//! Shared NIP-77 negentropy set reconciliation.
2//!
3//! One acquisition primitive for the whole app. DM and community sync differ only
4//! in their fingerprint source and processing; the reconcile-against-relays
5//! step is identical, so it lives here.
6
7use std::collections::HashSet;
8use std::time::Duration;
9
10use nostr_sdk::prelude::*;
11
12// ============================================================================
13// NIP-77 capability cache
14// ============================================================================
15//
16// Some relay software never implemented negentropy (nostr-rs-relay answers a
17// NEG-OPEN with an unrecognized NOTICE at best), and nostr-sdk's support check
18// only recognizes strfry-style refusals — so every sync against such a relay
19// silently burns the full initial_timeout before failing. Verdicts persist in
20// the account settings KV with a TTL: boots skip doomed reconciles, and a
21// relay that upgrades its software is re-probed within a day.
22
23const NEG_CAP_TTL_SECS: u64 = 24 * 3600;
24
25// `neg_cap2`: a `neg_cap:` row can hold a no verdict a capable relay earned by one slow answer.
26fn cap_key(relay_url: &str) -> String {
27    format!("neg_cap2:{}", relay_url.trim_end_matches('/'))
28}
29
30fn now_secs() -> u64 {
31    crate::clock::now_secs()
32}
33
34/// Cached NIP-77 verdict for a relay. `None` = unknown or stale — attempt
35/// negentropy and let the outcome refresh the cache.
36pub fn neg_supported_cached(relay_url: &str) -> Option<bool> {
37    let raw = crate::db::get_sql_setting(cap_key(relay_url)).ok()??;
38    let (supported, checked_at) = parse_cap_entry(&raw)?;
39    (now_secs().saturating_sub(checked_at) < NEG_CAP_TTL_SECS).then_some(supported)
40}
41
42/// Has this relay ever reconciled for us? Read past the TTL: a relay that has spoken
43/// NIP-77 and then goes quiet is slow, not unable, and only a refusal unlearns it.
44pub fn neg_ever_confirmed(relay_url: &str) -> bool {
45    crate::db::get_sql_setting(cap_key(relay_url))
46        .ok()
47        .flatten()
48        .and_then(|raw| parse_cap_entry(&raw))
49        .is_some_and(|(supported, _)| supported)
50}
51
52/// Persist a fresh verdict (value format: `0|1:<unix seconds>`). The verdict is
53/// relay-global truth, so a raced write is wasted work, never wrong data.
54pub fn record_neg_support(relay_url: &str, supported: bool) {
55    let _ = crate::db::set_sql_setting(
56        cap_key(relay_url),
57        format!("{}:{}", u8::from(supported), now_secs()),
58    );
59}
60
61fn parse_cap_entry(raw: &str) -> Option<(bool, u64)> {
62    let (flag, ts) = raw.split_once(':')?;
63    let supported = match flag {
64        "1" => true,
65        "0" => false,
66        _ => return None,
67    };
68    Some((supported, ts.parse().ok()?))
69}
70
71/// Interpret a `relay.sync` error. `Some(false)` = the relay cannot
72/// reconcile: either the SDK recognized the refusal outright, or a relay that
73/// was CONNECTED stayed silent past the initial timeout — healthy negentropy
74/// implementations answer the first frame in well under a second, so silence
75/// on a live connection is the no-implementation signature. A timeout on a
76/// relay that wasn't connected is an outage and classifies as nothing.
77/// Wait briefly for a relay to reach Connected before a sync attempt.
78/// `false` = never connected inside the allowance — callers treat that as a
79/// TRANSIENT skip (no verdict, no skip-list, no cursor touch): an unreachable
80/// relay must cost the allowance, not a full negentropy initial_timeout. The
81/// Monitor-driven reconnect catch-up covers it the moment it truly connects.
82pub async fn wait_connected(relay: &Relay, allowance: Duration) -> bool {
83    let deadline = crate::rt::time::Instant::now() + allowance;
84    loop {
85        match relay.status() {
86            RelayStatus::Connected => return true,
87            RelayStatus::Terminated | RelayStatus::Banned => return false,
88            _ => {}
89        }
90        if crate::rt::time::Instant::now() >= deadline {
91            return false;
92        }
93        crate::rt::time::sleep(Duration::from_millis(150)).await;
94    }
95}
96
97// ============================================================================
98// Per-relay reconcile cursor
99// ============================================================================
100//
101// "Reconcile-verified through T": the boot quick sync reconciles a cursored
102// relay only from (cursor − NIP-59 slack), and the full-history pass runs
103// solely as a one-time bootstrap for relays with no cursor. A cursor advances
104// exclusively on PROOF — a zero-missing reconcile (the wrapper ledger only
105// gains rows after commit, so zero-missing means relay and ledger agree
106// through the window), or a bootstrap whose every requested event was
107// actually received. Never on a failed or partial pass: a wrong cursor
108// silently loses history, a stalled one merely re-reconciles a small window.
109
110fn cursor_key(relay_url: &str) -> String {
111    format!("neg_cursor:{}", relay_url.trim_end_matches('/'))
112}
113
114/// The relay's reconcile cursor (unix seconds), if it has ever earned one.
115pub fn reconcile_cursor(relay_url: &str) -> Option<u64> {
116    crate::db::get_sql_setting(cursor_key(relay_url)).ok()??.parse().ok()
117}
118
119/// Monotonic advance — one SQL upsert (the stored value only grows), so a
120/// late or concurrent writer can never regress the cursor. Session-gated
121/// IMMEDIATELY before the write: a swap landing after the caller's own check
122/// must not stamp this account's cursor into the next account's KV — that
123/// would both skew its quick window and silently skip its bootstrap.
124pub fn advance_reconcile_cursor(relay_url: &str, anchor_secs: u64) {
125    let _ = crate::db::advance_u64_setting(cursor_key(relay_url), anchor_secs);
126}
127
128/// True when a `relay.sync` failure says nothing durable about the relay —
129/// connection-state errors and timeouts. Only deterministic refusals (protocol
130/// errors, query caps) repeat identically on a later attempt, so only those
131/// belong on a same-boot skip-list; a connected relay that timed out is
132/// handled through the capability cache instead.
133pub fn is_transient_sync_error(err: &str) -> bool {
134    err == "timeout"
135        || err.contains("not connected")
136        || err.contains("transport dispatcher")
137        // SDK notification broadcast overflow on a busy connection — says
138        // nothing about the relay at all.
139        || err.contains("lagged")
140}
141
142pub fn classify_neg_sync_error(err: &str, relay_was_connected: bool) -> Option<bool> {
143    if err.contains("negentropy not supported")
144        || err.contains("unknown negentropy error")
145        || (err.contains("negentropy") && err.contains("protocol version"))
146    {
147        return Some(false);
148    }
149    if err == "timeout" && relay_was_connected {
150        return Some(false);
151    }
152    None
153}
154
155/// Race every trusted relay exchanging negentropy fingerprints for `filter`,
156/// and return the union of event IDs that relays hold but we don't.
157///
158/// `local_items` is our fingerprint set: `(event_id, created_at)` for
159/// everything we already possess. Each relay reports only the IDs absent from
160/// that set, so the union across relays is the complete missing set reachable
161/// from our trusted relays.
162///
163/// Every relay is drained (not just the first to respond): completeness beats
164/// latency here, and one relay may lack events another holds. Each relay is
165/// bounded by `timeout`.
166pub async fn reconcile_missing(
167    filter: Filter,
168    local_items: Vec<(EventId, Timestamp)>,
169    timeout: Duration,
170) -> Result<HashSet<EventId>, String> {
171    crate::db::scoped(async move {
172        use futures_util::stream::{FuturesUnordered, StreamExt};
173
174        let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
175
176        let opts = SyncOptions::new()
177            .direction(SyncDirection::Down)
178            .initial_timeout(timeout)
179            .dry_run();
180
181        // Resolve trusted relay URLs to live Relay handles, skipping relays with a
182        // fresh no-NIP-77 verdict — each would burn the full timeout for nothing.
183        let relay_map = client.relays().await;
184        let trusted = crate::state::active_trusted_relays().await;
185        let relays: Vec<(String, Relay)> = trusted.iter().filter_map(|url| {
186            if neg_supported_cached(url) == Some(false) {
187                crate::log_debug!("[Negentropy] {} skipped (cached: no NIP-77)", url);
188                return None;
189            }
190            let normalized = url.trim_end_matches('/');
191            relay_map.iter()
192                .find(|(u, _)| u.as_str().trim_end_matches('/') == normalized)
193                .map(|(_, r)| (url.to_string(), r.clone()))
194        }).collect();
195        drop(relay_map);
196
197        if relays.is_empty() {
198            crate::log_warn!("[Negentropy] No trusted relays available for reconciliation");
199            return Ok(HashSet::new());
200        }
201
202        let connect_allowance = crate::relay_request_timeout(Duration::from_secs(3)).min(timeout);
203        // One shared copy: the set can be every wrap we hold, and each relay keeps its future alive.
204        let local_items = std::sync::Arc::new(local_items);
205        let mut futs = FuturesUnordered::new();
206        for (url, relay) in &relays {
207            let url = url.clone();
208            let relay = relay.clone();
209            let f = filter.clone();
210            let items = local_items.clone();
211            let o = opts.clone();
212            futs.push(async move {
213                if !wait_connected(&relay, connect_allowance).await {
214                    return (url, None, false);
215                }
216                let r = crate::rt::time::timeout(timeout, relay.sync(f).items(items.iter().copied()).opts(o)).await;
217                let connected = relay.status() == RelayStatus::Connected;
218                (url, Some(r), connected)
219            });
220        }
221
222        let session = crate::db::current_session();
223        let mut missing: HashSet<EventId> = HashSet::new();
224        while let Some((url, result, connected)) = futs.next().await {
225            let Some(result) = result else {
226                crate::log_debug!("[Negentropy] {} skipped: not connected", url);
227                continue;
228            };
229            match result {
230                Ok(Ok(recon)) => {
231                    let n = recon.remote.len();
232                    missing.extend(recon.remote);
233                    crate::log_debug!("[Negentropy] {} reconciled: {} missing", url, n);
234                    record_neg_support(&url, true);
235                }
236                Ok(Err(e)) => {
237                    crate::log_warn!("[Negentropy] {} failed: {}", url, e);
238                    if session.is_live()
239                        && classify_neg_sync_error(&e.to_string(), connected && !neg_ever_confirmed(&url)) == Some(false)
240                    {
241                        crate::log_info!("[Negentropy] {} marked no-NIP-77 for 24h", url);
242                        record_neg_support(&url, false);
243                    }
244                }
245                Err(_) => crate::log_warn!("[Negentropy] {} timed out", url),
246            }
247        }
248
249        Ok(missing)
250    })
251    .await
252}
253
254#[cfg(test)]
255mod cap_tests {
256    use super::*;
257
258    #[test]
259    fn classify_detects_deterministic_refusals_regardless_of_connection() {
260        for err in [
261            "negentropy not supported",
262            "unknown negentropy error",
263            "negentropy: unsupported protocol version",
264        ] {
265            assert_eq!(classify_neg_sync_error(err, true), Some(false), "{err}");
266            assert_eq!(classify_neg_sync_error(err, false), Some(false), "{err}");
267        }
268    }
269
270    #[test]
271    fn classify_timeout_only_counts_when_connected() {
272        assert_eq!(classify_neg_sync_error("timeout", true), Some(false));
273        assert_eq!(classify_neg_sync_error("timeout", false), None);
274    }
275
276    #[test]
277    fn classify_ignores_unrelated_errors() {
278        for err in [
279            "auth-required: we can't serve DMs to unauthenticated users",
280            "relay message too large: size=200000, max_size=131072",
281            "not connected",
282            "timeout exceeded", // only the SDK's exact Display counts
283        ] {
284            assert_eq!(classify_neg_sync_error(err, true), None, "{err}");
285        }
286    }
287
288    #[test]
289    fn transient_errors_never_skip_the_archive() {
290        assert!(is_transient_sync_error("timeout"));
291        assert!(is_transient_sync_error("relay not connected"));
292        assert!(is_transient_sync_error("not connected"));
293        assert!(is_transient_sync_error("can't send message to the transport dispatcher"));
294        assert!(is_transient_sync_error("channel lagged by 558"));
295        assert!(!is_transient_sync_error("negentropy not supported"));
296        assert!(!is_transient_sync_error("unknown negentropy error"));
297        assert!(!is_transient_sync_error("blocked: sync too big"));
298    }
299
300    #[test]
301    fn cap_entry_parses_and_rejects() {
302        assert_eq!(parse_cap_entry("1:1753900000"), Some((true, 1753900000)));
303        assert_eq!(parse_cap_entry("0:42"), Some((false, 42)));
304        assert_eq!(parse_cap_entry("2:42"), None);
305        assert_eq!(parse_cap_entry("1:"), None);
306        assert_eq!(parse_cap_entry("1"), None);
307        assert_eq!(parse_cap_entry("nonsense"), None);
308        assert_eq!(parse_cap_entry(""), None);
309    }
310
311    #[test]
312    fn cap_key_normalizes_trailing_slash() {
313        assert_eq!(cap_key("wss://r.example/"), cap_key("wss://r.example"));
314        assert_eq!(cursor_key("wss://r.example/"), cursor_key("wss://r.example"));
315    }
316
317}