Skip to main content

vector_core/
blossom.rs

1use crate::signer::VectorSigner;
2use crate::blossom_error::{host_of, summarise_failures, Refusal, UploadFailure};
3use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEventAsync, Kind, Tag, Timestamp, Url};
4use bitcoin_hashes::sha256::Hash as Sha256Hash;
5use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE};
6use reqwest::{Body, StatusCode};
7use std::str::FromStr;
8use std::sync::{Arc, Mutex};
9use std::sync::atomic::{AtomicBool, Ordering};
10use futures_util::Stream;
11use std::pin::Pin;
12use std::task::{Context, Poll};
13
14/// Progress callback function type
15pub type ProgressCallback = std::sync::Arc<dyn Fn(Option<u8>, Option<u64>) -> Result<(), String> + Send + Sync>;
16
17/// The upload body: slices of the one ciphertext buffer, counted as the socket pulls
18/// them. A slice shares the buffer, so nothing is copied on the way out.
19#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
20struct ProgressTrackingStream {
21    data: bytes::Bytes,
22    position: usize,
23    bytes_sent: Arc<Mutex<u64>>,
24}
25
26/// Lends an `Arc`'d buffer to `Bytes` without copying it.
27#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
28struct SharedBuffer(Arc<Vec<u8>>);
29
30impl AsRef<[u8]> for SharedBuffer {
31    fn as_ref(&self) -> &[u8] {
32        &self.0
33    }
34}
35
36#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
37impl ProgressTrackingStream {
38    /// Progress is observed per slice pulled, so the slice is the slowest rate that
39    /// still reads as progress: 16 KB in a 60 s stall window is about 2 kbit/s.
40    const SLICE: usize = 16 * 1024;
41
42    fn new(data: Arc<Vec<u8>>, bytes_sent: Arc<Mutex<u64>>) -> Self {
43        Self { data: bytes::Bytes::from_owner(SharedBuffer(data)), position: 0, bytes_sent }
44    }
45}
46
47impl Stream for ProgressTrackingStream {
48    type Item = Result<bytes::Bytes, std::io::Error>;
49
50    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
51        if self.position >= self.data.len() {
52            return Poll::Ready(None);
53        }
54        let end = (self.position + Self::SLICE).min(self.data.len());
55        let slice = self.data.slice(self.position..end);
56        self.position = end;
57        *self.bytes_sent.lock().unwrap() += slice.len() as u64;
58        Poll::Ready(Some(Ok(slice)))
59    }
60}
61
62/// What an upload sends: bytes in hand, or a file read from disk as the socket
63/// takes it, so a blob of any size costs one slice of memory.
64#[derive(Clone)]
65pub enum UploadBody {
66    Memory(Arc<Vec<u8>>),
67    /// A file whose length and SHA-256 are already known: the auth event and the
68    /// preflight need the hash before the first byte goes.
69    File { path: std::path::PathBuf, len: u64, sha256: Sha256Hash },
70}
71
72impl UploadBody {
73    /// A file body from its path, length and hex SHA-256.
74    pub fn file(path: std::path::PathBuf, len: u64, sha256_hex: &str) -> Result<Self, String> {
75        let sha256 = Sha256Hash::from_str(sha256_hex).map_err(|e| format!("bad blob hash: {e}"))?;
76        Ok(Self::File { path, len, sha256 })
77    }
78
79    pub fn len(&self) -> u64 {
80        match self {
81            Self::Memory(data) => data.len() as u64,
82            Self::File { len, .. } => *len,
83        }
84    }
85
86    pub fn is_empty(&self) -> bool {
87        self.len() == 0
88    }
89
90    fn sha256(&self) -> Sha256Hash {
91        match self {
92            Self::Memory(data) => Sha256Hash::hash(data),
93            Self::File { sha256, .. } => *sha256,
94        }
95    }
96
97    /// The body as a stream, counting into `bytes_sent` as slices are pulled.
98    #[cfg(not(target_arch = "wasm32"))]
99    fn stream(&self, bytes_sent: Arc<Mutex<u64>>) -> Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Send>> {
100        match self {
101            Self::Memory(data) => Box::pin(ProgressTrackingStream::new(Arc::clone(data), bytes_sent)),
102            Self::File { path, len, .. } => {
103                // Large: every read is a trip to the blocking pool, and each slice is handed
104                // to the body whole, so fewer, bigger ones (about a thousand per GB).
105                const FILE_SLICE: u64 = 1024 * 1024;
106                let start = (None::<tokio::fs::File>, path.clone(), *len);
107                Box::pin(futures_util::stream::unfold(start, move |(file, path, remaining)| {
108                    let bytes_sent = Arc::clone(&bytes_sent);
109                    async move {
110                        use tokio::io::AsyncReadExt;
111                        if remaining == 0 {
112                            return None;
113                        }
114                        let mut file = match file {
115                            Some(f) => f,
116                            None => match tokio::fs::File::open(&path).await {
117                                Ok(f) => f,
118                                Err(e) => return Some((Err(e), (None, path, 0))),
119                            },
120                        };
121                        let mut slice = vec![0u8; remaining.min(FILE_SLICE) as usize];
122                        match file.read_exact(&mut slice).await {
123                            Ok(_) => {
124                                *bytes_sent.lock().unwrap() += slice.len() as u64;
125                                let left = remaining - slice.len() as u64;
126                                Some((Ok(bytes::Bytes::from(slice)), (Some(file), path, left)))
127                            }
128                            Err(e) => Some((Err(e), (None, path, 0))),
129                        }
130                    }
131                }))
132            }
133        }
134    }
135}
136
137/// After the last byte is handed to the socket there is nothing left to watch:
138/// what remains is buffered bytes draining, an ingress relay forwarding the
139/// blob to its origin, and the origin storing it — none of which is visible
140/// from here. This bounds that wait.
141///
142/// Five minutes because the relay hop is real work: a gigabyte across a
143/// datacenter backhaul at the ~6 MB/s a single stream manages is nearly three
144/// of them, and giving up then would discard an upload that had in fact
145/// arrived.
146const RESPONSE_WAIT: std::time::Duration = std::time::Duration::from_secs(300);
147
148/// Why an upload was abandoned.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150enum Stall {
151    /// The socket accepted nothing for the whole stall window.
152    NoProgress { idle: std::time::Duration },
153    /// Every byte was handed over and the server never answered.
154    NoResponse { waited: std::time::Duration },
155}
156
157/// Progress-based watchdog for an upload: gives up on a transfer that stops
158/// moving, never on one that is merely slow.
159struct StallWatch {
160    total: u64,
161    last_bytes: u64,
162    last_progress: crate::rt::time::Instant,
163    stall_limit: std::time::Duration,
164    response_limit: std::time::Duration,
165}
166
167impl StallWatch {
168    fn new(total: u64, stall_limit: std::time::Duration, response_limit: std::time::Duration) -> Self {
169        Self {
170            total,
171            last_bytes: 0,
172            last_progress: crate::rt::time::Instant::now(),
173            stall_limit,
174            response_limit,
175        }
176    }
177
178    /// Feed the latest byte count; `Some` means give up.
179    fn observe(&mut self, bytes_sent: u64) -> Option<Stall> {
180        let now = crate::rt::time::Instant::now();
181        if bytes_sent > self.last_bytes {
182            self.last_bytes = bytes_sent;
183            self.last_progress = now;
184            return None;
185        }
186        let idle = now.duration_since(self.last_progress);
187        if bytes_sent >= self.total {
188            (idle > self.response_limit).then_some(Stall::NoResponse { waited: idle })
189        } else {
190            (idle > self.stall_limit).then_some(Stall::NoProgress { idle })
191        }
192    }
193}
194
195/// A progress callback's refusal, as an upload failure: it says "Upload
196/// cancelled" when the user pressed stop, and that must stay a cancellation
197/// rather than an error.
198fn callback_failure(e: String) -> UploadFailure {
199    if e == "Upload cancelled" {
200        UploadFailure::Cancelled
201    } else {
202        UploadFailure::Other(e)
203    }
204}
205
206/// Send `body` as the body of `request`, watching progress rather than
207/// the clock.
208///
209/// There is no total time limit. A transfer moving at any rate runs to
210/// completion; one that stops for `stall_limit` is abandoned, as is one whose
211/// server goes silent after receiving everything.
212async fn send_upload(
213    client: &crate::net::HttpClient,
214    request: crate::net::Req,
215    server_url: &Url,
216    body: &UploadBody,
217    stall_limit: std::time::Duration,
218    cancel_flag: Option<&Arc<AtomicBool>>,
219    progress_callback: Option<&ProgressCallback>,
220) -> Result<crate::net::Resp, UploadFailure> {
221    let total_size = body.len();
222    let bytes_sent = Arc::new(Mutex::new(0u64));
223    #[cfg(not(target_arch = "wasm32"))]
224    let request_body = Body::wrap_stream(crate::net::guard_body(
225        body.stream(Arc::clone(&bytes_sent)),
226        crate::transport::epoch(),
227        client.owner(),
228    ));
229    #[cfg(target_arch = "wasm32")]
230    let _ = client;
231    // fetch cannot stream a request body, so the web sends it whole.
232    #[cfg(target_arch = "wasm32")]
233    let request_body = match body {
234        UploadBody::Memory(data) => {
235            *bytes_sent.lock().unwrap() = data.len() as u64;
236            Body::from(data.as_ref().clone())
237        }
238        UploadBody::File { .. } => return Err(UploadFailure::Transport("no filesystem on the web".into())),
239    };
240    let mut request_future = Box::pin(request.body(request_body).send());
241
242    // fetch reports no upload progress, so the whole transfer happens inside the
243    // response wait: give it room for the body at a slow 64 KB/s.
244    #[cfg(target_arch = "wasm32")]
245    let response_wait = RESPONSE_WAIT + std::time::Duration::from_secs(total_size / (64 * 1024));
246    #[cfg(not(target_arch = "wasm32"))]
247    let response_wait = RESPONSE_WAIT;
248    let mut watch = StallWatch::new(total_size, stall_limit, response_wait);
249    let mut last_percentage = 0;
250    let mut poll_interval = crate::rt::time::interval(crate::rt::time::Duration::from_millis(100));
251
252    let response = loop {
253        tokio::select! {
254            response = &mut request_future => {
255                break response.map_err(upload_failure)?;
256            },
257            _ = poll_interval.tick() => {
258                if let Some(flag) = cancel_flag {
259                    if flag.load(Ordering::Relaxed) {
260                        return Err(UploadFailure::Cancelled);
261                    }
262                }
263
264                let current_bytes = *bytes_sent.lock().unwrap();
265                match watch.observe(current_bytes) {
266                    Some(Stall::NoProgress { idle }) => {
267                        return Err(UploadFailure::Transport(format!(
268                            "Upload stalled: {} accepted nothing for {}s ({} of {} bytes sent)",
269                            server_url, idle.as_secs(), current_bytes, total_size,
270                        )));
271                    }
272                    Some(Stall::NoResponse { waited }) => {
273                        return Err(UploadFailure::Transport(format!(
274                            "Upload stalled: {} received all {} bytes but gave no answer in {}s",
275                            server_url, total_size, waited.as_secs(),
276                        )));
277                    }
278                    None => {}
279                }
280
281                if let Some(cb) = progress_callback {
282                    let percentage = if total_size > 0 {
283                        ((current_bytes as f64 / total_size as f64) * 100.0) as u8
284                    } else {
285                        0
286                    };
287                    if percentage != last_percentage {
288                        cb(Some(percentage), Some(current_bytes)).map_err(callback_failure)?;
289                        last_percentage = percentage;
290                    }
291                }
292            }
293        }
294    };
295
296    if let Some(cb) = progress_callback {
297        let final_bytes = *bytes_sent.lock().unwrap();
298        if final_bytes == total_size && last_percentage < 100 {
299            cb(Some(100), Some(total_size)).map_err(callback_failure)?;
300        }
301    }
302    Ok(response)
303}
304
305/// How many network changes one upload waits out, as the download paths do.
306const MAX_NETWORK_WAITS: u32 = 8;
307
308/// An HTTP failure as an upload failure: a network switch or a network still connecting waits
309/// and resumes, a transport policy refusal is final for this server.
310fn upload_failure(e: crate::net::HttpError) -> UploadFailure {
311    if e.is_transient() {
312        UploadFailure::Network(e.to_string())
313    } else if matches!(e, crate::net::HttpError::Refused(_)) {
314        // Refused before any byte left: a policy, a replaced session, or a block only the user
315        // can lift. No retry here changes it.
316        UploadFailure::Other(e.to_string())
317    } else {
318        UploadFailure::Transport(format!("Upload request failed: {}", e))
319    }
320}
321
322/// What a BUD-01 authorization covers: named blobs, or a whole server.
323pub(crate) enum AuthScope<'a> {
324    Blob(Sha256Hash),
325    Server(&'a Url),
326}
327
328fn auth_event(verb: &str, scope: AuthScope<'_>, content: &str, expiration: Timestamp) -> EventBuilder {
329    let scope = match scope {
330        AuthScope::Blob(hash) => Tag::custom("x", [hash.to_string()]),
331        AuthScope::Server(url) => Tag::custom("server", [url.to_string()]),
332    };
333    EventBuilder::new(Kind::BlossomAuth, content)
334        .tags([scope, Tag::expiration(expiration), Tag::hashtag(verb)])
335        .custom_created_at(crate::clock::timestamp())
336}
337
338/// A signed BUD-01 `Authorization: Nostr <base64 kind 24242>` header for `verb`, valid for `ttl`.
339pub(crate) async fn auth_header<T>(
340    signer: &T,
341    verb: &str,
342    scope: AuthScope<'_>,
343    content: &str,
344    ttl: std::time::Duration,
345) -> Result<HeaderValue, String>
346where
347    T: VectorSigner,
348{
349    let event: Event = auth_event(verb, scope, content, crate::clock::timestamp() + ttl)
350        .finalize_async(signer)
351        .await
352        .map_err(|e| format!("Failed to sign auth event: {}", e))?;
353    let encoded = crate::simd::base64::STANDARD.encode_to_string(event.as_json());
354    HeaderValue::try_from(format!("Nostr {}", encoded))
355        .map_err(|e| format!("Failed to create header value: {}", e))
356}
357
358async fn build_auth_header<T>(signer: &T, hash: Sha256Hash) -> Result<HeaderValue, String>
359where
360    T: VectorSigner,
361{
362    let ttl = std::time::Duration::from_secs(300);
363    auth_header(signer, "upload", AuthScope::Blob(hash), "Blossom upload authorization", ttl).await
364}
365
366/// The server's reply to an upload or mirror (BUD-02); only the fields Vector checks.
367#[derive(serde::Deserialize)]
368struct BlobDescriptor {
369    #[serde(deserialize_with = "from_str")]
370    url: Url,
371    #[serde(deserialize_with = "from_str")]
372    sha256: Sha256Hash,
373}
374
375fn from_str<'de, D, T>(d: D) -> Result<T, D::Error>
376where
377    D: serde::Deserializer<'de>,
378    T: FromStr,
379    T::Err: std::fmt::Display,
380{
381    let s: String = serde::Deserialize::deserialize(d)?;
382    s.parse().map_err(serde::de::Error::custom)
383}
384
385/// Upload to a single Blossom server with progress callbacks.
386/// `retry_count` defaults to 0; `retry_spacing` defaults to 1s.
387#[allow(clippy::too_many_arguments)]
388pub async fn upload_blob_with_progress<T>(
389    signer: T,
390    server_url: &Url,
391    file_data: Arc<Vec<u8>>,
392    mime_type: Option<&str>,
393    progress_callback: ProgressCallback,
394    retry_count: Option<u32>,
395    retry_spacing: Option<std::time::Duration>,
396    cancel_flag: Option<Arc<AtomicBool>>,
397) -> Result<String, UploadFailure>
398where
399    T: VectorSigner + Clone,
400{
401    upload_with_retries(signer, server_url, UploadBody::Memory(file_data), mime_type, progress_callback, retry_count, retry_spacing, cancel_flag, true).await
402}
403
404/// [`upload_blob_with_progress`], with the BUD-06 preflight optional: a caller that
405/// already knows the server takes this blob spares the round trip.
406#[allow(clippy::too_many_arguments)]
407async fn upload_with_retries<T>(
408    signer: T,
409    server_url: &Url,
410    body: UploadBody,
411    mime_type: Option<&str>,
412    progress_callback: ProgressCallback,
413    retry_count: Option<u32>,
414    retry_spacing: Option<std::time::Duration>,
415    cancel_flag: Option<Arc<AtomicBool>>,
416    preflight_first: bool,
417) -> Result<String, UploadFailure>
418where
419    T: VectorSigner + Clone,
420{
421    let retry_count = retry_count.unwrap_or(0);
422    let retry_spacing = retry_spacing.unwrap_or(std::time::Duration::from_secs(1));
423
424    let mut last_error = None;
425    let mut next_delay = retry_spacing;
426
427    let mut attempt = 0;
428    // A network that keeps flapping must not hold the upload forever.
429    let mut network_waits = 0u32;
430    while attempt <= retry_count {
431        if attempt > 0 {
432            crate::rt::time::sleep(next_delay).await;
433            next_delay = retry_spacing;
434        }
435
436        if let Some(ref flag) = cancel_flag {
437            if flag.load(Ordering::Relaxed) {
438                return Err(UploadFailure::Cancelled);
439            }
440        }
441
442        match upload_attempt(
443            signer.clone(),
444            server_url,
445            body.clone(),
446            mime_type,
447            &progress_callback,
448            cancel_flag.clone(),
449            preflight_first,
450        ).await {
451            Ok(url) => return Ok(url),
452            Err(UploadFailure::Cancelled) => return Err(UploadFailure::Cancelled),
453            // The network changed or is still connecting: hold for it, then resume without
454            // spending an attempt.
455            Err(UploadFailure::Network(e)) => {
456                if network_waits >= MAX_NETWORK_WAITS || !crate::db::session_is_live() {
457                    return Err(UploadFailure::Network(e));
458                }
459                network_waits += 1;
460                let budget = crate::transport::budget(crate::transport::Op::Startup, std::time::Duration::ZERO);
461                if let Err(t) = crate::transport::wait_ready(budget).await {
462                    return Err(UploadFailure::Network(t));
463                }
464                crate::log_info!("[Blossom] {} resumes after a network change: {}", server_url, e);
465                continue;
466            }
467            Err(e) => {
468                crate::log_warn!(
469                    "[Blossom] Attempt {}/{} to {} failed: {}",
470                    attempt + 1, retry_count + 1, server_url, e,
471                );
472                let again = match &e {
473                    // The server said what it meant; believe it. A coded
474                    // `later` names how long, and a plain server is retried
475                    // unless its status is one that never changes.
476                    UploadFailure::Refused(r) => r.worth_retrying_here(),
477                    // On large uploads, mid-stream drops are almost always a
478                    // size policy; don't burn retries. Below 8MB, treat as a
479                    // genuine transient blip and retry.
480                    UploadFailure::Transport(_) => {
481                        !(e.is_mid_stream_drop() && body.len() > 8 * 1024 * 1024)
482                    }
483                    UploadFailure::Integrity(_) | UploadFailure::Other(_) | UploadFailure::Cancelled | UploadFailure::Network(_) => false,
484                };
485                if !again {
486                    if let Some(r) = e.refusal() {
487                        if crate::blossom_error::is_gateway_status(r.status) && r.code().is_none() {
488                            crate::log_warn!(
489                                "[Blossom] {} origin unreachable (status {}) on {} bytes; routing to the next server",
490                                server_url, r.status, body.len(),
491                            );
492                        }
493                    } else if e.is_mid_stream_drop() {
494                        crate::log_warn!(
495                            "[Blossom] {} dropped the connection mid-upload of {} bytes, treating as permanent",
496                            server_url, body.len(),
497                        );
498                    }
499                    return Err(e);
500                }
501                if let Some(wait) = e.refusal().and_then(|r| r.retry_after()) {
502                    next_delay = next_delay.max(wait);
503                }
504                last_error = Some(e);
505            }
506        }
507        attempt += 1;
508    }
509
510    // All attempts failed, return the last error
511    Err(last_error.unwrap_or_else(|| UploadFailure::Other("No upload attempts were made".to_string())))
512}
513
514/// What the server said before the body was sent.
515enum Preflight {
516    /// Send it.
517    Proceed,
518    /// The server already holds this exact blob and named its URL; there is
519    /// nothing to send.
520    AlreadyStored(String),
521}
522
523/// BUD-06 preflight: `HEAD /upload` with the blob's hash, size and type, so a
524/// server that will refuse can say so before the bytes go out.
525///
526/// Best-effort: a server without BUD-06 answers 404/405 and is sent the body
527/// regardless. A server with Magnitude's vocabulary puts `X-Error-Code` on the
528/// refusal, and every such code is final for this server — a quota, a closed
529/// client gate, a blocked hash are as final as a size limit, and sending the
530/// body would only earn the same answer after the transfer. A plain server is
531/// believed only on the two statuses BUD-06 defines (413, 415) and on a body
532/// that reads as a type rejection.
533///
534/// A 2xx with `X-Already-Stored: true` and `X-Blob-URL` means the server has
535/// these bytes already and the caller can stop here with the link.
536async fn preflight(
537    client: &crate::net::HttpClient,
538    upload_url: &Url,
539    server_url: &Url,
540    auth_header: &HeaderValue,
541    hash: Sha256Hash,
542    total_size: u64,
543    mime_type: Option<&str>,
544) -> Result<Preflight, UploadFailure> {
545    let mut head_headers = HeaderMap::new();
546    head_headers.insert(AUTHORIZATION, auth_header.clone());
547    head_headers.insert(
548        "X-Content-Length",
549        HeaderValue::from_str(&total_size.to_string())
550            .map_err(|e| UploadFailure::Other(format!("Invalid X-Content-Length: {}", e)))?,
551    );
552    // BUD-06 requires lowercase hex. SIMD encode of the 32-byte digest (sha256::Hash displays
553    // in forward byte order, matching to_byte_array — see the parity test).
554    head_headers.insert(
555        "X-SHA-256",
556        HeaderValue::from_str(&crate::simd::hex::bytes_to_hex_32(&hash.to_byte_array()))
557            .map_err(|e| UploadFailure::Other(format!("Invalid X-SHA-256: {}", e)))?,
558    );
559    if let Some(ct) = mime_type {
560        head_headers.insert(
561            "X-Content-Type",
562            HeaderValue::from_str(ct).map_err(|e| UploadFailure::Other(format!("Invalid X-Content-Type: {}", e)))?,
563        );
564    }
565    let asked_at = web_time::Instant::now();
566    let resp = match crate::rt::time::timeout(
567        crate::transport::budget(crate::transport::Op::BestEffort, std::time::Duration::from_secs(5)),
568        client.head(upload_url.clone()).headers(head_headers).send(),
569    ).await {
570        Ok(Ok(resp)) => {
571            crate::blossom_stats::record_latency(server_url.as_str(), asked_at.elapsed().as_secs_f64() * 1000.0);
572            resp
573        }
574        Ok(Err(e)) => {
575            crate::log_debug!("[Blossom Preflight] {} HEAD failed: {}, falling through to PUT", server_url, e);
576            return Ok(Preflight::Proceed);
577        }
578        Err(_) => {
579            crate::log_debug!("[Blossom Preflight] {} HEAD timed out, falling through to PUT", server_url);
580            return Ok(Preflight::Proceed);
581        }
582    };
583
584    let status = resp.status();
585    if status.is_success() {
586        let already = resp.headers().get("x-already-stored")
587            .and_then(|v| v.to_str().ok())
588            .is_some_and(|v| v.eq_ignore_ascii_case("true"));
589        let url = resp.headers().get("x-blob-url")
590            .and_then(|v| v.to_str().ok())
591            .map(|s| s.to_string());
592        if let (true, Some(url)) = (already, url) {
593            // The link must name our hash: a server pointing at some other blob
594            // would have us embed a stranger's bytes in a message.
595            match parse_blob_url(&url) {
596                Ok((_, stored)) if stored == hash => {
597                    crate::log_info!(
598                        "[Blossom Preflight] {} already holds {} ({} bytes); nothing to send",
599                        server_url, hash, total_size,
600                    );
601                    return Ok(Preflight::AlreadyStored(url));
602                }
603                _ => crate::log_warn!(
604                    "[Blossom Preflight] {} claims to hold the blob at {} which is not {}; uploading anyway",
605                    server_url, url, hash,
606                ),
607            }
608        }
609        crate::log_debug!(
610            "[Blossom Preflight] {} → {} ({} bytes); proceeding to PUT",
611            server_url, status, total_size,
612        );
613        return Ok(Preflight::Proceed);
614    }
615
616    // A HEAD has no body: the headers are the whole answer. BUD-02 says the
617    // prose in X-Reason is display-only; a body, if any, feeds the keyword
618    // classifier for servers that 400 instead of 415.
619    let headers = resp.headers().clone();
620    let body = resp.text().await.unwrap_or_default();
621    let refusal = Refusal::from_response(status.as_u16(), &headers, &body);
622    let is_413 = status == StatusCode::PAYLOAD_TOO_LARGE;
623    let is_415 = status == StatusCode::UNSUPPORTED_MEDIA_TYPE;
624    let final_here = refusal.code().is_some()
625        || is_413
626        || is_415
627        || (status.is_client_error() && refusal.is_mime());
628    if final_here {
629        crate::log_warn!(
630            "[Blossom Preflight] {} REJECTED {} ({} bytes, {}): {}",
631            server_url, status, total_size,
632            mime_type.unwrap_or("(no mime)"), refusal.message,
633        );
634        return Err(UploadFailure::Refused(refusal));
635    }
636    crate::log_debug!(
637        "[Blossom Preflight] {} → {} ({} bytes); proceeding to PUT",
638        server_url, status, total_size,
639    );
640    Ok(Preflight::Proceed)
641}
642
643/// Read a rejected PUT into a refusal. The body feeds the classifier; the
644/// headers carry the code when the server has one.
645async fn refusal_from(response: crate::net::Resp) -> Refusal {
646    let status = response.status().as_u16();
647    let headers = response.headers().clone();
648    let body = response.text().await.unwrap_or_default();
649    Refusal::from_response(status, &headers, &body)
650}
651
652/// Internal function that performs a single upload attempt with progress tracking
653async fn upload_attempt<T>(
654    signer: T,
655    server_url: &Url,
656    body: UploadBody,
657    mime_type: Option<&str>,
658    progress_callback: &ProgressCallback,
659    cancel_flag: Option<Arc<AtomicBool>>,
660    preflight_first: bool,
661) -> Result<String, UploadFailure>
662where
663    T: VectorSigner,
664{
665    let upload_url = server_url.join("upload")
666        .map_err(|e| UploadFailure::Other(format!("Invalid server URL: {}", e)))?;
667
668    let total_size = body.len();
669    let hash = body.sha256();
670
671    progress_callback(Some(0), Some(0)).map_err(callback_failure)?;
672
673    // One auth event covers both HEAD preflight and PUT.
674    let auth_header = build_auth_header(&signer, hash).await.map_err(UploadFailure::Other)?;
675
676    // No deadlines: the upload is bounded by progress in `send_upload`.
677    // Redirects disabled: a 3xx mid-PUT would re-issue as GET and drop the body.
678    // The user's lane: the request carries their signed authorization.
679    let client = crate::net::build_http_client_for(crate::net::Lane::Account, None, None, false)
680        .map_err(UploadFailure::Other)?;
681
682    if preflight_first {
683        match preflight(&client, &upload_url, server_url, &auth_header, hash, total_size, mime_type).await? {
684            Preflight::Proceed => {}
685            Preflight::AlreadyStored(url) => {
686                progress_callback(Some(100), Some(total_size)).map_err(callback_failure)?;
687                return Ok(url);
688            }
689        }
690    }
691
692    let mut headers = HeaderMap::new();
693    headers.insert(AUTHORIZATION, auth_header);
694    if let Some(ct) = mime_type {
695        headers.insert(
696            CONTENT_TYPE,
697            HeaderValue::from_str(ct).map_err(|e| UploadFailure::Other(format!("Invalid content type: {}", e)))?
698        );
699    }
700    // `Body::wrap_stream` is unknown-length so reqwest would default to
701    // chunked encoding and omit Content-Length — some servers (e.g.
702    // blossom.data.haus) then 411.
703    headers.insert(CONTENT_LENGTH, HeaderValue::from(total_size));
704
705    let started = web_time::Instant::now();
706    let response = send_upload(
707        &client,
708        client.put(upload_url.clone()).headers(headers),
709        server_url,
710        &body,
711        crate::net::transfer_stall(),
712        cancel_flag.as_ref(),
713        Some(progress_callback),
714    ).await?;
715
716    // BUD-02: accept any 2xx (200 OK or 201 Created).
717    let status = response.status();
718    if status.is_success() {
719        crate::blossom_stats::record_upload(server_url.as_str(), total_size, started.elapsed().as_secs_f64() * 1000.0);
720        let descriptor: BlobDescriptor = response.json().await
721            .map_err(|e| UploadFailure::Other(format!("Failed to parse response: {}", e)))?;
722        // Integrity gate: a compliant server stores our bytes verbatim, so the
723        // returned descriptor hash MUST equal what we uploaded. A mismatch means
724        // the server transformed/re-encoded the blob, which is fatal for an
725        // encrypted upload (corrupts the ciphertext). The failover loop routes
726        // around the server like a hard rejection.
727        if descriptor.sha256 != hash {
728            return Err(UploadFailure::Integrity(format!(
729                "[INTEGRITY] {} transformed the upload (returned {}, expected {})",
730                server_url, descriptor.sha256, hash,
731            )));
732        }
733        Ok(descriptor.url.to_string())
734    } else {
735        let refusal = refusal_from(response).await;
736        crate::log_net_fail!(
737            "[Blossom] upload rejected: HTTP {}{} — {}",
738            status,
739            refusal.code().map(|c| format!(" [{}]", c)).unwrap_or_default(),
740            refusal.message,
741        );
742        Err(UploadFailure::Refused(refusal))
743    }
744}
745
746/// Simple upload without progress reporting.
747///
748/// `stall_timeout` is how long the server may accept nothing before it is
749/// treated as dead and failover moves on; `None` is [`crate::net::TRANSFER_STALL`].
750/// Small uploads (emoji, avatars) pass a short one so a broken host costs
751/// seconds. There is no total time limit at any size.
752pub async fn upload_blob<T>(
753    signer: T,
754    server_url: &Url,
755    file_data: Arc<Vec<u8>>,
756    mime_type: Option<&str>,
757    stall_timeout: Option<std::time::Duration>,
758) -> Result<String, UploadFailure>
759where
760    T: VectorSigner,
761{
762    let upload_url = server_url.join("upload")
763        .map_err(|e| UploadFailure::Other(format!("Invalid server URL: {}", e)))?;
764
765    let hash = Sha256Hash::hash(&file_data);
766    let total_size = file_data.len() as u64;
767
768    let auth_header = build_auth_header(&signer, hash).await.map_err(UploadFailure::Other)?;
769
770    // Redirects disabled so a 3xx mid-PUT doesn't re-issue as GET.
771    let client = crate::net::build_http_client_for(crate::net::Lane::Account, None, None, false)
772        .map_err(UploadFailure::Other)?;
773
774    if let Preflight::AlreadyStored(url) =
775        preflight(&client, &upload_url, server_url, &auth_header, hash, total_size, mime_type).await?
776    {
777        return Ok(url);
778    }
779
780    let mut headers = HeaderMap::new();
781    headers.insert(AUTHORIZATION, auth_header);
782    if let Some(ct) = mime_type {
783        headers.insert(
784            CONTENT_TYPE,
785            HeaderValue::from_str(ct).map_err(|e| UploadFailure::Other(format!("Invalid content type: {}", e)))?
786        );
787    }
788    headers.insert(CONTENT_LENGTH, HeaderValue::from(total_size));
789
790    let started = web_time::Instant::now();
791    let response = send_upload(
792        &client,
793        client.put(upload_url).headers(headers),
794        server_url,
795        &UploadBody::Memory(file_data),
796        stall_timeout.unwrap_or_else(crate::net::transfer_stall),
797        None,
798        None,
799    ).await?;
800
801    // BUD-02: accept any 2xx (200 OK or 201 Created).
802    let status = response.status();
803    if status.is_success() {
804        crate::blossom_stats::record_upload(server_url.as_str(), total_size, started.elapsed().as_secs_f64() * 1000.0);
805        let descriptor: BlobDescriptor = response.json().await
806            .map_err(|e| UploadFailure::Other(format!("Failed to parse response: {}", e)))?;
807        // Integrity gate (see upload_attempt): reject a server that returns a
808        // different hash than we uploaded — it re-encoded the blob.
809        if descriptor.sha256 != hash {
810            return Err(UploadFailure::Integrity(format!(
811                "[INTEGRITY] {} transformed the upload (returned {}, expected {})",
812                server_url, descriptor.sha256, hash,
813            )));
814        }
815        Ok(descriptor.url.to_string())
816    } else {
817        Err(UploadFailure::Refused(refusal_from(response).await))
818    }
819}
820
821/// STRICT liveness for smart-forward reuse: only a positive 2xx HEAD counts.
822/// The post-upload verifier (`uploaded_blob_serves`) fails OPEN, since an unreachable
823/// server shouldn't sink an upload that ACKed; a REUSE decision is the opposite: on
824/// anything but proof the blob serves, fall through to a fresh upload, which always works.
825pub async fn blob_is_served(url: &str, timeout: std::time::Duration) -> bool {
826    matches!(crate::net::remote_status(url, timeout).await, Some(200..=299))
827}
828
829/// Post-upload liveness gate: confirm the server actually SERVES the blob it just ACKed.
830/// Some servers 2xx an upload they dedupe against a stale index or quietly drop, so only a
831/// cache-cold fetch tells the truth. A definitive 404/410 (after a short grace retry) fails
832/// the server; anything else passes, so a flaky HEAD can't sink a good upload.
833async fn uploaded_blob_serves(url: &str) -> bool {
834    for attempt in 0..2 {
835        if attempt > 0 {
836            crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
837        }
838        match uploaded_blob_status(url).await {
839            Some(404) | Some(410) => continue,
840            Some(_) => return true,
841            None => {
842                crate::log_net_info!("[Blossom] {} unreachable for post-upload verify — assuming stored", url);
843                return true;
844            }
845        }
846    }
847    crate::log_net_fail!("[Blossom] {} ACKed the upload but serves 404/410 — treating as dropped", url);
848    false
849}
850
851/// The status a just-uploaded blob answers with. Asked directly, it rides the
852/// upload's pooled connection instead of opening a fresh one to the same host.
853async fn uploaded_blob_status(url: &str) -> Option<u16> {
854    let timeout = crate::transport::budget(crate::transport::Op::BestEffort, std::time::Duration::from_secs(10));
855    if crate::net::egress(url).await.proxied() {
856        return crate::net::remote_status(url, timeout).await;
857    }
858    let client = crate::net::build_http_client_with_options(None, None, false).ok()?;
859    let status = crate::rt::time::timeout(timeout, client.head(url).send()).await.ok()?.ok()?.status();
860    if status == StatusCode::METHOD_NOT_ALLOWED || status == StatusCode::NOT_IMPLEMENTED {
861        return crate::net::remote_status(url, timeout).await;
862    }
863    Some(status.as_u16())
864}
865
866/// What a failure says about the server's state for the status pill: gone
867/// (nothing arrived) or full (a quota or the disk). A refusal about the file
868/// itself says nothing about the server.
869fn note_failure(server_url: &str, e: &UploadFailure) {
870    match e {
871        UploadFailure::Transport(_) => {
872            crate::blossom_stats::record_failure(server_url, crate::blossom_stats::FAIL_OFFLINE)
873        }
874        UploadFailure::Refused(r) => {
875            if matches!(r.code(), Some("quota_storage_exceeded" | "quota_daily_exceeded" | "server_full")) {
876                crate::blossom_stats::record_failure(server_url, crate::blossom_stats::FAIL_MAXED);
877            } else {
878                crate::blossom_stats::record_ok(server_url);
879            }
880        }
881        _ => {}
882    }
883}
884
885/// Upload to multiple Blossom servers with failover, in input order.
886///
887/// **Does NOT participate in the capability cache.** Used by the
888/// marketplace (plaintext mini-app uploads); for high-volume callers
889/// prefer `upload_blob_with_progress_and_failover` so they benefit
890/// from cache-aware routing.
891pub async fn upload_blob_with_failover<T>(
892    signer: T,
893    server_urls: Vec<String>,
894    file_data: Arc<Vec<u8>>,
895    mime_type: Option<&str>,
896    stall_timeout: Option<std::time::Duration>,
897) -> Result<String, String>
898where
899    T: VectorSigner + Clone,
900{
901    let mut failures: Vec<(String, UploadFailure)> = Vec::new();
902
903    for (index, server_url_str) in server_urls.iter().enumerate() {
904        let host = host_of(server_url_str);
905        let server_url = match Url::parse(server_url_str) {
906            Ok(url) => url,
907            Err(e) => {
908                crate::log_net_fail!("[Blossom] invalid server URL '{}': {}", server_url_str, e);
909                failures.push((host, UploadFailure::Other(format!("Invalid server URL: {}", e))));
910                continue;
911            }
912        };
913
914        crate::log_info!("[Blossom] Attempting upload to server {} of {}: {}",
915            index + 1, server_urls.len(), server_url_str);
916
917        match upload_blob(signer.clone(), &server_url, file_data.clone(), mime_type, stall_timeout).await {
918            Ok(url) => {
919                if !uploaded_blob_serves(&url).await {
920                    crate::log_warn!(
921                        "[Blossom Error] {} ACKed the upload but does not serve {} — failing over",
922                        server_url_str, url,
923                    );
924                    failures.push((host, UploadFailure::Other(format!(
925                        "{} accepted the upload but the blob is not retrievable", server_url_str,
926                    ))));
927                    continue;
928                }
929                crate::log_net_info!("[Blossom] upload OK via {}", server_url_str);
930                crate::blossom_stats::record_ok(server_url_str);
931                return Ok(url);
932            }
933            Err(e) => {
934                crate::log_net_fail!("[Blossom] upload failed to {}: {}", server_url_str, e);
935                note_failure(server_url_str, &e);
936                failures.push((host, e));
937            }
938        }
939    }
940
941    let summary = summarise_failures(&failures);
942    crate::log_net_fail!("[Blossom] ALL servers failed: {}", summary);
943    Err(summary)
944}
945
946/// An upload that a server accepted.
947///
948/// `url` is the descriptor the server returned; `server` is the address Vector
949/// actually talked to. They are frequently NOT the same host: an ingress relay
950/// takes the bytes on a regional name and the origin hands back its own
951/// canonical `public_url`. Both name the same server, and mirroring needs to
952/// know that — a BUD-04 mirror aimed at either one asks a server to fetch a
953/// blob it is already holding.
954#[derive(Debug, Clone, PartialEq, Eq)]
955pub struct AcceptedUpload {
956    pub url: String,
957    pub server: String,
958}
959
960/// Open a pooled connection to the server an upload of this kind would try first,
961/// so a send that follows starts on a live TLS session rather than a handshake.
962/// Best-effort and bodiless: the answer is irrelevant, the connection is the point.
963pub async fn warm_upload_connection(server_urls: Vec<String>, mime_type: &str, is_encrypted: bool, size_bytes: u64) {
964    let ranked = crate::blossom_capabilities::rank_servers(server_urls, mime_type, is_encrypted, size_bytes);
965    let Some(url) = ranked.first().and_then(|u| Url::parse(u).ok()) else { return };
966    // The same lane and options as `upload_attempt`, so the upload draws from this pool.
967    let Ok(client) = crate::net::build_http_client_for(crate::net::Lane::Account, None, None, false) else { return };
968    let _ = crate::rt::time::timeout(std::time::Duration::from_secs(10), client.head(url).send()).await;
969}
970
971/// Upload with progress + failover, cache-aware routing, and capability learning.
972#[allow(clippy::too_many_arguments)]
973pub async fn upload_blob_with_progress_and_failover<T>(
974    signer: T,
975    server_urls: Vec<String>,
976    file_data: Arc<Vec<u8>>,
977    mime_type: Option<&str>,
978    is_encrypted: bool,
979    progress_callback: ProgressCallback,
980    retry_count: Option<u32>,
981    retry_spacing: Option<std::time::Duration>,
982    cancel_flag: Option<Arc<AtomicBool>>,
983) -> Result<AcceptedUpload, String>
984where
985    T: VectorSigner + Clone,
986{
987    upload_body_with_progress_and_failover(
988        signer, server_urls, UploadBody::Memory(file_data), mime_type, is_encrypted,
989        progress_callback, retry_count, retry_spacing, cancel_flag,
990    ).await
991}
992
993/// [`upload_blob_with_progress_and_failover`] for any [`UploadBody`], a file on
994/// disk included.
995#[allow(clippy::too_many_arguments)]
996pub async fn upload_body_with_progress_and_failover<T>(
997    signer: T,
998    server_urls: Vec<String>,
999    body: UploadBody,
1000    mime_type: Option<&str>,
1001    is_encrypted: bool,
1002    progress_callback: ProgressCallback,
1003    retry_count: Option<u32>,
1004    retry_spacing: Option<std::time::Duration>,
1005    cancel_flag: Option<Arc<AtomicBool>>,
1006) -> Result<AcceptedUpload, String>
1007where
1008    T: VectorSigner + Clone,
1009{
1010    let mut failures: Vec<(String, UploadFailure)> = Vec::new();
1011
1012    // Known-good first, unknown second, MIME-rejected last. Stable within
1013    // tier so the user's BUD-03 trust order wins ties.
1014    let size_bytes = body.len();
1015    let mime_for_routing = mime_type.unwrap_or("application/octet-stream");
1016    let ranked = crate::blossom_capabilities::rank_servers(server_urls, mime_for_routing, is_encrypted, size_bytes);
1017
1018    for (index, server_url_str) in ranked.iter().enumerate() {
1019        if let Some(ref flag) = cancel_flag {
1020            if flag.load(Ordering::Relaxed) {
1021                return Err("Upload cancelled".to_string());
1022            }
1023        }
1024
1025        let host = host_of(server_url_str);
1026        let server_url = match Url::parse(server_url_str) {
1027            Ok(url) => url,
1028            Err(e) => {
1029                crate::log_net_fail!("[Blossom] invalid server URL '{}': {}", server_url_str, e);
1030                failures.push((host, UploadFailure::Other(format!("Invalid server URL: {}", e))));
1031                continue;
1032            }
1033        };
1034
1035        crate::log_info!("[Blossom] Attempting upload to server {} of {}: {}",
1036            index + 1, ranked.len(), server_url_str);
1037
1038        // A fresh random key makes every ciphertext new, so a preflight can only
1039        // refuse; it is skipped where this server has already taken its like.
1040        let preflight_first = !crate::blossom_capabilities::preflight_redundant(
1041            server_url_str, mime_for_routing, is_encrypted, size_bytes,
1042        );
1043        match upload_with_retries(
1044            signer.clone(),
1045            &server_url,
1046            body.clone(),
1047            mime_type,
1048            progress_callback.clone(),
1049            retry_count,
1050            retry_spacing,
1051            cancel_flag.clone(),
1052            preflight_first,
1053        ).await {
1054            Ok(url) => {
1055                if !uploaded_blob_serves(&url).await {
1056                    crate::log_warn!(
1057                        "[Blossom Error] {} ACKed the upload but does not serve {} — failing over",
1058                        server_url_str, url,
1059                    );
1060                    failures.push((host, UploadFailure::Other(format!(
1061                        "{} accepted the upload but the blob is not retrievable", server_url_str,
1062                    ))));
1063                    let _ = progress_callback(Some(0), Some(0));
1064                    continue;
1065                }
1066                crate::log_net_info!("[Blossom] upload OK via {}", server_url_str);
1067                if let Err(err) = crate::blossom_capabilities::record_accepted(
1068                    server_url_str, mime_for_routing, is_encrypted, size_bytes,
1069                ) {
1070                    crate::log_warn!("[Blossom Cap] record_accepted failed: {}", err);
1071                }
1072                crate::blossom_info::note_upload(server_url_str, size_bytes);
1073                crate::blossom_stats::record_ok(server_url_str);
1074                return Ok(AcceptedUpload {
1075                    url,
1076                    server: server_url_str.clone(),
1077                });
1078            }
1079            Err(UploadFailure::Cancelled) => {
1080                return Err("Upload cancelled".to_string());
1081            }
1082            Err(e) => {
1083                crate::log_net_fail!("[Blossom] upload failed to {}: {}", server_url_str, e);
1084                note_failure(server_url_str, &e);
1085                // Worth remembering about this server: a type it does not
1086                // take, a size it does not take, bytes it does not keep intact.
1087                // A quota, a rate limit, a closed gate or a bad clock say
1088                // nothing about the NEXT upload and are not cached.
1089                match &e {
1090                    UploadFailure::Integrity(_) => {
1091                        if let Err(err) = crate::blossom_capabilities::record_rejected_mime(
1092                            server_url_str, mime_for_routing, is_encrypted,
1093                        ) {
1094                            crate::log_warn!("[Blossom Cap] record_rejected_mime failed: {}", err);
1095                        }
1096                    }
1097                    UploadFailure::Refused(r) if r.is_mime() => {
1098                        if let Err(err) = crate::blossom_capabilities::record_rejected_mime(
1099                            server_url_str, mime_for_routing, is_encrypted,
1100                        ) {
1101                            crate::log_warn!("[Blossom Cap] record_rejected_mime failed: {}", err);
1102                        }
1103                    }
1104                    UploadFailure::Refused(r) if r.is_size_limit() => {
1105                        // A server that named its limit has told us the exact
1106                        // edge; one that only said 413 has told us this size.
1107                        let rejects_from = r.limit().map(|l| l.saturating_add(1)).unwrap_or(size_bytes).min(size_bytes);
1108                        if let Err(err) = crate::blossom_capabilities::record_rejected_size(
1109                            server_url_str, mime_for_routing, is_encrypted, rejects_from,
1110                        ) {
1111                            crate::log_warn!("[Blossom Cap] record_rejected_size failed: {}", err);
1112                        }
1113                    }
1114                    // Mid-stream drops aren't cached (too ambiguous); only
1115                    // an explicit size refusal sets min_rejected_size.
1116                    _ => {}
1117                }
1118                // The network itself never came back: every other server would wait it out the
1119                // same way, to fail with the same words.
1120                let network_down = matches!(e, UploadFailure::Network(_));
1121                failures.push((host, e));
1122                let _ = progress_callback(Some(0), Some(0));
1123                if network_down {
1124                    break;
1125                }
1126            }
1127        }
1128    }
1129
1130    let summary = summarise_failures(&failures);
1131    crate::log_net_fail!("[Blossom] ALL servers failed: {}", summary);
1132    Err(summary)
1133}
1134
1135// ============================================================================
1136// Blossom DELETE — paired with NIP-17 message deletion
1137// ============================================================================
1138
1139async fn build_delete_auth_header<T>(signer: &T, hash: Sha256Hash) -> Result<HeaderValue, String>
1140where
1141    T: VectorSigner,
1142{
1143    let ttl = std::time::Duration::from_secs(300);
1144    auth_header(signer, "delete", AuthScope::Blob(hash), "Blossom delete authorization", ttl).await
1145}
1146
1147/// Delete a blob from a Blossom server. 2xx and 404 both count as
1148/// success (idempotent: "blob is gone" is the goal). 401/403/5xx and
1149/// network errors propagate.
1150pub async fn delete_blob<T>(
1151    signer: T,
1152    server_url: &Url,
1153    hash: Sha256Hash,
1154) -> Result<(), String>
1155where
1156    T: VectorSigner + Clone,
1157{
1158    let auth_header = build_delete_auth_header(&signer, hash).await?;
1159
1160    let mut url = server_url.clone();
1161    // BUD-01 DELETE endpoint: `<origin>/<hash>`.
1162    url.set_path(&format!("/{}", hash));
1163
1164    let mut headers = HeaderMap::new();
1165    headers.insert(AUTHORIZATION, auth_header);
1166
1167    let client = crate::net::build_http_client_for(crate::net::Lane::Account, Some(std::time::Duration::from_secs(30)), None, true)?;
1168
1169    let response = client
1170        .delete(url)
1171        .headers(headers)
1172        .send()
1173        .await
1174        .map_err(|e| format!("Blossom DELETE request failed: {}", e))?;
1175
1176    let status = response.status();
1177    if status.is_success() || status == StatusCode::NOT_FOUND {
1178        Ok(())
1179    } else {
1180        let body = response.text().await.unwrap_or_else(|_| "<no body>".into());
1181        // "with status N" phrasing so `parse_status_from_error` can read the
1182        // code (the probe uses it to detect deletion-refusal). 404 already
1183        // counts as success above (blob gone = effectively deleted).
1184        Err(format!("Blossom DELETE failed with status {}: {}", status, body))
1185    }
1186}
1187
1188/// Parse a Blossom blob URL into its server origin and SHA-256 hash
1189/// (last non-empty path segment, optional `.ext` stripped).
1190pub fn parse_blob_url(url_str: &str) -> Result<(Url, Sha256Hash), String> {
1191    let parsed = Url::parse(url_str)
1192        .map_err(|e| format!("Invalid Blossom URL: {}", e))?;
1193    let last_segment = parsed
1194        .path_segments()
1195        .and_then(|segs| segs.rev().find(|s| !s.is_empty()))
1196        .ok_or_else(|| "Blossom URL has no path segment".to_string())?;
1197    let hash_str = last_segment.split('.').next().unwrap_or("");
1198    let hash = Sha256Hash::from_str(hash_str)
1199        .map_err(|e| format!("Path is not a SHA-256 hash: {}", e))?;
1200    let mut origin = parsed.clone();
1201    origin.set_path("/");
1202    origin.set_query(None);
1203    origin.set_fragment(None);
1204    Ok((origin, hash))
1205}
1206
1207/// The SHA-256 a Blossom URL names, as hex: what its bytes must hash to. `None`
1208/// for a URL that isn't content-addressed.
1209pub fn blob_hash(url_str: &str) -> Option<String> {
1210    parse_blob_url(url_str).ok().map(|(_, hash)| hash.to_string())
1211}
1212
1213/// Whether plaintext from `url` hashing to `sha256` (hex) is the file the message named: it
1214/// matches the URL's content address and the sender's claim, each where there is one. A link
1215/// with neither is taken as served, as any linked file is.
1216pub fn plaintext_matches(url: &str, claim: Option<&str>, sha256: &str) -> bool {
1217    blob_hash(url).is_none_or(|a| a.eq_ignore_ascii_case(sha256)) && claim.is_none_or(|c| c.eq_ignore_ascii_case(sha256))
1218}
1219
1220/// Verify a downloaded body against its URL's content address.
1221/// `Some(true)` = bytes match the blob hash, `Some(false)` = the source served
1222/// the wrong bytes, `None` = the URL carries no content address to check.
1223pub fn verify_blob_content(url_str: &str, bytes: &[u8]) -> Option<bool> {
1224    let (_, expected) = parse_blob_url(url_str).ok()?;
1225    Some(Sha256Hash::hash(bytes) == expected)
1226}
1227
1228/// Parse a Blossom blob URL into (origin, hash) and DELETE that blob.
1229/// Awaitable single-URL variant of `delete_blobs_best_effort` — caller
1230/// drives sequencing + per-URL UI feedback.
1231pub async fn delete_blob_by_url<T>(signer: T, url_str: &str) -> Result<(), String>
1232where
1233    T: VectorSigner + Clone,
1234{
1235    let (origin, hash) = parse_blob_url(url_str)?;
1236
1237    crate::log_info!("[Blossom] DELETE {} from {}", hash, origin);
1238    // Hard ceiling — a black-holed server must not hang the caller's
1239    // UI (e.g. the pack creator's "Deleting…" overlay) indefinitely.
1240    // 15s is generous for a healthy server and short enough that a
1241    // misbehaving one fails over to the next blob in a batch quickly.
1242    let timeout = crate::net::tor_http_timeout(std::time::Duration::from_secs(15));
1243    match crate::rt::time::timeout(timeout, delete_blob(signer, &origin, hash)).await {
1244        Ok(Ok(())) => {
1245            crate::log_info!("[Blossom] DELETE successful: {} from {}", hash, origin);
1246            Ok(())
1247        }
1248        Ok(Err(e)) => {
1249            crate::log_warn!("[Blossom] DELETE failed: {} from {}: {}", hash, origin, e);
1250            Err(e)
1251        }
1252        Err(_) => {
1253            let msg = format!("DELETE timed out after {}s", timeout.as_secs());
1254            crate::log_warn!("[Blossom] {} ({} from {})", msg, hash, origin);
1255            Err(msg)
1256        }
1257    }
1258}
1259
1260/// Derive BUD-03 hash-swap candidates: the same content-address on each of
1261/// `servers`. Blossom URLs are `<origin>/<sha256>[.ext]`, so any server in
1262/// the author's list may serve a blob whose embedded URLs have all died.
1263/// Servers matching `primary_url`'s origin (already tried) are skipped.
1264pub fn hash_swap_candidates(primary_url: &str, servers: &[String]) -> Vec<String> {
1265    let Ok((primary_origin, hash)) = parse_blob_url(primary_url) else {
1266        return Vec::new();
1267    };
1268    // Extension from the parsed path segment, never the raw string — a raw
1269    // rsplit would drag the query/fragment along into every derived URL.
1270    let ext = Url::parse(primary_url)
1271        .ok()
1272        .and_then(|u| {
1273            u.path_segments()
1274                .and_then(|segs| segs.rev().find(|s| !s.is_empty()).map(|s| s.to_string()))
1275        })
1276        .and_then(|leaf| leaf.split_once('.').map(|(_, e)| e.to_string()))
1277        .filter(|e| !e.is_empty() && e.len() <= 8 && e.bytes().all(|b| b.is_ascii_alphanumeric()));
1278    let leaf = match ext {
1279        Some(e) => format!("{}.{}", hash, e),
1280        None => hash.to_string(),
1281    };
1282    servers
1283        .iter()
1284        .filter_map(|s| {
1285            let base = Url::parse(&format!("{}/", s.trim_end_matches('/'))).ok()?;
1286            if base.origin() == primary_origin.origin() {
1287                return None;
1288            }
1289            base.join(&leaf).ok().map(|u| u.to_string())
1290        })
1291        .collect()
1292}
1293
1294/// BUD-04: ask `target_server` to mirror the blob at `source_url` by pulling
1295/// it server-to-server (the client sends one small JSON request, never the
1296/// bytes). Authorized by the same hash-scoped upload event as a direct
1297/// upload. The mirror's ACK gets the same serve-check as an upload ACK.
1298/// Returns the mirror's URL for the blob.
1299pub async fn mirror_blob<T>(signer: T, target_server: &Url, source_url: &str) -> Result<String, String>
1300where
1301    T: VectorSigner + Clone,
1302{
1303    let (source_origin, hash) = parse_blob_url(source_url)?;
1304    if target_server.origin() == source_origin.origin() {
1305        return Err("Mirror target is the source server".to_string());
1306    }
1307    let auth_header = build_auth_header(&signer, hash).await?;
1308    let mirror_url = target_server
1309        .join("mirror")
1310        .map_err(|e| format!("Invalid mirror URL: {}", e))?;
1311
1312    let client = crate::net::build_http_client_for(crate::net::Lane::Account, Some(std::time::Duration::from_secs(30)), None, true)?;
1313    let response = client
1314        .put(mirror_url)
1315        .header(AUTHORIZATION, auth_header)
1316        .header(CONTENT_TYPE, "application/json")
1317        .body(format!("{{\"url\":{}}}", serde_json::to_string(source_url).map_err(|e| e.to_string())?))
1318        .send()
1319        .await
1320        .map_err(|e| format!("Mirror request failed: {}", e))?;
1321
1322    let status = response.status();
1323    if !status.is_success() {
1324        let body = response.text().await.unwrap_or_else(|_| "<no body>".into());
1325        return Err(format!("Mirror failed with status {}: {}", status, body));
1326    }
1327    let descriptor: BlobDescriptor = response
1328        .json()
1329        .await
1330        .map_err(|e| format!("Failed to parse mirror response: {}", e))?;
1331    if descriptor.sha256 != hash {
1332        return Err(format!(
1333            "[INTEGRITY] {} mirrored a different hash (returned {}, expected {})",
1334            target_server, descriptor.sha256, hash,
1335        ));
1336    }
1337    let url = descriptor.url.to_string();
1338    // BUD-04: the mirror serves the blob ITSELF. A descriptor pointing at a
1339    // foreign origin, a downgraded scheme, or carrying a query string is a
1340    // protocol violation (or a tracking beacon) — never embed it in messages.
1341    let same_origin = Url::parse(&url)
1342        .map(|u| u.origin() == target_server.origin() && u.query().is_none())
1343        .unwrap_or(false);
1344    if !same_origin {
1345        return Err(format!("{} returned a foreign descriptor URL: {}", target_server, url));
1346    }
1347    if !uploaded_blob_serves(&url).await {
1348        return Err(format!("{} ACKed the mirror but does not serve it", target_server));
1349    }
1350    Ok(url)
1351}
1352
1353/// Which of the user's servers are worth mirroring to.
1354///
1355/// A server that already holds the blob gains nothing from being told to fetch
1356/// it, and mirroring exists for redundancy across DISTINCT servers — a server
1357/// that just accepted the upload is by definition not adding any.
1358///
1359/// The source URL alone does not identify those servers. An upload sent to an
1360/// ingress relay comes back carrying the origin's canonical `public_url`, so
1361/// `asia.magnitude.jskitty.com` and `magnitude.jskitty.com` are one server
1362/// wearing two names, and no amount of string comparison relates them. The
1363/// caller knows which address it actually uploaded to, so it passes that in
1364/// via `already_held_by` and both names are excluded.
1365fn mirror_targets(
1366    source_url: &str,
1367    server_urls: &[String],
1368    max_mirrors: usize,
1369    already_held_by: &[String],
1370) -> Vec<Url> {
1371    let source_origin = match parse_blob_url(source_url) {
1372        Ok((origin, _)) => origin,
1373        Err(e) => {
1374            crate::log_debug!("[Blossom Mirror] unparseable source {}: {}", source_url, e);
1375            return Vec::new();
1376        }
1377    };
1378    let excluded: Vec<url::Origin> = std::iter::once(source_origin.origin())
1379        .chain(
1380            already_held_by
1381                .iter()
1382                .filter_map(|s| Url::parse(s).ok())
1383                .map(|u| u.origin()),
1384        )
1385        .collect();
1386    server_urls
1387        .iter()
1388        .filter_map(|s| Url::parse(s).ok())
1389        .filter(|u| !excluded.contains(&u.origin()))
1390        .take(max_mirrors)
1391        .collect()
1392}
1393
1394/// Best-effort BUD-04 fan-out: mirror `source_url` onto up to `max_mirrors`
1395/// of the user's other servers, concurrently, under one wall-clock `budget`.
1396/// Returns only the mirror URLs that verifiably serve — the caller embeds
1397/// these as NIP-17 / imeta `fallback` sources. Never fails the send: an
1398/// empty Vec just means the message ships with no fallbacks.
1399pub async fn mirror_blob_to_servers<T>(
1400    signer: T,
1401    source_url: &str,
1402    server_urls: Vec<String>,
1403    max_mirrors: usize,
1404    budget: std::time::Duration,
1405    already_held_by: &[String],
1406) -> Vec<String>
1407where
1408    T: VectorSigner + Clone,
1409{
1410    let targets = mirror_targets(source_url, &server_urls, max_mirrors, already_held_by);
1411    if targets.is_empty() {
1412        return Vec::new();
1413    }
1414    let budget = crate::transport::budget(crate::transport::Op::BestEffort, budget);
1415
1416    let futures = targets.into_iter().map(|target| {
1417        let signer = signer.clone();
1418        let source = source_url.to_string();
1419        async move {
1420            // Per-target budget: a hung server cancels only itself. A mirror
1421            // that completed must keep its result — an unrecorded live copy
1422            // is invisible to every future deletion sweep.
1423            match crate::rt::time::timeout(budget, mirror_blob(signer, &target, &source)).await {
1424                Ok(Ok(url)) => {
1425                    crate::log_net_info!("[Blossom Mirror] {} now serves {}", target, url);
1426                    Some(url)
1427                }
1428                Ok(Err(e)) => {
1429                    crate::log_net_fail!("[Blossom Mirror] {} refused: {}", target, e);
1430                    None
1431                }
1432                Err(_) => {
1433                    crate::log_net_fail!("[Blossom Mirror] {} exceeded {:?} budget", target, budget);
1434                    None
1435                }
1436            }
1437        }
1438    });
1439    futures_util::future::join_all(futures)
1440        .await
1441        .into_iter()
1442        .flatten()
1443        .collect()
1444}
1445
1446/// Fire-and-forget DELETE for each parseable blob URL. Pairs with
1447/// `delete_own_dm` so removing a NIP-17 file message also removes
1448/// the ciphertext from the server it was uploaded to.
1449pub fn delete_blobs_best_effort<T>(signer: T, urls: Vec<String>)
1450where
1451    T: VectorSigner + Clone + Send + Sync + 'static,
1452{
1453    for url_str in urls {
1454        let url = match Url::parse(&url_str) {
1455            Ok(u) => u,
1456            Err(_) => continue,
1457        };
1458
1459        // Last non-empty path segment (trailing-slash URLs leave an empty tail).
1460        let last_segment = match url.path_segments()
1461            .and_then(|segs| segs.rev().find(|s| !s.is_empty()))
1462        {
1463            Some(s) => s,
1464            None => continue,
1465        };
1466        // Strip an optional `.ext` suffix some servers append.
1467        let hash_str = last_segment.split('.').next().unwrap_or("");
1468        let hash = match Sha256Hash::from_str(hash_str) {
1469            Ok(h) => h,
1470            Err(_) => continue,
1471        };
1472
1473        let mut origin = url.clone();
1474        origin.set_path("/");
1475        origin.set_query(None);
1476        origin.set_fragment(None);
1477
1478        let signer = signer.clone();
1479        // spawn-detached: deleting one probe blob from a server — signer in hand, no account storage.
1480        crate::rt::spawn(async move {
1481            if let Err(e) = delete_blob(signer, &origin, hash).await {
1482                crate::log_warn!("[Blossom delete] {} from {}: {}", hash, origin, e);
1483            }
1484        });
1485    }
1486}
1487
1488/// Probe `(server, application/octet-stream, encrypted=true)` with a
1489/// 32-byte random blob to learn whether the server accepts the binary
1490/// uploads Vector produces for chat attachments. Single-shot per
1491/// (server,mime,encrypted). Successful probes are cleaned up via DELETE.
1492pub async fn probe_servers_for_octet_stream<T>(
1493    signer: T,
1494    server_urls: Vec<String>,
1495) -> Result<usize, String>
1496where
1497    T: VectorSigner + Clone,
1498{
1499    use rand::RngCore;
1500    if server_urls.is_empty() { return Ok(0); }
1501
1502    const PROBE_MIME: &str = "application/octet-stream";
1503    let mut payload = vec![0u8; 32];
1504    rand::thread_rng().fill_bytes(&mut payload[..]);
1505    let payload = Arc::new(payload);
1506    let payload_size = payload.len() as u64;
1507
1508    let mut probed = 0usize;
1509    for server_url_str in &server_urls {
1510        if crate::blossom_capabilities::has_fresh_capability_for(server_url_str, PROBE_MIME, true) {
1511            continue;
1512        }
1513        let parsed = match Url::parse(server_url_str) {
1514            Ok(u) => u,
1515            Err(_) => continue,
1516        };
1517        // 4s per-server budget bounds worst-case probe pass.
1518        let no_op_progress: ProgressCallback = Arc::new(|_, _| Ok(()));
1519        match crate::rt::time::timeout(
1520            std::time::Duration::from_secs(4),
1521            upload_blob_with_progress(
1522                signer.clone(),
1523                &parsed,
1524                payload.clone(),
1525                Some(PROBE_MIME),
1526                no_op_progress,
1527                Some(0),
1528                None,
1529                None,
1530            ),
1531        ).await {
1532            Ok(Ok(url)) => {
1533                // Race-guard: server may have been disabled/removed
1534                // between spawn and now (purge_server already cleared).
1535                if !crate::blossom_servers::is_enabled_server(server_url_str) {
1536                    if let Some(hash) = extract_hash_from_blossom_url(&url) {
1537                        let _ = delete_blob(signer.clone(), &parsed, hash).await;
1538                    }
1539                    continue;
1540                }
1541                // Reaching here means the upload succeeded AND the returned hash
1542                // matched (upload_attempt's integrity gate) — so the server
1543                // accepts our encrypted type and stores it verbatim. Final gate:
1544                // it must honor BUD-01 deletion, else removing a message can't
1545                // remove its blob. The probe blob is deleted either way (cleanup);
1546                // a 4s budget bounds the wait, and only a definitive refusal
1547                // (403/405/501) sinks the server — transient failures stay optimistic.
1548                let delete_result = match extract_hash_from_blossom_url(&url) {
1549                    Some(hash) => crate::rt::time::timeout(
1550                        std::time::Duration::from_secs(4),
1551                        delete_blob(signer.clone(), &parsed, hash),
1552                    ).await.ok(),
1553                    None => None,
1554                };
1555                let refuses_deletion = matches!(
1556                    &delete_result,
1557                    Some(Err(e)) if matches!(parse_status_from_error(e), Some(403) | Some(405) | Some(501)),
1558                );
1559                if refuses_deletion {
1560                    if let Err(err) = crate::blossom_capabilities::record_rejected_mime(
1561                        server_url_str, PROBE_MIME, true,
1562                    ) {
1563                        crate::log_warn!("[Blossom Probe] record_rejected_mime failed: {}", err);
1564                    }
1565                    probed += 1;
1566                    crate::log_info!("[Blossom Probe] {} refuses deletion; routing around", server_url_str);
1567                } else {
1568                    if let Err(e) = crate::blossom_capabilities::record_accepted(
1569                        server_url_str, PROBE_MIME, true, payload_size,
1570                    ) {
1571                        crate::log_warn!("[Blossom Probe] record_accepted failed: {}", e);
1572                    }
1573                    probed += 1;
1574                    crate::log_info!("[Blossom Probe] {} validated (accepts + verbatim + deletes)", server_url_str);
1575                }
1576            }
1577            Ok(Err(e)) => {
1578                // A transformed probe blob is as unsuitable as a hard MIME
1579                // rejection. A closed gate, a quota or a bad clock is not: the
1580                // server may take the next upload, so its reputation is left
1581                // alone and the probe runs again later.
1582                let unsuitable = matches!(e, UploadFailure::Integrity(_))
1583                    || e.refusal().is_some_and(|r| r.is_mime());
1584                if unsuitable {
1585                    if !crate::blossom_servers::is_enabled_server(server_url_str) {
1586                        continue;
1587                    }
1588                    if let Err(err) = crate::blossom_capabilities::record_rejected_mime(
1589                        server_url_str, PROBE_MIME, true,
1590                    ) {
1591                        crate::log_warn!("[Blossom Probe] record_rejected_mime failed: {}", err);
1592                    }
1593                    probed += 1;
1594                    crate::log_info!("[Blossom Probe] {} unsuitable; routing around: {}", server_url_str, e);
1595                } else {
1596                    // Transient — leave reputation unchanged so we re-probe later.
1597                    crate::log_debug!("[Blossom Probe] {} transient error (not cached): {}", server_url_str, e);
1598                }
1599            }
1600            Err(_) => {
1601                crate::log_debug!("[Blossom Probe] {} timed out, not cached", server_url_str);
1602            }
1603        }
1604    }
1605    Ok(probed)
1606}
1607
1608/// Parse the sha256 out of `<origin>/<sha256>[.<ext>][/]`. Skips an
1609/// empty trailing segment when the URL came back with a trailing slash.
1610fn extract_hash_from_blossom_url(url: &str) -> Option<Sha256Hash> {
1611    let parsed = Url::parse(url).ok()?;
1612    let last = parsed.path_segments()?.rev().find(|s| !s.is_empty())?;
1613    let stem = last.split('.').next()?;
1614    Sha256Hash::from_str(stem).ok()
1615}
1616
1617/// Extract the HTTP status from an error string. Anchored to the
1618/// `"with status NNN"` shape produced by `upload_blob_with_progress`
1619/// so unrelated `status` substrings don't false-match.
1620fn parse_status_from_error(msg: &str) -> Option<u16> {
1621    let key = "with status ";
1622    let i = msg.find(key)?;
1623    let tail = &msg[i + key.len()..];
1624    let digits: String = tail.chars().take_while(|c| c.is_ascii_digit()).collect();
1625    digits.parse::<u16>().ok()
1626}
1627
1628#[cfg(test)]
1629mod parse_status_tests {
1630    use super::parse_status_from_error;
1631
1632    #[test]
1633    fn extracts_status_code() {
1634        assert_eq!(parse_status_from_error("Upload failed with status 500 Internal Server Error: x"), Some(500));
1635        assert_eq!(parse_status_from_error("Upload failed with status 413 Payload Too Large"), Some(413));
1636        assert_eq!(parse_status_from_error("Upload failed with status 415"), Some(415));
1637        // Cloudflare gateway timeouts render as "<unknown status code>" — the failover branch relies
1638        // on this still parsing to the numeric code.
1639        assert_eq!(parse_status_from_error("Upload failed with status 524 <unknown status code>: gateway"), Some(524));
1640    }
1641
1642    #[test]
1643    fn returns_none_when_absent() {
1644        assert_eq!(parse_status_from_error("network error: timeout"), None);
1645    }
1646}
1647
1648#[cfg(test)]
1649mod network_failure_tests {
1650    use super::upload_failure;
1651    use crate::blossom_error::UploadFailure;
1652    use crate::net::HttpError;
1653    use crate::transport::{ConnectError, Refusal};
1654
1655    /// Only a network that comes back is waited for: a replaced account never does, and a policy
1656    /// refusal is that server's final answer.
1657    #[test]
1658    fn only_a_returning_network_is_waited_for() {
1659        assert!(matches!(upload_failure(HttpError::NetworkChanged), UploadFailure::Network(_)));
1660        assert!(matches!(upload_failure(HttpError::Refused(ConnectError::NotReady(None))), UploadFailure::Network(_)));
1661        assert!(matches!(upload_failure(HttpError::Refused(ConnectError::Stale)), UploadFailure::Other(_)));
1662        assert!(matches!(upload_failure(HttpError::Refused(ConnectError::Refused(Refusal::ExitOff))), UploadFailure::Other(_)));
1663    }
1664}
1665
1666#[cfg(test)]
1667mod plaintext_tests {
1668    use super::plaintext_matches;
1669
1670    const HASH: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
1671    const OTHER: &str = "0000000000000000000000000000000000000000000000000000000000000000";
1672
1673    /// A GIF link or a pasted file names no hash: what it serves is taken, as any link is.
1674    #[test]
1675    fn a_link_that_names_no_hash_is_taken_as_served() {
1676        assert!(plaintext_matches("https://media.example/party.gif", None, HASH));
1677    }
1678
1679    #[test]
1680    fn a_blob_address_and_a_claim_each_bind_the_bytes() {
1681        let blob = format!("https://blossom.example/{HASH}.xdc");
1682        assert!(plaintext_matches(&blob, None, HASH));
1683        assert!(!plaintext_matches(&blob, None, OTHER), "the server's own address");
1684        assert!(plaintext_matches("https://media.example/app.xdc", Some(HASH), HASH));
1685        assert!(!plaintext_matches("https://media.example/app.xdc", Some(OTHER), HASH), "the sender's claim");
1686        assert!(!plaintext_matches(&blob, Some(OTHER), HASH), "both, when both are there");
1687    }
1688}
1689
1690#[cfg(test)]
1691mod hash_swap_tests {
1692    use super::hash_swap_candidates;
1693
1694    const HASH: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
1695
1696    #[test]
1697    fn derives_clean_leaves_and_skips_the_source_origin() {
1698        // Query + fragment on the primary must NOT leak into derived URLs,
1699        // the source origin is skipped, junk servers are dropped.
1700        let primary = format!("https://a.example/{}.png?utm=track#frag", HASH);
1701        let servers = vec![
1702            "https://a.example".to_string(),
1703            "https://b.example".to_string(),
1704            "not a url".to_string(),
1705        ];
1706        assert_eq!(
1707            hash_swap_candidates(&primary, &servers),
1708            vec![format!("https://b.example/{}.png", HASH)],
1709        );
1710    }
1711
1712    #[test]
1713    fn extensionless_primary_yields_the_bare_hash() {
1714        let primary = format!("https://a.example/{}", HASH);
1715        assert_eq!(
1716            hash_swap_candidates(&primary, &["https://b.example/".to_string()]),
1717            vec![format!("https://b.example/{}", HASH)],
1718        );
1719    }
1720
1721    #[test]
1722    fn unparseable_primary_yields_nothing() {
1723        assert!(hash_swap_candidates("https://a.example/not-a-hash.png", &["https://b.example".to_string()]).is_empty());
1724    }
1725}
1726
1727#[cfg(test)]
1728mod hash_extract_tests {
1729    use super::extract_hash_from_blossom_url;
1730
1731    const HASH_HEX: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
1732
1733    #[test]
1734    fn plain_url() {
1735        let url = format!("https://srv.example/{}", HASH_HEX);
1736        assert!(extract_hash_from_blossom_url(&url).is_some());
1737    }
1738
1739    #[test]
1740    fn with_extension() {
1741        let url = format!("https://srv.example/{}.jpg", HASH_HEX);
1742        assert!(extract_hash_from_blossom_url(&url).is_some());
1743    }
1744
1745    #[test]
1746    fn trailing_slash_still_resolves() {
1747        // Some servers append a trailing slash to the descriptor URL.
1748        let url = format!("https://srv.example/{}/", HASH_HEX);
1749        assert!(extract_hash_from_blossom_url(&url).is_some());
1750    }
1751
1752    #[test]
1753    fn malformed_returns_none() {
1754        assert!(extract_hash_from_blossom_url("https://srv.example/").is_none());
1755        assert!(extract_hash_from_blossom_url("not a url").is_none());
1756        assert!(extract_hash_from_blossom_url("https://srv.example/notahash").is_none());
1757    }
1758
1759    #[test]
1760    fn x_sha256_simd_hex_matches_lowerhex() {
1761        use bitcoin_hashes::sha256::Hash as Sha256Hash;
1762        // The X-SHA-256 header swapped format!("{:x}") for the SIMD encoder; they MUST agree
1763        // byte-for-byte (sha256::Hash displays in forward order — a reversed-display hash type would
1764        // silently corrupt the upload header).
1765        let hash = Sha256Hash::hash(b"vector blossom x-sha-256 parity check");
1766        assert_eq!(
1767            crate::simd::hex::bytes_to_hex_32(&hash.to_byte_array()),
1768            format!("{:x}", hash),
1769        );
1770    }
1771}
1772
1773#[cfg(test)]
1774mod mirror_target_tests {
1775    use super::mirror_targets;
1776
1777    /// `parse_blob_url` demands a full 64-hex SHA-256, so the fixture carries
1778    /// a real one; a truncated hash makes every call return no targets.
1779    const BLOB: &str = "3ad3648700bc0000000000000000000000000000000000000000000000000000.bin";
1780
1781    fn servers(v: &[&str]) -> Vec<String> {
1782        v.iter().map(|s| s.to_string()).collect()
1783    }
1784
1785    fn names(t: Vec<url::Url>) -> Vec<String> {
1786        t.into_iter().map(|u| u.host_str().unwrap_or("").to_string()).collect()
1787    }
1788
1789    #[test]
1790    fn the_server_that_accepted_the_upload_is_not_a_mirror_target() {
1791        // The case observed in production: the bytes went to the regional
1792        // ingress name and the descriptor came back on the origin's canonical
1793        // name. Both are the same server, and neither is worth mirroring to.
1794        // Comparing the descriptor's host alone does NOT catch this — the two
1795        // strings differ — which is why the accepting address is passed in.
1796        let t = mirror_targets(
1797            &format!("https://magnitude.jskitty.com/{BLOB}"),
1798            &servers(&["https://asia.magnitude.jskitty.com", "https://blossom.band"]),
1799            2,
1800            &["https://asia.magnitude.jskitty.com".to_string()],
1801        );
1802        assert_eq!(names(t), vec!["blossom.band"]);
1803    }
1804
1805    #[test]
1806    fn genuinely_different_servers_are_still_mirrored_to() {
1807        let t = mirror_targets(
1808            &format!("https://magnitude.jskitty.com/{BLOB}"),
1809            &servers(&["https://blossom.band", "https://nostr.download"]),
1810            2,
1811            &["https://asia.magnitude.jskitty.com".to_string()],
1812        );
1813        assert_eq!(names(t), vec!["blossom.band", "nostr.download"]);
1814    }
1815
1816    #[test]
1817    fn the_source_origin_is_excluded_even_with_nothing_passed_in() {
1818        // The pre-existing guarantee, unchanged by the new argument.
1819        let t = mirror_targets(
1820            &format!("https://magnitude.jskitty.com/{BLOB}"),
1821            &servers(&["https://magnitude.jskitty.com", "https://blossom.band"]),
1822            2,
1823            &[],
1824        );
1825        assert_eq!(names(t), vec!["blossom.band"]);
1826    }
1827
1828    #[test]
1829    fn max_mirrors_is_applied_after_exclusion_not_before() {
1830        // Taking first and filtering second would yield nothing here, and the
1831        // message would ship with no fallback sources at all.
1832        let t = mirror_targets(
1833            &format!("https://magnitude.jskitty.com/{BLOB}"),
1834            &servers(&[
1835                "https://asia.magnitude.jskitty.com",
1836                "https://magnitude.jskitty.com",
1837                "https://blossom.band",
1838            ]),
1839            1,
1840            &["https://asia.magnitude.jskitty.com".to_string()],
1841        );
1842        assert_eq!(names(t), vec!["blossom.band"]);
1843    }
1844
1845    #[test]
1846    fn a_port_or_scheme_difference_is_a_different_server() {
1847        // Origin comparison, not host comparison: a self-hosted server on
1848        // another port is genuinely somewhere else.
1849        let t = mirror_targets(
1850            &format!("https://example.com/{BLOB}"),
1851            &servers(&["https://example.com:8443"]),
1852            2,
1853            &[],
1854        );
1855        assert_eq!(names(t), vec!["example.com"]);
1856    }
1857
1858    #[test]
1859    fn an_unparseable_source_mirrors_nowhere() {
1860        let t = mirror_targets("not a url", &servers(&["https://blossom.band"]), 2, &[]);
1861        assert!(t.is_empty());
1862    }
1863}
1864
1865#[cfg(test)]
1866mod stall_watch_tests {
1867    use super::{Stall, StallWatch};
1868    use std::time::Duration;
1869
1870    const STALL: Duration = Duration::from_secs(60);
1871    const RESPONSE: Duration = Duration::from_secs(300);
1872
1873    #[tokio::test(start_paused = true)]
1874    async fn a_transfer_moving_at_any_rate_is_never_abandoned() {
1875        // One 16 KB chunk every 50 s is under 3 kbit/s, and the watchdog is
1876        // content: 300 s of wall time here would have killed it under a deadline.
1877        let mut w = StallWatch::new(1 << 20, STALL, RESPONSE);
1878        let mut sent = 0u64;
1879        for _ in 0..8 {
1880            crate::rt::time::advance(Duration::from_secs(50)).await;
1881            sent += 16 * 1024;
1882            assert_eq!(w.observe(sent), None);
1883        }
1884    }
1885
1886    #[tokio::test(start_paused = true)]
1887    async fn a_transfer_that_stops_is_abandoned_after_the_window() {
1888        let mut w = StallWatch::new(1 << 20, STALL, RESPONSE);
1889        assert_eq!(w.observe(4096), None);
1890        crate::rt::time::advance(Duration::from_secs(59)).await;
1891        assert_eq!(w.observe(4096), None, "inside the window it is only slow");
1892        crate::rt::time::advance(Duration::from_secs(2)).await;
1893        assert!(matches!(w.observe(4096), Some(Stall::NoProgress { .. })));
1894    }
1895
1896    #[tokio::test(start_paused = true)]
1897    async fn progress_resets_the_window() {
1898        let mut w = StallWatch::new(1 << 20, STALL, RESPONSE);
1899        w.observe(100);
1900        crate::rt::time::advance(Duration::from_secs(55)).await;
1901        w.observe(200);
1902        crate::rt::time::advance(Duration::from_secs(55)).await;
1903        assert_eq!(w.observe(200), None, "the clock restarted at the second byte");
1904    }
1905
1906    #[tokio::test(start_paused = true)]
1907    async fn after_the_last_byte_the_server_gets_longer_but_not_forever() {
1908        let total = 1 << 20;
1909        let mut w = StallWatch::new(total, STALL, RESPONSE);
1910        w.observe(total);
1911        // Long enough for a relay to push a large blob to its origin.
1912        crate::rt::time::advance(Duration::from_secs(240)).await;
1913        assert_eq!(w.observe(total), None, "buffers drain and the blob is stored");
1914        crate::rt::time::advance(Duration::from_secs(61)).await;
1915        assert!(matches!(w.observe(total), Some(Stall::NoResponse { .. })));
1916    }
1917
1918    #[tokio::test(start_paused = true)]
1919    async fn an_empty_upload_is_waiting_on_the_server_from_the_start() {
1920        let mut w = StallWatch::new(0, STALL, RESPONSE);
1921        crate::rt::time::advance(STALL + Duration::from_secs(1)).await;
1922        assert_eq!(w.observe(0), None, "nothing to send is not a stall");
1923        crate::rt::time::advance(RESPONSE).await;
1924        assert!(matches!(w.observe(0), Some(Stall::NoResponse { .. })));
1925    }
1926}
1927
1928#[cfg(test)]
1929mod auth_tests {
1930    use super::*;
1931    use nostr_sdk::prelude::{FinalizeUnsignedEvent, Keys};
1932
1933    const HASH: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
1934
1935    fn tags(verb: &str, scope: AuthScope<'_>) -> String {
1936        let exp = Timestamp::from(1_900_000_000);
1937        let event = auth_event(verb, scope, "c", exp).finalize_unsigned(Keys::generate().public_key());
1938        assert_eq!(event.kind, Kind::BlossomAuth);
1939        serde_json::to_string(&event.tags).unwrap()
1940    }
1941
1942    #[test]
1943    fn auth_event_tags_follow_bud01() {
1944        let hash: Sha256Hash = HASH.parse().unwrap();
1945        let url: Url = "https://blossom.example.com/".parse().unwrap();
1946        assert_eq!(
1947            tags("upload", AuthScope::Blob(hash)),
1948            format!(r#"[["x","{HASH}"],["expiration","1900000000"],["t","upload"]]"#)
1949        );
1950        assert_eq!(
1951            tags("get", AuthScope::Server(&url)),
1952            r#"[["server","https://blossom.example.com/"],["expiration","1900000000"],["t","get"]]"#
1953        );
1954    }
1955
1956    #[test]
1957    fn blob_descriptor_needs_only_url_and_hash() {
1958        let full = format!(r#"{{"url":"https://cdn.example.com/x.bin","sha256":"{HASH}","size":3,"type":"application/octet-stream","uploaded":1700000000}}"#);
1959        let bare = format!(r#"{{"url":"https://cdn.example.com/x.bin","sha256":"{HASH}"}}"#);
1960        for json in [full, bare] {
1961            let d: BlobDescriptor = serde_json::from_str(&json).unwrap();
1962            assert_eq!(d.sha256.to_string(), HASH);
1963            assert_eq!(d.url.as_str(), "https://cdn.example.com/x.bin");
1964        }
1965        assert!(serde_json::from_str::<BlobDescriptor>(r#"{"url":"https://a/","sha256":"zz"}"#).is_err());
1966    }
1967}