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.execute(
15        "INSERT OR IGNORE INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) VALUES (?1, ?2, ?3)",
16        rusqlite::params![&wrapper_id_bytes[..], wrapper_created_at as i64, transport],
17    ).map_err(|e| format!("Failed to save processed wrapper: {}", e))?;
18    Ok(())
19}
20
21/// Sync existence check against the ledger (any transport) — the DB half of the outer-event dedup
22/// for callers that can't reach the async `WRAPPER_ID_CACHE` (e.g. the synchronous Concord ingest).
23/// Returns false on a missing/closed DB so a dedup failure never drops a genuinely-new event.
24pub fn processed_wrapper_exists(wrapper_id_bytes: &[u8; 32]) -> bool {
25    let conn = match super::get_db_connection_guard_static() {
26        Ok(c) => c,
27        Err(_) => return false,
28    };
29    conn.query_row(
30        "SELECT EXISTS(SELECT 1 FROM processed_wrappers WHERE wrapper_id = ?1)",
31        rusqlite::params![&wrapper_id_bytes[..]],
32        |row| row.get(0),
33    ).unwrap_or(false)
34}
35
36/// Backfill a wrapper timestamp onto an EXISTING ledger row (pre-migration-17 rows hold 0).
37/// UPDATE-only by design: the ledger is the negentropy fingerprint set, and message wrappers
38/// may be deferred (batch-buffered) — an INSERT here could ledger a message before its row
39/// lands, marking it "have" forever. Inserting belongs to the save paths, never this backfill.
40pub fn update_wrapper_timestamp(wrapper_id_bytes: &[u8; 32], wrapper_created_at: u64) -> Result<(), String> {
41    let conn = super::get_write_connection_guard_static()?;
42    conn.execute(
43        "UPDATE processed_wrappers SET wrapper_created_at = ?2 \
44         WHERE wrapper_id = ?1 AND wrapper_created_at = 0",
45        rusqlite::params![&wrapper_id_bytes[..], wrapper_created_at as i64],
46    ).map_err(|e| format!("Failed to backfill wrapper timestamp: {}", e))?;
47    Ok(())
48}
49
50/// Load all processed wrapper IDs as raw bytes for the dedup cache.
51pub fn load_processed_wrappers() -> Result<Vec<[u8; 32]>, String> {
52    let conn = match super::get_db_connection_guard_static() {
53        Ok(c) => c,
54        Err(_) => return Ok(Vec::new()),
55    };
56    // NIP-17 only: this feeds the WRAPPER_ID_CACHE, the DM gift-wrap dedup. Concord uses the
57    // synchronous ledger check (processed_wrapper_exists), not this in-memory cache.
58    let mut stmt = conn.prepare("SELECT wrapper_id FROM processed_wrappers WHERE transport = 0")
59        .map_err(|e| format!("Failed to prepare processed_wrappers query: {}", e))?;
60    let rows = stmt.query_map([], |row| {
61        let blob: Vec<u8> = row.get(0)?;
62        if blob.len() == 32 {
63            let mut arr = [0u8; 32];
64            arr.copy_from_slice(&blob);
65            Ok(arr)
66        } else {
67            Err(rusqlite::Error::InvalidParameterCount(blob.len(), 32))
68        }
69    }).map_err(|e| format!("Failed to query processed_wrappers: {}", e))?;
70
71    Ok(rows.flatten().collect())
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    Ok(rows.flatten().collect())
97}
98
99/// Load recent wrapper IDs from events table (last N days) as raw bytes.
100pub fn load_recent_wrapper_ids(days: u64) -> Result<Vec<[u8; 32]>, String> {
101    let conn = match super::get_db_connection_guard_static() {
102        Ok(c) => c,
103        Err(_) => return Ok(Vec::new()),
104    };
105
106    let cutoff_secs = std::time::SystemTime::now()
107        .duration_since(std::time::UNIX_EPOCH).unwrap()
108        .as_secs()
109        .saturating_sub(days * 24 * 60 * 60);
110
111    // DM cache only: exclude Community chats (chat_type 2). Concord stamps its OUTER id on
112    // `events.wrapper_event_id` too (atomic message dedup), so without this join those ids would warm
113    // the DM gift-wrap cache — harmless (they'd never match a gift-wrap lookup) but wasteful. Concord
114    // dedup uses the synchronous `processed_wrapper_exists` ledger, not this cache.
115    let mut stmt = conn.prepare(
116        "SELECT e.wrapper_event_id FROM events e \
117         JOIN chats c ON e.chat_id = c.id \
118         WHERE e.wrapper_event_id IS NOT NULL AND e.wrapper_event_id != '' \
119         AND e.created_at >= ?1 AND c.chat_type != 2"
120    ).map_err(|e| format!("Failed to prepare wrapper_id query: {}", e))?;
121
122    // Decoded straight off the borrowed column text. Collecting owned `String`s
123    // first would allocate once per row and hold the whole hex set resident
124    // alongside the decoded one, for no gain — each id is read exactly once.
125    let mut rows = stmt
126        .query(rusqlite::params![cutoff_secs as i64])
127        .map_err(|e| format!("Failed to query wrapper_ids: {}", e))?;
128
129    let mut result: Vec<[u8; 32]> = Vec::new();
130    while let Some(row) = rows
131        .next()
132        .map_err(|e| format!("Failed to read wrapper_id row: {}", e))?
133    {
134        let Ok(hex) = row.get_ref(0).and_then(|v| v.as_str().map_err(Into::into)) else {
135            continue;
136        };
137        if hex.len() == 64 {
138            result.push(crate::simd::hex::hex_to_bytes_32(hex));
139        }
140    }
141    Ok(result)
142}
143
144/// Load all processed wrappers as (EventId, Timestamp) pairs for negentropy (NIP-77).
145pub fn load_negentropy_items() -> Result<Vec<(EventId, Timestamp)>, String> {
146    load_negentropy_items_inner(None)
147}
148
149/// Fingerprint items no older than `since_secs`.
150///
151/// Reconnect and quick reconciles cover a window of days, not all of history —
152/// on an established account that is a few dozen items out of six figures, so
153/// the bound belongs in SQL rather than in a filter over a fully materialised
154/// set.
155pub fn load_negentropy_items_since(
156    since_secs: u64,
157) -> Result<Vec<(EventId, Timestamp)>, String> {
158    load_negentropy_items_inner(Some(since_secs))
159}
160
161fn load_negentropy_items_inner(
162    since_secs: Option<u64>,
163) -> Result<Vec<(EventId, Timestamp)>, String> {
164    let conn = super::get_db_connection_guard_static()
165        .map_err(|_| "No DB connection".to_string())?;
166
167    // NIP-77 reconciles gift-wraps for our pubkey, so fingerprint ONLY the 'nip17' carrier.
168    // Concord outer events share the ledger for dedup but must never enter DM negentropy.
169    //
170    // Ordered so negentropy's `seal()` sorts an already-sorted set rather than a
171    // scan-ordered one. This is only cheap because `idx_processed_wrappers_neg`
172    // (migration 87) carries all three columns: against an index missing
173    // `wrapper_id` the same ORDER BY costs a temp B-tree and a row lookup per
174    // hit, which is far more than the sort it saves.
175    let sql = if since_secs.is_some() {
176        "SELECT wrapper_id, wrapper_created_at FROM processed_wrappers \
177         WHERE transport = 0 AND wrapper_created_at >= ?1 \
178         ORDER BY wrapper_created_at, wrapper_id"
179    } else {
180        "SELECT wrapper_id, wrapper_created_at FROM processed_wrappers \
181         WHERE transport = 0 \
182         ORDER BY wrapper_created_at, wrapper_id"
183    };
184
185    let mut stmt = conn
186        .prepare(sql)
187        .map_err(|e| format!("Failed to prepare negentropy query: {}", e))?;
188
189    // Ids are read as borrowed blobs: `get::<Vec<u8>>` would heap-allocate once
190    // per row, which on a six-figure set is the bulk of this function's cost.
191    let mut rows = match since_secs {
192        Some(since) => stmt.query(rusqlite::params![since as i64]),
193        None => stmt.query([]),
194    }
195    .map_err(|e| format!("Failed to query processed_wrappers: {}", e))?;
196
197    let mut items: Vec<(EventId, Timestamp)> = Vec::new();
198    while let Some(row) = rows
199        .next()
200        .map_err(|e| format!("Failed to read processed_wrappers row: {}", e))?
201    {
202        let Ok(blob) = row.get_ref(0).and_then(|v| v.as_blob().map_err(Into::into)) else {
203            continue;
204        };
205        if blob.len() != 32 {
206            continue;
207        }
208        let mut arr = [0u8; 32];
209        arr.copy_from_slice(blob);
210        // A malformed row is skipped, never fatal: callers fall back to an empty
211        // set on `Err`, and an empty fingerprint set tells negentropy we hold
212        // nothing, which re-downloads the entire history.
213        let Ok(created_at) = row.get::<_, i64>(1) else {
214            continue;
215        };
216        items.push((
217            EventId::from_byte_array(arr),
218            Timestamp::from_secs(created_at as u64),
219        ));
220    }
221
222    Ok(items)
223}