use crate::event_ext::FinalizeUnsignedWithId;
use crate::event_ext::FinalizeOnClock;
use nostr_sdk::prelude::*;
use crate::inbox_relays::{get_publish_tracker, resolve_gift_wrap_targets, send_gift_wrap, teardown_gift_wrap_targets};
use crate::state::{my_public_key, nostr_client};
pub(crate) const COOPERATIVE_HIDE_EXPIRY_SECS: u64 = 60 * 60 * 24 * 30;
const WRAP_DELETION_EXPIRY_SECS: u64 = 60 * 60 * 24 * 90;
pub(crate) const WRAPS_PER_DELETION: usize = 100;
#[derive(serde::Serialize, Debug, Clone, Default)]
pub struct DeleteOutcome {
pub wraps_dispatched: usize,
pub wraps_total: usize,
pub cooperative_hide_sent: bool,
pub blobs_dispatched: usize,
pub any_network_action: bool,
}
pub async fn delete_own_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
let client = nostr_client().ok_or("Not logged in")?;
let rumor_hex = rumor_id.to_hex();
if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
}
crate::state::note_message_deleted(&rumor_hex);
let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(rumor_id)
.unwrap_or_default();
let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
let (all_attachments, recipient_from_state) = {
let state = crate::state::STATE.lock().await;
match state.find_message(&rumor_id.to_hex()) {
Some((chat, msg)) => {
debug_assert!(
matches!(chat.chat_type, crate::chat::ChatType::DirectMessage),
"delete_own_dm called on non-DM chat — caller bug"
);
let recipient = nostr_sdk::prelude::PublicKey::from_bech32(&chat.id).ok();
(msg.attachments.clone(), recipient)
}
None => (Vec::new(), None),
}
};
let unique_attachments = filter_unreferenced_attachments(
&rumor_id.to_hex(),
all_attachments,
).await;
delete_cached_attachment_files(&unique_attachments);
let attachment_urls: Vec<String> = scrub_safe_urls(&unique_attachments, &rumor_id.to_hex());
let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
let cooperative_recipient = keys
.iter()
.find(|k| {
k.role == crate::db::nip17_keys::WrapRole::Recipient
|| k.role == crate::db::nip17_keys::WrapRole::Retry
})
.map(|k| k.recipient_pubkey)
.or(recipient_from_state);
let mut cooperative_hide_sent = false;
if let Some(recipient) = cooperative_recipient {
match publish_cooperative_hide(&client, rumor_id, Some(&recipient), 14).await {
Ok(()) => cooperative_hide_sent = true,
Err(e) => crate::log_warn!("[NIP-17 delete] cooperative-hide notice failed: {}", e),
}
}
let mut blobs_dispatched = 0usize;
if !attachment_urls.is_empty() {
if let Ok(signer) = crate::signer::active_signer() {
blobs_dispatched = attachment_urls.len();
crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
}
}
let any_network_action =
wraps_dispatched > 0 || cooperative_hide_sent || blobs_dispatched > 0;
Ok(DeleteOutcome {
wraps_total,
wraps_dispatched,
cooperative_hide_sent,
blobs_dispatched,
any_network_action,
})
}
pub async fn delete_own_reaction(
reaction_id: &EventId,
recipient: PublicKey,
) -> Result<DeleteOutcome, String> {
let client = nostr_client().ok_or("Not logged in")?;
let reaction_hex = reaction_id.to_hex();
if let Err(e) = crate::db::events::add_message_tombstone(&reaction_hex) {
crate::log_warn!("[reaction delete] tombstone write failed: {}", e);
}
crate::state::note_message_deleted(&reaction_hex);
let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(reaction_id)
.unwrap_or_default();
let received = crate::db::events::wrapper_event_id_of(&reaction_hex);
let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
let cooperative_recipient = keys
.iter()
.find(|k| {
k.role == crate::db::nip17_keys::WrapRole::Recipient
|| k.role == crate::db::nip17_keys::WrapRole::Retry
})
.map(|k| k.recipient_pubkey)
.unwrap_or(recipient);
let mut cooperative_hide_sent = false;
match publish_cooperative_hide(&client, reaction_id, Some(&cooperative_recipient), 7).await {
Ok(()) => cooperative_hide_sent = true,
Err(e) => crate::log_warn!("[reaction delete] cooperative-hide failed: {}", e),
}
let any_network_action = wraps_dispatched > 0 || cooperative_hide_sent;
Ok(DeleteOutcome {
wraps_total,
wraps_dispatched,
cooperative_hide_sent,
blobs_dispatched: 0,
any_network_action,
})
}
pub async fn delete_received_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
let client = nostr_client().ok_or("Not logged in")?;
let rumor_hex = rumor_id.to_hex();
if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
}
crate::state::note_message_deleted(&rumor_hex);
let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
let attachments = {
let state = crate::state::STATE.lock().await;
state.find_message(&rumor_hex).map(|(_, msg)| msg.attachments.clone()).unwrap_or_default()
};
delete_cached_attachment_files(&filter_unreferenced_attachments(&rumor_hex, attachments).await);
let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &[], received).await;
let cooperative_hide_sent = match publish_cooperative_hide(&client, rumor_id, None, 14).await {
Ok(()) => true,
Err(e) => {
crate::log_warn!("[NIP-17 delete] hide request to our devices failed: {}", e);
false
}
};
Ok(DeleteOutcome {
wraps_total,
wraps_dispatched,
cooperative_hide_sent,
blobs_dispatched: 0,
any_network_action: wraps_dispatched > 0 || cooperative_hide_sent,
})
}
pub(crate) fn wrap_deletion(wrap_ids: &[EventId]) -> EventBuilder {
let expires = crate::clock::timestamp().as_secs().saturating_add(WRAP_DELETION_EXPIRY_SECS);
wrap_ids
.iter()
.fold(EventBuilder::new(Kind::EventDeletion, ""), |b, id| b.tag(Tag::event(*id)))
.tag(Tag::custom("k", ["1059"]))
.tag(Tag::expiration(Timestamp::from(expires)))
}
async fn owner_deletion(wrap_ids: &[EventId], owner: &PublicKey) -> Result<Event, String> {
let deletion = crate::sign_builder(wrap_deletion(wrap_ids)).await?;
if deletion.pubkey != *owner {
return Err("the account changed before the deletion was signed".to_string());
}
Ok(deletion)
}
async fn dispatch_wrap_deletions(
client: &Client,
keys: &[crate::db::nip17_keys::StoredWrapKey],
received: Option<EventId>,
) -> (usize, usize) {
let Some(me) = my_public_key() else { return (0, keys.len()) };
let own = own_wraps(keys, received);
let known = own.len() + keys.iter().filter(|k| !own.contains(&k.wrap_event_id)).count();
let mut dispatched = 0usize;
for wrap_id in own {
match owner_deletion(&[wrap_id], &me).await {
Ok(deletion) => {
let client = client.clone();
crate::db::spawn_bound(async move {
delete_wrap_per_relay(&client, wrap_id, &deletion, &me, true).await;
});
dispatched += 1;
}
Err(e) => crate::log_warn!("[NIP-17 delete] our own copy {} stays: {}", wrap_id.to_hex(), e),
}
}
for stored in keys {
let deletion = match wrap_deletion(&[stored.wrap_event_id]).finalize_on_clock(&Keys::new(stored.secret.clone())) {
Ok(ev) => ev,
Err(e) => {
crate::log_warn!("[NIP-17 delete] failed to sign deletion for wrap {}: {}", stored.wrap_event_id.to_hex(), e);
continue;
}
};
let (client, wrap_id, owner) = (client.clone(), stored.wrap_event_id, stored.recipient_pubkey);
crate::db::spawn_bound(async move {
delete_wrap_per_relay(&client, wrap_id, &deletion, &owner, false).await;
});
dispatched += 1;
}
let wraps: Vec<EventId> = keys.iter().map(|k| k.wrap_event_id).collect();
if let Err(e) = crate::db::nip17_keys::purge_wrap_keys(&wraps) {
crate::log_warn!("[NIP-17 delete] failed to purge wrap keys: {}", e);
}
(dispatched, known)
}
fn own_wraps(keys: &[crate::db::nip17_keys::StoredWrapKey], received: Option<EventId>) -> Vec<EventId> {
use crate::db::nip17_keys::WrapRole;
let mut own: Vec<EventId> = keys.iter().filter(|k| k.role == WrapRole::SelfSend).map(|k| k.wrap_event_id).collect();
if let Some(w) = received.filter(|w| !own.contains(w)) {
own.push(w);
}
own
}
struct ReceivedWrapDeletions;
fn received_wrap_deletions() -> std::sync::Arc<std::sync::Mutex<Vec<EventId>>> {
crate::db::current_session().scoped::<ReceivedWrapDeletions, _>()
}
#[cfg(test)]
pub(crate) fn queued_received_wrap_deletions() -> Vec<EventId> {
received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub(crate) fn delete_received_wrap(wrap_id: EventId) {
let pending = received_wrap_deletions();
let first = {
let mut q = pending.lock().unwrap_or_else(|e| e.into_inner());
if q.contains(&wrap_id) {
return;
}
q.push(wrap_id);
q.len() == 1
};
if !first {
return;
}
crate::db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
let wraps = std::mem::take(&mut *pending.lock().unwrap_or_else(|e| e.into_inner()));
let (Some(client), Some(me)) = (nostr_client(), my_public_key()) else { return };
for batch in wraps.chunks(WRAPS_PER_DELETION) {
match owner_deletion(batch, &me).await {
Ok(deletion) => publish_to_inbox(&client, &me, &deletion, true).await,
Err(e) => crate::log_warn!("[NIP-17 delete] {} received wrap(s) stay: {}", batch.len(), e),
}
}
});
}
async fn delete_wrap_per_relay(client: &Client, wrap_event_id: EventId, deletion: &Event, owner: &PublicKey, verify: bool) {
let Some(tracker) = get_publish_tracker(&wrap_event_id) else {
publish_to_inbox(client, owner, deletion, verify).await;
return;
};
let mut delivered = 0usize;
let mut cursor = 0usize;
while let Some(url) = tracker.next_success(&mut cursor).await {
let relay = client.relays().await.get(&url).cloned();
match relay {
Some(relay) if send_to_one_relay(client, &url, &relay, deletion, verify).await => delivered += 1,
Some(_) => {}
None => crate::log_warn!("[delete] relay {} not in pool — deletion not delivered", url),
}
}
crate::log_info!("[NIP-17 delete] wrap {} — deletion delivered to {} relay(s) via tracker", wrap_event_id.to_hex(), delivered);
}
async fn publish_to_inbox(client: &Client, owner: &PublicKey, deletion: &Event, verify: bool) {
let targets = resolve_gift_wrap_targets(client, owner).await;
let total = targets.resolved.len();
let mut delivered = 0usize;
for (url, relay) in &targets.resolved {
if send_to_one_relay(client, url, relay, deletion, verify).await {
delivered += 1;
}
}
teardown_gift_wrap_targets(client, &targets).await;
crate::log_info!("[NIP-17 delete] deletion {} delivered to {}/{} inbox relay(s)", deletion.id.to_hex(), delivered, total);
}
pub fn delete_cached_attachment_files_pub(attachments: &[crate::types::Attachment]) {
delete_cached_attachment_files(attachments);
}
pub async fn filter_unreferenced_attachments(
excluding_message_id: &str,
attachments: Vec<crate::types::Attachment>,
) -> Vec<crate::types::Attachment> {
if attachments.is_empty() {
return attachments;
}
let state_referenced: Vec<bool> = {
let state = crate::state::STATE.lock().await;
attachments
.iter()
.map(|att| {
let hash = &*att.id;
if hash.is_empty() {
return false;
}
state.chats.iter().any(|chat| {
chat.iter_compact().any(|m| {
let msg_id_hex = m.id_hex();
msg_id_hex != excluding_message_id
&& m.attachments.iter().any(|a| a.id_eq(hash))
})
})
})
.collect()
};
attachments
.into_iter()
.zip(state_referenced)
.filter(|(att, in_state)| {
if *in_state {
return false;
}
let hash = &*att.id;
if hash.is_empty() {
return true;
}
!crate::db::attachments::hash_referenced_elsewhere(hash, excluding_message_id).unwrap_or(true)
})
.map(|(att, _)| att)
.collect()
}
pub fn scrub_safe_urls(attachments: &[crate::types::Attachment], excluding_event_id: &str) -> Vec<String> {
let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
if urls.is_empty() {
return urls;
}
crate::db::attachments::urls_unreferenced_elsewhere(&urls, excluding_event_id).unwrap_or_default()
}
fn delete_cached_attachment_files(attachments: &[crate::types::Attachment]) {
if attachments.is_empty() {
return;
}
let hashes: Vec<[u8; 32]> = attachments.iter().filter_map(|a| crate::simd::hex::hex_to_bytes_32_checked(&a.id)).collect();
for hash in &hashes {
crate::media::pending::forget(hash);
#[cfg(not(target_arch = "wasm32"))]
crate::media::store::forget(hash);
#[cfg(target_arch = "wasm32")]
{
let hash = *hash;
crate::media::store::stop_holding(&hash);
crate::db::spawn_bound(async move { crate::media::store::forget(&hash).await });
}
}
#[cfg(target_arch = "wasm32")]
{
let dir = crate::db::get_download_dir();
let paths: Vec<std::path::PathBuf> = attachments
.iter()
.map(|a| std::path::PathBuf::from(&*a.path))
.filter(|p| p.starts_with(&dir) && !p.components().any(|c| c == std::path::Component::ParentDir))
.collect();
crate::db::spawn_bound(async move {
for p in paths {
crate::webfiles::remove(&p).await;
}
});
}
#[cfg(not(target_arch = "wasm32"))]
delete_cached_attachment_files_native(attachments);
let ram = crate::media::ram::cache();
for hash in &hashes {
ram.remove(hash);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn delete_cached_attachment_files_native(attachments: &[crate::types::Attachment]) {
let roots: Vec<std::path::PathBuf> = crate::db::download_roots().iter().filter_map(|r| r.canonicalize().ok()).collect();
if roots.is_empty() {
return;
}
for att in attachments {
if att.path.is_empty() {
continue;
}
let candidate = match std::path::PathBuf::from(&*att.path).canonicalize() {
Ok(p) => p,
Err(_) => continue,
};
if !roots.iter().any(|root| candidate.starts_with(root)) {
continue;
}
if crate::db::saved::is_saved(&candidate.to_string_lossy()).unwrap_or(true) {
continue;
}
if let Err(e) = std::fs::remove_file(&candidate) {
crate::log_warn!(
"[delete] failed to remove cached attachment {}: {}",
candidate.display(),
e
);
}
}
}
async fn send_to_one_relay(client: &Client, url: &RelayUrl, relay: &Relay, event: &Event, verify: bool) -> bool {
const MAX_RATELIMIT_RETRIES: u32 = 20;
const RATELIMIT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);
let mut retries = 0u32;
let wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
loop {
match relay.send_event(event).ok_timeout(wait).authentication_timeout(wait).await {
Ok(_) => {
if retries == 0 {
crate::log_info!("[delete] relay {} ACK'd NIP-09", url);
} else {
crate::log_info!(
"[delete] relay {} ACK'd NIP-09 (after {} retr{})",
url,
retries,
if retries == 1 { "y" } else { "ies" }
);
}
schedule_verify(client, url, event, verify);
return true;
}
Err(e) => {
let err_str = e.to_string();
let lc = err_str.to_ascii_lowercase();
let is_rate_limit = lc.contains("rate-limit")
|| lc.contains("rate limit")
|| lc.contains("noting too much");
let is_transient = lc.contains("timeout")
|| lc.contains("timed out")
|| lc.contains("connection reset")
|| lc.contains("connection refused")
|| lc.contains("connection closed")
|| lc.contains("broken pipe")
|| lc.contains("not connected");
let retryable = is_rate_limit || is_transient;
if retryable && retries < MAX_RATELIMIT_RETRIES {
retries += 1;
let reason = if is_rate_limit { "rate-limited" } else { "transient error" };
crate::log_warn!(
"[delete] relay {} {} (attempt {}/{}; err: {}); waiting {}s",
url,
reason,
retries,
MAX_RATELIMIT_RETRIES,
err_str,
RATELIMIT_BACKOFF.as_secs()
);
crate::rt::time::sleep(RATELIMIT_BACKOFF).await;
continue;
}
if retryable {
crate::log_warn!(
"[delete] relay {} still failing after {} retries ({}); scheduling verify probe in case it eventually accepted",
url,
retries,
err_str
);
schedule_verify(client, url, event, verify);
} else {
crate::log_warn!("[delete] relay {} rejected NIP-09: {}", url, err_str);
}
return false;
}
}
}
}
fn deletion_targets(deletion: &Event) -> Vec<EventId> {
deletion
.tags
.iter()
.filter_map(|tag| {
let s = tag.as_slice();
(s.len() >= 2 && s[0] == "e").then(|| EventId::from_hex(&s[1]).ok()).flatten()
})
.collect()
}
fn schedule_verify(client: &Client, url: &RelayUrl, deletion: &Event, verify: bool) {
let wraps = deletion_targets(deletion);
if !verify || wraps.is_empty() {
return;
}
let (client, url) = (client.clone(), url.clone());
crate::db::spawn_bound(async move {
verify_relay_dropped(&client, &url, &wraps).await;
});
}
async fn verify_relay_dropped(client: &Client, url: &RelayUrl, wraps: &[EventId]) {
crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
let Some(relay) = client.relays().await.get(url).cloned() else { return };
let filter = Filter::new().ids(wraps.iter().copied());
match relay
.fetch_events(filter)
.timeout(std::time::Duration::from_secs(5))
.policy(ReqExitPolicy::ExitOnEOSE)
.await
{
Ok(events) => {
let kept = events.len();
if kept > 0 {
crate::log_warn!("[delete-verify] relay {} STILL HAS {}/{} wrap(s) after acknowledging their deletion", url, kept, wraps.len());
} else {
crate::log_info!("[delete-verify] relay {} confirmed {} wrap(s) GONE", url, wraps.len());
}
}
Err(e) => crate::log_warn!("[delete-verify] relay {} probe failed: {}", url, e),
}
}
async fn publish_cooperative_hide(
client: &Client,
target_rumor_id: &EventId,
recipient: Option<&PublicKey>,
original_kind: u16,
) -> Result<(), String> {
let my_pk = my_public_key().ok_or("Public key not set")?;
let now = crate::clock::now_secs();
let expiration_ts = now + COOPERATIVE_HIDE_EXPIRY_SECS;
let rumor = EventBuilder::new(Kind::EventDeletion, "")
.tag(Tag::event(*target_rumor_id))
.tag(Tag::custom("k", [original_kind.to_string()]))
.tag(Tag::expiration(Timestamp::from(expiration_ts)))
.finalize_unsigned_with_id(my_pk);
let expires = || [Tag::expiration(Timestamp::from(expiration_ts))];
let to_them = match recipient {
Some(recipient) => send_gift_wrap(client, recipient, rumor.clone(), expires()).await.is_ok(),
None => false,
};
let to_me = send_gift_wrap(client, &my_pk, rumor, expires()).await.is_ok();
if !to_them && !to_me {
return Err("no cooperative-hide delivery went out".to_string());
}
Ok(())
}
#[cfg(test)]
pub(crate) fn pending_received_wrap_deletions() -> Vec<EventId> {
received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::nip17_keys::{StoredWrapKey, WrapRole};
fn stored(role: WrapRole) -> StoredWrapKey {
let k = Keys::generate();
StoredWrapKey {
wrap_event_id: EventBuilder::new(Kind::GiftWrap, "").finalize(&k).unwrap().id,
rumor_id: EventId::from_byte_array([0; 32]),
recipient_pubkey: Keys::generate().public_key(),
role,
secret: k.secret_key().clone(),
relay_urls: Vec::new(),
}
}
#[test]
fn a_wrap_deletion_names_its_wraps_and_expires() {
let wraps = [EventId::from_byte_array([0; 32]), EventId::from_byte_array([7; 32])];
let ev = wrap_deletion(&wraps).finalize(&Keys::generate()).unwrap();
assert_eq!(ev.kind, Kind::EventDeletion);
let tag = |name: &str| ev.tags.iter().filter(|t| t.as_slice()[0] == name).map(|t| t.as_slice()[1].clone()).collect::<Vec<_>>();
assert_eq!(tag("e"), wraps.iter().map(|w| w.to_hex()).collect::<Vec<_>>());
assert_eq!(tag("k"), vec!["1059".to_string()]);
let expires: u64 = tag("expiration")[0].parse().unwrap();
let now = Timestamp::now().as_secs();
assert!(expires > now + WRAP_DELETION_EXPIRY_SECS - 60 && expires <= now + WRAP_DELETION_EXPIRY_SECS, "it leaves the relays in time");
}
#[test]
fn our_own_key_deletes_the_copies_addressed_to_us() {
let (mine, theirs, retry) = (stored(WrapRole::SelfSend), stored(WrapRole::Recipient), stored(WrapRole::Retry));
let keys = [mine.clone(), theirs, retry];
let received = EventId::from_byte_array([9; 32]);
assert_eq!(own_wraps(&keys, Some(received)), vec![mine.wrap_event_id, received], "our self-copy and the wrap that reached us");
assert_eq!(own_wraps(&keys, Some(mine.wrap_event_id)), vec![mine.wrap_event_id], "named once");
assert_eq!(own_wraps(&keys, None), vec![mine.wrap_event_id]);
}
#[tokio::test]
async fn an_owner_deletion_is_signed_by_us_and_never_for_someone_else() {
let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let wraps = [EventId::from_byte_array([3; 32])];
let deletion = owner_deletion(&wraps, &me.public_key()).await.unwrap();
assert_eq!(deletion.pubkey, me.public_key());
assert!(deletion.verify().is_ok());
assert!(owner_deletion(&wraps, &Keys::generate().public_key()).await.is_err(), "a swapped account signs nothing for the last one");
}
}