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
14pub type ProgressCallback = std::sync::Arc<dyn Fn(Option<u8>, Option<u64>) -> Result<(), String> + Send + Sync>;
16
17#[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#[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 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#[derive(Clone)]
65pub enum UploadBody {
66 Memory(Arc<Vec<u8>>),
67 File { path: std::path::PathBuf, len: u64, sha256: Sha256Hash },
70}
71
72impl UploadBody {
73 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 #[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 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
137const RESPONSE_WAIT: std::time::Duration = std::time::Duration::from_secs(300);
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150enum Stall {
151 NoProgress { idle: std::time::Duration },
153 NoResponse { waited: std::time::Duration },
155}
156
157struct 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 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
195fn callback_failure(e: String) -> UploadFailure {
199 if e == "Upload cancelled" {
200 UploadFailure::Cancelled
201 } else {
202 UploadFailure::Other(e)
203 }
204}
205
206async 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 #[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 #[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
305const MAX_NETWORK_WAITS: u32 = 8;
307
308fn 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 UploadFailure::Other(e.to_string())
317 } else {
318 UploadFailure::Transport(format!("Upload request failed: {}", e))
319 }
320}
321
322pub(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
338pub(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#[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#[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#[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 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 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 UploadFailure::Refused(r) => r.worth_retrying_here(),
477 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 Err(last_error.unwrap_or_else(|| UploadFailure::Other("No upload attempts were made".to_string())))
512}
513
514enum Preflight {
516 Proceed,
518 AlreadyStored(String),
521}
522
523async 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 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 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 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
643async 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
652async 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 let auth_header = build_auth_header(&signer, hash).await.map_err(UploadFailure::Other)?;
675
676 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 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 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 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
746pub 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 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 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 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
821pub 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
829async 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
851async 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
866fn 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
885pub 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#[derive(Debug, Clone, PartialEq, Eq)]
955pub struct AcceptedUpload {
956 pub url: String,
957 pub server: String,
958}
959
960pub 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 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#[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#[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 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 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 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 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 _ => {}
1117 }
1118 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
1135async 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
1147pub 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 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 Err(format!("Blossom DELETE failed with status {}: {}", status, body))
1185 }
1186}
1187
1188pub 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
1207pub fn blob_hash(url_str: &str) -> Option<String> {
1210 parse_blob_url(url_str).ok().map(|(_, hash)| hash.to_string())
1211}
1212
1213pub 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
1220pub 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
1228pub 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 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
1260pub 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 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
1294pub 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 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
1353fn 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
1394pub 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 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
1446pub 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 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 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 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
1488pub 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 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 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 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 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 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
1608fn 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
1617fn 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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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}