Skip to main content

vector_core/db/
wrappers.rs

1//! Wrapper tracking — NIP-59 gift wrap dedup + NIP-77 negentropy.
2
3use nostr_sdk::prelude::{EventId, Timestamp};
4
5/// Transport carriers for the shared outer-event ledger — stored as a small INTEGER discriminator
6/// (cheaper than a per-row string, and the ledger can grow large). Never renumber an existing value.
7pub const TRANSPORT_NIP17: i64 = 0;
8pub const TRANSPORT_CONCORD: i64 = 1;
9
10/// Persist an outer-event id for cross-session dedup (INSERT OR IGNORE), tagged by `transport`
11/// so the ledger is shared across transports while negentropy stays NIP-17-scoped.
12pub fn save_processed_wrapper(wrapper_id_bytes: &[u8; 32], wrapper_created_at: u64, transport: i64) -> Result<(), String> {
13    let conn = super::get_write_connection_guard_static()?;
14    conn.prepare_cached("INSERT OR IGNORE INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) VALUES (?1, ?2, ?3)")
15        .and_then(|mut stmt| stmt.execute(rusqlite::params![&wrapper_id_bytes[..], wrapper_created_at as i64, transport]))
16        .map_err(|e| format!("Failed to save processed wrapper: {}", e))?;
17    Ok(())
18}
19
20/// Sync existence check against the ledger (any transport) — the DB half of the outer-event dedup
21/// for callers that can't reach the async `WRAPPER_ID_CACHE` (e.g. the synchronous Concord ingest).
22/// Returns false on a missing/closed DB so a dedup failure never drops a genuinely-new event.
23pub fn processed_wrapper_exists(wrapper_id_bytes: &[u8; 32]) -> bool {
24    let conn = match super::get_db_connection_guard_static() {
25        Ok(c) => c,
26        Err(_) => return false,
27    };
28    conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM processed_wrappers WHERE wrapper_id = ?1)")
29        .and_then(|mut stmt| stmt.query_row(rusqlite::params![&wrapper_id_bytes[..]], |row| row.get(0)))
30        .unwrap_or(false)
31}
32
33/// Backfill a wrapper timestamp onto an EXISTING ledger row (pre-migration-17 rows hold 0).
34/// UPDATE-only by design: the ledger is the negentropy fingerprint set, and message wrappers
35/// may be deferred (batch-buffered) — an INSERT here could ledger a message before its row
36/// lands, marking it "have" forever. Inserting belongs to the save paths, never this backfill.
37pub fn update_wrapper_timestamp(wrapper_id_bytes: &[u8; 32], wrapper_created_at: u64) -> Result<(), String> {
38    let conn = super::get_write_connection_guard_static()?;
39    conn.execute(
40        "UPDATE processed_wrappers SET wrapper_created_at = ?2 \
41         WHERE wrapper_id = ?1 AND wrapper_created_at = 0",
42        rusqlite::params![&wrapper_id_bytes[..], wrapper_created_at as i64],
43    ).map_err(|e| format!("Failed to backfill wrapper timestamp: {}", e))?;
44    Ok(())
45}
46
47/// Load all processed wrapper IDs as raw bytes for the dedup cache.
48pub fn load_processed_wrappers() -> Result<Vec<[u8; 32]>, String> {
49    let conn = match super::get_db_connection_guard_static() {
50        Ok(c) => c,
51        Err(_) => return Ok(Vec::new()),
52    };
53    // NIP-17 only: this feeds the WRAPPER_ID_CACHE, the DM gift-wrap dedup. Concord uses the
54    // synchronous ledger check (processed_wrapper_exists), not this in-memory cache.
55    let mut stmt = conn.prepare("SELECT wrapper_id FROM processed_wrappers WHERE transport = 0")
56        .map_err(|e| format!("Failed to prepare processed_wrappers query: {}", e))?;
57    let rows = stmt.query_map([], |row| {
58        let blob: Vec<u8> = row.get(0)?;
59        if blob.len() == 32 {
60            let mut arr = [0u8; 32];
61            arr.copy_from_slice(&blob);
62            Ok(arr)
63        } else {
64            Err(rusqlite::Error::InvalidParameterCount(blob.len(), 32))
65        }
66    }).map_err(|e| format!("Failed to query processed_wrappers: {}", e))?;
67
68    // The dedup cache holds this for a whole sync, and collect's doubling can leave it half empty.
69    let mut ids: Vec<[u8; 32]> = rows.flatten().collect();
70    ids.shrink_to_fit();
71    Ok(ids)
72}
73
74/// [`load_processed_wrappers`] bounded to `wrapper_created_at >= since_secs` —
75/// the dedup cache only needs the window the planned reconciles can touch;
76/// anything older that still arrives dedups through the DB fallback.
77pub fn load_processed_wrappers_since(since_secs: u64) -> Result<Vec<[u8; 32]>, String> {
78    let conn = match super::get_db_connection_guard_static() {
79        Ok(c) => c,
80        Err(_) => return Ok(Vec::new()),
81    };
82    let mut stmt = conn.prepare(
83        "SELECT wrapper_id FROM processed_wrappers WHERE transport = 0 AND wrapper_created_at >= ?1",
84    ).map_err(|e| format!("Failed to prepare processed_wrappers query: {}", e))?;
85    let rows = stmt.query_map(rusqlite::params![since_secs as i64], |row| {
86        let blob: Vec<u8> = row.get(0)?;
87        if blob.len() == 32 {
88            let mut arr = [0u8; 32];
89            arr.copy_from_slice(&blob);
90            Ok(arr)
91        } else {
92            Err(rusqlite::Error::InvalidParameterCount(blob.len(), 32))
93        }
94    }).map_err(|e| format!("Failed to query processed_wrappers: {}", e))?;
95
96    let mut ids: Vec<[u8; 32]> = rows.flatten().collect();
97    ids.shrink_to_fit();
98    Ok(ids)
99}
100
101/// Load all processed wrappers as (EventId, Timestamp) pairs for negentropy (NIP-77).
102pub fn load_negentropy_items() -> Result<Vec<(EventId, Timestamp)>, String> {
103    load_negentropy_items_inner(None)
104}
105
106/// Fingerprint items no older than `since_secs`.
107///
108/// Reconnect and quick reconciles cover a window of days, not all of history —
109/// on an established account that is a few dozen items out of six figures, so
110/// the bound belongs in SQL rather than in a filter over a fully materialised
111/// set.
112pub fn load_negentropy_items_since(
113    since_secs: u64,
114) -> Result<Vec<(EventId, Timestamp)>, String> {
115    load_negentropy_items_inner(Some(since_secs))
116}
117
118fn load_negentropy_items_inner(
119    since_secs: Option<u64>,
120) -> Result<Vec<(EventId, Timestamp)>, String> {
121    let conn = super::get_db_connection_guard_static()
122        .map_err(|_| "No DB connection".to_string())?;
123
124    // NIP-77 reconciles gift-wraps for our pubkey, so fingerprint ONLY the 'nip17' carrier.
125    // Concord outer events share the ledger for dedup but must never enter DM negentropy.
126    //
127    // Ordered so negentropy's `seal()` sorts an already-sorted set rather than a
128    // scan-ordered one. This is only cheap because `idx_processed_wrappers_neg`
129    // (migration 87) carries all three columns: against an index missing
130    // `wrapper_id` the same ORDER BY costs a temp B-tree and a row lookup per
131    // hit, which is far more than the sort it saves.
132    let sql = if since_secs.is_some() {
133        "SELECT wrapper_id, wrapper_created_at FROM processed_wrappers \
134         WHERE transport = 0 AND wrapper_created_at >= ?1 \
135         ORDER BY wrapper_created_at, wrapper_id"
136    } else {
137        "SELECT wrapper_id, wrapper_created_at FROM processed_wrappers \
138         WHERE transport = 0 \
139         ORDER BY wrapper_created_at, wrapper_id"
140    };
141
142    let mut stmt = conn
143        .prepare(sql)
144        .map_err(|e| format!("Failed to prepare negentropy query: {}", e))?;
145
146    // Ids are read as borrowed blobs: `get::<Vec<u8>>` would heap-allocate once
147    // per row, which on a six-figure set is the bulk of this function's cost.
148    let mut rows = match since_secs {
149        Some(since) => stmt.query(rusqlite::params![since as i64]),
150        None => stmt.query([]),
151    }
152    .map_err(|e| format!("Failed to query processed_wrappers: {}", e))?;
153
154    let mut items: Vec<(EventId, Timestamp)> = Vec::new();
155    while let Some(row) = rows
156        .next()
157        .map_err(|e| format!("Failed to read processed_wrappers row: {}", e))?
158    {
159        let Ok(blob) = row.get_ref(0).and_then(|v| v.as_blob().map_err(Into::into)) else {
160            continue;
161        };
162        if blob.len() != 32 {
163            continue;
164        }
165        let mut arr = [0u8; 32];
166        arr.copy_from_slice(blob);
167        // A malformed row is skipped, never fatal: callers fall back to an empty
168        // set on `Err`, and an empty fingerprint set tells negentropy we hold
169        // nothing, which re-downloads the entire history.
170        let Ok(created_at) = row.get::<_, i64>(1) else {
171            continue;
172        };
173        items.push((
174            EventId::from_byte_array(arr),
175            Timestamp::from_secs(created_at as u64),
176        ));
177    }
178    // An archive reconcile holds the set for minutes.
179    items.shrink_to_fit();
180
181    Ok(items)
182}