Skip to main content

vector_core/
event_handler.rs

1//! Event handler — gift wrap receive, unwrap, process, commit pipeline.
2//!
3//! Two-phase architecture:
4//! - **Phase 1** (`prepare_event`): Parallel-safe — dedup, unwrap, process_rumor
5//! - **Phase 2** (`commit_prepared_event`): Sequential — save DB, update STATE, emit
6//!
7//! Platform-specific behavior (notifications) handled by `InboundEventHandler` trait.
8
9use nostr_sdk::prelude::*;
10
11use crate::rumor::{RumorProcessingResult, RumorEvent, RumorContext, ConversationType, process_rumor};
12use crate::types::Message;
13use crate::state::WRAPPER_ID_CACHE;
14
15/// Platform-specific callbacks for inbound event processing.
16///
17/// Same pattern as SendCallback/ProfileSyncHandler — trait with default no-ops.
18/// Platforms implement only the hooks they need.
19pub trait InboundEventHandler: Send + Sync {
20    /// A DM text message was received and committed to STATE + DB.
21    fn on_dm_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
22
23    /// A DM file attachment was received and committed to STATE + DB.
24    fn on_file_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
25
26    /// A reaction was received and applied to a message.
27    fn on_reaction_received(&self, _chat_id: &str, _msg: &Message) {}
28
29    /// A previously-stored message was deleted by its sender (Layer 2
30    /// cooperative hide via NIP-09 over NIP-17). Frontend drops the row.
31    fn on_message_deleted(&self, _chat_id: &str, _message_id: &str) {}
32
33    /// A Community invite was received over a gift wrap and the local user was
34    /// joined (member-view Community persisted). Platform refreshes the Community
35    /// subscription so messages start flowing, and surfaces the new Community in the UI.
36    fn on_community_invite(&self, _community_id: &str) {}
37
38    // --- Community realtime (Concord channel events; `chat_id` is the channel id hex) ---
39
40    /// A new Community channel message was received, ingested into STATE, and persisted.
41    fn on_community_message(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
42
43    /// A reaction or edit was applied to an existing Community message. `target_id` is the
44    /// affected message; `msg` is the live-updated view.
45    fn on_community_update(&self, _chat_id: &str, _target_id: &str, _msg: &Message) {}
46
47    /// A Community message was removed (cooperative delete / moderation tombstone).
48    fn on_community_removed(&self, _chat_id: &str, _target_id: &str) {}
49
50    /// A join/leave presence announcement. `created_at` is the authenticated inner timestamp;
51    /// `invited_by`/`invited_label` carry invite attribution when present.
52    #[allow(clippy::too_many_arguments)]
53    fn on_community_presence(
54        &self,
55        _chat_id: &str,
56        _npub: &str,
57        _joined: bool,
58        _event_id: &str,
59        _created_at: u64,
60        _invited_by: Option<&str>,
61        _invited_label: Option<&str>,
62    ) {}
63
64    /// A Community typing indicator (ephemeral). `until` is the unix-secs the typer stops being active.
65    fn on_community_typing(&self, _chat_id: &str, _npub: &str, _until: u64) {}
66
67    /// Someone joined or left a voice Channel's call, or went stale (`community::v2::voice`).
68    fn on_voice_presence(&self, _channel_id: &str) {}
69
70    /// A WebXDC realtime peer signal. `node_addr` = `Some` advertises an Iroh node, `None` = peer-left.
71    #[allow(clippy::too_many_arguments)]
72    fn on_community_webxdc(
73        &self,
74        _chat_id: &str,
75        _npub: &str,
76        _topic_id: &str,
77        _node_addr: Option<&str>,
78        _event_id: &str,
79        _created_at: u64,
80    ) {}
81
82    /// A WebXDC realtime peer signal in a DM. `contact` is the DM's npub; `node_addr` =
83    /// `Some` advertises an Iroh node, `None` = peer-left. Clients without Iroh ignore it.
84    #[allow(clippy::too_many_arguments)]
85    fn on_webxdc_signal(
86        &self,
87        _contact: &str,
88        _npub: &str,
89        _topic_id: &str,
90        _node_addr: Option<&str>,
91        _event_id: &str,
92        _created_at: u64,
93    ) {}
94
95    /// The local user was removed from a Community (kick / ban / a leave authored on another device).
96    /// Local data is torn down (epoch keys retained); the platform surfaces it + refreshes subs.
97    fn on_community_self_removed(&self, _community_id: &str) {}
98
99    /// A Private channel is now readable — its key arrived, by rekey delivery or
100    /// by a grant's key vend. `channel_id` is the 32-byte hex id.
101    ///
102    /// The inverse of the silent-mute failure: a bot granted access can act the
103    /// moment it can actually read, rather than polling for a channel it has no
104    /// way to know it is waiting on.
105    ///
106    /// `backfilled` counts the messages that predate the grant and were pulled
107    /// into LOCAL STATE before this fired. A listener is told of those sent since it
108    /// began listening; older ones are history: read them explicitly
109    /// (`get_messages_before`) and decide what deserves acting on.
110    fn on_channel_keyed(&self, _community_id: &str, _channel_id: &str, _backfilled: usize) {}
111
112    /// The realtime Community subscription REGISTERED: healthy relays deliver
113    /// live channel events from this moment (AUTH-gating relays join as their
114    /// stream auth completes in the background). Fires once per
115    /// [`listen`](crate::VectorCore::listen), after the startup refresh commits —
116    /// even when `communities` is 0, so "subscribed to nothing" and "still
117    /// connecting" are distinguishable. With [`CatchUp::Inline`](crate::CatchUp::Inline),
118    /// whatever was sent since `listen` began reaches the handler however it arrives,
119    /// before this or after ([`crate::news`]).
120    fn on_subscription_ready(&self, _communities: usize) {}
121
122    /// A Community's control plane was refreshed in realtime (banlist/roles/metadata/mode change,
123    /// or a re-founding followed). The platform re-reads display state.
124    fn on_community_refreshed(&self, _community_id: &str) {}
125
126    /// A Community was DISSOLVED by its owner (CORD-02 §9): sealed read-only, held keys still open
127    /// history but nothing new is honored. The platform surfaces the grave.
128    fn on_community_dissolved(&self, _community_id: &str) {}
129
130    // --- Typed changes. DM and Community alike: `chat_id` is the contact's npub or the channel
131    // id. The coarse hooks above still fire; these say what happened.
132
133    /// A reaction landed. `msg` is the message with it applied. `at` (unix ms, here and below)
134    /// is when it was sent, as its sender dated it.
135    fn on_reaction_added(&self, _chat_id: &str, _msg: &Message, _reaction: &crate::types::Reaction, _at: u64) {}
136
137    /// A reaction was withdrawn by its reactor, `by` (an npub). `msg` is the message without it.
138    fn on_reaction_removed(&self, _chat_id: &str, _msg: &Message, _reaction_id: &str, _by: &str, _at: u64) {}
139
140    /// A message was edited by its author. `msg` carries the new content.
141    fn on_message_edited(&self, _chat_id: &str, _msg: &Message, _at: u64) {}
142
143    /// A message was removed by `by` (an npub): its author, or a moderator when `moderated`.
144    /// `by` is `None` when the Community's own rules took it back (a post held for review
145    /// that no longer stands), which reads as `moderated`; `at` is then when this device judged it.
146    fn on_message_removed(&self, _chat_id: &str, _message_id: &str, _by: Option<&str>, _moderated: bool, _at: u64) {}
147
148    /// A DM typing indicator. `until` is the unix-secs the typer stops being active.
149    fn on_dm_typing(&self, _chat_id: &str, _npub: &str, _until: u64) {}
150
151    /// Opt in to [`on_community_change`](Self::on_community_change): each refresh is then
152    /// compared with the last, which costs a few local reads per Community refresh.
153    fn wants_community_changes(&self) -> bool { false }
154
155    /// One change to a Community's settings, Roles, Channels or members, with who made it.
156    /// Fires only when [`wants_community_changes`](Self::wants_community_changes) says so.
157    fn on_community_change(&self, _community_id: &str, _change: &crate::community::v2::changes::CommunityChange) {}
158
159    /// Bulk-sync persist intercept: return `true` to take ownership of persisting a committed
160    /// DM/file message — the commit then SKIPS its per-message save AND its wrapper-ledger
161    /// write (`wrapper` = the gift-wrap's `(id_bytes, created_at)`; the owner MUST commit it
162    /// in the same transaction as the message row, or the message loses crash/drop
163    /// recoverability). Streaming sync loops (see [`BatchingPersist`]) buffer here and drain
164    /// many messages into one transaction. Default `false` keeps the per-message save.
165    fn buffer_persist(&self, _chat_id: &str, _msg: &Message, _wrapper: Option<([u8; 32], u64)>) -> bool { false }
166}
167
168/// No-op handler for CLI/tests.
169pub struct NoOpEventHandler;
170impl InboundEventHandler for NoOpEventHandler {}
171
172/// For catch-up syncs: forwards to `inner` only what is live rather than
173/// history. Mini App peer signals and Community invites always: each is live state, and a
174/// sync that opens one ledgers its wrapper, so the live subscription will never
175/// deliver it again. With [`from`](Self::from), also messages, reactions, edits and
176/// deletions sent since that moment: a sync may be the only path that carries them.
177pub struct LiveOnly<'a> {
178    inner: &'a dyn InboundEventHandler,
179    live_from_ms: Option<u64>,
180}
181
182impl<'a> LiveOnly<'a> {
183    /// Signals only.
184    pub fn signals(inner: &'a dyn InboundEventHandler) -> Self {
185        LiveOnly { inner, live_from_ms: None }
186    }
187
188    /// Signals, and messages sent at or after `ms` (unix milliseconds).
189    pub fn from(inner: &'a dyn InboundEventHandler, ms: u64) -> Self {
190        LiveOnly { inner, live_from_ms: Some(ms) }
191    }
192
193    fn is_live(&self, msg: &Message) -> bool {
194        self.is_live_at(msg.at)
195    }
196
197    fn is_live_at(&self, at_ms: u64) -> bool {
198        self.live_from_ms.is_some_and(|from| at_ms >= from)
199    }
200}
201
202impl InboundEventHandler for LiveOnly<'_> {
203    /// An invite a sync parks is waiting on a decision now, however old its wrap.
204    fn on_community_invite(&self, community_id: &str) {
205        self.inner.on_community_invite(community_id)
206    }
207
208    fn on_community_webxdc(&self, chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) {
209        self.inner.on_community_webxdc(chat_id, npub, topic_id, node_addr, event_id, created_at)
210    }
211
212    fn on_webxdc_signal(&self, contact: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) {
213        self.inner.on_webxdc_signal(contact, npub, topic_id, node_addr, event_id, created_at)
214    }
215
216    fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
217        if self.is_live(msg) {
218            self.inner.on_dm_received(chat_id, msg, is_new)
219        }
220    }
221
222    fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
223        if self.is_live(msg) {
224            self.inner.on_file_received(chat_id, msg, is_new)
225        }
226    }
227
228    fn on_reaction_added(&self, chat_id: &str, msg: &Message, reaction: &crate::types::Reaction, at: u64) {
229        if self.is_live_at(at) {
230            self.inner.on_reaction_added(chat_id, msg, reaction, at)
231        }
232    }
233
234    fn on_reaction_removed(&self, chat_id: &str, msg: &Message, reaction_id: &str, by: &str, at: u64) {
235        if self.is_live_at(at) {
236            self.inner.on_reaction_removed(chat_id, msg, reaction_id, by, at)
237        }
238    }
239
240    fn on_message_edited(&self, chat_id: &str, msg: &Message, at: u64) {
241        if self.is_live_at(at) {
242            self.inner.on_message_edited(chat_id, msg, at)
243        }
244    }
245
246    fn on_message_removed(&self, chat_id: &str, message_id: &str, by: Option<&str>, moderated: bool, at: u64) {
247        if self.is_live_at(at) {
248            self.inner.on_message_removed(chat_id, message_id, by, moderated, at)
249        }
250    }
251}
252
253/// One deferred DM persist: the message, its chat, and its gift-wrap ledger entry — the
254/// ledger row commits in the same flush transaction as the message row (see
255/// `save_messages_batch_multi`), so a lost batch leaves the wrapper unledgered.
256struct BufferedDm {
257    chat_id: String,
258    msg: Message,
259    wrapper: Option<([u8; 32], u64)>,
260}
261
262/// Wraps any handler for a bulk-sync drain loop: every callback delegates to the inner
263/// handler, but committed messages BUFFER here instead of saving one transaction each —
264/// the loop calls [`BatchingPersist::flush`] periodically and at stream end to land them
265/// in batched transactions (`save_messages_batch_multi`).
266///
267/// Deferral is recoverable because the wrapper ledger (the negentropy fingerprint set)
268/// rides the flush transaction: a message lost to a crash, a stale-session drop, or a
269/// failed flush leaves its wrapper unledgered, so the next reconciliation re-delivers it.
270pub struct BatchingPersist<'a> {
271    inner: &'a dyn InboundEventHandler,
272    buf: std::sync::Mutex<Vec<BufferedDm>>,
273    /// The account whose messages are in the buffer.
274    ///
275    /// Held rather than resolved at flush time: this outlives the calls that
276    /// fill it, and a flush reached after a swap would otherwise write one
277    /// account's inbox into another's. Holding it means the buffer always
278    /// drains where it was filled, from any caller, bound or not.
279    session: std::sync::Arc<crate::db::Session>,
280}
281
282impl<'a> BatchingPersist<'a> {
283    pub fn new(inner: &'a dyn InboundEventHandler) -> Self {
284        Self {
285            inner,
286            buf: std::sync::Mutex::new(Vec::new()),
287            session: crate::db::current_session(),
288        }
289    }
290
291    /// How many messages are waiting — the loop's flush-threshold probe.
292    pub fn buffered(&self) -> usize {
293        self.buf.lock().map(|b| b.len()).unwrap_or(0)
294    }
295
296    /// Drain the buffer into batched transactions (grouped by chat, arrival order kept),
297    /// against the account that filled it.
298    pub async fn flush(&self) -> usize {
299        self.try_flush().await.unwrap_or(0)
300    }
301
302    /// [`Self::flush`], but a persist failure is distinguishable from "nothing
303    /// to write" — callers that gate follow-on effects on the ledger actually
304    /// holding the batch (reconcile-cursor births) need the difference: an
305    /// advance over an unledgered batch skips those events forever.
306    pub async fn try_flush(&self) -> Result<usize, String> {
307        crate::db::with_session(self.session.clone(), async move {
308            let mut drained: Vec<BufferedDm> = match self.buf.lock() {
309                Ok(mut b) => b.drain(..).collect(),
310                Err(_) => return Ok(0),
311            };
312            if drained.is_empty() {
313                return Ok(0);
314            }
315            // A deletion may have landed (live subscription or this stream) while an entry sat
316            // buffered: its delete_event no-ops on the not-yet-written row, so persisting the
317            // buffered copy would resurrect a deleted message. Keyed on the POSITIVE deletion
318            // tombstone, never STATE absence — the LRU evicts old messages from STATE, and
319            // archive-synced history is exactly that tail (an evicted message must still
320            // persist). A dropped entry's wrapper stays unledgered and re-delivers next sync,
321            // where the DB dedup sees the (still-deleted) state cleanly.
322            drained.retain(|e| !crate::state::was_message_deleted(&e.msg.id));
323            if drained.is_empty() {
324                return Ok(0);
325            }
326            // Group by chat preserving first-seen chat order + per-chat arrival order.
327            let mut groups: Vec<crate::db::events::ChatBatch<'_>> = Vec::new();
328            for e in &drained {
329                match groups.iter_mut().find(|(c, _)| c == &e.chat_id) {
330                    Some((_, v)) => v.push((&e.msg, e.wrapper)),
331                    None => groups.push((e.chat_id.clone(), vec![(&e.msg, e.wrapper)])),
332                }
333            }
334            match crate::db::events::save_messages_batch_multi(&groups).await {
335                Ok(n) => {
336                    // The arrivals were announced as they were processed, before this commit, so
337                    // any unread count read meanwhile missed them: have it read again now.
338                    let chats: Vec<&str> = groups.iter().map(|(c, _)| c.as_str()).collect();
339                    crate::emit_event("unread_counts_stale", &serde_json::json!({ "chats": chats }));
340                    Ok(n)
341                }
342                Err(e) => {
343                    crate::log_warn!("[Sync] batched persist failed ({} msgs): {}", drained.len(), e);
344                    Err(e)
345                }
346            }
347        })
348        .await
349    }
350}
351
352impl InboundEventHandler for BatchingPersist<'_> {
353    fn buffer_persist(&self, chat_id: &str, msg: &Message, wrapper: Option<([u8; 32], u64)>) -> bool {
354        match self.buf.lock() {
355            Ok(mut b) => {
356                b.push(BufferedDm { chat_id: chat_id.to_string(), msg: msg.clone(), wrapper });
357                true
358            }
359            // Poisoned lock: fall back to the commit's own per-message save.
360            Err(_) => false,
361        }
362    }
363
364    fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
365        self.inner.on_dm_received(chat_id, msg, is_new)
366    }
367    fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
368        self.inner.on_file_received(chat_id, msg, is_new)
369    }
370    fn on_reaction_received(&self, chat_id: &str, msg: &Message) {
371        self.inner.on_reaction_received(chat_id, msg)
372    }
373    fn on_message_deleted(&self, chat_id: &str, message_id: &str) {
374        // The deletion's delete_event no-ops when the target is still buffered here —
375        // purge it (unledgered wrapper → re-delivers → dedups against the deleted state)
376        // so the flush can't resurrect a deleted message.
377        if let Ok(mut b) = self.buf.lock() {
378            b.retain(|e| e.msg.id != message_id);
379        }
380        self.inner.on_message_deleted(chat_id, message_id)
381    }
382    fn on_community_invite(&self, community_id: &str) {
383        self.inner.on_community_invite(community_id)
384    }
385    fn on_community_message(&self, chat_id: &str, msg: &Message, is_new: bool) {
386        self.inner.on_community_message(chat_id, msg, is_new)
387    }
388    fn on_community_update(&self, chat_id: &str, target_id: &str, msg: &Message) {
389        self.inner.on_community_update(chat_id, target_id, msg)
390    }
391    fn on_community_removed(&self, chat_id: &str, target_id: &str) {
392        self.inner.on_community_removed(chat_id, target_id)
393    }
394    fn on_community_presence(
395        &self,
396        chat_id: &str,
397        npub: &str,
398        joined: bool,
399        event_id: &str,
400        created_at: u64,
401        invited_by: Option<&str>,
402        invited_label: Option<&str>,
403    ) {
404        self.inner.on_community_presence(chat_id, npub, joined, event_id, created_at, invited_by, invited_label)
405    }
406    fn on_community_typing(&self, chat_id: &str, npub: &str, until: u64) {
407        self.inner.on_community_typing(chat_id, npub, until)
408    }
409    fn on_community_webxdc(
410        &self,
411        chat_id: &str,
412        npub: &str,
413        topic_id: &str,
414        node_addr: Option<&str>,
415        event_id: &str,
416        created_at: u64,
417    ) {
418        self.inner.on_community_webxdc(chat_id, npub, topic_id, node_addr, event_id, created_at)
419    }
420    fn on_webxdc_signal(
421        &self,
422        contact: &str,
423        npub: &str,
424        topic_id: &str,
425        node_addr: Option<&str>,
426        event_id: &str,
427        created_at: u64,
428    ) {
429        self.inner.on_webxdc_signal(contact, npub, topic_id, node_addr, event_id, created_at)
430    }
431    fn on_community_self_removed(&self, community_id: &str) {
432        self.inner.on_community_self_removed(community_id)
433    }
434    fn on_community_refreshed(&self, community_id: &str) {
435        self.inner.on_community_refreshed(community_id)
436    }
437    fn on_community_dissolved(&self, community_id: &str) {
438        self.inner.on_community_dissolved(community_id)
439    }
440    fn on_reaction_added(&self, chat_id: &str, msg: &Message, reaction: &crate::types::Reaction, at: u64) {
441        self.inner.on_reaction_added(chat_id, msg, reaction, at)
442    }
443    fn on_reaction_removed(&self, chat_id: &str, msg: &Message, reaction_id: &str, by: &str, at: u64) {
444        self.inner.on_reaction_removed(chat_id, msg, reaction_id, by, at)
445    }
446    fn on_message_edited(&self, chat_id: &str, msg: &Message, at: u64) {
447        self.inner.on_message_edited(chat_id, msg, at)
448    }
449    fn on_message_removed(&self, chat_id: &str, message_id: &str, by: Option<&str>, moderated: bool, at: u64) {
450        if let Ok(mut b) = self.buf.lock() {
451            b.retain(|e| e.msg.id != message_id);
452        }
453        self.inner.on_message_removed(chat_id, message_id, by, moderated, at)
454    }
455    fn on_dm_typing(&self, chat_id: &str, npub: &str, until: u64) {
456        self.inner.on_dm_typing(chat_id, npub, until)
457    }
458    fn wants_community_changes(&self) -> bool {
459        self.inner.wants_community_changes()
460    }
461    fn on_community_change(&self, community_id: &str, change: &crate::community::v2::changes::CommunityChange) {
462        self.inner.on_community_change(community_id, change)
463    }
464}
465
466/// Result of Phase 1 (prepare_event) — everything needed for sequential commit.
467#[allow(clippy::large_enum_variant)] // boxing a public variant's payload is an API break
468pub enum PreparedEvent {
469    /// A contact's push tickets (`vector-push`): kept so our DMs can wake their devices.
470    PushTickets {
471        contact: String,
472        is_mine: bool,
473        content: String,
474        wrapper_event_id_bytes: [u8; 32],
475        wrapper_created_at: u64,
476    },
477    /// Fully processed DM rumor — ready for state commit.
478    Processed {
479        result: RumorProcessingResult,
480        contact: String,
481        sender: PublicKey,
482        is_mine: bool,
483        wrapper_event_id: String,
484        wrapper_event_id_bytes: [u8; 32],
485        wrapper_created_at: u64,
486        /// The rumor's own send time (unix ms): the wrap's is randomised.
487        rumor_at_ms: u64,
488        /// Time spent on ECDH + ChaCha20Poly1305 decryption (nanoseconds)
489        unwrap_ns: u64,
490        /// Time spent on rumor parsing (nanoseconds)
491        parse_ns: u64,
492    },
493    /// Concord v2 Direct Invite (inner kind 3313) — parked for explicit consent.
494    /// Carries the raw bundle JSON (parked verbatim; the accept path re-parses it).
495    CommunityInviteV2 {
496        bundle_json: String,
497        community_id: String,
498        /// Inviter's npub (hex) — the proven seal signer.
499        inviter: String,
500        is_mine: bool,
501        wrapper_event_id_bytes: [u8; 32],
502        wrapper_created_at: u64,
503        /// Inner rumor `created_at` (seconds) — the real send time; NIP-59 backdates the
504        /// outer wrapper up to 2 days.
505        rumor_created_at: u64,
506        /// Sender-declared NIP-40 expiry (unix secs); 0 = none, so permanent.
507        expires_at: u64,
508    },
509    /// A message dated ahead of this device's clock: its wrap waits for its time
510    /// ([`crate::early`]), unmarked, so it comes back if this session ends first.
511    Early {
512        wrap: Event,
513        at_ms: u64,
514    },
515    /// Duplicate event — just persist wrapper for negentropy.
516    DedupSkip {
517        wrapper_id_bytes: [u8; 32],
518        wrapper_created_at: u64,
519    },
520    /// Error during unwrap/processing — persist wrapper for negentropy.
521    ErrorSkip {
522        wrapper_id_bytes: [u8; 32],
523        wrapper_created_at: u64,
524    },
525}
526
527/// Phase 1: Prepare an event for commit (parallel-safe, no state mutation).
528///
529/// Performs dedup check, gift wrap decryption, and rumor parsing.
530/// Safe to call from multiple tokio tasks concurrently.
531pub async fn prepare_event(
532    event: Event,
533    _client: &Client,
534    my_public_key: PublicKey,
535) -> PreparedEvent {
536    if let Some(skip) = dedup_skip(&event).await {
537        return skip;
538    }
539    let unwrap_start = web_time::Instant::now();
540    let unwrapped = crate::signer::unwrap_gift_wrap(&event).await;
541    finish_prepare(&event, unwrapped, unwrap_start.elapsed().as_nanos() as u64, my_public_key)
542}
543
544/// Wraps per [`prepare_events`] call on bulk paths (syncs, catch-up). Their seal signatures
545/// are checked in one batch, so a bigger batch checks each for less; the vault still opens
546/// them [`crate::crypto::WRAPS_PER_VAULT_READ`] at a time. A chunk holds whatever has
547/// arrived, up to this many: nothing waits to fill one.
548pub const UNWRAP_BATCH: usize = 64;
549
550/// [`prepare_event`] for many events, one result per event in order. The wraps that pass
551/// dedup are opened together, under one vault read for a local key.
552pub async fn prepare_events(events: &[Event], my_public_key: PublicKey) -> Vec<PreparedEvent> {
553    let mut out: Vec<Option<PreparedEvent>> = Vec::with_capacity(events.len());
554    for event in events {
555        out.push(dedup_skip(event).await);
556    }
557    let todo: Vec<&Event> = events.iter().zip(&out).filter(|(_, o)| o.is_none()).map(|(e, _)| e).collect();
558    if !todo.is_empty() {
559        let unwrap_start = web_time::Instant::now();
560        let unwrapped = crate::signer::unwrap_gift_wraps(&todo).await;
561        let unwrap_ns = unwrap_start.elapsed().as_nanos() as u64 / todo.len() as u64;
562        let mut unwrapped = unwrapped.into_iter();
563        for (event, slot) in events.iter().zip(out.iter_mut()) {
564            if slot.is_none() {
565                let u = unwrapped.next().unwrap_or_else(|| Err("missing unwrap result".into()));
566                *slot = Some(finish_prepare(event, u, unwrap_ns, my_public_key));
567            }
568        }
569    }
570    out.into_iter().flatten().collect()
571}
572
573/// `Some(DedupSkip)` when this wrap has been seen before.
574async fn dedup_skip(event: &Event) -> Option<PreparedEvent> {
575    let wrapper_created_at = event.created_at.as_secs();
576    let wrapper_event_id_bytes: [u8; 32] = event.id.to_bytes();
577    let skip = || Some(PreparedEvent::DedupSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at });
578
579    // Dedup: in-memory cache first, then DB fallback
580    {
581        let cache = WRAPPER_ID_CACHE.lock().await;
582        if cache.contains(&wrapper_event_id_bytes) {
583            return skip();
584        }
585    }
586
587    // The ledger, not the events table: it holds every DM wrap (migration 96 backfilled the
588    // pre-ledger rows), including a DELETED message's, which no longer has an events row.
589    if crate::db::wrappers::processed_wrapper_exists(&wrapper_event_id_bytes) {
590        return skip();
591    }
592    None
593}
594
595/// Everything after the unwrap: classify the rumor and parse it.
596fn finish_prepare(
597    event: &Event,
598    unwrapped: Result<UnwrappedGift, String>,
599    unwrap_ns: u64,
600    my_public_key: PublicKey,
601) -> PreparedEvent {
602    let wrapper_created_at = event.created_at.as_secs();
603    let wrapper_event_id_bytes: [u8; 32] = event.id.to_bytes();
604    let wrapper_event_id = event.id.to_hex();
605
606    let (rumor, sender) = match unwrapped {
607        Ok(UnwrappedGift { rumor, sender }) => (rumor, sender),
608        Err(_) => return PreparedEvent::ErrorSkip {
609            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
610        },
611    };
612
613    // Inner rumor send time (seconds). The outer wrapper's `created_at` is NIP-59
614    // backdated up to 2 days, so it can't order an invite against a decline tombstone.
615    let rumor_created_at = rumor.created_at.as_secs();
616
617    let is_mine = sender == my_public_key;
618    let contact = if is_mine {
619        rumor.tags.public_keys().next()
620            .and_then(|pk| pk.to_bech32().ok())
621            .unwrap_or_else(|| sender.to_bech32().unwrap_or_default())
622    } else {
623        sender.to_bech32().unwrap_or_default()
624    };
625
626    // Skip NIP-17 group messages (multiple p-tags) — Vector DMs are 1:1
627    if rumor.tags.public_keys().count() > 1 {
628        return PreparedEvent::ErrorSkip {
629            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
630        };
631    }
632
633    if rumor.kind == Kind::ApplicationSpecificData
634        && crate::tags::TagsExt::find_kind(&rumor.tags, "d").and_then(|t| t.content()) == Some(vector_push::TICKET_RUMOR_D)
635    {
636        return PreparedEvent::PushTickets {
637            contact,
638            is_mine,
639            content: rumor.content,
640            wrapper_event_id_bytes,
641            wrapper_created_at,
642        };
643    }
644
645    // A retired Concord v1 invite (kind 3304), still reachable through DM history: skipped,
646    // never processed as an unknown rumor, which would open a DM thread holding its keys.
647    if rumor.kind == Kind::Custom(3304) {
648        return PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at };
649    }
650
651    // Concord v2 Direct Invite (inner kind 3313) — the v2 join carrier. `from_bundle_json`
652    // validates the owner commitment + bounds; we park the canonical re-serialized bundle.
653    if rumor.kind == Kind::Custom(crate::community::v2::kind::DIRECT_INVITE) {
654        return match crate::community::v2::invite::CommunityInvite::from_bundle_json(&rumor.content)
655            .ok()
656            .and_then(|b| serde_json::to_string(&b).ok().map(|j| (b.community_id, j)))
657        {
658            Some((community_id, bundle_json)) => PreparedEvent::CommunityInviteV2 {
659                community_id,
660                bundle_json,
661                inviter: contact.clone(), // the seal signer's npub (bech32)
662                is_mine,
663                wrapper_event_id_bytes,
664                wrapper_created_at,
665                rumor_created_at,
666                expires_at: crate::community::v2::invite::expiration_secs(&rumor.tags).unwrap_or(0),
667            },
668            None => PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at },
669        };
670    }
671
672    // Build RumorEvent for processing
673    let Some(rumor_id) = rumor.id else {
674        return PreparedEvent::ErrorSkip {
675            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
676        };
677    };
678
679    let rumor_at_ms = rumor.created_at.as_secs().saturating_mul(1000);
680    let rumor_event = RumorEvent {
681        id: rumor_id,
682        kind: rumor.kind,
683        content: rumor.content,
684        tags: rumor.tags,
685        created_at: rumor.created_at,
686        pubkey: rumor.pubkey,
687    };
688    let rumor_context = RumorContext {
689        sender,
690        is_mine,
691        conversation_id: contact.clone(),
692        conversation_type: ConversationType::DirectMessage,
693    };
694
695    let parse_start = web_time::Instant::now();
696    let download_dir = crate::db::get_download_dir();
697    match process_rumor(rumor_event, rumor_context, &download_dir) {
698        Ok(RumorProcessingResult::TextMessage(msg) | RumorProcessingResult::FileAttachment(msg)) if crate::early::is_early(msg.at) => {
699            PreparedEvent::Early { wrap: event.clone(), at_ms: msg.at }
700        }
701        Ok(result) => {
702            let parse_ns = parse_start.elapsed().as_nanos() as u64;
703            PreparedEvent::Processed {
704                result, contact, sender, is_mine,
705                wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at,
706                rumor_at_ms, unwrap_ns, parse_ns,
707            }
708        }
709        Err(e) => {
710            log_warn!("[EventHandler] Failed to process rumor: {}", e);
711            PreparedEvent::ErrorSkip {
712                wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
713            }
714        }
715    }
716}
717
718// ============================================================================
719// Phase 2: Commit — sequential state mutation, DB save, emit
720// ============================================================================
721
722/// Phase 2: commit a prepared event (sequential — not parallel-safe).
723/// Saves to DB, updates STATE, emits to frontend, calls handler hooks.
724/// Returns true if a new displayable message was committed.
725///
726/// Session-safety: captures the generation at the first line. If a swap
727/// occurred between `prepare_event()` and here (e.g. long-running
728/// negentropy fetch queued events for commit), bail before any STATE /
729/// DB write. Centralized so individual spawn sites (sync.rs fetch_messages,
730/// archive task, sync_dms, subscription_handler) don't have to wrap.
731/// Direct Invites live 24 hours BY DESIGN, and the RECIPIENT enforces it: a
732/// sender that omits the NIP-40 tag (older clients, other implementations)
733/// must not mint a permanent invite, and an archive sync that resurrects a
734/// months-old wrap must not park a ghost (a re-founded community's stale
735/// invite has no held id for the exists-guard to match). The sender's
736/// declared deadline is honored when EARLIER; the rumor-age lifetime is the
737/// ceiling either way. One hour of slack absorbs sender clock skew.
738pub const DIRECT_INVITE_LIFETIME_SECS: u64 = 24 * 3600 + 3600;
739
740/// Park the Private-Channel keys a CATCH-UP bundle carries that we don't hold.
741///
742/// This is delivery, never authority: nothing is adopted here. The bundle's
743/// self-certification is checked (a forged community binding never parks), the
744/// keys are stashed, and [`judge_channel_key_vend`] rules on them against our own
745/// fold after the next control follow. A vend that races its Grant therefore
746/// parks quietly instead of being dropped, which is what makes an admin's grant
747/// actually reach a member who is already in the community.
748///
749/// `inviter` is the seal author's npub (bech32) — recorded so the judge can
750/// require an entitled vendor.
751fn park_catch_up_channel_keys(
752    community_id: &str,
753    bundle_json: &str,
754    inviter: &str,
755) {
756    use crate::community::v2::invite::CommunityInvite;
757    let Ok(bundle) = CommunityInvite::from_bundle_json(bundle_json) else { return };
758    // (1) Self-cert: the bundle cannot claim to be this community while naming a
759    // different owner. Cheap, and it keeps garbage out of the park table.
760    let (Some(cid), Some(owner), Some(salt)) = (
761        crate::simd::hex::hex_to_bytes_32_checked(&bundle.community_id),
762        crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner),
763        crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner_salt),
764    ) else {
765        return;
766    };
767    if !crate::community::v2::derive::verify_community_id(&crate::community::CommunityId(cid), &owner, &salt) {
768        log_warn!("[community] catch-up bundle failed self-certification — dropped");
769        return;
770    }
771    let Ok(sender) = PublicKey::parse(inviter) else { return };
772    let sender_hex = sender.to_hex();
773    // The commit path's guard was captured before an await; re-check before the
774    // writes below or a swap mid-commit parks account A's channel key into
775    // account B's database.
776    let held = crate::db::community::load_community_v2(&crate::community::CommunityId(cid)).ok().flatten();
777    let mut parked_any = false;
778    for grant in &bundle.channels {
779        let Some(chan) = crate::simd::hex::hex_to_bytes_32_checked(&grant.id) else { continue };
780        let Some(key) = crate::simd::hex::hex_to_bytes_32_checked(&grant.key) else { continue };
781        // Only park what we LACK: a key at or below the held epoch is already
782        // superseded, and a public channel's "key" is just the root.
783        if let Some(c) = held.as_ref().and_then(|h| h.channel(&crate::community::ChannelId(chan))) {
784            if !c.private || (c.key.is_some() && grant.epoch <= c.epoch.0) {
785                continue;
786            }
787        }
788        if let Err(e) = crate::db::community::park_channel_key(community_id, &grant.id, grant.epoch, &key, &sender_hex) {
789            log_warn!("[community] parking a vended channel key failed: {e}");
790            continue;
791        }
792        parked_any = true;
793    }
794    // Judge it now rather than whenever the next edition happens by. A vend that
795    // lands AFTER its Grant folded changes no control state, so without a nudge
796    // there is nothing left to trigger the re-judge.
797    if parked_any {
798        crate::community::v2::realtime::enqueue_follow(&crate::community::CommunityId(cid));
799    }
800}
801
802fn expired_invite(expires_at: u64, rumor_created_at: u64) -> bool {
803    let now = crate::clock::timestamp().as_secs();
804    if expires_at != 0 && expires_at <= now {
805        return true;
806    }
807    rumor_created_at.saturating_add(DIRECT_INVITE_LIFETIME_SECS) <= now
808}
809
810#[cfg(test)]
811mod revoked_reaction_tests {
812    use super::*;
813
814    #[tokio::test]
815    async fn a_revoked_reaction_is_refused_under_any_wrapper() {
816        // The deleted set lives on the session, which a test switching accounts would move.
817        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
818        let id = "7".repeat(64);
819        let reaction = crate::types::Reaction {
820            id: id.clone(),
821            reference_id: "message".into(),
822            author_id: "author".into(),
823            emoji: "+".into(),
824            emoji_url: None,
825        };
826        crate::state::note_message_deleted(&id);
827        let wrap = EventId::from_byte_array([8; 32]);
828        assert!(!commit_reaction(reaction, "contact", false, &wrap.to_hex(), 0, &NoOpEventHandler).await);
829        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "and that wrap leaves the relays");
830    }
831}
832
833#[cfg(test)]
834mod received_wrap_deletion_tests {
835    use super::*;
836
837    fn fresh_account() -> std::sync::MutexGuard<'static, ()> {
838        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
839        crate::db::close_database();
840        crate::db::clear_id_caches();
841        let account = Keys::generate().public_key().to_bech32().unwrap();
842        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
843        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&account)).unwrap();
844        crate::db::set_current_account(account.clone()).unwrap();
845        crate::db::init_database(&account).unwrap();
846        guard
847    }
848
849    #[tokio::test]
850    async fn a_contact_cannot_edit_what_we_sent() {
851        let _guard = fresh_account();
852        let contact = Keys::generate().public_key().to_bech32().unwrap();
853        let ours = crate::types::Message { id: "c".repeat(64), content: "ours".into(), at: 1_700_000_000_000, mine: true, ..Default::default() };
854        crate::db::events::save_message(&contact, &ours).await.unwrap();
855        crate::state::STATE.lock().await.add_message_to_participant(&contact, &ours);
856        let edit = |id: &str| crate::stored_event::StoredEventBuilder::new().id(id.to_string()).kind(crate::stored_event::event_kind::MESSAGE_EDIT).content("forged".to_string()).build();
857        let forged = commit_edit(&mut edit(&"d".repeat(64)), &contact, &ours.id, "forged", 1_700_000_001_000, vec![], vec![], &"e".repeat(64), false, &NoOpEventHandler).await;
858        assert!(!forged, "the contact's edit of our message is refused");
859        let content = crate::state::STATE.lock().await.find_message(&ours.id).map(|(_, m)| m.content);
860        assert_eq!(content.as_deref(), Some("ours"));
861        let own = commit_edit(&mut edit(&"f".repeat(64)), &contact, &ours.id, "ours, edited", 1_700_000_002_000, vec![], vec![], &"e".repeat(64), true, &NoOpEventHandler).await;
862        assert!(own, "our own edit applies");
863    }
864
865    #[tokio::test]
866    async fn an_honoured_hide_request_deletes_the_wrap_that_brought_the_message() {
867        let _guard = fresh_account();
868        let (peer, stranger) = (Keys::generate().public_key(), Keys::generate().public_key());
869        let contact = peer.to_bech32().unwrap();
870        let wrap = EventId::from_byte_array([5; 32]);
871        let msg = crate::types::Message {
872            id: "a".repeat(64),
873            content: "hi".into(),
874            at: 1_700_000_000_000,
875            wrapper_event_id: Some(wrap.to_hex()),
876            ..Default::default()
877        };
878        crate::db::events::save_message(&contact, &msg).await.unwrap();
879        crate::state::STATE.lock().await.add_message_to_participant(&contact, &msg);
880        assert!(!commit_deletion(&msg.id, &contact, &stranger, 0, &NoOpEventHandler).await, "only its author asks");
881        assert!(!crate::deletion::pending_received_wrap_deletions().contains(&wrap));
882        assert!(commit_deletion(&msg.id, &contact, &peer, 0, &NoOpEventHandler).await);
883        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "our copy leaves the relays too");
884        crate::db::close_database();
885    }
886
887    #[tokio::test]
888    async fn our_own_hide_request_takes_a_received_message_off_our_other_devices() {
889        let _guard = fresh_account();
890        let (me, peer) = (Keys::generate().public_key(), Keys::generate().public_key());
891        crate::state::set_my_public_key(me);
892        let contact = peer.to_bech32().unwrap();
893        let (wrap, ours_wrap) = (EventId::from_byte_array([8; 32]), EventId::from_byte_array([9; 32]));
894        let theirs = crate::types::Message { id: "c".repeat(64), content: "from them".into(), at: 1_700_000_000_000, wrapper_event_id: Some(wrap.to_hex()), ..Default::default() };
895        let ours = crate::types::Message { id: "d".repeat(64), content: "from us".into(), at: 1_700_000_000_000, mine: true, wrapper_event_id: Some(ours_wrap.to_hex()), ..Default::default() };
896        for msg in [&theirs, &ours] {
897            crate::db::events::save_message(&contact, msg).await.unwrap();
898        }
899        assert!(!commit_deletion(&ours.id, &contact, &peer, 0, &NoOpEventHandler).await, "what we sent is never theirs to take down");
900        assert!(commit_deletion(&theirs.id, &contact, &me, 0, &NoOpEventHandler).await);
901        assert!(!crate::db::events::event_exists(&theirs.id).unwrap() && crate::state::was_message_deleted(&theirs.id));
902        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "this device's copy leaves the relays too");
903        crate::db::close_database();
904    }
905
906    #[tokio::test]
907    async fn our_own_early_hide_request_waits_for_a_message_we_received() {
908        let _guard = fresh_account();
909        let (me, peer) = (Keys::generate().public_key(), Keys::generate().public_key());
910        crate::state::set_my_public_key(me);
911        let contact = peer.to_bech32().unwrap();
912        let early = "3".repeat(64);
913        hold_deletion_until_met(&early, &me).await;
914        let wrap = [6u8; 32];
915        let msg = crate::types::Message { id: early.clone(), content: "x".into(), at: 1_700_000_000_000, ..Default::default() };
916        assert!(!commit_dm_message(msg, &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&wrap), wrap, 1_700_000_000, &NoOpEventHandler, false).await, "we asked first, on another device");
917        assert!(crate::state::was_message_deleted(&early));
918        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(wrap)));
919        crate::db::close_database();
920    }
921
922    #[tokio::test]
923    async fn an_honoured_reaction_revocation_deletes_the_wrap_that_brought_it() {
924        let _guard = fresh_account();
925        let peer = Keys::generate().public_key();
926        let contact = peer.to_bech32().unwrap();
927        let msg = crate::types::Message { id: "c".repeat(64), content: "hi".into(), at: 1_700_000_000_000, mine: true, ..Default::default() };
928        crate::db::events::save_message(&contact, &msg).await.unwrap();
929        let reaction = crate::types::Reaction { id: "d".repeat(64), reference_id: msg.id.clone(), author_id: contact.clone(), emoji: "+".into(), emoji_url: None };
930        let wrap = EventId::from_byte_array([4; 32]);
931        let chat_id = crate::db::id_cache::get_or_create_chat_id(&contact).unwrap();
932        crate::db::events::save_reaction_event(&reaction, chat_id, None, false, Some(wrap.to_hex())).await.unwrap();
933        {
934            let mut state = crate::state::STATE.lock().await;
935            state.add_message_to_participant(&contact, &msg);
936            state.add_reaction_to_message(&msg.id, reaction.clone());
937        }
938        assert!(commit_reaction_deletion(&reaction.id, &peer, 0, &NoOpEventHandler).await);
939        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
940        crate::db::close_database();
941    }
942
943    #[tokio::test]
944    async fn a_hide_request_reaches_a_message_no_longer_in_memory() {
945        let _guard = fresh_account();
946        let peer = Keys::generate().public_key();
947        let contact = peer.to_bech32().unwrap();
948        let wrap = EventId::from_byte_array([2; 32]);
949        let msg = crate::types::Message { id: "e".repeat(64), content: "old".into(), at: 1_600_000_000_000, wrapper_event_id: Some(wrap.to_hex()), ..Default::default() };
950        crate::db::events::save_message(&contact, &msg).await.unwrap();
951        assert!(commit_deletion(&msg.id, &contact, &peer, 0, &NoOpEventHandler).await, "stored, if not in memory");
952        assert!(!crate::db::events::event_exists(&msg.id).unwrap());
953        assert!(crate::state::was_message_deleted(&msg.id));
954        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
955        crate::db::close_database();
956    }
957
958    #[tokio::test]
959    async fn a_hide_request_that_comes_first_waits_for_its_message() {
960        let _guard = fresh_account();
961        let (peer, stranger) = (Keys::generate().public_key(), Keys::generate().public_key());
962        let contact = peer.to_bech32().unwrap();
963        let (early, forged) = ("1".repeat(64), "2".repeat(64));
964        hold_deletion_until_met(&early, &peer).await;
965        hold_deletion_until_met(&forged, &stranger).await;
966        let wrap = [3u8; 32];
967        let msg = |id: &str| crate::types::Message { id: id.into(), content: "x".into(), at: 1_700_000_000_000, ..Default::default() };
968        assert!(!commit_dm_message(msg(&early), &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&wrap), wrap, 1_700_000_000, &NoOpEventHandler, false).await, "its author asked first");
969        assert!(crate::state::was_message_deleted(&early));
970        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(wrap)));
971        let other = [4u8; 32];
972        assert!(commit_dm_message(msg(&forged), &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&other), other, 1_700_000_000, &NoOpEventHandler, false).await, "nobody else's request takes it down");
973        // One left waiting past its hide request's life is let go.
974        crate::db::get_write_connection_guard_static().unwrap()
975            .execute("INSERT INTO pending_deletions (target, requester, expires_at) VALUES (?1, ?2, 1)", rusqlite::params!["7".repeat(64), peer.to_hex()])
976            .unwrap();
977        assert!(crate::db::events::take_pending_deletion(&"7".repeat(64)).is_none());
978        // A target already here is the live path's, never held.
979        let held = "5".repeat(64);
980        crate::db::events::save_message(&contact, &msg(&held)).await.unwrap();
981        hold_deletion_until_met(&held, &stranger).await;
982        assert!(crate::db::events::take_pending_deletion(&held).is_none());
983        crate::db::close_database();
984    }
985
986    #[tokio::test]
987    async fn a_reaction_revoked_before_it_arrived_never_lands() {
988        let _guard = fresh_account();
989        let author = Keys::generate().public_key();
990        let reaction = crate::types::Reaction { id: "6".repeat(64), reference_id: "m".into(), author_id: author.to_bech32().unwrap(), emoji: "+".into(), emoji_url: None };
991        hold_deletion_until_met(&reaction.id, &author).await;
992        let wrap = EventId::from_byte_array([1; 32]);
993        assert!(!commit_reaction(reaction.clone(), "contact", false, &wrap.to_hex(), 0, &NoOpEventHandler).await);
994        assert!(crate::state::was_message_deleted(&reaction.id));
995        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
996        crate::db::close_database();
997    }
998
999    #[tokio::test]
1000    async fn a_deleted_message_met_again_takes_that_wrap_down_too() {
1001        let _guard = fresh_account();
1002        let contact = Keys::generate().public_key().to_bech32().unwrap();
1003        let msg = crate::types::Message { id: "b".repeat(64), content: "gone".into(), at: 1_700_000_000_000, ..Default::default() };
1004        crate::state::note_message_deleted(&msg.id);
1005        let another = [6u8; 32];
1006        assert!(!commit_dm_message(msg, &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&another), another, 1_700_000_000, &NoOpEventHandler, false).await);
1007        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(another)));
1008        crate::db::close_database();
1009    }
1010}
1011
1012#[cfg(test)]
1013mod invite_expiry_tests {
1014    use super::*;
1015
1016    fn now() -> u64 {
1017        crate::clock::timestamp().as_secs()
1018    }
1019
1020    #[test]
1021    fn declared_deadline_is_honored() {
1022        assert!(expired_invite(now() - 10, now()));
1023        assert!(!expired_invite(now() + 3600, now()));
1024    }
1025
1026    #[test]
1027    fn tagless_invites_die_at_the_recipient_lifetime() {
1028        // Fresh, no tag: parks.
1029        assert!(!expired_invite(0, now() - 3600));
1030        // A day-and-slack old, no tag: never parks — the class the archive
1031        // recovery resurrected (months-old invite to a re-founded community).
1032        assert!(expired_invite(0, now() - DIRECT_INVITE_LIFETIME_SECS));
1033        assert!(expired_invite(0, now() - 90 * 24 * 3600));
1034    }
1035
1036    #[test]
1037    fn lifetime_caps_a_generous_declared_deadline() {
1038        // Sender promised a week — the recipient's 24h ceiling still wins.
1039        assert!(expired_invite(now() + 7 * 24 * 3600, now() - DIRECT_INVITE_LIFETIME_SECS));
1040    }
1041}
1042
1043pub async fn commit_prepared_event(
1044    prepared: PreparedEvent,
1045    is_new: bool,
1046    handler: &dyn InboundEventHandler,
1047) -> bool {
1048    let session = crate::db::current_session();
1049    if !session.is_live() {
1050        return false;
1051    }
1052    match prepared {
1053        PreparedEvent::Processed { result, contact, sender, is_mine, wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, rumor_at_ms, .. } => {
1054            // Cache wrapper for session dedup
1055            {
1056                let mut cache = WRAPPER_ID_CACHE.lock().await;
1057                cache.insert(wrapper_event_id_bytes);
1058            }
1059
1060            // Blocked check — drop content from blocked contacts (wrapper still ledgered so
1061            // the dropped content never re-syncs)
1062            if !is_mine {
1063                let blocked = {
1064                    let state = crate::state::STATE.lock().await;
1065                    state.get_profile(&contact).is_some_and(|p| p.flags.is_blocked())
1066                };
1067                if blocked {
1068                    let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1069                    return false;
1070                }
1071            }
1072
1073            // Persist for cross-session dedup + negentropy — EXCEPT message rumors: the
1074            // ledger IS the negentropy fingerprint set, and a batching handler may defer the
1075            // message's save, so its wrapper must never be ledgered before its row lands (a
1076            // ledgered-but-unpersisted message reads as "have" and is never re-delivered).
1077            // Message wrappers ledger inside commit_dm_message / the batch-flush transaction.
1078            if !matches!(result, RumorProcessingResult::TextMessage(_) | RumorProcessingResult::FileAttachment(_)) {
1079                let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1080            }
1081
1082            match result {
1083                RumorProcessingResult::TextMessage(mut msg) => {
1084                    msg.wrapper_event_id = Some(wrapper_event_id.clone());
1085                    commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, false).await
1086                }
1087                RumorProcessingResult::FileAttachment(mut msg) => {
1088                    msg.wrapper_event_id = Some(wrapper_event_id.clone());
1089                    // If the sender's client (e.g. 0xChat) didn't ship `size` in
1090                    // the imeta tag, probe the URL via Content-Length so the
1091                    // frontend's auto-download gate has accurate metadata to
1092                    // decide on.
1093                    //
1094                    // Skip for self-echoes (is_mine): we just uploaded these
1095                    // files, the local Attachment.size is authoritative, and
1096                    // probing our own blossom URL right after upload is a
1097                    // correlation-fingerprint privacy regression.
1098                    //
1099                    // Each probe is bounded by a 3s outer timeout so a slow or
1100                    // dead server can't stall the inbound rumor pipeline. If
1101                    // the probe times out, we ship size=0 and the frontend
1102                    // falls back to a manual "Click to Download" affordance.
1103                    // Nor for someone whose request waits: the probe would reach a server
1104                    // they chose before we've said yes to anything.
1105                    let probe = !is_mine
1106                        && !(crate::requests::shielded() && crate::state::STATE.lock().await.dm_unanswered(&contact));
1107                    if probe {
1108                        for att in &mut msg.attachments {
1109                            if att.size == 0
1110                                && (att.url.starts_with("https://") || att.url.starts_with("http://"))
1111                            {
1112                                if let Ok(Some(size)) = crate::rt::time::timeout(
1113                                    crate::net::tor_http_timeout(std::time::Duration::from_secs(3)),
1114                                    crate::net::get_remote_file_size(&att.url),
1115                                ).await {
1116                                    att.size = size;
1117                                }
1118                            }
1119                        }
1120                    }
1121                    // A claim whose bytes are already on disk verifies at ARRIVAL,
1122                    // not at tap: the box renders downloaded from its first paint and
1123                    // no bytes are re-fetched. The ledger probe is an indexed lookup;
1124                    // the content hash only runs when a plausible candidate exists.
1125                    crate::db::attachments::verify_message_attachments(&mut msg, None).await;
1126                    commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, true).await
1127                }
1128                RumorProcessingResult::Reaction(reaction) => {
1129                    commit_reaction(reaction, &contact, is_mine, &wrapper_event_id, rumor_at_ms, handler).await
1130                }
1131                RumorProcessingResult::Edit { message_id, new_content, edited_at, emoji_tags, text_spans, mut event } => {
1132                    commit_edit(&mut event, &contact, &message_id, &new_content, edited_at, emoji_tags, text_spans, &wrapper_event_id, is_mine, handler).await
1133                }
1134                RumorProcessingResult::TypingIndicator { profile_id, until } => {
1135                    let active_typers = {
1136                        let mut state = crate::state::STATE.lock().await;
1137                        state.update_typing_and_get_active(&contact, &profile_id, until)
1138                    };
1139                    crate::traits::emit_event("typing-update", &serde_json::json!({
1140                        "conversation_id": contact,
1141                        "typers": active_typers,
1142                    }));
1143                    handler.on_dm_typing(&contact, &profile_id, until);
1144                    false
1145                }
1146                RumorProcessingResult::PivxPayment { gift_code, amount_piv, address, message_id, mut event } => {
1147                    if crate::db::events::event_exists(&event.id).unwrap_or(false) {
1148                        return false;
1149                    }
1150                    event.wrapper_event_id = Some(wrapper_event_id.clone());
1151                    let ts = event.created_at;
1152                    let _ = crate::db::events::save_pivx_payment_event(&contact, event).await;
1153                    crate::traits::emit_event("pivx_payment_received", &serde_json::json!({
1154                        "conversation_id": contact,
1155                        "gift_code": gift_code, "amount_piv": amount_piv,
1156                        "address": address, "message_id": message_id,
1157                        "sender": sender.to_hex(), "is_mine": is_mine,
1158                        "at": ts * 1000,
1159                    }));
1160                    true
1161                }
1162                RumorProcessingResult::UnknownEvent(mut event) => {
1163                    event.wrapper_event_id = Some(wrapper_event_id.clone());
1164                    // Store unknown events for forward compatibility
1165                    if let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(&contact) {
1166                        event.chat_id = chat_id;
1167                    }
1168                    let _ = crate::db::events::save_event(&event).await;
1169                    false
1170                }
1171                RumorProcessingResult::LeaveRequest { .. } => false,
1172                RumorProcessingResult::WebxdcPeerAdvertisement { event_id, topic_id, node_addr, sender_npub, created_at } => {
1173                    handler.on_webxdc_signal(&contact, &sender_npub, &topic_id, Some(&node_addr), &event_id, created_at);
1174                    false
1175                }
1176                RumorProcessingResult::WebxdcPeerLeft { event_id, topic_id, sender_npub, created_at } => {
1177                    handler.on_webxdc_signal(&contact, &sender_npub, &topic_id, None, &event_id, created_at);
1178                    false
1179                }
1180                #[cfg(feature = "calls")]
1181                RumorProcessingResult::CallSignal { call_id, signal, node_addr, sender_npub, created_at, video, media, .. } => {
1182                    // Only the DM's other party may signal; a group member cannot ring us through a channel.
1183                    if contact == sender_npub {
1184                        crate::calls::session::on_signal(&sender_npub, &call_id, &signal, node_addr.as_deref(), created_at, video.as_deref(), media.as_deref()).await;
1185                    }
1186                    false
1187                }
1188                #[cfg(not(feature = "calls"))]
1189                RumorProcessingResult::CallSignal { .. } => false,
1190                RumorProcessingResult::WallpaperChanged {
1191                    sender_npub, created_at, url, decryption_key, decryption_nonce,
1192                    plaintext_hash, mime, blur, dim, event_id,
1193                } => {
1194                    let _ = crate::wallpaper::apply_received_wallpaper(
1195                        &contact, &sender_npub, created_at, &url,
1196                        &decryption_key, &decryption_nonce,
1197                        plaintext_hash.as_deref(), mime.as_deref(),
1198                        blur, dim,
1199                        &event_id,
1200                    ).await;
1201                    // System event is saved inside apply_received_wallpaper.
1202                    // Return true so the caller treats this as a stored event.
1203                    true
1204                }
1205                RumorProcessingResult::DeletionRequest { target_event_id } => {
1206                    // A deletion targets a message OR a reaction (both event ids,
1207                    // never colliding). Try the message path; if it's not a known
1208                    // message, treat it as a reaction revocation.
1209                    if commit_deletion(&target_event_id, &contact, &sender, rumor_at_ms, handler).await
1210                        || commit_reaction_deletion(&target_event_id, &sender, rumor_at_ms, handler).await
1211                    {
1212                        true
1213                    } else {
1214                        hold_deletion_until_met(&target_event_id, &sender).await;
1215                        false
1216                    }
1217                }
1218                RumorProcessingResult::Ignored => false,
1219            }
1220        }
1221        PreparedEvent::CommunityInviteV2 { bundle_json, community_id, inviter, is_mine, wrapper_event_id_bytes, wrapper_created_at, rumor_created_at, expires_at } => {
1222            {
1223                let mut cache = WRAPPER_ID_CACHE.lock().await;
1224                cache.insert(wrapper_event_id_bytes);
1225            }
1226            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1227
1228            // Never park our own echoed invite.
1229            if is_mine {
1230                return false;
1231            }
1232            // Past the sender's deadline or the 24h lifetime (a stale wrap from a
1233            // catch-up sync, a relay that ignores expiry): never park it.
1234            if expired_invite(expires_at, rumor_created_at) {
1235                return false;
1236            }
1237            // Idempotency on the INNER community_id (already validated hex), not the
1238            // attacker-controlled wrapper id: already held, or already parked → drop.
1239            let held = match crate::simd::hex::hex_to_bytes_32_checked(&community_id) {
1240                Some(b) => crate::community::CommunityId(b),
1241                None => return false,
1242            };
1243            // Already a member? Then this is not an invitation but a CATCH-UP: a
1244            // grant's Private-Channel key vend (CORD-03 "delivered on grant"), or
1245            // an admin healing us forward. Park the keys we lack for the judge to
1246            // rule on after the next control fold — dropping it here is why a
1247            // granted member (or bot) stayed silently keyless.
1248            if crate::db::community::community_exists(&held).unwrap_or(false) {
1249                park_catch_up_channel_keys(&community_id, &bundle_json, &inviter);
1250                return false;
1251            }
1252            let wrap_hex = crate::simd::hex::bytes_to_hex_32(&wrapper_event_id_bytes);
1253            if crate::db::community::pending_invite_exists(&community_id).unwrap_or(false) {
1254                let _ = crate::db::community::note_pending_invite_wrap(&community_id, &wrap_hex);
1255                return false;
1256            }
1257            // From someone we blocked: declined on arrival, never shown or announced.
1258            if crate::requests::shielded()
1259                && crate::state::STATE.lock().await.get_profile(&inviter).is_some_and(|p| p.flags.is_blocked())
1260            {
1261                return false;
1262            }
1263            // Supersession: a decline/leave tombstone suppresses a re-wrapped invite no newer
1264            // than the decision, so a declined/left community can't be re-nagged by a fresh
1265            // ephemeral wrap. Ordered on the inner rumor time, not the NIP-59-backdated wrapper.
1266            // Its copy on our relays goes too, as the decision's own invite did.
1267            if crate::community::v2::service::tombstone_suppresses(&community_id, rumor_created_at) {
1268                crate::deletion::delete_received_wrap(EventId::from_byte_array(wrapper_event_id_bytes));
1269                return false;
1270            }
1271            // Park for explicit consent — do NOT join/subscribe here. Accept via the command layer.
1272            match crate::db::community::save_pending_invite(&community_id, &bundle_json, &inviter, expires_at as i64) {
1273                Ok(true) => {
1274                    let _ = crate::db::community::set_pending_invite_sent(&community_id, rumor_created_at as i64);
1275                    let _ = crate::db::community::note_pending_invite_wrap(&community_id, &wrap_hex);
1276                    handler.on_community_invite(&community_id)
1277                }
1278                Ok(false) => {} // raced — already parked
1279                Err(e) => log_warn!("[community] v2 invite park failed: {}", e),
1280            }
1281            false
1282        }
1283        PreparedEvent::PushTickets { contact, is_mine, content, wrapper_event_id_bytes, wrapper_created_at } => {
1284            if !is_mine {
1285                crate::push::store_tickets(&contact, &content).await;
1286            }
1287            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1288            false
1289        }
1290        PreparedEvent::Early { wrap, at_ms } => {
1291            crate::early::hold(wrap, crate::early::Via::Dm, at_ms);
1292            false
1293        }
1294        PreparedEvent::DedupSkip { wrapper_id_bytes, wrapper_created_at } => {
1295            // Persist wrapper timestamp for negentropy backfill (skip no-op writes).
1296            // Guarded: a cache-hit skip can name a wrapper whose message is still sitting in
1297            // a batch buffer (deferred ledger) — inserting it here would mark the message
1298            // "have" before its row exists. Only touch the ledger when the wrapper is
1299            // already ledgered (timestamp backfill) or its row is verifiably persisted
1300            // (legacy pre-ledger events, whose wrapper lives only on the events row).
1301            if wrapper_created_at > 0 {
1302                if crate::db::wrappers::processed_wrapper_exists(&wrapper_id_bytes) {
1303                    let _ = crate::db::wrappers::update_wrapper_timestamp(&wrapper_id_bytes, wrapper_created_at);
1304                } else {
1305                    let wrapper_hex = crate::simd::hex::bytes_to_hex_32(&wrapper_id_bytes);
1306                    if crate::db::events::wrapper_event_exists(&wrapper_hex).unwrap_or(false) {
1307                        let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1308                    }
1309                }
1310            }
1311            false
1312        }
1313        PreparedEvent::ErrorSkip { wrapper_id_bytes, wrapper_created_at } => {
1314            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
1315            false
1316        }
1317    }
1318}
1319
1320/// Commit a DM text or file message (shared logic for both).
1321///
1322/// Owns this message's wrapper-ledger write (`processed_wrappers` = the negentropy
1323/// fingerprint set): the wrapper is ledgered only once the message row is durably handled —
1324/// immediately after a successful save, inside the batch-flush transaction when a handler
1325/// defers, or right away when the message is a known duplicate. An unledgered wrapper is
1326/// re-delivered by the next reconciliation, which is what makes a dropped batch recoverable.
1327#[allow(clippy::too_many_arguments)]
1328async fn commit_dm_message(
1329    mut msg: Message,
1330    contact: &str,
1331    _is_mine: bool,
1332    is_new: bool,
1333    wrapper_event_id: &str,
1334    wrapper_event_id_bytes: [u8; 32],
1335    wrapper_created_at: u64,
1336    handler: &dyn InboundEventHandler,
1337    is_file: bool,
1338) -> bool {
1339    let ledger_wrapper = || {
1340        let _ = crate::db::wrappers::save_processed_wrapper(
1341            &wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17,
1342        );
1343    };
1344    // A tombstoned (user-deleted) message must never re-commit, whatever wrap
1345    // carried it — a retry wrap this device never ledgered can still deliver
1346    // the deleted rumor. Ledger the wrap so it stops re-delivering.
1347    if crate::state::was_message_deleted(&msg.id) {
1348        ledger_wrapper();
1349        crate::deletion::delete_received_wrap(nostr_sdk::prelude::EventId::from_byte_array(wrapper_event_id_bytes));
1350        return false;
1351    }
1352    // Its author, or we from another device, asked for it gone before it got here: it lands deleted.
1353    if let Some(requester) = crate::db::events::take_pending_deletion(&msg.id) {
1354        let me = crate::state::my_public_key();
1355        let author = if msg.mine { me } else { PublicKey::from_bech32(contact).ok() };
1356        if author.is_some_and(|a| a.to_hex() == requester) || me.is_some_and(|m| m.to_hex() == requester) {
1357            crate::state::note_message_deleted(&msg.id);
1358            if let Err(e) = crate::db::events::add_message_tombstone(&msg.id) {
1359                crate::log_warn!("[NIP-17 cooperative-delete] tombstone write failed: {}", e);
1360            }
1361            ledger_wrapper();
1362            crate::deletion::delete_received_wrap(nostr_sdk::prelude::EventId::from_byte_array(wrapper_event_id_bytes));
1363            return false;
1364        }
1365    }
1366
1367    // Dedup: check if message already in DB
1368    if let Ok(true) = crate::db::events::message_exists_in_db(&msg.id) {
1369        // Already in DB — try to backfill wrapper_event_id
1370        if let Ok(updated) = crate::db::events::update_wrapper_event_id(&msg.id, wrapper_event_id) {
1371            if !updated {
1372                let mut cache = WRAPPER_ID_CACHE.lock().await;
1373                cache.insert(wrapper_event_id_bytes);
1374            }
1375        }
1376        ledger_wrapper();
1377        return false;
1378    }
1379
1380    // Populate reply context
1381    if !msg.replied_to.is_empty() {
1382        let _ = crate::db::events::populate_reply_context(&mut msg).await;
1383    }
1384
1385    // Add to STATE (+ clear typing indicator for file senders)
1386    let added = {
1387        let mut state = crate::state::STATE.lock().await;
1388        let added = state.add_message_to_participant(contact, &msg);
1389        if is_file && added {
1390            state.update_typing_and_get_active(contact, contact, 0);
1391        }
1392        added
1393    };
1394
1395    // A banned author's message is stored but never SHOWN: the queries that build a
1396    // page already drop it, and painting it live was the one way it still reached the
1397    // screen. Gated at emission rather than at persist so an unban restores their
1398    // history — the row is still there, the filter simply stops matching.
1399    // A DM's contact is an npub, never a (hex) channel id: skip the community lookup.
1400    let hidden_author = added && !contact.starts_with("npub1") && msg
1401        .npub
1402        .as_deref()
1403        .and_then(|author| {
1404            let community = crate::db::community::community_id_for_channel(contact).ok().flatten()?;
1405            nostr_sdk::prelude::PublicKey::parse(author)
1406                .ok()
1407                .map(|pk| crate::db::community::is_author_banned(&community, &pk))
1408        })
1409        .unwrap_or(false);
1410
1411    if added && !hidden_author {
1412        // Emit to frontend
1413        crate::traits::emit_message_new(contact, &msg);
1414
1415        // Platform callback (notifications, badge, etc.)
1416        if is_file {
1417            handler.on_file_received(contact, &msg, is_new);
1418        } else {
1419            handler.on_dm_received(contact, &msg, is_new);
1420        }
1421
1422        // Save to DB — unless a bulk-sync handler owns batched persistence (the handler then
1423        // also owns the wrapper-ledger write, inside its flush transaction). On the immediate
1424        // path the wrapper ledgers only after a successful save: a failed save left unledgered
1425        // re-delivers on the next reconciliation instead of being lost.
1426        if !handler.buffer_persist(contact, &msg, Some((wrapper_event_id_bytes, wrapper_created_at)))
1427            && crate::db::events::save_message(contact, &msg).await.is_ok()
1428        {
1429            ledger_wrapper();
1430        }
1431    } else {
1432        // STATE-level duplicate: a same-session twin owns the row; this wrapper carried
1433        // nothing new, so ledger it now (parity with the old eager ledger).
1434        ledger_wrapper();
1435    }
1436
1437    added
1438}
1439
1440/// Bring the DM a reaction or edit aims at into STATE from the database when it isn't resident:
1441/// STATE holds a window, and the change must land on older messages too.
1442async fn hydrate_dm_target(contact: &str, message_id: &str) {
1443    if crate::state::STATE.lock().await.find_message(message_id).is_some() {
1444        return;
1445    }
1446    if let Ok(Some((chat, msg))) = crate::db::events::get_message_by_id(message_id).await {
1447        if chat == contact {
1448            crate::state::STATE.lock().await.add_message_to_participant(contact, &msg);
1449        }
1450    }
1451}
1452
1453/// Commit a reaction event.
1454async fn commit_reaction(
1455    reaction: crate::types::Reaction,
1456    contact: &str,
1457    is_mine: bool,
1458    wrapper_event_id: &str,
1459    at: u64,
1460    handler: &dyn InboundEventHandler,
1461) -> bool {
1462    // A revoked reaction can come back under a new wrapper id; its own id is the stable key.
1463    let revoked_early = || {
1464        let requester = crate::db::events::take_pending_deletion(&reaction.id)?;
1465        let author = PublicKey::parse(&reaction.author_id).ok()?;
1466        (author.to_hex() == requester).then_some(())
1467    };
1468    if crate::state::was_message_deleted(&reaction.id) || revoked_early().is_some() {
1469        crate::state::note_message_deleted(&reaction.id);
1470        if let Err(e) = crate::db::events::add_message_tombstone(&reaction.id) {
1471            crate::log_warn!("[reaction-delete] tombstone write failed: {}", e);
1472        }
1473        if let Ok(wrap) = nostr_sdk::prelude::EventId::from_hex(wrapper_event_id) {
1474            crate::deletion::delete_received_wrap(wrap);
1475        }
1476        return false;
1477    }
1478
1479    hydrate_dm_target(contact, &reaction.reference_id).await;
1480    // Add to STATE
1481    let msg_for_emit = {
1482        let mut state = crate::state::STATE.lock().await;
1483        if let Some((chat_id, was_added)) = state.add_reaction_to_message(&reaction.reference_id, reaction.clone()) {
1484            if was_added {
1485                state.find_message(&reaction.reference_id)
1486                    .map(|(_, msg)| (chat_id, msg))
1487            } else { None }
1488        } else { None }
1489    };
1490
1491    if let Some((chat_id, mut msg)) = msg_for_emit {
1492        crate::traits::emit_message_update(&chat_id, &reaction.reference_id, &mut msg).await;
1493        handler.on_reaction_received(&chat_id, &msg);
1494        handler.on_reaction_added(&chat_id, &msg, &reaction, at);
1495    }
1496
1497    // The kind-7 row is the reaction's only storage: the parent row never carries it.
1498    if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
1499        let user_id = crate::db::id_cache::get_or_create_user_id(&reaction.author_id).ok().flatten();
1500        let _ = crate::db::events::save_reaction_event(
1501            &reaction, chat_id, user_id, is_mine, Some(wrapper_event_id.to_string())
1502        ).await;
1503    }
1504
1505    true
1506}
1507
1508/// Commit a message edit.
1509#[allow(clippy::too_many_arguments)]
1510async fn commit_edit(
1511    event: &mut crate::stored_event::StoredEvent,
1512    contact: &str,
1513    message_id: &str,
1514    new_content: &str,
1515    edited_at: u64,
1516    emoji_tags: Vec<crate::types::EmojiTag>,
1517    text_spans: Vec<crate::text_spans::TextSpan>,
1518    wrapper_event_id: &str,
1519    is_mine: bool,
1520    handler: &dyn InboundEventHandler,
1521) -> bool {
1522    if crate::db::events::event_exists(&event.id).unwrap_or(false) {
1523        return false;
1524    }
1525    // Only a message's author edits it: in a DM, the other side can't rewrite what we sent.
1526    let resident = crate::state::STATE.lock().await.find_message(message_id).map(|(_, m)| m.mine);
1527    let target_mine = match resident {
1528        Some(mine) => Some(mine),
1529        None => crate::db::events::get_message_by_id(message_id).await.ok().flatten().map(|(_, m)| m.mine),
1530    };
1531    if target_mine.is_some_and(|mine| mine != is_mine) {
1532        return false;
1533    }
1534    if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
1535        event.chat_id = chat_id;
1536    }
1537    event.wrapper_event_id = Some(wrapper_event_id.to_string());
1538    let _ = crate::db::events::save_event(event).await;
1539
1540    hydrate_dm_target(contact, message_id).await;
1541    let msg_for_emit = {
1542        let mut state = crate::state::STATE.lock().await;
1543        state.update_message_in_chat_with(contact, message_id, |msg, i| {
1544            msg.apply_edit(new_content.to_string(), edited_at, emoji_tags.clone(), text_spans.clone(), i);
1545        })
1546    };
1547    if let Some(mut msg) = msg_for_emit {
1548        crate::traits::emit_message_update(contact, message_id, &mut msg).await;
1549        if crate::news::first_telling_hex(&event.id) {
1550            handler.on_message_edited(contact, &msg, edited_at);
1551        }
1552    }
1553    true
1554}
1555
1556/// Commit a NIP-09 cooperative deletion request.
1557///
1558/// Authorization: only the original message's author can delete it
1559/// (matches NIP-09's `event.pubkey == deletion.pubkey` rule applied to
1560/// the inner rumor). For DMs, that means either the sender is `MY` (we
1561/// deleted from another device) or the sender is the chat counterpart
1562/// who originally sent that message. Anyone else's deletion is silently
1563/// ignored.
1564///
1565/// On success: drops the message from in-memory STATE, removes the row
1566/// from the events table, and emits `message_removed` so the frontend
1567/// can fade the row out — same code path as failed-message cleanup.
1568async fn commit_deletion(
1569    target_event_id: &str,
1570    contact: &str,
1571    sender: &PublicKey,
1572    at: u64,
1573    handler: &dyn InboundEventHandler,
1574) -> bool {
1575    // Not held here: the caller parks the request until its message arrives
1576    // ([`hold_deletion_until_met`]). A DM row stores no author: it is us when `mine`,
1577    // else the counterpart, whose npub is the chat id.
1578    let in_memory = {
1579        let state = crate::state::STATE.lock().await;
1580        state.find_message(target_event_id).map(|(chat, msg)| (msg.mine, chat.id.clone()))
1581    };
1582    // Memory holds only recent messages; an older one is still ours to drop.
1583    let (mine, chat_id, stored) = match in_memory {
1584        Some((mine, chat_id)) => (mine, chat_id, None),
1585        None => match crate::db::events::get_message_by_id(target_event_id).await.ok().flatten() {
1586            Some((chat_id, msg)) => (msg.mine, chat_id, Some(msg)),
1587            None => return false,
1588        },
1589    };
1590
1591    // Its author may take it down, and so may we, from another of our devices: we may delete
1592    // anything we hold, so a message we received goes from all of them.
1593    let authorized = crate::state::my_public_key() == Some(*sender)
1594        || (!mine && nostr_sdk::prelude::PublicKey::from_bech32(&chat_id).is_ok_and(|counterpart| *sender == counterpart));
1595    if !authorized {
1596        eprintln!(
1597            "[NIP-17 cooperative-delete] unauthorized: sender {} not the author of target {} (mine={}, chat={})",
1598            sender.to_hex(), target_event_id, mine, chat_id
1599        );
1600        return false;
1601    }
1602
1603    // The wrap that brought it here is ours to delete: it is addressed to us.
1604    let carried = crate::db::events::wrapper_event_id_of(target_event_id);
1605
1606    // Drop from in-memory state.
1607    let removed = {
1608        let mut state = crate::state::STATE.lock().await;
1609        state.remove_message(target_event_id)
1610    };
1611    let removed_msg = match (removed, stored) {
1612        (Some((_, msg)), _) | (None, Some(msg)) => msg,
1613        (None, None) => return false,
1614    };
1615    // Tombstone BEFORE the row delete: the target may sit unflushed in a sync batch buffer
1616    // (delete_event below would no-op) — the flush consults this and drops it. The durable
1617    // row keeps the refusal across restarts: the sender's NIP-09 may never land on every
1618    // relay, and this side must not resurrect what it already agreed to drop.
1619    crate::state::note_message_deleted(target_event_id);
1620    if let Err(e) = crate::db::events::add_message_tombstone(target_event_id) {
1621        crate::log_warn!("[NIP-17 cooperative-delete] tombstone write failed: {}", e);
1622    }
1623
1624    // Nuke any cached attachment files for this message — sender asked
1625    // for the message to disappear, and a downloaded file the receiver
1626    // never moved out of Vector's cache should go with it.
1627    //
1628    // Refcount filter: drop attachments still referenced by sibling
1629    // messages so we don't yank a cached file from messages that
1630    // still need it (Vector dedupes by SHA-256, so the same file
1631    // can back multiple messages). User-managed paths are also left
1632    // alone (canonicalize + starts_with check).
1633    let unique = crate::deletion::filter_unreferenced_attachments(
1634        target_event_id,
1635        removed_msg.attachments,
1636    ).await;
1637    crate::deletion::delete_cached_attachment_files_pub(&unique);
1638
1639    // Drop from the events table.
1640    if let Err(e) = crate::db::events::delete_event(target_event_id).await {
1641        eprintln!(
1642            "[NIP-17 cooperative-delete] DB delete failed for {}: {}",
1643            target_event_id, e
1644        );
1645    }
1646    if let Some(wrap) = carried {
1647        crate::deletion::delete_received_wrap(wrap);
1648    }
1649
1650    // Tell the frontend to fade the row out. Reuses the existing
1651    // message_removed event handled in main.js, so no new wiring.
1652    crate::traits::emit_event(
1653        "message_removed",
1654        &serde_json::json!({
1655            "id": target_event_id,
1656            "chat_id": &chat_id,
1657            "reason": if crate::state::my_public_key() == Some(*sender) { "deleted" } else { "deleted-by-sender" },
1658        }),
1659    );
1660
1661    handler.on_message_deleted(&chat_id, target_event_id);
1662    if crate::news::first_telling_hex(&format!("deleted {target_event_id}")) {
1663        handler.on_message_removed(&chat_id, target_event_id, Some(&sender.to_bech32().unwrap_or_else(|_| sender.to_hex())), false, at);
1664    }
1665    let _ = contact;
1666    true
1667}
1668
1669/// Hold a hide request for a target this device hasn't met: wraps are backdated, so a sync
1670/// can bring it before what it names. It only ever takes down something `sender` wrote.
1671async fn hold_deletion_until_met(target: &str, sender: &PublicKey) {
1672    if deletion_target_known(target).await {
1673        return;
1674    }
1675    let expires = crate::clock::now_secs()
1676        .saturating_add(crate::deletion::COOPERATIVE_HIDE_EXPIRY_SECS);
1677    if let Err(e) = crate::db::events::park_pending_deletion(target, &sender.to_hex(), expires) {
1678        crate::log_warn!("[NIP-17 cooperative-delete] {}", e);
1679    }
1680}
1681
1682/// Whether this device holds `target`, as a message or a reaction, in memory or stored.
1683async fn deletion_target_known(target: &str) -> bool {
1684    {
1685        let state = crate::state::STATE.lock().await;
1686        if state.find_message(target).is_some() || state.find_reaction(target).is_some() {
1687            return true;
1688        }
1689    }
1690    crate::db::events::event_exists(target).unwrap_or(true)
1691}
1692
1693/// Apply a cooperative reaction revocation (NIP-09 k=7) from the reaction's
1694/// author. Removes the reaction from its parent message and drops the kind-7
1695/// row, then live-refreshes the parent's chips. Returns false if we don't hold
1696/// the reaction or the sender isn't its author.
1697async fn commit_reaction_deletion(target_reaction_id: &str, sender: &PublicKey, at: u64, handler: &dyn InboundEventHandler) -> bool {
1698    let found = {
1699        let state = crate::state::STATE.lock().await;
1700        state.find_reaction(target_reaction_id)
1701    };
1702    let (chat_id, message_id, author_npub, _is_community) = match found {
1703        Some(v) => v,
1704        None => return false,
1705    };
1706
1707    // Authorization: only the reaction's own author may revoke it.
1708    let authorized = nostr_sdk::prelude::PublicKey::parse(&author_npub)
1709        .map(|pk| pk == *sender)
1710        .unwrap_or(false);
1711    if !authorized {
1712        eprintln!(
1713            "[reaction-delete] unauthorized: sender {} is not the author of reaction {}",
1714            sender.to_hex(), target_reaction_id
1715        );
1716        return false;
1717    }
1718
1719    crate::state::note_message_deleted(target_reaction_id);
1720    if let Err(e) = crate::db::events::add_message_tombstone(target_reaction_id) {
1721        crate::log_warn!("[reaction-delete] tombstone write failed: {}", e);
1722    }
1723
1724    let updated = {
1725        let mut state = crate::state::STATE.lock().await;
1726        state.remove_reaction_from_message(&message_id, target_reaction_id)
1727    };
1728    let mut message = match updated {
1729        Some((_cid, msg)) => msg,
1730        None => return false,
1731    };
1732
1733    // save_message is additive for reactions, so the kind-7 row must be
1734    // dropped explicitly or it resurrects on reload.
1735    let carried = crate::db::events::wrapper_event_id_of(target_reaction_id);
1736    if let Err(e) = crate::db::events::delete_event(target_reaction_id).await {
1737        eprintln!("[reaction-delete] DB delete failed for {}: {}", target_reaction_id, e);
1738    }
1739    if let Some(wrap) = carried {
1740        crate::deletion::delete_received_wrap(wrap);
1741    }
1742
1743    crate::traits::emit_message_update(&chat_id, &message_id, &mut message).await;
1744    if crate::news::first_telling_hex(&format!("deleted {target_reaction_id}")) {
1745        handler.on_reaction_removed(&chat_id, &message, target_reaction_id, &sender.to_bech32().unwrap_or_else(|_| sender.to_hex()), at);
1746    }
1747    true
1748}
1749
1750// ============================================================================
1751// Convenience: single-call event processing
1752// ============================================================================
1753
1754/// Process a single event through the full pipeline (prepare + commit).
1755///
1756/// Gets client and public key from globals. For callers that manage their
1757/// own notification loop but want the full vector-core processing pipeline.
1758pub async fn process_event(
1759    event: Event,
1760    is_new: bool,
1761    handler: &dyn InboundEventHandler,
1762) -> std::result::Result<bool, String> {
1763    let client = crate::state::nostr_client()
1764        .ok_or_else(|| "Nostr client not initialized".to_string())?;
1765    let my_pk = crate::state::my_public_key()
1766        .ok_or_else(|| "Public key not initialized".to_string())?;
1767    let prepared = prepare_event(event, &client, my_pk).await;
1768    Ok(commit_prepared_event(prepared, is_new, handler).await)
1769}
1770
1771#[cfg(test)]
1772mod early_dm_tests {
1773    use super::*;
1774    use crate::event_ext::FinalizeUnsignedWithId;
1775
1776    #[test]
1777    fn a_dm_dated_ahead_of_this_device_waits_for_its_time() {
1778        let (me, them) = (Keys::generate(), Keys::generate());
1779        let wrap = EventBuilder::new(Kind::GiftWrap, "").finalize(&Keys::generate()).unwrap();
1780        let prepared = |ahead_secs: u64| {
1781            let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hi")
1782                .tag(Tag::public_key(me.public_key()))
1783                .custom_created_at(Timestamp::from_secs(crate::clock::now_secs() + ahead_secs))
1784                .finalize_unsigned_with_id(them.public_key());
1785            finish_prepare(&wrap, Ok(UnwrappedGift { rumor, sender: them.public_key() }), 0, me.public_key())
1786        };
1787        assert!(matches!(prepared(120), PreparedEvent::Early { .. }), "two minutes ahead waits");
1788        assert!(matches!(prepared(0), PreparedEvent::Processed { .. }), "on time shows at once");
1789        assert!(matches!(prepared(3), PreparedEvent::Processed { .. }), "a few seconds fast too");
1790    }
1791}
1792
1793#[cfg(test)]
1794mod signals_only_tests {
1795    use super::*;
1796    use std::sync::atomic::{AtomicUsize, Ordering};
1797
1798    #[derive(Default)]
1799    struct Counts {
1800        signals: AtomicUsize,
1801        messages: AtomicUsize,
1802    }
1803
1804    impl InboundEventHandler for Counts {
1805        fn on_webxdc_signal(&self, _: &str, _: &str, _: &str, _: Option<&str>, _: &str, _: u64) {
1806            self.signals.fetch_add(1, Ordering::Relaxed);
1807        }
1808        fn on_community_webxdc(&self, _: &str, _: &str, _: &str, _: Option<&str>, _: &str, _: u64) {
1809            self.signals.fetch_add(1, Ordering::Relaxed);
1810        }
1811        fn on_dm_received(&self, _: &str, _: &Message, _: bool) {
1812            self.messages.fetch_add(1, Ordering::Relaxed);
1813        }
1814        fn on_file_received(&self, _: &str, _: &Message, _: bool) {
1815            self.messages.fetch_add(1, Ordering::Relaxed);
1816        }
1817    }
1818
1819    #[test]
1820    fn a_catch_up_sync_passes_on_signals_and_nothing_else() {
1821        let inner = Counts::default();
1822        let sync = LiveOnly::signals(&inner);
1823        sync.on_webxdc_signal("npub1a", "npub1a", "T", Some("addr"), "e1", 1);
1824        sync.on_community_webxdc("chan", "npub1a", "T", None, "e2", 1);
1825        sync.on_dm_received("npub1a", &Message { at: u64::MAX, ..Default::default() }, true);
1826        assert_eq!(inner.signals.load(Ordering::Relaxed), 2);
1827        assert_eq!(inner.messages.load(Ordering::Relaxed), 0, "messages from a sync are history");
1828    }
1829
1830    #[test]
1831    fn a_startup_sync_passes_on_messages_sent_since_listening_began() {
1832        let inner = Counts::default();
1833        let sync = LiveOnly::from(&inner, 5_000);
1834        sync.on_dm_received("npub1a", &Message { at: 4_999, ..Default::default() }, true);
1835        assert_eq!(inner.messages.load(Ordering::Relaxed), 0, "before: history");
1836        sync.on_dm_received("npub1a", &Message { at: 5_000, ..Default::default() }, true);
1837        sync.on_file_received("npub1a", &Message { at: 6_000, ..Default::default() }, true);
1838        assert_eq!(inner.messages.load(Ordering::Relaxed), 2, "since: live");
1839    }
1840}
1841
1842#[cfg(test)]
1843mod wrapper_dedup_tests {
1844    use super::*;
1845
1846    fn wrap() -> Event {
1847        EventBuilder::new(Kind::GiftWrap, "").finalize(&Keys::generate()).unwrap()
1848    }
1849
1850    /// A wrap held only on a pre-ledger events row: unseen until migration 96 ledgers it,
1851    /// then skipped by the ledger lookup before any unwrap.
1852    #[tokio::test]
1853    async fn a_pre_ledger_dm_wrap_is_skipped_once_backfilled() {
1854        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1855        crate::db::close_database();
1856        crate::db::clear_id_caches();
1857        let account = Keys::generate().public_key().to_bech32().unwrap();
1858        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
1859        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&account)).unwrap();
1860        crate::db::set_current_account(account.clone()).unwrap();
1861        crate::db::init_database(&account).unwrap();
1862        WRAPPER_ID_CACHE.lock().await.clear();
1863
1864        let legacy = wrap();
1865        let peer = Keys::generate().public_key().to_bech32().unwrap();
1866        let id = legacy.id.to_bytes();
1867        let msg = crate::types::Message {
1868            id: "f".repeat(64),
1869            content: "legacy".into(),
1870            at: 1_700_000_000_000,
1871            npub: Some(peer.clone()),
1872            wrapper_event_id: Some(crate::simd::hex::bytes_to_hex_32(&id)),
1873            ..Default::default()
1874        };
1875        crate::db::events::save_message(&peer, &msg).await.unwrap();
1876        assert!(dedup_skip(&legacy).await.is_none(), "the events column alone no longer dedups");
1877
1878        {
1879            let conn = crate::db::get_write_connection_guard_static().unwrap();
1880            assert_eq!(crate::db::schema::backfill_dm_wrapper_ledger(&conn).unwrap(), 1);
1881        }
1882        assert!(matches!(dedup_skip(&legacy).await, Some(PreparedEvent::DedupSkip { .. })));
1883        assert!(dedup_skip(&wrap()).await.is_none(), "an unseen wrap still processes");
1884        crate::db::close_database();
1885    }
1886}
1887
1888#[cfg(test)]
1889mod invite_wrap_tests {
1890    use super::*;
1891
1892    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
1893        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1894        crate::db::close_database();
1895        crate::db::clear_id_caches();
1896        let tmp = tempfile::tempdir().unwrap();
1897        let account = Keys::generate().public_key().to_bech32().unwrap();
1898        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
1899        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
1900        crate::db::set_current_account(account.clone()).unwrap();
1901        crate::db::init_database(&account).unwrap();
1902        (tmp, guard)
1903    }
1904
1905    fn invite(community_id: &str, wrap: u8, rumor_created_at: u64) -> PreparedEvent {
1906        PreparedEvent::CommunityInviteV2 {
1907            bundle_json: "{}".into(),
1908            community_id: community_id.into(),
1909            inviter: Keys::generate().public_key().to_hex(),
1910            is_mine: false,
1911            wrapper_event_id_bytes: [wrap; 32],
1912            wrapper_created_at: rumor_created_at,
1913            rumor_created_at,
1914            expires_at: 0,
1915        }
1916    }
1917
1918    #[tokio::test]
1919    async fn every_wrap_that_delivers_an_invite_is_kept_and_a_decline_deletes_them_all() {
1920        let (_tmp, _guard) = init_test_db();
1921        let cid = "ab".repeat(32);
1922        let now = crate::clock::timestamp().as_secs();
1923        commit_prepared_event(invite(&cid, 0x11, now), true, &NoOpEventHandler).await;
1924        commit_prepared_event(invite(&cid, 0x22, now), true, &NoOpEventHandler).await;
1925        assert_eq!(crate::db::community::pending_invite_wraps(&cid).unwrap(), ["11".repeat(32), "22".repeat(32)]);
1926        assert_eq!(crate::db::community::list_pending_invites().unwrap()[0].sent_at, now as i64, "parked with its send time");
1927
1928        crate::VectorCore.decline_community_invite(&cid).await.unwrap();
1929        assert!(crate::db::community::get_pending_invite(&cid).unwrap().is_none());
1930        let queued = crate::deletion::queued_received_wrap_deletions();
1931        assert_eq!(queued, [EventId::from_byte_array([0x11; 32]), EventId::from_byte_array([0x22; 32])]);
1932    }
1933
1934    #[tokio::test]
1935    async fn an_invite_met_again_after_its_decline_is_deleted_not_parked() {
1936        let (_tmp, _guard) = init_test_db();
1937        let cid = "cd".repeat(32);
1938        let now = crate::clock::timestamp().as_secs();
1939        crate::community::v2::service::note_local_removal(&cid, now * 1000);
1940        commit_prepared_event(invite(&cid, 0x33, now - 60), true, &NoOpEventHandler).await;
1941        assert!(crate::db::community::get_pending_invite(&cid).unwrap().is_none());
1942        assert_eq!(crate::deletion::queued_received_wrap_deletions(), [EventId::from_byte_array([0x33; 32])]);
1943    }
1944}
1945
1946#[cfg(test)]
1947mod live_only_tests {
1948    #[test]
1949    fn a_sync_forwards_reactions_edits_and_deletions_sent_since_its_cutoff() {
1950        #[derive(Default)]
1951        struct Seen(std::sync::Mutex<Vec<&'static str>>);
1952        impl InboundEventHandler for Seen {
1953            fn on_reaction_added(&self, _: &str, _: &Message, _: &crate::types::Reaction, _: u64) {
1954                self.0.lock().unwrap().push("react");
1955            }
1956            fn on_reaction_removed(&self, _: &str, _: &Message, _: &str, _: &str, _: u64) {
1957                self.0.lock().unwrap().push("unreact");
1958            }
1959            fn on_message_edited(&self, _: &str, _: &Message, _: u64) {
1960                self.0.lock().unwrap().push("edit");
1961            }
1962            fn on_message_removed(&self, _: &str, _: &str, _: Option<&str>, _: bool, _: u64) {
1963                self.0.lock().unwrap().push("remove");
1964            }
1965        }
1966        let seen = Seen::default();
1967        let live = LiveOnly::from(&seen, 1_000);
1968        let msg = Message::default();
1969        let reaction = crate::types::Reaction { id: String::new(), reference_id: String::new(), author_id: String::new(), emoji: "+".into(), emoji_url: None };
1970        for at in [999, 1_000] {
1971            live.on_reaction_added("c", &msg, &reaction, at);
1972            live.on_reaction_removed("c", &msg, "r", "b", at);
1973            live.on_message_edited("c", &msg, at);
1974            live.on_message_removed("c", "m", None, false, at);
1975        }
1976        assert_eq!(*seen.0.lock().unwrap(), vec!["react", "unreact", "edit", "remove"], "only what was sent from the cutoff on");
1977    }
1978
1979    use super::*;
1980
1981    #[derive(Default)]
1982    struct Invites(std::sync::Mutex<Vec<String>>);
1983    impl InboundEventHandler for Invites {
1984        fn on_community_invite(&self, community_id: &str) {
1985            self.0.lock().unwrap().push(community_id.to_string());
1986        }
1987    }
1988
1989    #[test]
1990    fn an_invite_a_sync_parks_reaches_the_handler() {
1991        let inner = Invites::default();
1992        LiveOnly::from(&inner, u64::MAX).on_community_invite("ab");
1993        LiveOnly::signals(&inner).on_community_invite("cd");
1994        assert_eq!(*inner.0.lock().unwrap(), vec!["ab", "cd"]);
1995    }
1996}