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