1use crate::event_ext::FinalizeUnsignedWithId;
26use crate::event_ext::FinalizeOnClock;
27use nostr_sdk::prelude::*;
28
29use crate::inbox_relays::{get_publish_tracker, resolve_gift_wrap_targets, send_gift_wrap, teardown_gift_wrap_targets};
30use crate::state::{my_public_key, nostr_client};
31
32pub(crate) const COOPERATIVE_HIDE_EXPIRY_SECS: u64 = 60 * 60 * 24 * 30;
35
36const WRAP_DELETION_EXPIRY_SECS: u64 = 60 * 60 * 24 * 90;
39
40pub(crate) const WRAPS_PER_DELETION: usize = 100;
42
43#[derive(serde::Serialize, Debug, Clone, Default)]
51pub struct DeleteOutcome {
52 pub wraps_dispatched: usize,
55 pub wraps_total: usize,
57 pub cooperative_hide_sent: bool,
60 pub blobs_dispatched: usize,
63 pub any_network_action: bool,
68}
69
70pub async fn take_back_failed_dm(rumor_id: &EventId, recipient: &nostr_sdk::prelude::PublicKey) -> bool {
74 let Some(client) = nostr_client() else { return false };
75 let rumor_hex = rumor_id.to_hex();
76 if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
77 crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
78 }
79 crate::state::note_message_deleted(&rumor_hex);
80 let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(rumor_id).unwrap_or_default();
81 dispatch_wrap_deletions(&client, &keys, None).await;
82 match publish_cooperative_hide(&client, rumor_id, Some(recipient), 14).await {
83 Ok(()) => true,
84 Err(e) => {
85 crate::log_warn!("[NIP-17 delete] couldn't take back a failed DM: {}", e);
86 false
87 }
88 }
89}
90
91pub async fn delete_own_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
95 let client = nostr_client().ok_or("Not logged in")?;
96 let rumor_hex = rumor_id.to_hex();
99 if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
100 crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
101 }
102 crate::state::note_message_deleted(&rumor_hex);
103 let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(rumor_id)
104 .unwrap_or_default();
105 let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
106
107 let (all_attachments, recipient_from_state) = {
119 let state = crate::state::STATE.lock().await;
120 match state.find_message(&rumor_id.to_hex()) {
121 Some((chat, msg)) => {
122 debug_assert!(
123 matches!(chat.chat_type, crate::chat::ChatType::DirectMessage),
124 "delete_own_dm called on non-DM chat — caller bug"
125 );
126 let recipient = nostr_sdk::prelude::PublicKey::from_bech32(&chat.id).ok();
127 (msg.attachments.clone(), recipient)
128 }
129 None => (Vec::new(), None),
130 }
131 };
132
133 let unique_attachments = filter_unreferenced_attachments(
140 &rumor_id.to_hex(),
141 all_attachments,
142 ).await;
143
144 delete_cached_attachment_files(&unique_attachments);
146
147 let attachment_urls: Vec<String> = scrub_safe_urls(&unique_attachments, &rumor_id.to_hex());
151
152 let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
153
154 let cooperative_recipient = keys
157 .iter()
158 .find(|k| {
159 k.role == crate::db::nip17_keys::WrapRole::Recipient
160 || k.role == crate::db::nip17_keys::WrapRole::Retry
161 })
162 .map(|k| k.recipient_pubkey)
163 .or(recipient_from_state);
164
165 let mut cooperative_hide_sent = false;
166 if let Some(recipient) = cooperative_recipient {
167 match publish_cooperative_hide(&client, rumor_id, Some(&recipient), 14).await {
168 Ok(()) => cooperative_hide_sent = true,
169 Err(e) => crate::log_warn!("[NIP-17 delete] cooperative-hide notice failed: {}", e),
170 }
171 }
172
173 let mut blobs_dispatched = 0usize;
178 if !attachment_urls.is_empty() {
179 if let Ok(signer) = crate::signer::active_signer() {
180 blobs_dispatched = attachment_urls.len();
181 crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
182 }
183 }
184
185 let any_network_action =
186 wraps_dispatched > 0 || cooperative_hide_sent || blobs_dispatched > 0;
187
188 Ok(DeleteOutcome {
189 wraps_total,
190 wraps_dispatched,
191 cooperative_hide_sent,
192 blobs_dispatched,
193 any_network_action,
194 })
195}
196
197pub async fn delete_own_reaction(
201 reaction_id: &EventId,
202 recipient: PublicKey,
203) -> Result<DeleteOutcome, String> {
204 let client = nostr_client().ok_or("Not logged in")?;
205 let reaction_hex = reaction_id.to_hex();
208 if let Err(e) = crate::db::events::add_message_tombstone(&reaction_hex) {
209 crate::log_warn!("[reaction delete] tombstone write failed: {}", e);
210 }
211 crate::state::note_message_deleted(&reaction_hex);
212 let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(reaction_id)
213 .unwrap_or_default();
214 let received = crate::db::events::wrapper_event_id_of(&reaction_hex);
215 let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
216
217 let cooperative_recipient = keys
220 .iter()
221 .find(|k| {
222 k.role == crate::db::nip17_keys::WrapRole::Recipient
223 || k.role == crate::db::nip17_keys::WrapRole::Retry
224 })
225 .map(|k| k.recipient_pubkey)
226 .unwrap_or(recipient);
227
228 let mut cooperative_hide_sent = false;
229 match publish_cooperative_hide(&client, reaction_id, Some(&cooperative_recipient), 7).await {
230 Ok(()) => cooperative_hide_sent = true,
231 Err(e) => crate::log_warn!("[reaction delete] cooperative-hide failed: {}", e),
232 }
233
234 let any_network_action = wraps_dispatched > 0 || cooperative_hide_sent;
235 Ok(DeleteOutcome {
236 wraps_total,
237 wraps_dispatched,
238 cooperative_hide_sent,
239 blobs_dispatched: 0,
240 any_network_action,
241 })
242}
243
244pub async fn delete_received_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
248 let client = nostr_client().ok_or("Not logged in")?;
249 let rumor_hex = rumor_id.to_hex();
250 if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
252 crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
253 }
254 crate::state::note_message_deleted(&rumor_hex);
255 let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
256
257 let attachments = {
259 let state = crate::state::STATE.lock().await;
260 state.find_message(&rumor_hex).map(|(_, msg)| msg.attachments.clone()).unwrap_or_default()
261 };
262 delete_cached_attachment_files(&filter_unreferenced_attachments(&rumor_hex, attachments).await);
263
264 let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &[], received).await;
265 let cooperative_hide_sent = match publish_cooperative_hide(&client, rumor_id, None, 14).await {
266 Ok(()) => true,
267 Err(e) => {
268 crate::log_warn!("[NIP-17 delete] hide request to our devices failed: {}", e);
269 false
270 }
271 };
272 Ok(DeleteOutcome {
273 wraps_total,
274 wraps_dispatched,
275 cooperative_hide_sent,
276 blobs_dispatched: 0,
277 any_network_action: wraps_dispatched > 0 || cooperative_hide_sent,
278 })
279}
280
281pub(crate) fn wrap_deletion(wrap_ids: &[EventId]) -> EventBuilder {
284 let expires = crate::clock::timestamp().as_secs().saturating_add(WRAP_DELETION_EXPIRY_SECS);
285 wrap_ids
286 .iter()
287 .fold(EventBuilder::new(Kind::EventDeletion, ""), |b, id| b.tag(Tag::event(*id)))
288 .tag(Tag::custom("k", ["1059"]))
289 .tag(Tag::expiration(Timestamp::from(expires)))
290}
291
292async fn owner_deletion(wrap_ids: &[EventId], owner: &PublicKey) -> Result<Event, String> {
295 let deletion = crate::sign_builder(wrap_deletion(wrap_ids)).await?;
296 if deletion.pubkey != *owner {
297 return Err("the account changed before the deletion was signed".to_string());
298 }
299 Ok(deletion)
300}
301
302async fn dispatch_wrap_deletions(
306 client: &Client,
307 keys: &[crate::db::nip17_keys::StoredWrapKey],
308 received: Option<EventId>,
309) -> (usize, usize) {
310 let Some(me) = my_public_key() else { return (0, keys.len()) };
311 let own = own_wraps(keys, received);
312 let known = own.len() + keys.iter().filter(|k| !own.contains(&k.wrap_event_id)).count();
313 let mut dispatched = 0usize;
314 for wrap_id in own {
315 match owner_deletion(&[wrap_id], &me).await {
317 Ok(deletion) => {
318 let client = client.clone();
319 crate::db::spawn_bound(async move {
320 delete_wrap_per_relay(&client, wrap_id, &deletion, &me, true).await;
321 });
322 dispatched += 1;
323 }
324 Err(e) => crate::log_warn!("[NIP-17 delete] our own copy {} stays: {}", wrap_id.to_hex(), e),
325 }
326 }
327 for stored in keys {
328 let deletion = match wrap_deletion(&[stored.wrap_event_id]).finalize_on_clock(&Keys::new(stored.secret.clone())) {
329 Ok(ev) => ev,
330 Err(e) => {
331 crate::log_warn!("[NIP-17 delete] failed to sign deletion for wrap {}: {}", stored.wrap_event_id.to_hex(), e);
332 continue;
333 }
334 };
335 let (client, wrap_id, owner) = (client.clone(), stored.wrap_event_id, stored.recipient_pubkey);
336 crate::db::spawn_bound(async move {
337 delete_wrap_per_relay(&client, wrap_id, &deletion, &owner, false).await;
338 });
339 dispatched += 1;
340 }
341 let wraps: Vec<EventId> = keys.iter().map(|k| k.wrap_event_id).collect();
342 if let Err(e) = crate::db::nip17_keys::purge_wrap_keys(&wraps) {
343 crate::log_warn!("[NIP-17 delete] failed to purge wrap keys: {}", e);
344 }
345 (dispatched, known)
346}
347
348fn own_wraps(keys: &[crate::db::nip17_keys::StoredWrapKey], received: Option<EventId>) -> Vec<EventId> {
351 use crate::db::nip17_keys::WrapRole;
352 let mut own: Vec<EventId> = keys.iter().filter(|k| k.role == WrapRole::SelfSend).map(|k| k.wrap_event_id).collect();
353 if let Some(w) = received.filter(|w| !own.contains(w)) {
354 own.push(w);
355 }
356 own
357}
358
359struct ReceivedWrapDeletions;
362
363fn received_wrap_deletions() -> std::sync::Arc<std::sync::Mutex<Vec<EventId>>> {
364 crate::db::current_session().scoped::<ReceivedWrapDeletions, _>()
365}
366
367#[cfg(test)]
368pub(crate) fn queued_received_wrap_deletions() -> Vec<EventId> {
369 received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
370}
371
372pub(crate) fn delete_received_wrap(wrap_id: EventId) {
375 let pending = received_wrap_deletions();
376 let first = {
377 let mut q = pending.lock().unwrap_or_else(|e| e.into_inner());
378 if q.contains(&wrap_id) {
379 return;
380 }
381 q.push(wrap_id);
382 q.len() == 1
383 };
384 if !first {
385 return;
386 }
387 crate::db::spawn_bound(async move {
388 crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
389 let wraps = std::mem::take(&mut *pending.lock().unwrap_or_else(|e| e.into_inner()));
390 let (Some(client), Some(me)) = (nostr_client(), my_public_key()) else { return };
391 for batch in wraps.chunks(WRAPS_PER_DELETION) {
392 match owner_deletion(batch, &me).await {
393 Ok(deletion) => publish_to_inbox(&client, &me, &deletion, true).await,
394 Err(e) => crate::log_warn!("[NIP-17 delete] {} received wrap(s) stay: {}", batch.len(), e),
395 }
396 }
397 });
398}
399
400async fn delete_wrap_per_relay(client: &Client, wrap_event_id: EventId, deletion: &Event, owner: &PublicKey, verify: bool) {
405 let Some(tracker) = get_publish_tracker(&wrap_event_id) else {
406 publish_to_inbox(client, owner, deletion, verify).await;
407 return;
408 };
409 let mut delivered = 0usize;
410 let mut cursor = 0usize;
411 while let Some(url) = tracker.next_success(&mut cursor).await {
412 let relay = client.relays().await.get(&url).cloned();
413 match relay {
414 Some(relay) if send_to_one_relay(client, &url, &relay, deletion, verify).await => delivered += 1,
415 Some(_) => {}
416 None => crate::log_warn!("[delete] relay {} not in pool — deletion not delivered", url),
417 }
418 }
419 crate::log_info!("[NIP-17 delete] wrap {} — deletion delivered to {} relay(s) via tracker", wrap_event_id.to_hex(), delivered);
420}
421
422async fn publish_to_inbox(client: &Client, owner: &PublicKey, deletion: &Event, verify: bool) {
424 let targets = resolve_gift_wrap_targets(client, owner).await;
425 let total = targets.resolved.len();
426 let mut delivered = 0usize;
427 for (url, relay) in &targets.resolved {
428 if send_to_one_relay(client, url, relay, deletion, verify).await {
429 delivered += 1;
430 }
431 }
432 teardown_gift_wrap_targets(client, &targets).await;
433 crate::log_info!("[NIP-17 delete] deletion {} delivered to {}/{} inbox relay(s)", deletion.id.to_hex(), delivered, total);
434}
435
436pub fn delete_cached_attachment_files_pub(attachments: &[crate::types::Attachment]) {
449 delete_cached_attachment_files(attachments);
450}
451
452pub async fn filter_unreferenced_attachments(
466 excluding_message_id: &str,
467 attachments: Vec<crate::types::Attachment>,
468) -> Vec<crate::types::Attachment> {
469 if attachments.is_empty() {
470 return attachments;
471 }
472 let state_referenced: Vec<bool> = {
474 let state = crate::state::STATE.lock().await;
475 attachments
476 .iter()
477 .map(|att| {
478 let hash = &*att.id;
481 if hash.is_empty() {
482 return false;
483 }
484 state.chats.iter().any(|chat| {
485 chat.iter_compact().any(|m| {
486 let msg_id_hex = m.id_hex();
487 msg_id_hex != excluding_message_id
488 && m.attachments.iter().any(|a| a.id_eq(hash))
489 })
490 })
491 })
492 .collect()
493 };
494 attachments
499 .into_iter()
500 .zip(state_referenced)
501 .filter(|(att, in_state)| {
502 if *in_state {
503 return false;
504 }
505 let hash = &*att.id;
506 if hash.is_empty() {
507 return true;
508 }
509 !crate::db::attachments::hash_referenced_elsewhere(hash, excluding_message_id).unwrap_or(true)
510 })
511 .map(|(att, _)| att)
512 .collect()
513}
514
515pub fn scrub_safe_urls(attachments: &[crate::types::Attachment], excluding_event_id: &str) -> Vec<String> {
520 let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
521 if urls.is_empty() {
522 return urls;
523 }
524 crate::db::attachments::urls_unreferenced_elsewhere(&urls, excluding_event_id).unwrap_or_default()
525}
526
527fn delete_cached_attachment_files(attachments: &[crate::types::Attachment]) {
528 if attachments.is_empty() {
529 return;
530 }
531 let hashes: Vec<[u8; 32]> = attachments.iter().filter_map(|a| crate::simd::hex::hex_to_bytes_32_checked(&a.id)).collect();
532 for hash in &hashes {
533 crate::media::pending::forget(hash);
534 #[cfg(not(target_arch = "wasm32"))]
535 crate::media::store::forget(hash);
536 #[cfg(target_arch = "wasm32")]
537 {
538 let hash = *hash;
539 crate::media::store::stop_holding(&hash);
540 crate::db::spawn_bound(async move { crate::media::store::forget(&hash).await });
541 }
542 }
543 #[cfg(target_arch = "wasm32")]
544 {
545 let dir = crate::db::get_download_dir();
546 let paths: Vec<std::path::PathBuf> = attachments
547 .iter()
548 .map(|a| std::path::PathBuf::from(&*a.path))
549 .filter(|p| p.starts_with(&dir) && !p.components().any(|c| c == std::path::Component::ParentDir))
550 .collect();
551 crate::db::spawn_bound(async move {
552 for p in paths {
553 crate::webfiles::remove(&p).await;
554 }
555 });
556 }
557 #[cfg(not(target_arch = "wasm32"))]
558 delete_cached_attachment_files_native(attachments);
559 let ram = crate::media::ram::cache();
562 for hash in &hashes {
563 ram.remove(hash);
564 }
565}
566
567#[cfg(not(target_arch = "wasm32"))]
568fn delete_cached_attachment_files_native(attachments: &[crate::types::Attachment]) {
569 let roots: Vec<std::path::PathBuf> = crate::db::download_roots().iter().filter_map(|r| r.canonicalize().ok()).collect();
570 if roots.is_empty() {
571 return;
572 }
573 for att in attachments {
574 if att.path.is_empty() {
575 continue;
576 }
577 let candidate = match std::path::PathBuf::from(&*att.path).canonicalize() {
578 Ok(p) => p,
579 Err(_) => continue,
581 };
582 if !roots.iter().any(|root| candidate.starts_with(root)) {
583 continue;
586 }
587 if crate::db::saved::is_saved(&candidate.to_string_lossy()).unwrap_or(true) {
588 continue;
589 }
590 if let Err(e) = std::fs::remove_file(&candidate) {
591 crate::log_warn!(
592 "[delete] failed to remove cached attachment {}: {}",
593 candidate.display(),
594 e
595 );
596 }
597 }
598}
599
600async fn send_to_one_relay(client: &Client, url: &RelayUrl, relay: &Relay, event: &Event, verify: bool) -> bool {
623 const MAX_RATELIMIT_RETRIES: u32 = 20;
629 const RATELIMIT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);
631
632 let mut retries = 0u32;
633 let wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
634 loop {
635 match relay.send_event(event).ok_timeout(wait).authentication_timeout(wait).await {
636 Ok(_) => {
637 if retries == 0 {
638 crate::log_info!("[delete] relay {} ACK'd NIP-09", url);
639 } else {
640 crate::log_info!(
641 "[delete] relay {} ACK'd NIP-09 (after {} retr{})",
642 url,
643 retries,
644 if retries == 1 { "y" } else { "ies" }
645 );
646 }
647 schedule_verify(client, url, event, verify);
648 return true;
649 }
650 Err(e) => {
651 let err_str = e.to_string();
652 let lc = err_str.to_ascii_lowercase();
653 let is_rate_limit = lc.contains("rate-limit")
654 || lc.contains("rate limit")
655 || lc.contains("noting too much");
656 let is_transient = lc.contains("timeout")
657 || lc.contains("timed out")
658 || lc.contains("connection reset")
659 || lc.contains("connection refused")
660 || lc.contains("connection closed")
661 || lc.contains("broken pipe")
662 || lc.contains("not connected");
663 let retryable = is_rate_limit || is_transient;
664 if retryable && retries < MAX_RATELIMIT_RETRIES {
665 retries += 1;
666 let reason = if is_rate_limit { "rate-limited" } else { "transient error" };
667 crate::log_warn!(
668 "[delete] relay {} {} (attempt {}/{}; err: {}); waiting {}s",
669 url,
670 reason,
671 retries,
672 MAX_RATELIMIT_RETRIES,
673 err_str,
674 RATELIMIT_BACKOFF.as_secs()
675 );
676 crate::rt::time::sleep(RATELIMIT_BACKOFF).await;
677 continue;
678 }
679 if retryable {
680 crate::log_warn!(
681 "[delete] relay {} still failing after {} retries ({}); scheduling verify probe in case it eventually accepted",
682 url,
683 retries,
684 err_str
685 );
686 schedule_verify(client, url, event, verify);
692 } else {
693 crate::log_warn!("[delete] relay {} rejected NIP-09: {}", url, err_str);
694 }
695 return false;
696 }
697 }
698 }
699}
700
701fn deletion_targets(deletion: &Event) -> Vec<EventId> {
703 deletion
704 .tags
705 .iter()
706 .filter_map(|tag| {
707 let s = tag.as_slice();
708 (s.len() >= 2 && s[0] == "e").then(|| EventId::from_hex(&s[1]).ok()).flatten()
709 })
710 .collect()
711}
712
713fn schedule_verify(client: &Client, url: &RelayUrl, deletion: &Event, verify: bool) {
714 let wraps = deletion_targets(deletion);
715 if !verify || wraps.is_empty() {
716 return;
717 }
718 let (client, url) = (client.clone(), url.clone());
719 crate::db::spawn_bound(async move {
720 verify_relay_dropped(&client, &url, &wraps).await;
721 });
722}
723
724async fn verify_relay_dropped(client: &Client, url: &RelayUrl, wraps: &[EventId]) {
727 crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
728 let Some(relay) = client.relays().await.get(url).cloned() else { return };
729 let filter = Filter::new().ids(wraps.iter().copied());
730 match relay
731 .fetch_events(filter)
732 .timeout(std::time::Duration::from_secs(5))
733 .policy(ReqExitPolicy::ExitOnEOSE)
734 .await
735 {
736 Ok(events) => {
737 let kept = events.len();
738 if kept > 0 {
739 crate::log_warn!("[delete-verify] relay {} STILL HAS {}/{} wrap(s) after acknowledging their deletion", url, kept, wraps.len());
740 } else {
741 crate::log_info!("[delete-verify] relay {} confirmed {} wrap(s) GONE", url, wraps.len());
742 }
743 }
744 Err(e) => crate::log_warn!("[delete-verify] relay {} probe failed: {}", url, e),
745 }
746}
747
748async fn publish_cooperative_hide(
751 client: &Client,
752 target_rumor_id: &EventId,
753 recipient: Option<&PublicKey>,
754 original_kind: u16,
755) -> Result<(), String> {
756 let my_pk = my_public_key().ok_or("Public key not set")?;
757 let now = crate::clock::now_secs();
758 let expiration_ts = now + COOPERATIVE_HIDE_EXPIRY_SECS;
759
760 let rumor = EventBuilder::new(Kind::EventDeletion, "")
765 .tag(Tag::event(*target_rumor_id))
766 .tag(Tag::custom("k", [original_kind.to_string()]))
767 .tag(Tag::expiration(Timestamp::from(expiration_ts)))
768 .finalize_unsigned_with_id(my_pk);
769
770 let expires = || [Tag::expiration(Timestamp::from(expiration_ts))];
773 let to_them = match recipient {
774 Some(recipient) => send_gift_wrap(client, recipient, rumor.clone(), expires()).await.is_ok(),
775 None => false,
776 };
777 let to_me = send_gift_wrap(client, &my_pk, rumor, expires()).await.is_ok();
778 if !to_them && !to_me {
779 return Err("no cooperative-hide delivery went out".to_string());
780 }
781 Ok(())
782}
783
784#[cfg(test)]
785pub(crate) fn pending_received_wrap_deletions() -> Vec<EventId> {
786 received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
787}
788
789#[cfg(test)]
790mod tests {
791 use super::*;
792 use crate::db::nip17_keys::{StoredWrapKey, WrapRole};
793
794 fn stored(role: WrapRole) -> StoredWrapKey {
795 let k = Keys::generate();
796 StoredWrapKey {
797 wrap_event_id: EventBuilder::new(Kind::GiftWrap, "").finalize(&k).unwrap().id,
798 rumor_id: EventId::from_byte_array([0; 32]),
799 recipient_pubkey: Keys::generate().public_key(),
800 role,
801 secret: k.secret_key().clone(),
802 relay_urls: Vec::new(),
803 }
804 }
805
806 #[test]
807 fn a_wrap_deletion_names_its_wraps_and_expires() {
808 let wraps = [EventId::from_byte_array([0; 32]), EventId::from_byte_array([7; 32])];
809 let ev = wrap_deletion(&wraps).finalize(&Keys::generate()).unwrap();
810 assert_eq!(ev.kind, Kind::EventDeletion);
811 let tag = |name: &str| ev.tags.iter().filter(|t| t.as_slice()[0] == name).map(|t| t.as_slice()[1].clone()).collect::<Vec<_>>();
812 assert_eq!(tag("e"), wraps.iter().map(|w| w.to_hex()).collect::<Vec<_>>());
813 assert_eq!(tag("k"), vec!["1059".to_string()]);
814 let expires: u64 = tag("expiration")[0].parse().unwrap();
815 let now = Timestamp::now().as_secs();
816 assert!(expires > now + WRAP_DELETION_EXPIRY_SECS - 60 && expires <= now + WRAP_DELETION_EXPIRY_SECS, "it leaves the relays in time");
817 }
818
819 #[test]
820 fn our_own_key_deletes_the_copies_addressed_to_us() {
821 let (mine, theirs, retry) = (stored(WrapRole::SelfSend), stored(WrapRole::Recipient), stored(WrapRole::Retry));
822 let keys = [mine.clone(), theirs, retry];
823 let received = EventId::from_byte_array([9; 32]);
824 assert_eq!(own_wraps(&keys, Some(received)), vec![mine.wrap_event_id, received], "our self-copy and the wrap that reached us");
825 assert_eq!(own_wraps(&keys, Some(mine.wrap_event_id)), vec![mine.wrap_event_id], "named once");
826 assert_eq!(own_wraps(&keys, None), vec![mine.wrap_event_id]);
827 }
828
829 #[tokio::test]
830 async fn an_owner_deletion_is_signed_by_us_and_never_for_someone_else() {
831 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
832 let me = Keys::generate();
833 crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
834 crate::state::set_my_public_key(me.public_key());
835 let wraps = [EventId::from_byte_array([3; 32])];
836 let deletion = owner_deletion(&wraps, &me.public_key()).await.unwrap();
837 assert_eq!(deletion.pubkey, me.public_key());
838 assert!(deletion.verify().is_ok());
839 assert!(owner_deletion(&wraps, &Keys::generate().public_key()).await.is_err(), "a swapped account signs nothing for the last one");
840 }
841}