Skip to main content

vector_core/community/
message_delete.rs

1//! Deleting what the local user sent to a Community, from its relays.
2//!
3//! Every wrap on a plane is signed by the plane's shared key, so a deletion by that key could
4//! come from any member: CORD-01 §Deletions has relays refuse it and honour the wrap's
5//! `p`-tagged owner instead. Vector derives that `p` key from the author's key and the message
6//! ([`derive::wrap_owner_key`]), so every device of the author can delete any of their
7//! messages. A remote-signer account can't derive it, so its sending device keeps a random one.
8//! Owners are kept in `community_wrap_owners`, plane keys in `community_message_keys`.
9//!
10//! A delete sends the owner's deletion and, best-effort, the plane key's: a relay that only
11//! honours authors drops the wrap on that one, and a relay following the spec ignores it. A
12//! message sent before owners were kept has only its plane key, so those relays keep its wrap
13//! and the in-plane delete alone hides it.
14
15use nostr_sdk::prelude::*;
16use crate::event_ext::FinalizeOnClock;
17
18use super::transport::Transport;
19use super::v2::{chat::ChatEvent, derive, stream};
20
21/// How long the in-plane delete of a message its owner deleted from relays stays on them.
22const OWNED_DELETE_EXPIRY_SECS: u64 = crate::deletion::COOPERATIVE_HIDE_EXPIRY_SECS;
23
24/// The `p` key for my wrap of `rumor_id` at `address`: derived when this device holds the
25/// identity's key, otherwise a fresh one only this device will hold.
26pub(crate) fn own_wrap_owner(author: &PublicKey, address: &PublicKey, rumor_id: &EventId) -> Keys {
27    derived_owner(author, address, rumor_id).unwrap_or_else(Keys::generate)
28}
29
30fn derived_owner(author: &PublicKey, address: &PublicKey, rumor_id: &EventId) -> Option<Keys> {
31    crate::state::MY_SECRET_KEY
32        .with_keys(|keys| {
33            let secret: &[u8; 32] = keys.secret_key().as_secret_bytes().try_into().ok()?;
34            (keys.public_key() == *author).then(|| derive::wrap_owner_key(secret, address, rumor_id.as_bytes()))
35        })
36        .flatten()
37}
38
39/// Keep what deletes my own `wrap`, met on a relay and sent from this device or another: its
40/// owner when it is the key this identity derives, and `plane`, the key that signed it, when
41/// the caller holds it. Fills only a confirmed gap. Returns whether its owner is newly kept.
42pub(crate) fn heal_own_wrap(event: &ChatEvent, wrap: &Event, plane: Option<&Keys>, relays: &[String]) -> bool {
43    if !matches!(event, ChatEvent::Message { .. } | ChatEvent::Reaction { .. } | ChatEvent::Edit { .. }) {
44        return false;
45    }
46    let opened = event.opened();
47    if crate::state::my_public_key() != Some(opened.author) {
48        return false;
49    }
50    let (rumor_hex, wrap_hex) = (opened.rumor_id.to_hex(), wrap.id.to_hex());
51    if let Some(plane) = plane {
52        if matches!(crate::db::community::has_message_key(&rumor_hex), Ok(false)) {
53            let _ = crate::db::community::store_message_key(&rumor_hex, &wrap_hex, plane, relays);
54        }
55    }
56    if !matches!(crate::db::community::has_wrap_owner(&rumor_hex), Ok(false)) {
57        return false;
58    }
59    let Some(owner) = derived_owner(&opened.author, &wrap.pubkey, &opened.rumor_id) else {
60        return false;
61    };
62    stream::wrap_owner(wrap) == Some(owner.public_key())
63        && crate::db::community::store_wrap_owner(&rumor_hex, &wrap_hex, &owner, relays).is_ok()
64}
65
66/// What deleting one of my own events from relays reached.
67#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
68pub struct Scrubbed {
69    /// Its owner's deletion went out, which every relay following CORD-01 honours.
70    pub by_owner: bool,
71    /// Its plane key's deletion was sent: a relay judging by author honours it, and one following
72    /// CORD-01 refuses it, which is why its answer counts for nothing.
73    pub by_plane: bool,
74}
75
76impl Scrubbed {
77    /// Whether every relay that honours a deletion at all was asked in the way it honours.
78    pub fn everywhere(&self) -> bool {
79        self.by_owner && self.by_plane
80    }
81}
82
83/// Delete my own `message_id` from relays, with its stored edits (they carry its text), by
84/// every key kept for their wraps: one deletion per wrap, so none ties wraps together for a
85/// relay. `relays` is where its Community lives now: a relay move copies wraps over. An owner
86/// key is dropped once its deletion went out, a plane key once its deletion was sent.
87pub async fn scrub_own<T: Transport + ?Sized>(transport: &T, relays: &[String], message_id: &str) -> Result<Scrubbed, String> {
88    crate::db::scoped(async move {
89        if !crate::db::current_session().is_live() {
90            return Err("account changed; aborting delete".to_string());
91        }
92        let mut targets = vec![message_id.to_string()];
93        targets.extend(crate::db::events::edits_of(message_id).unwrap_or_default());
94
95        let mut scrubbed = Scrubbed::default();
96        for target in &targets {
97            let owners = crate::db::community::wrap_owners(target)?;
98            let by_owner = owners.iter().map(|k| deletion_by(k, relays)).collect::<Result<Vec<_>, _>>()?;
99            let by_plane = crate::db::community::get_message_key(target)?.map(|k| deletion_by(&k, relays)).transpose()?;
100            // The owner's deletion must land. The plane key's is a single best-effort send: a relay
101            // following CORD-01 refuses it, and a durable publish would wait out that refusal.
102            let (owner_sent, plane_sent) = futures_util::future::join(
103                futures_util::future::join_all(by_owner.iter().map(|(d, to)| transport.publish_durable(d, to))),
104                async {
105                    match &by_plane {
106                        Some((d, to)) => Some(transport.publish(d, to).await),
107                        None => None,
108                    }
109                },
110            )
111            .await;
112            if let Some(e) = owner_sent.iter().find_map(|r| r.as_ref().err()) {
113                crate::log_warn!("[Community] an owner's deletion of {target} failed: {e}");
114            }
115            if !owners.is_empty() && owner_sent.iter().all(Result::is_ok) {
116                crate::db::community::forget_wrap_owners(target)?;
117                scrubbed.by_owner |= target == message_id;
118            }
119            if let Some(sent) = plane_sent {
120                if let Err(e) = sent {
121                    crate::log_debug!("[Community] the plane key's deletion of {target} was not taken: {e}");
122                }
123                crate::db::community::delete_message_key(target)?;
124                scrubbed.by_plane |= target == message_id;
125            }
126        }
127        Ok(scrubbed)
128    })
129    .await
130}
131
132/// One wrap a second: a deleted Channel's history leaves the relays without flooding them, or
133/// this device, however much of it there was.
134const SCRUB_PACE: std::time::Duration = std::time::Duration::from_secs(1);
135
136struct ScrubbingWraps;
137
138fn scrubbing() -> std::sync::Arc<std::sync::atomic::AtomicBool> {
139    crate::db::current_session().scoped::<ScrubbingWraps, _>()
140}
141
142/// Queue my own `message_ids` in `community_id` to leave the relays, one at a time
143/// ([`SCRUB_PACE`]), resuming across restarts.
144pub(crate) fn queue_scrubs(community_id: &str, message_ids: &[String]) {
145    if message_ids.is_empty() {
146        return;
147    }
148    if let Err(e) = crate::db::community::queue_wrap_scrubs(community_id, message_ids) {
149        crate::log_warn!("[Community] queueing {} wrap deletion(s) failed: {e}", message_ids.len());
150        return;
151    }
152    resume_scrubs();
153}
154
155/// Work through the queued scrubs until none is left. One that can't go out stays queued, at
156/// the back, and the next resume tries again.
157pub(crate) fn resume_scrubs() {
158    if crate::state::nostr_client().is_none() || !matches!(crate::db::community::next_wrap_scrub(), Ok(Some(_))) {
159        return;
160    }
161    let running = scrubbing();
162    if running.swap(true, std::sync::atomic::Ordering::AcqRel) {
163        return;
164    }
165    crate::db::spawn_bound(async move {
166        struct Release(std::sync::Arc<std::sync::atomic::AtomicBool>);
167        impl Drop for Release {
168            fn drop(&mut self) {
169                self.0.store(false, std::sync::atomic::Ordering::Release);
170            }
171        }
172        let _release = Release(running);
173        let transport = super::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
174        drain_scrubs(&transport, SCRUB_PACE).await;
175    });
176}
177
178/// Scrub the queue in order, `pace` apart, until it is empty or one can't go out. Returns how
179/// many left the queue.
180pub(crate) async fn drain_scrubs<T: Transport + ?Sized>(transport: &T, pace: std::time::Duration) -> usize {
181    let mut done = 0;
182    while let Ok(Some((message_id, community_id))) = crate::db::community::next_wrap_scrub() {
183        let relays = crate::community::id32_from_hex(&community_id)
184            .and_then(|id| crate::db::community::load_community_v2(&crate::community::CommunityId(id)).ok().flatten())
185            .map(|c| c.relays)
186            .unwrap_or_default();
187        let gone = scrub_own(transport, &relays, &message_id).await.is_ok() && matches!(crate::db::community::has_wrap_owner(&message_id), Ok(false));
188        if crate::db::community::settle_wrap_scrub(&message_id, !gone).is_err() || !gone {
189            break;
190        }
191        done += 1;
192        if !pace.is_zero() {
193            crate::rt::time::sleep(pace).await;
194        }
195    }
196    done
197}
198
199/// When the in-plane delete of `message_id` may leave relays, given what its scrub reached:
200/// once the wrap was deleted [`Scrubbed::everywhere`], 30 days on, or with the message when
201/// that comes sooner. Otherwise never, since it alone hides a wrap a relay still holds.
202pub async fn in_plane_delete_expiry(message_id: &str, scrubbed: Scrubbed) -> Option<u64> {
203    if !scrubbed.everywhere() {
204        return None;
205    }
206    let until = crate::clock::timestamp().as_secs().saturating_add(OWNED_DELETE_EXPIRY_SECS);
207    let message = crate::self_destruct::edit_expiry(message_id).await.ok().flatten();
208    Some(message.map_or(until, |m| m.min(until)))
209}
210
211/// The deletion of one wrap by the key kept for it, and the relays it goes to.
212fn deletion_by((keys, outer, sent_to): &(Keys, String, Vec<String>), relays: &[String]) -> Result<(Event, Vec<String>), String> {
213    let wrap = EventId::from_hex(outer).map_err(|e| e.to_string())?;
214    let deletion = crate::deletion::wrap_deletion(&[wrap]).finalize_on_clock(keys).map_err(|e| e.to_string())?;
215    Ok((deletion, union(relays, sent_to)))
216}
217
218fn union(a: &[String], b: &[String]) -> Vec<String> {
219    let mut out = a.to_vec();
220    for r in b {
221        if !out.contains(r) {
222            out.push(r.clone());
223        }
224    }
225    out
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::community::transport::memory::MemoryRelay;
232    use crate::community::transport::{PlaneFetch, Query};
233
234    /// A transport whose publish always fails (fetch returns nothing).
235    struct FailingRelay;
236    #[async_trait::async_trait]
237    impl Transport for FailingRelay {
238        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
239            Ok(PlaneFetch::whole(self.fetch(query, relays).await?))
240        }
241        async fn publish(&self, _event: &Event, _relays: &[String]) -> Result<(), String> {
242            Err("relay unreachable".to_string())
243        }
244        async fn publish_durable(&self, _event: &Event, _relays: &[String]) -> Result<(), String> {
245            Err("relay unreachable".to_string())
246        }
247        async fn fetch(&self, _query: &Query, _relays: &[String]) -> Result<Vec<Event>, String> {
248            Ok(Vec::new())
249        }
250    }
251
252    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(7700);
253
254    fn make_test_npub(n: u32) -> String {
255        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
256        let mut payload = vec![b'q'; 58];
257        let mut x = n as u64;
258        let mut i = 58;
259        while x > 0 && i > 0 {
260            i -= 1;
261            payload[i] = BECH32[(x as usize) % 32];
262            x /= 32;
263        }
264        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
265    }
266
267    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
268        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
269        crate::db::close_database();
270        crate::db::clear_id_caches();
271        let tmp = tempfile::tempdir().unwrap();
272        let account = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
273        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
274        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
275        crate::db::set_current_account(account.clone()).unwrap();
276        crate::db::init_database(&account).unwrap();
277        (tmp, guard)
278    }
279
280    fn relays() -> Vec<String> {
281        vec!["r1".into(), "r2".into(), "r3".into()]
282    }
283
284    /// A wrap as a plane publishes it: signed by the shared `plane` key, `p`-tagged to `owner`.
285    async fn published(relay: &MemoryRelay, plane: &Keys, owner: &Keys) -> Event {
286        let wrap = EventBuilder::new(Kind::Custom(1059), "sealed").tag(Tag::public_key(owner.public_key())).finalize(plane).unwrap();
287        relay.publish_durable(&wrap, &relays()).await.unwrap();
288        wrap
289    }
290
291    async fn still_there(relay: &MemoryRelay, id: EventId) -> bool {
292        let q = Query { ids: vec![id.to_hex()], ..Default::default() };
293        !relay.fetch(&q, &relays()).await.unwrap().is_empty()
294    }
295
296    #[tokio::test]
297    async fn a_relay_following_cord01_takes_a_wraps_deletion_only_from_its_owner() {
298        let relay = MemoryRelay::new();
299        relay.follow_cord01(&relays());
300        let (plane, owner) = (Keys::generate(), Keys::generate());
301        let wrap = published(&relay, &plane, &owner).await;
302
303        let by_plane = crate::deletion::wrap_deletion(&[wrap.id]).finalize(&plane).unwrap();
304        relay.publish_durable(&by_plane, &relays()).await.unwrap();
305        assert!(still_there(&relay, wrap.id).await, "any member holds the plane key, so it deletes nothing");
306
307        let by_owner = crate::deletion::wrap_deletion(&[wrap.id]).finalize(&owner).unwrap();
308        relay.publish_durable(&by_owner, &["r1".to_string()]).await.unwrap();
309        assert!(still_there(&relay, wrap.id).await, "a deletion on a subset leaves it on the rest");
310        relay.publish_durable(&by_owner, &relays()).await.unwrap();
311        assert!(!still_there(&relay, wrap.id).await);
312    }
313
314    #[tokio::test]
315    async fn a_scrub_deletes_by_owner_and_plane_and_spends_both_keys() {
316        let (_tmp, _guard) = init_test_db();
317        let (cord01, stock) = (MemoryRelay::new(), MemoryRelay::new());
318        cord01.follow_cord01(&relays());
319        let (plane, owner) = (Keys::generate(), Keys::generate());
320        let message_id = "00".repeat(32);
321        for relay in [&cord01, &stock] {
322            let wrap = published(relay, &plane, &owner).await;
323            crate::db::community::store_message_key(&message_id, &wrap.id.to_hex(), &plane, &relays()).unwrap();
324            crate::db::community::store_wrap_owner(&message_id, &wrap.id.to_hex(), &owner, &relays()).unwrap();
325
326            assert_eq!(scrub_own(relay, &relays(), &message_id).await.unwrap(), Scrubbed { by_owner: true, by_plane: true });
327            assert!(!still_there(relay, wrap.id).await, "the owner deletes it where CORD-01 holds, the plane key elsewhere");
328            assert!(!crate::db::community::has_wrap_owner(&message_id).unwrap());
329            assert!(!crate::db::community::has_message_key(&message_id).unwrap());
330        }
331    }
332
333    /// Records which publish each event went through, accepting everything.
334    #[derive(Default)]
335    struct Recording {
336        durable: std::sync::Mutex<Vec<PublicKey>>,
337        once: std::sync::Mutex<Vec<PublicKey>>,
338    }
339    #[async_trait::async_trait]
340    impl Transport for Recording {
341        async fn fetch_plane(&self, _plane: &Keys, _query: &Query, _relays: &[String]) -> Result<PlaneFetch, String> {
342            Ok(PlaneFetch::whole(Vec::new()))
343        }
344        async fn publish(&self, event: &Event, _relays: &[String]) -> Result<(), String> {
345            self.once.lock().unwrap().push(event.pubkey);
346            Ok(())
347        }
348        async fn publish_durable(&self, event: &Event, _relays: &[String]) -> Result<(), String> {
349            self.durable.lock().unwrap().push(event.pubkey);
350            Ok(())
351        }
352        async fn fetch(&self, _query: &Query, _relays: &[String]) -> Result<Vec<Event>, String> {
353            Ok(Vec::new())
354        }
355    }
356
357    #[tokio::test]
358    async fn only_the_owners_deletion_waits_to_land() {
359        let (_tmp, _guard) = init_test_db();
360        let (plane, owner) = (Keys::generate(), Keys::generate());
361        let message_id = "66".repeat(32);
362        crate::db::community::store_message_key(&message_id, &"77".repeat(32), &plane, &relays()).unwrap();
363        crate::db::community::store_wrap_owner(&message_id, &"77".repeat(32), &owner, &relays()).unwrap();
364        let relay = Recording::default();
365        scrub_own(&relay, &relays(), &message_id).await.unwrap();
366        assert_eq!(*relay.durable.lock().unwrap(), vec![owner.public_key()]);
367        assert_eq!(*relay.once.lock().unwrap(), vec![plane.public_key()], "a CORD-01 relay refuses it, so nothing waits on it");
368    }
369
370    #[tokio::test]
371    async fn an_owner_deletion_no_relay_took_keeps_its_key_and_expires_nothing() {
372        let (_tmp, _guard) = init_test_db();
373        let message_id = "44".repeat(32);
374        crate::db::community::store_message_key(&message_id, &"55".repeat(32), &Keys::generate(), &relays()).unwrap();
375        crate::db::community::store_wrap_owner(&message_id, &"55".repeat(32), &Keys::generate(), &relays()).unwrap();
376
377        let scrubbed = scrub_own(&FailingRelay, &relays(), &message_id).await.unwrap();
378        assert_eq!(scrubbed, Scrubbed { by_owner: false, by_plane: true }, "a refused plane deletion still counts as sent");
379        assert!(crate::db::community::has_wrap_owner(&message_id).unwrap(), "the owner key stays for another try");
380        assert!(!crate::db::community::has_message_key(&message_id).unwrap());
381        assert_eq!(in_plane_delete_expiry(&message_id, scrubbed).await, None);
382    }
383
384    #[tokio::test]
385    async fn a_message_sent_before_owners_were_kept_stays_on_a_cord01_relay() {
386        let (_tmp, _guard) = init_test_db();
387        let relay = MemoryRelay::new();
388        relay.follow_cord01(&relays());
389        let plane = Keys::generate();
390        let wrap = published(&relay, &plane, &Keys::generate()).await;
391        let message_id = "11".repeat(32);
392        crate::db::community::store_message_key(&message_id, &wrap.id.to_hex(), &plane, &relays()).unwrap();
393
394        let scrubbed = scrub_own(&relay, &relays(), &message_id).await.unwrap();
395        assert_eq!(scrubbed, Scrubbed { by_owner: false, by_plane: true });
396        assert!(still_there(&relay, wrap.id).await);
397        assert_eq!(in_plane_delete_expiry(&message_id, scrubbed).await, None, "its in-plane delete never leaves");
398        let owner_only = Scrubbed { by_owner: true, by_plane: false };
399        assert_eq!(in_plane_delete_expiry(&message_id, owner_only).await, None, "nor while a relay judging by author holds it");
400    }
401
402    #[tokio::test]
403    async fn a_scrub_reaches_the_communitys_relays_beyond_those_it_was_sent_to() {
404        let (_tmp, _guard) = init_test_db();
405        let relay = MemoryRelay::new();
406        let moved = vec!["r9".to_string()];
407        relay.follow_cord01(&relays());
408        relay.follow_cord01(&moved);
409        let (plane, owner) = (Keys::generate(), Keys::generate());
410        let wrap = published(&relay, &plane, &owner).await;
411        relay.inject(&wrap, &moved);
412        let message_id = "22".repeat(32);
413        crate::db::community::store_wrap_owner(&message_id, &wrap.id.to_hex(), &owner, &relays()).unwrap();
414
415        scrub_own(&relay, &moved, &message_id).await.unwrap();
416        let q = Query { ids: vec![wrap.id.to_hex()], ..Default::default() };
417        assert!(relay.fetch(&q, &moved).await.unwrap().is_empty(), "the copy a relay move made goes too");
418        assert!(!still_there(&relay, wrap.id).await);
419    }
420
421    #[tokio::test]
422    async fn an_owned_delete_leaves_relays_after_30_days() {
423        let (_tmp, _guard) = init_test_db();
424        let now = Timestamp::now().as_secs();
425        let until = in_plane_delete_expiry(&"33".repeat(32), Scrubbed { by_owner: true, by_plane: true }).await.unwrap();
426        assert!((now + OWNED_DELETE_EXPIRY_SECS..=now + OWNED_DELETE_EXPIRY_SECS + 5).contains(&until));
427    }
428
429    #[tokio::test]
430    async fn scrubbing_a_message_we_hold_no_keys_for_reaches_nothing() {
431        let (_tmp, _guard) = init_test_db();
432        assert_eq!(scrub_own(&MemoryRelay::new(), &relays(), &"00".repeat(32)).await.unwrap(), Scrubbed::default());
433    }
434}