Skip to main content

ant_core/data/client/
batch.rs

1//! Batch chunk upload with wave-based pipelined EVM payments.
2//!
3//! Groups chunks into waves of 64 and pays for each
4//! wave in a single EVM transaction. Stores from wave N are pipelined
5//! with quote collection for wave N+1 via `tokio::join!`.
6
7use crate::data::client::adaptive::observe_op;
8use crate::data::client::classify_error;
9use crate::data::client::file::UploadEvent;
10use crate::data::client::payment::{peer_id_to_encoded, SINGLE_NODE_PAYMENT_MULTIPLIER};
11use crate::data::client::Client;
12use crate::data::error::{Error, PartialUploadSpend, Result};
13use ant_protocol::evm::{
14    Amount, EncodedPeerId, PayForQuotesError, PaymentQuote, ProofOfPayment, QuoteHash,
15    RewardsAddress, TxHash, Wallet,
16};
17use ant_protocol::payment::{
18    deserialize_proof, serialize_single_node_proof, PaymentProof, QuotePaymentInfo,
19};
20use ant_protocol::transport::{MultiAddr, PeerId};
21use ant_protocol::{compute_address, XorName, CLOSE_GROUP_SIZE, DATA_TYPE_CHUNK};
22use bytes::Bytes;
23use futures::stream::{self, FuturesUnordered, StreamExt};
24use std::collections::{HashMap, HashSet};
25use std::time::{Duration, Instant};
26use tokio::sync::mpsc;
27use tracing::{debug, info, warn};
28
29/// Number of chunks per payment wave.
30const PAYMENT_WAVE_SIZE: usize = 64;
31
32/// Soft ceiling on the combined body size of chunks stored concurrently in a
33/// single wave. Caps store concurrency for large chunks so the send path's
34/// per-peer body buffers can't pin multiple GB at once (see V2-461). At ~4 MB
35/// chunks this permits ~16 concurrent stores; small chunks hit the chunk-count
36/// / adaptive limits instead and are unaffected.
37const STORE_INFLIGHT_BYTE_BUDGET: usize = 64 * 1024 * 1024;
38
39/// Variable-size single-node payment plan for a chunk.
40///
41/// The shared `ant-protocol::payment::SingleNodePayment` helper still models
42/// the legacy fixed `CLOSE_GROUP_SIZE` quote set. Node-side verification now
43/// accepts any non-empty quote bundle up to `CLOSE_GROUP_SIZE`, so the client
44/// keeps the same 3x-median payment rule while allowing the single-node path to
45/// proceed with as few as one valid quote.
46#[derive(Debug, Clone)]
47pub struct SingleNodeQuotePayment {
48    /// Quotes sorted by price; the median-priced quote receives 3x payment and
49    /// the rest receive zero.
50    pub quotes: Vec<QuotePaymentInfo>,
51}
52
53impl SingleNodeQuotePayment {
54    /// Build a single-node payment from one or more quotes.
55    ///
56    /// The quotes are sorted by price, the median quote receives 3x its quoted
57    /// price, and every other quote is included with a zero amount so proof and
58    /// payment intent construction stay aligned.
59    pub fn from_quotes(mut quotes: Vec<PaymentQuote>) -> Result<Self> {
60        let quote_count = quotes.len();
61        if !(1..=CLOSE_GROUP_SIZE).contains(&quote_count) {
62            return Err(Error::Payment(format!(
63                "Single-node payment requires 1..={CLOSE_GROUP_SIZE} quotes, got {quote_count}"
64            )));
65        }
66
67        quotes.sort_by_key(|quote| quote.price);
68        let median_index = quote_count / 2;
69        let median_price = quotes[median_index].price;
70        let enhanced_price = median_price
71            .checked_mul(Amount::from(SINGLE_NODE_PAYMENT_MULTIPLIER))
72            .ok_or_else(|| {
73                Error::Payment("Price overflow when calculating 3x median".to_string())
74            })?;
75
76        let quotes = quotes
77            .into_iter()
78            .enumerate()
79            .map(|(idx, quote)| {
80                let quote_hash = quote.hash();
81                QuotePaymentInfo {
82                    quote_hash,
83                    rewards_address: quote.rewards_address,
84                    amount: if idx == median_index {
85                        enhanced_price
86                    } else {
87                        Amount::ZERO
88                    },
89                    price: quote.price,
90                }
91            })
92            .collect();
93
94        Ok(Self { quotes })
95    }
96
97    /// Total on-chain amount paid by this single-node payment.
98    #[must_use]
99    pub fn total_amount(&self) -> Amount {
100        self.quotes.iter().map(|q| q.amount).sum()
101    }
102
103    /// Pay the non-zero median quote on-chain, returning tx hashes for the
104    /// non-zero entries that must appear in the payment proof.
105    pub async fn pay(&self, wallet: &Wallet) -> Result<Vec<TxHash>> {
106        let quote_payments: Vec<_> = self
107            .quotes
108            .iter()
109            .map(|q| (q.quote_hash, q.rewards_address, q.amount))
110            .collect();
111
112        let (tx_hashes, _gas_info) =
113            wallet
114                .pay_for_quotes(quote_payments)
115                .await
116                .map_err(|PayForQuotesError(err, _)| {
117                    Error::Payment(format!("Failed to pay for quotes: {err}"))
118                })?;
119
120        let mut result_hashes = Vec::new();
121        for quote_info in &self.quotes {
122            if !quote_info.amount.is_zero() {
123                let tx_hash = tx_hashes.get(&quote_info.quote_hash).ok_or_else(|| {
124                    Error::Payment(format!(
125                        "Missing transaction hash for non-zero quote {}",
126                        quote_info.quote_hash
127                    ))
128                })?;
129                result_hashes.push(*tx_hash);
130            }
131        }
132
133        Ok(result_hashes)
134    }
135}
136
137/// Chunk quoted but not yet paid. Produced by [`Client::prepare_chunk_payment`].
138#[derive(Debug)]
139pub struct PreparedChunk {
140    /// The chunk content bytes.
141    pub content: Bytes,
142    /// Content address (BLAKE3 hash).
143    pub address: XorName,
144    /// Ordered PUT targets from quote planning.
145    ///
146    /// Kept under the legacy `quoted_peers` name for API compatibility; the
147    /// list can include non-quoted fallback peers beyond the quoted close
148    /// group.
149    pub quoted_peers: Vec<(PeerId, Vec<MultiAddr>)>,
150    /// Payment structure (quotes sorted, median selected, not yet paid on-chain).
151    pub payment: SingleNodeQuotePayment,
152    /// Peer quotes for building `ProofOfPayment`.
153    pub peer_quotes: Vec<(EncodedPeerId, PaymentQuote)>,
154    /// ADR-0004: the signed commitments the bound quotes shipped, forwarded as
155    /// sidecars in the PUT bundle so storers cross-check synchronously. Empty
156    /// when every quote was baseline (no commitment to pin).
157    pub commitment_sidecars: Vec<Vec<u8>>,
158}
159
160/// Chunk paid but not yet stored. Produced by [`Client::batch_pay`].
161#[derive(Debug, Clone)]
162pub struct PaidChunk {
163    /// The chunk content bytes.
164    pub content: Bytes,
165    /// Content address (BLAKE3 hash).
166    pub address: XorName,
167    /// Ordered PUT targets from quote planning.
168    ///
169    /// Kept under the legacy `quoted_peers` name for API compatibility; the
170    /// list can include non-quoted fallback peers beyond the quoted close
171    /// group.
172    pub quoted_peers: Vec<(PeerId, Vec<MultiAddr>)>,
173    /// Serialized [`PaymentProof`] bytes.
174    pub proof_bytes: Vec<u8>,
175}
176
177/// Result of storing a wave of paid chunks, with retry tracking.
178#[derive(Debug)]
179pub struct WaveResult {
180    /// Successfully stored chunk addresses.
181    pub stored: Vec<XorName>,
182    /// Chunks that failed to store after all retries.
183    pub failed: Vec<(XorName, String)>,
184    /// Sum of store-RPC attempts across all chunks in this wave (>= stored.len() + failed.len()).
185    pub chunk_attempts_total: usize,
186    /// Per-chunk wall-clock (ms) from first attempt to successful store. Only populated for stored chunks.
187    pub store_durations_ms: Vec<u64>,
188    /// Histogram of which retry-round each stored chunk succeeded on (index 0 = first attempt).
189    pub retries_per_chunk: Vec<u32>,
190}
191
192/// Aggregated retry / wall-clock stats across one or more [`WaveResult`]s.
193///
194/// Used by [`Client::batch_upload_chunks_with_events`] (which may store
195/// multiple waves per call) and surfaced upward into `FileUploadResult` so
196/// downstream tooling can record per-upload retry pressure and per-chunk
197/// store wall-clock without needing log parsing.
198#[derive(Debug, Default, Clone)]
199pub struct WaveAggregateStats {
200    /// Sum of store-RPC attempts across all waves (>= chunks_stored).
201    pub chunk_attempts_total: usize,
202    /// Per-chunk wall-clock (ms) from first attempt to successful store,
203    /// concatenated across waves.
204    pub store_durations_ms: Vec<u64>,
205    /// Count of stored chunks that succeeded on each retry round
206    /// (index 0 = first attempt, 1 = first retry, etc.). Indices match
207    /// the retry rounds emitted by `Client::store_paid_chunks_with_events`
208    /// which caps at `MAX_RETRIES = 3`, so an array of 4 suffices.
209    pub retries_histogram: [usize; 4],
210}
211
212impl WaveAggregateStats {
213    /// Fold one [`WaveResult`]'s stats into the running aggregate.
214    pub fn absorb(&mut self, wave: &WaveResult) {
215        self.chunk_attempts_total = self
216            .chunk_attempts_total
217            .saturating_add(wave.chunk_attempts_total);
218        self.store_durations_ms.extend(&wave.store_durations_ms);
219        for &r in &wave.retries_per_chunk {
220            let idx = (r as usize).min(self.retries_histogram.len() - 1);
221            self.retries_histogram[idx] = self.retries_histogram[idx].saturating_add(1);
222        }
223    }
224}
225
226/// Compute a percentile from an unsorted slice of `u64` values.
227///
228/// `p` is in `[0.0, 1.0]`. Returns 0 for an empty slice. Uses nearest-rank;
229/// callers don't need numerical precision here — these are coarse log/metric
230/// summaries.
231fn percentile(values: &[u64], p: f64) -> u64 {
232    if values.is_empty() {
233        return 0;
234    }
235    let mut sorted = values.to_vec();
236    sorted.sort_unstable();
237    let p = p.clamp(0.0, 1.0);
238    // Nearest-rank: ceil(p * n) - 1, clamped to [0, n-1].
239    let n = sorted.len();
240    #[allow(
241        clippy::cast_possible_truncation,
242        clippy::cast_sign_loss,
243        clippy::cast_precision_loss
244    )]
245    let rank = ((p * n as f64).ceil() as usize)
246        .saturating_sub(1)
247        .min(n - 1);
248    sorted[rank]
249}
250
251/// Payment data for external signing.
252///
253/// Contains the information needed to construct and submit the on-chain
254/// payment transaction without requiring a local wallet or private key.
255#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
256pub struct PaymentIntent {
257    /// Individual payment entries: (quote_hash, rewards_address, amount).
258    pub payments: Vec<(QuoteHash, RewardsAddress, Amount)>,
259    /// Total amount across all payments.
260    pub total_amount: Amount,
261}
262
263impl PaymentIntent {
264    /// Build from a set of prepared chunks.
265    ///
266    /// Collects all non-zero payment entries and computes the total.
267    pub fn from_prepared_chunks(prepared: &[PreparedChunk]) -> Self {
268        let mut payments = Vec::new();
269        let mut total = Amount::ZERO;
270        for chunk in prepared {
271            for info in &chunk.payment.quotes {
272                if !info.amount.is_zero() {
273                    payments.push((info.quote_hash, info.rewards_address, info.amount));
274                    total += info.amount;
275                }
276            }
277        }
278        Self {
279            payments,
280            total_amount: total,
281        }
282    }
283}
284
285/// Build [`PaidChunk`]s from prepared chunks and externally-provided transaction hashes.
286///
287/// Shared by [`Client::batch_pay`] (wallet flow) and [`finalize_batch_payment`] (external signer).
288///
289/// Returns an error if any non-zero-amount quote hash is missing from `tx_hash_map`,
290/// since chunks uploaded without valid proofs would be rejected by the network.
291fn build_paid_chunks(
292    prepared: Vec<PreparedChunk>,
293    tx_hash_map: &HashMap<QuoteHash, TxHash>,
294) -> Result<Vec<PaidChunk>> {
295    let mut paid_chunks = Vec::with_capacity(prepared.len());
296    for chunk in prepared {
297        let mut tx_hashes = Vec::new();
298        for info in &chunk.payment.quotes {
299            if !info.amount.is_zero() {
300                let tx_hash = tx_hash_map.get(&info.quote_hash).copied().ok_or_else(|| {
301                    Error::Payment(format!(
302                        "Missing tx hash for quote {} — external signer did not return a receipt for this payment",
303                        hex::encode(info.quote_hash)
304                    ))
305                })?;
306                tx_hashes.push(tx_hash);
307            }
308        }
309
310        let proof = PaymentProof {
311            proof_of_payment: ProofOfPayment {
312                peer_quotes: chunk.peer_quotes,
313            },
314            tx_hashes,
315            // ADR-0004: forward the bound quotes' commitments so storers
316            // cross-check synchronously; stripped before persistence node-side.
317            commitment_sidecars: chunk.commitment_sidecars,
318        };
319
320        let proof_bytes = serialize_single_node_proof(&proof)
321            .map_err(|e| Error::Serialization(format!("Failed to serialize payment proof: {e}")))?;
322
323        paid_chunks.push(PaidChunk {
324            content: chunk.content,
325            address: chunk.address,
326            quoted_peers: chunk.quoted_peers,
327            proof_bytes,
328        });
329    }
330    Ok(paid_chunks)
331}
332
333/// Finalize a batch payment using externally-provided transaction hashes.
334///
335/// Takes prepared chunks and a map of `quote_hash -> tx_hash` from the
336/// external signer. Builds per-chunk `PaymentProof` bytes without needing a wallet.
337pub fn finalize_batch_payment(
338    prepared: Vec<PreparedChunk>,
339    tx_hash_map: &HashMap<QuoteHash, TxHash>,
340) -> Result<Vec<PaidChunk>> {
341    build_paid_chunks(prepared, tx_hash_map)
342}
343
344impl Client {
345    /// Prepare a single chunk for batch payment.
346    ///
347    /// Collects quotes and uses node-reported prices without making any
348    /// on-chain transaction. Returns `Ok(None)` if the chunk is already
349    /// stored on the network.
350    ///
351    /// # Errors
352    ///
353    /// Returns an error if quote collection or payment construction fails.
354    pub async fn prepare_chunk_payment(&self, content: Bytes) -> Result<Option<PreparedChunk>> {
355        let address = compute_address(&content);
356        let data_size = u64::try_from(content.len())
357            .map_err(|e| Error::InvalidData(format!("content size too large: {e}")))?;
358
359        let quote_plan = match self
360            .get_store_quote_plan(&address, data_size, DATA_TYPE_CHUNK)
361            .await
362        {
363            Ok(plan) => plan,
364            Err(Error::AlreadyStored) => {
365                debug!("Chunk {} already stored, skipping", hex::encode(address));
366                return Ok(None);
367            }
368            Err(e) => return Err(e),
369        };
370        let quotes_with_peers = quote_plan.quotes;
371
372        // Capture the ordered PUT target set for replication. This can be
373        // wider than the peers that supplied the paid quotes.
374        let quoted_peers = quote_plan.put_peers;
375
376        // Build peer_quotes for ProofOfPayment + quotes for single-node payment.
377        // Use node-reported prices directly — no contract price fetch needed.
378        let mut peer_quotes = Vec::with_capacity(quotes_with_peers.len());
379        let mut quotes_for_payment = Vec::with_capacity(quotes_with_peers.len());
380        // ADR-0004: forward each bound quote's commitment sidecar (baseline
381        // quotes ship none); `get_store_quotes` already verified the binding.
382        let mut commitment_sidecars = Vec::new();
383
384        for (peer_id, _addrs, quote, _price, commitment) in quotes_with_peers {
385            let encoded = peer_id_to_encoded(&peer_id)?;
386            peer_quotes.push((encoded, quote.clone()));
387            quotes_for_payment.push(quote);
388            if let Some(sidecar) = commitment {
389                commitment_sidecars.push(sidecar);
390            }
391        }
392
393        let payment = SingleNodeQuotePayment::from_quotes(quotes_for_payment)
394            .map_err(|e| Error::Payment(format!("Failed to create payment: {e}")))?;
395
396        Ok(Some(PreparedChunk {
397            content,
398            address,
399            quoted_peers,
400            payment,
401            peer_quotes,
402            commitment_sidecars,
403        }))
404    }
405
406    /// Pay for multiple chunks in a single EVM transaction.
407    ///
408    /// Flattens all quote payments from the prepared chunks into one
409    /// `wallet.pay_for_quotes()` call, then maps transaction hashes
410    /// back to per-chunk [`PaymentProof`] bytes.
411    ///
412    /// # Errors
413    ///
414    /// Returns an error if the wallet is not configured or the on-chain
415    /// payment fails.
416    /// Returns `(paid_chunks, storage_cost_atto, gas_cost_wei)`.
417    pub async fn batch_pay(
418        &self,
419        prepared: Vec<PreparedChunk>,
420    ) -> Result<(Vec<PaidChunk>, String, u128)> {
421        if prepared.is_empty() {
422            return Ok((Vec::new(), "0".to_string(), 0));
423        }
424
425        let wallet = self.require_wallet()?;
426
427        // Compute total storage cost from the prepared chunks before paying.
428        let intent = PaymentIntent::from_prepared_chunks(&prepared);
429        let storage_cost_atto = intent.total_amount.to_string();
430
431        // Flatten all quote payments from all chunks into a single batch.
432        let total_quotes: usize = prepared.iter().map(|c| c.payment.quotes.len()).sum();
433        let mut all_payments = Vec::with_capacity(total_quotes);
434        for chunk in &prepared {
435            for info in &chunk.payment.quotes {
436                all_payments.push((info.quote_hash, info.rewards_address, info.amount));
437            }
438        }
439
440        debug!(
441            "Batch payment for {} chunks ({} quote entries)",
442            prepared.len(),
443            all_payments.len()
444        );
445
446        let (tx_hash_map, gas_info) =
447            wallet
448                .pay_for_quotes(all_payments)
449                .await
450                .map_err(|PayForQuotesError(err, _)| {
451                    Error::Payment(format!("Batch payment failed: {err}"))
452                })?;
453
454        info!(
455            "Batch payment succeeded: {} transactions",
456            tx_hash_map.len()
457        );
458
459        let tx_hash_map: HashMap<QuoteHash, TxHash> = tx_hash_map.into_iter().collect();
460        let paid_chunks = build_paid_chunks(prepared, &tx_hash_map)?;
461        Ok((paid_chunks, storage_cost_atto, gas_info.gas_cost_wei))
462    }
463
464    /// Upload chunks in waves with pipelined EVM payments.
465    ///
466    /// Processes chunks in waves of `PAYMENT_WAVE_SIZE` (64). Within each wave:
467    /// 1. **Prepare**: collect quotes for all chunks concurrently
468    /// 2. **Pay**: single EVM transaction for the whole wave
469    /// 3. **Store**: concurrent chunk replication to close group
470    ///
471    /// Stores from wave N overlap with quote collection for wave N+1
472    /// via `tokio::join!`.
473    ///
474    /// # Errors
475    ///
476    /// Returns an error if any payment or store operation fails.
477    /// Returns `(addresses, total_storage_cost_atto, total_gas_cost_wei)`.
478    pub async fn batch_upload_chunks(
479        &self,
480        chunks: Vec<Bytes>,
481    ) -> Result<(Vec<XorName>, String, u128)> {
482        let (addresses, storage, gas, _stats) = self
483            .batch_upload_chunks_with_events(chunks, None, 0, 0, None)
484            .await?;
485        Ok((addresses, storage, gas))
486    }
487
488    /// Same as [`Client::batch_upload_chunks`] but sends [`UploadEvent::ChunkStored`]
489    /// events as each chunk is stored, enabling per-chunk progress bars.
490    ///
491    /// `stored_offset` is the number of chunks already stored in previous waves
492    /// (so events report cumulative progress). `file_total` is the total chunk
493    /// count across ALL waves (for the `total` field in events).
494    ///
495    /// When `resume_key` is `Some`, per-wave payment proofs are persisted
496    /// to `<data_dir>/payments/single/<ts>_<hash(resume_key)>` via
497    /// `crate::data::client::cached_single` so that a partial-upload
498    /// failure can be resumed on the next attempt without paying twice.
499    /// The caller is responsible for deleting the cache entry on full
500    /// success (typically `upload_with_options` in `file.rs`).
501    pub async fn batch_upload_chunks_with_events(
502        &self,
503        chunks: Vec<Bytes>,
504        progress: Option<&mpsc::Sender<UploadEvent>>,
505        stored_offset: usize,
506        file_total: usize,
507        resume_key: Option<&str>,
508    ) -> Result<(Vec<XorName>, String, u128, WaveAggregateStats)> {
509        if chunks.is_empty() {
510            return Ok((
511                Vec::new(),
512                "0".to_string(),
513                0,
514                WaveAggregateStats::default(),
515            ));
516        }
517
518        let total_chunks = chunks.len();
519        let quote_cap = self.controller().quote.current();
520        let store_cap = self.controller().store.current();
521        debug!(
522            "Batch uploading {total_chunks} chunks in waves of {PAYMENT_WAVE_SIZE} \
523             (current adaptive caps — quote: {quote_cap}, store: {store_cap})"
524        );
525
526        // Load any previously-cached single-node receipt for this
527        // upload. Each chunk whose address is in the cache will skip
528        // the quote + pay phases and have its `PaidChunk` constructed
529        // directly from the cached proof + fresh quoted peers. The
530        // caller is responsible for deleting the cache on full
531        // success; we only read here, never write the load result back.
532        //
533        // Before trusting any cached proof, decode it locally and drop
534        // any whose quote.timestamp is past the storer's per-quote age
535        // budget (`QUOTE_MAX_AGE_SECS`, mirrored here as
536        // `CACHED_PROOF_EXPIRY_SECS`). The previous design trusted a
537        // substring match on remote error text, which a Byzantine
538        // storer could spoof to force double-payment. Local pre-flight
539        // is decision-pure: we never hand a doomed proof to a storer,
540        // and the cache is updated under our own lock with no remote
541        // text involved.
542        // Load only the cached PROOFS (for reuse). The cost this function
543        // returns is a per-call DELTA — what was freshly paid in THIS call —
544        // not the cache's cumulative. The single-node wave driver
545        // (`upload_spill_addresses_single`) calls this once per wave and SUMS
546        // the per-call costs, so seeding the return with the cumulative cache
547        // (which grows as each wave appends to it) double-counts:
548        // A + (A+B) + (A+B+C) instead of A+B+C.
549        let cached_proofs: HashMap<XorName, Vec<u8>> = match resume_key {
550            Some(key) => match crate::data::client::cached_single::try_load_for_file(key) {
551                Some((_, receipt)) => prune_locally_expired_proofs(key, receipt.proofs),
552                None => HashMap::new(),
553            },
554            None => HashMap::new(),
555        };
556
557        let mut all_addresses = Vec::with_capacity(total_chunks);
558        let mut seen_addresses: HashSet<XorName> = HashSet::new();
559
560        // Accumulate only THIS call's freshly-paid cost (per-call delta; see
561        // the proof-load comment above for why this must not include the cache).
562        let mut total_storage = Amount::ZERO;
563        let mut total_gas: u128 = 0;
564        let mut agg_stats = WaveAggregateStats::default();
565
566        // Deduplicate chunks by content address.
567        let mut unique_chunks = Vec::with_capacity(total_chunks);
568        for chunk in chunks {
569            let address = compute_address(&chunk);
570            if seen_addresses.insert(address) {
571                unique_chunks.push(chunk);
572            } else {
573                debug!("Skipping duplicate chunk {}", hex::encode(address));
574                all_addresses.push(address);
575                if let Some(tx) = progress {
576                    let _ = tx.try_send(UploadEvent::ChunkStored {
577                        stored: stored_offset + all_addresses.len(),
578                        total: file_total,
579                    });
580                }
581            }
582        }
583
584        // Split into waves.
585        let waves: Vec<Vec<Bytes>> = unique_chunks
586            .chunks(PAYMENT_WAVE_SIZE)
587            .map(<[Bytes]>::to_vec)
588            .collect();
589        let wave_count = waves.len();
590
591        debug!(
592            "{total_chunks} chunks -> {} unique -> {wave_count} waves",
593            seen_addresses.len()
594        );
595
596        let mut pending_store: Option<Vec<PaidChunk>> = None;
597        let mut total_quoted: usize = 0;
598
599        for (wave_idx, wave_chunks) in waves.into_iter().enumerate() {
600            let wave_num = wave_idx + 1;
601            let wave_size = wave_chunks.len();
602
603            // Pipeline: store previous wave while preparing this one.
604            let (prepare_result, store_result) = match pending_store.take() {
605                Some(paid_chunks) => {
606                    let store_offset = stored_offset + all_addresses.len();
607                    let quoted_offset = stored_offset + total_quoted;
608                    let (prep, stored) = tokio::join!(
609                        self.prepare_wave(wave_chunks, progress, quoted_offset, file_total),
610                        self.store_paid_chunks_with_events(
611                            paid_chunks,
612                            progress,
613                            store_offset,
614                            file_total
615                        )
616                    );
617                    (prep, Some(stored))
618                }
619                None => {
620                    let quoted_offset = stored_offset + total_quoted;
621                    let result = self
622                        .prepare_wave(wave_chunks, progress, quoted_offset, file_total)
623                        .await;
624                    (result, None)
625                }
626            };
627            total_quoted += wave_size;
628
629            // Track partial progress from previous wave.
630            if let Some(wave_result) = store_result {
631                all_addresses.extend(&wave_result.stored);
632                agg_stats.absorb(&wave_result);
633                if !wave_result.failed.is_empty() {
634                    let failed_count = wave_result.failed.len();
635                    warn!("{failed_count} chunks failed to store after retries");
636                    return Err(Error::PartialUpload {
637                        stored: all_addresses.clone(),
638                        stored_count: stored_offset + all_addresses.len(),
639                        failed: wave_result.failed,
640                        failed_count,
641                        total_chunks: file_total,
642                        spend: Box::new(PartialUploadSpend {
643                            storage_cost_atto: total_storage.to_string(),
644                            gas_cost_wei: total_gas,
645                        }),
646                        reason: "wave store failed after retries".into(),
647                    });
648                }
649            }
650
651            let (prepared_chunks, already_stored) = prepare_result?;
652            all_addresses.extend(&already_stored);
653            if let Some(tx) = progress {
654                for _ in &already_stored {
655                    let _ = tx.try_send(UploadEvent::ChunkStored {
656                        stored: stored_offset + all_addresses.len(),
657                        total: file_total,
658                    });
659                }
660            }
661
662            if prepared_chunks.is_empty() {
663                info!("Wave {wave_num}/{wave_count}: all chunks already stored");
664                continue;
665            }
666
667            // Split prepared chunks into "already paid in a previous
668            // attempt" (cached) and "needs payment" (fresh). Cached
669            // chunks build a `PaidChunk` from the cached proof + the
670            // freshly-quoted peers, bypassing the EVM transaction.
671            let mut needs_pay: Vec<PreparedChunk> = Vec::with_capacity(prepared_chunks.len());
672            let mut cached_paid: Vec<PaidChunk> = Vec::new();
673            for prep in prepared_chunks {
674                if let Some(proof_bytes) = cached_proofs.get(&prep.address).cloned() {
675                    cached_paid.push(PaidChunk {
676                        content: prep.content,
677                        address: prep.address,
678                        quoted_peers: prep.quoted_peers,
679                        proof_bytes,
680                    });
681                } else {
682                    needs_pay.push(prep);
683                }
684            }
685            if !cached_paid.is_empty() {
686                info!(
687                    "Wave {wave_num}/{wave_count}: reusing {} cached payment proofs",
688                    cached_paid.len()
689                );
690            }
691
692            let (mut paid_chunks, wave_storage, wave_gas) = if needs_pay.is_empty() {
693                (Vec::new(), "0".to_string(), 0u128)
694            } else {
695                info!(
696                    "Wave {wave_num}/{wave_count}: paying for {} chunks",
697                    needs_pay.len()
698                );
699                self.batch_pay(needs_pay).await?
700            };
701            if let Ok(cost) = wave_storage.parse::<Amount>() {
702                total_storage += cost;
703            }
704            total_gas = total_gas.saturating_add(wave_gas);
705
706            // Persist the freshly-paid wave's proofs so a later
707            // failure can resume without re-paying.
708            if let Some(key) = resume_key {
709                if !paid_chunks.is_empty() {
710                    let new_proofs: HashMap<[u8; 32], Vec<u8>> = paid_chunks
711                        .iter()
712                        .map(|pc| (pc.address, pc.proof_bytes.clone()))
713                        .collect();
714                    crate::data::client::cached_single::try_append_wave(
715                        key,
716                        new_proofs,
717                        &wave_storage,
718                        wave_gas,
719                    );
720                }
721            }
722
723            paid_chunks.extend(cached_paid);
724            pending_store = Some(paid_chunks);
725        }
726
727        // Store the last wave.
728        if let Some(paid_chunks) = pending_store {
729            let store_offset = stored_offset + all_addresses.len();
730            let wave_result = self
731                .store_paid_chunks_with_events(paid_chunks, progress, store_offset, file_total)
732                .await;
733            all_addresses.extend(&wave_result.stored);
734            agg_stats.absorb(&wave_result);
735            if !wave_result.failed.is_empty() {
736                let failed_count = wave_result.failed.len();
737                warn!("{failed_count} chunks failed to store after retries (final wave)");
738                return Err(Error::PartialUpload {
739                    stored: all_addresses.clone(),
740                    stored_count: stored_offset + all_addresses.len(),
741                    failed: wave_result.failed,
742                    failed_count,
743                    total_chunks: file_total,
744                    spend: Box::new(PartialUploadSpend {
745                        storage_cost_atto: total_storage.to_string(),
746                        gas_cost_wei: total_gas,
747                    }),
748                    reason: "final wave store failed after retries".into(),
749                });
750            }
751        }
752
753        debug!("Batch upload complete: {} addresses", all_addresses.len());
754        Ok((
755            all_addresses,
756            total_storage.to_string(),
757            total_gas,
758            agg_stats,
759        ))
760    }
761
762    /// Prepare a wave of chunks by collecting quotes concurrently.
763    ///
764    /// Fires [`UploadEvent::ChunkQuoted`] as each chunk's quote completes.
765    /// Returns `(prepared_chunks, already_stored_addresses)`.
766    async fn prepare_wave(
767        &self,
768        chunks: Vec<Bytes>,
769        progress: Option<&mpsc::Sender<UploadEvent>>,
770        quoted_offset: usize,
771        file_total: usize,
772    ) -> Result<(Vec<PreparedChunk>, Vec<XorName>)> {
773        let chunk_count = chunks.len();
774        let chunks_with_addr: Vec<(Bytes, XorName)> = chunks
775            .into_iter()
776            .map(|c| {
777                let addr = compute_address(&c);
778                (c, addr)
779            })
780            .collect();
781
782        let quote_limiter = self.controller().quote.clone();
783        // Batch-aware fan-out: clamp to chunk_count so we never
784        // pay for fan-out slots we cannot fill on a partial wave.
785        // See PERF-RESULTS.md — measured ~30% slowdown when
786        // cap > batch size on quoting workloads (live mainnet).
787        let quote_concurrency = quote_limiter.current().min(chunk_count.max(1));
788        let mut quote_stream = stream::iter(chunks_with_addr)
789            .map(|(content, address)| {
790                let limiter = quote_limiter.clone();
791                async move {
792                    let result = observe_op(
793                        &limiter,
794                        || async move { self.prepare_chunk_payment(content).await },
795                        classify_error,
796                    )
797                    .await;
798                    (address, result)
799                }
800            })
801            .buffer_unordered(quote_concurrency);
802
803        let mut prepared = Vec::with_capacity(chunk_count);
804        let mut already_stored = Vec::new();
805        let mut quoted_count = 0usize;
806
807        while let Some((address, result)) = quote_stream.next().await {
808            let chunk_already_stored = result.as_ref().is_ok_and(|r| r.is_none());
809            match result? {
810                Some(chunk) => prepared.push(chunk),
811                None => already_stored.push(address),
812            }
813            quoted_count += 1;
814            let progress_num = quoted_offset + quoted_count;
815            if file_total > 0 {
816                if chunk_already_stored {
817                    info!("Verified {progress_num}/{file_total} (already stored)");
818                } else {
819                    info!("Quoted {progress_num}/{file_total}");
820                }
821            }
822            if let Some(tx) = progress {
823                let _ = tx.try_send(UploadEvent::ChunkQuoted {
824                    quoted: progress_num,
825                    total: file_total,
826                });
827            }
828        }
829
830        Ok((prepared, already_stored))
831    }
832
833    /// Store a batch of paid chunks concurrently to their close groups.
834    ///
835    /// Retries failed chunks up to 3 times with exponential backoff (500ms, 1s, 2s).
836    /// Returns a [`WaveResult`] with both successes and failures so callers can
837    /// track partial progress instead of losing information about stored chunks.
838    ///
839    /// When `progress` is `Some`, sends [`UploadEvent::ChunkStored`] as each
840    /// chunk is successfully stored. `stored_before` is the count of chunks
841    /// already stored in previous waves so the event reports an accurate
842    /// cumulative total; `total_chunks` is the total across all waves. Pass
843    /// `None`/0/0 when progress reporting is not needed.
844    pub(crate) async fn store_paid_chunks_with_events(
845        &self,
846        paid_chunks: Vec<PaidChunk>,
847        progress: Option<&mpsc::Sender<UploadEvent>>,
848        stored_before: usize,
849        total_chunks: usize,
850    ) -> WaveResult {
851        const MAX_RETRIES: u32 = 3;
852        const BASE_DELAY_MS: u64 = 500;
853
854        let mut stored = Vec::new();
855        let mut to_retry = paid_chunks;
856
857        // Per-chunk first-seen timestamps, keyed by chunk address.
858        // Inserted on first sight; never overwritten so wall-clock spans
859        // first attempt → eventual success across all retry rounds.
860        let mut first_seen: HashMap<XorName, Instant> = HashMap::with_capacity(to_retry.len());
861        for chunk in &to_retry {
862            first_seen.entry(chunk.address).or_insert_with(Instant::now);
863        }
864
865        // Bound concurrency by IN-FLIGHT BYTES, not just chunk count. Each
866        // concurrently-stored chunk is held in memory while it is sent to its
867        // close group, and the send path re-serializes the body once per peer,
868        // so a wave of large (~4 MB) chunks at full store concurrency can pin
869        // multiple GB and OOM a small host. Cap how many chunks store at once
870        // so their combined body size stays under the budget; small chunks are
871        // unaffected (the byte bound exceeds the chunk-count bound). The budget
872        // is deliberately conservative for the current per-peer send
873        // amplification and can be raised once that is reduced upstream.
874        let max_chunk_bytes = to_retry.iter().map(|c| c.content.len()).max().unwrap_or(0);
875        // `checked_div` yields `None` only when `max_chunk_bytes == 0` (an
876        // empty/zero-length wave), in which case there is no byte limit.
877        let byte_bound = STORE_INFLIGHT_BYTE_BUDGET
878            .checked_div(max_chunk_bytes)
879            .map_or(usize::MAX, |n| n.max(1));
880
881        let mut chunk_attempts_total: usize = 0;
882        let mut store_durations_ms: Vec<u64> = Vec::new();
883        let mut retries_per_chunk: Vec<u32> = Vec::new();
884
885        for attempt in 0..=MAX_RETRIES {
886            if attempt > 0 {
887                let delay = Duration::from_millis(BASE_DELAY_MS * 2u64.pow(attempt - 1));
888                tokio::time::sleep(delay).await;
889                info!(
890                    "Retry attempt {attempt}/{MAX_RETRIES} for {} chunks",
891                    to_retry.len()
892                );
893            }
894
895            // Each chunk in this round counts as one store-RPC attempt.
896            chunk_attempts_total = chunk_attempts_total.saturating_add(to_retry.len());
897
898            let store_limiter = self.controller().store.clone();
899            // Rolling scheduler: keep up to `cap()` stores in flight and re-read
900            // the cap as each slot frees, so mid-flight limiter growth reaches
901            // the rest of this wave instead of being frozen at a per-wave
902            // snapshot (V2-554). The in-flight BYTE budget (`byte_bound`) stays
903            // enforced so a wave of large chunks can't OOM a small host;
904            // iterator exhaustion bounds launches to the wave, so no explicit
905            // clamp to `to_retry.len()` is needed.
906            let make_store = |chunk: PaidChunk| {
907                let chunk_clone = chunk.clone();
908                let limiter = store_limiter.clone();
909                async move {
910                    let result = observe_op(
911                        &limiter,
912                        || async move {
913                            self.chunk_put_to_close_group(
914                                chunk.content,
915                                chunk.proof_bytes,
916                                &chunk.quoted_peers,
917                            )
918                            .await
919                        },
920                        classify_error,
921                    )
922                    .await;
923                    (chunk_clone, result)
924                }
925            };
926            let mut chunk_iter = to_retry.into_iter();
927            let mut in_flight = FuturesUnordered::new();
928
929            let mut failed_this_round = Vec::new();
930            loop {
931                let slots = store_limiter.current().min(byte_bound).max(1);
932                while in_flight.len() < slots {
933                    match chunk_iter.next() {
934                        Some(chunk) => in_flight.push(make_store(chunk)),
935                        None => break,
936                    }
937                }
938                let Some((chunk, result)) = in_flight.next().await else {
939                    break;
940                };
941                match result {
942                    Ok(name) => {
943                        let duration_ms = first_seen
944                            .get(&chunk.address)
945                            .map(|t| u64::try_from(t.elapsed().as_millis()).unwrap_or(u64::MAX))
946                            .unwrap_or(0);
947                        store_durations_ms.push(duration_ms);
948                        retries_per_chunk.push(attempt);
949                        stored.push(name);
950                        let stored_num = stored_before + stored.len();
951                        if total_chunks > 0 {
952                            info!("Stored {stored_num}/{total_chunks}");
953                        }
954                        if let Some(tx) = progress {
955                            let _ = tx.try_send(UploadEvent::ChunkStored {
956                                stored: stored_num,
957                                total: total_chunks,
958                            });
959                        }
960                    }
961                    Err(e) => failed_this_round.push((chunk, e.to_string())),
962                }
963            }
964
965            if failed_this_round.is_empty() {
966                let result = WaveResult {
967                    stored,
968                    failed: Vec::new(),
969                    chunk_attempts_total,
970                    store_durations_ms,
971                    retries_per_chunk,
972                };
973                log_wave_summary(&result);
974                return result;
975            }
976
977            if attempt == MAX_RETRIES {
978                let failed = failed_this_round
979                    .into_iter()
980                    .map(|(c, e)| (c.address, e))
981                    .collect();
982                let result = WaveResult {
983                    stored,
984                    failed,
985                    chunk_attempts_total,
986                    store_durations_ms,
987                    retries_per_chunk,
988                };
989                log_wave_summary(&result);
990                return result;
991            }
992
993            warn!(
994                "{} chunks failed on attempt {}, will retry",
995                failed_this_round.len(),
996                attempt + 1
997            );
998            to_retry = failed_this_round.into_iter().map(|(c, _)| c).collect();
999        }
1000
1001        // Unreachable due to loop structure, but satisfy the compiler.
1002        let result = WaveResult {
1003            stored,
1004            failed: Vec::new(),
1005            chunk_attempts_total,
1006            store_durations_ms,
1007            retries_per_chunk,
1008        };
1009        log_wave_summary(&result);
1010        result
1011    }
1012}
1013
1014/// Emit one structured info line summarising a wave's store-side stats.
1015///
1016/// Surfaces p50/p95/max chunk wall-clock and per-round retry counts so
1017/// log-based analysis tooling (Elasticsearch / Kibana) can identify
1018/// client-side quorum or retry cost without needing the `--json` output.
1019fn log_wave_summary(result: &WaveResult) {
1020    let retries_round_1 = result.retries_per_chunk.iter().filter(|&&r| r == 1).count();
1021    let retries_round_2 = result.retries_per_chunk.iter().filter(|&&r| r == 2).count();
1022    let retries_round_3 = result.retries_per_chunk.iter().filter(|&&r| r == 3).count();
1023    let chunk_attempts_total = result.chunk_attempts_total;
1024    info!(
1025        chunks_stored = result.stored.len(),
1026        chunks_failed = result.failed.len(),
1027        chunk_attempts_total,
1028        retries_round_1,
1029        retries_round_2,
1030        retries_round_3,
1031        store_duration_p50_ms = percentile(&result.store_durations_ms, 0.50),
1032        store_duration_p95_ms = percentile(&result.store_durations_ms, 0.95),
1033        store_duration_max_ms = result.store_durations_ms.iter().max().copied().unwrap_or(0),
1034        "chunk_store_wave_complete"
1035    );
1036}
1037
1038/// Safety margin subtracted from the storer's `QUOTE_MAX_AGE_SECS` (24 h)
1039/// when deciding to trust a cached proof.
1040///
1041/// A proof whose oldest `quote.timestamp` is closer than this to the
1042/// storer's hard limit is treated as already-expired locally. The
1043/// margin covers (a) clock skew between client and storer, (b) the
1044/// in-flight time between the local check and the storer's
1045/// `validate_quote_timestamps` call, and (c) the time spent uploading
1046/// the chunk body. 5 minutes is generous for all three combined and
1047/// cheap: a wrongly-kept proof costs an extra retry round trip, a
1048/// wrongly-dropped proof costs one re-pay (cheap chunk).
1049const CACHED_PROOF_SAFETY_MARGIN_SECS: u64 = 300;
1050
1051/// Storer-side budget for a quote's age. Mirrors `QUOTE_MAX_AGE_SECS`
1052/// in `ant-node/src/payment/verifier.rs`. If this value drifts on the
1053/// node side, the worst case is the client either keeps proofs slightly
1054/// past the storer limit (forced re-pay on next retry, no money lost)
1055/// or drops them slightly early (one extra re-pay, no money lost).
1056/// Either way, no payment is double-spent or stranded.
1057const CACHED_PROOF_MAX_AGE_SECS: u64 = 24 * 60 * 60;
1058
1059/// How far a cached quote's `timestamp` may be in the future before we
1060/// classify it as too-skewed-to-trust and prune.
1061///
1062/// Mirrors `QUOTE_FUTURE_SKEW_TOLERANCE_SECS = 300` in
1063/// `ant-node/src/payment/verifier.rs`. If the client's clock runs
1064/// slow relative to the storer that issued the quote, a perfectly
1065/// valid proof can appear future-dated to the client — rejecting any
1066/// forward drift would re-pay those chunks on every retry. Allow the
1067/// same 5-minute window the storer does so the client and node agree
1068/// on which proofs are fresh.
1069const CACHED_PROOF_FUTURE_SKEW_TOLERANCE_SECS: u64 = 300;
1070
1071/// Drop cached `proof_bytes` whose quote timestamps are too close to
1072/// the storer's expiry window to safely reuse.
1073///
1074/// Why this exists
1075/// ---------------
1076/// The cache stores `(chunk_address, proof_bytes)` so a retried upload
1077/// can skip re-paying. The proof bytes embed `quote.timestamp`s. Each
1078/// storer evaluates each `quote.timestamp` independently against its
1079/// 24 h `QUOTE_MAX_AGE_SECS` budget, so close to the 24 h boundary
1080/// (or on a multi-day-old cache that survived past the receipt's outer
1081/// expiry for some reason) the storer rejects what the client still
1082/// believes is fresh.
1083///
1084/// The previous design trusted a substring match on the storer's
1085/// returned error text to detect this and invalidate the cache after
1086/// the fact. That allowed a Byzantine storer to spoof the marker and
1087/// force the client to re-pay fresh proofs (double-payment). This
1088/// implementation is decision-pure: we decode the proof locally and
1089/// only re-use it if every embedded quote is comfortably within the
1090/// budget. No remote text involved.
1091///
1092/// Side-effect: dropped entries are removed from the on-disk cache so
1093/// they don't reappear on the next load.
1094fn prune_locally_expired_proofs(
1095    resume_key: &str,
1096    proofs: HashMap<[u8; 32], Vec<u8>>,
1097) -> HashMap<XorName, Vec<u8>> {
1098    let now = std::time::SystemTime::now();
1099    let max_safe_age = Duration::from_secs(
1100        CACHED_PROOF_MAX_AGE_SECS.saturating_sub(CACHED_PROOF_SAFETY_MARGIN_SECS),
1101    );
1102    let max_future_skew = Duration::from_secs(CACHED_PROOF_FUTURE_SKEW_TOLERANCE_SECS);
1103    let mut kept: HashMap<XorName, Vec<u8>> = HashMap::with_capacity(proofs.len());
1104    // Pair each expired address with the EXACT bytes we observed at
1105    // load time. The cache-side drop only removes the entry if those
1106    // bytes still match, so a concurrent re-pay that refreshed the
1107    // proof under its own lock is not clobbered (CAS semantics, fixes
1108    // the TOCTOU between unlocked-load and locked-drop).
1109    let mut expired: Vec<([u8; 32], Vec<u8>)> = Vec::new();
1110    for (addr, bytes) in proofs {
1111        match deserialize_proof(&bytes) {
1112            Ok((proof, _tx_hashes)) => {
1113                if proof_is_safely_fresh(&proof, now, max_safe_age, max_future_skew) {
1114                    kept.insert(addr, bytes);
1115                } else {
1116                    expired.push((addr, bytes));
1117                }
1118            }
1119            Err(_) => {
1120                // Unreadable cached entry: drop it so it doesn't sit
1121                // here forever. The chunk will re-quote+re-pay.
1122                expired.push((addr, bytes));
1123            }
1124        }
1125    }
1126    if !expired.is_empty() {
1127        info!(
1128            "Pruning {} stale cached proofs (quote.timestamp past safe-reuse window) \
1129             before resume",
1130            expired.len()
1131        );
1132        crate::data::client::cached_single::try_drop_proofs_for_file(resume_key, &expired);
1133    }
1134    kept
1135}
1136
1137/// True iff every quote in the proof has a timestamp not older than
1138/// `now - max_safe_age` AND not further in the future than
1139/// `max_future_skew`. The forward-skew check mirrors the storer's
1140/// `QUOTE_FUTURE_SKEW_TOLERANCE_SECS` (300s) so a slow-running client
1141/// clock doesn't cause us to wrongly prune perfectly fresh proofs
1142/// that the storer would still accept.
1143fn proof_is_safely_fresh(
1144    proof: &ProofOfPayment,
1145    now: std::time::SystemTime,
1146    max_safe_age: Duration,
1147    max_future_skew: Duration,
1148) -> bool {
1149    for (_peer, quote) in &proof.peer_quotes {
1150        match now.duration_since(quote.timestamp) {
1151            Ok(age) => {
1152                if age > max_safe_age {
1153                    return false;
1154                }
1155            }
1156            Err(future) => {
1157                if future.duration() > max_future_skew {
1158                    return false;
1159                }
1160            }
1161        }
1162    }
1163    true
1164}
1165
1166/// Compile-time assertions that batch method futures are Send.
1167#[cfg(test)]
1168mod send_assertions {
1169    use super::*;
1170
1171    fn _assert_send<T: Send>(_: &T) {}
1172
1173    #[allow(dead_code)]
1174    async fn _batch_upload_is_send(client: &Client) {
1175        let fut = client.batch_upload_chunks(Vec::new());
1176        _assert_send(&fut);
1177    }
1178}
1179
1180#[cfg(test)]
1181#[allow(clippy::unwrap_used)]
1182mod tests {
1183    use super::*;
1184    use ant_protocol::payment::SingleNodePayment;
1185
1186    /// Median index in the quotes array.
1187    const MEDIAN_INDEX: usize = CLOSE_GROUP_SIZE / 2;
1188
1189    /// Helper: build a `PreparedChunk` with `median_amount` at the median
1190    /// quote index and zero for all other quotes. Adapts automatically to
1191    /// `CLOSE_GROUP_SIZE` changes.
1192    fn make_prepared_chunk(median_amount: u64) -> PreparedChunk {
1193        let quotes: Vec<QuotePaymentInfo> = (0..CLOSE_GROUP_SIZE)
1194            .map(|i| {
1195                let amount = if i == MEDIAN_INDEX { median_amount } else { 0 };
1196                QuotePaymentInfo {
1197                    quote_hash: QuoteHash::from([i as u8 + 1; 32]),
1198                    rewards_address: RewardsAddress::new([i as u8 + 10; 20]),
1199                    amount: Amount::from(amount),
1200                    price: Amount::from(amount),
1201                }
1202            })
1203            .collect();
1204
1205        PreparedChunk {
1206            content: Bytes::from(vec![0xAA; 32]),
1207            address: [0u8; 32],
1208            quoted_peers: Vec::new(),
1209            payment: SingleNodeQuotePayment { quotes },
1210            peer_quotes: Vec::new(),
1211            commitment_sidecars: Vec::new(),
1212        }
1213    }
1214
1215    fn payment_quote(seed: u8, price: u64) -> PaymentQuote {
1216        PaymentQuote {
1217            content: xor_name::XorName([seed; 32]),
1218            timestamp: std::time::SystemTime::UNIX_EPOCH,
1219            price: Amount::from(price),
1220            rewards_address: RewardsAddress::new([seed; 20]),
1221            pub_key: Vec::new(),
1222            signature: Vec::new(),
1223            committed_key_count: 0,
1224            commitment_pin: None,
1225        }
1226    }
1227
1228    #[test]
1229    fn single_node_quote_payment_accepts_every_supported_quote_count() {
1230        for quote_count in 1..=CLOSE_GROUP_SIZE {
1231            let quotes = (0..quote_count)
1232                .rev()
1233                .map(|i| payment_quote(i as u8, i as u64 + 1))
1234                .collect();
1235
1236            let payment = SingleNodeQuotePayment::from_quotes(quotes)
1237                .expect("every supported quote count should produce an SNP payment");
1238            let median_index = quote_count / 2;
1239            let enhanced_price =
1240                payment.quotes[median_index].price * Amount::from(SINGLE_NODE_PAYMENT_MULTIPLIER);
1241
1242            assert_eq!(payment.quotes.len(), quote_count);
1243            assert!(
1244                payment
1245                    .quotes
1246                    .windows(2)
1247                    .all(|pair| pair[0].price <= pair[1].price),
1248                "quotes should be sorted by price"
1249            );
1250            for (index, quote) in payment.quotes.iter().enumerate() {
1251                let expected = if index == median_index {
1252                    enhanced_price
1253                } else {
1254                    Amount::ZERO
1255                };
1256                assert_eq!(quote.amount, expected);
1257            }
1258            assert_eq!(payment.total_amount(), enhanced_price);
1259        }
1260    }
1261
1262    #[test]
1263    fn full_quote_payment_matches_protocol_implementation() {
1264        let quotes = (0..CLOSE_GROUP_SIZE)
1265            .rev()
1266            .map(|i| payment_quote(i as u8, i as u64 + 1))
1267            .collect::<Vec<_>>();
1268
1269        let local = SingleNodeQuotePayment::from_quotes(quotes.clone()).unwrap();
1270        let protocol = SingleNodePayment::from_quotes(
1271            quotes
1272                .into_iter()
1273                .map(|quote| {
1274                    let price = quote.price;
1275                    (quote, price)
1276                })
1277                .collect(),
1278        )
1279        .unwrap();
1280
1281        assert_eq!(local.total_amount(), protocol.total_amount());
1282        for (local, protocol) in local.quotes.iter().zip(&protocol.quotes) {
1283            assert_eq!(local.quote_hash, protocol.quote_hash);
1284            assert_eq!(local.rewards_address, protocol.rewards_address);
1285            assert_eq!(local.amount, protocol.amount);
1286            assert_eq!(local.price, protocol.price);
1287        }
1288    }
1289
1290    #[test]
1291    fn single_node_quote_payment_rejects_zero_quotes() {
1292        let err = SingleNodeQuotePayment::from_quotes(Vec::new())
1293            .expect_err("empty SNP quote sets must remain invalid");
1294        assert!(
1295            err.to_string().contains("requires 1..="),
1296            "unexpected error: {err}"
1297        );
1298    }
1299
1300    #[test]
1301    fn single_node_quote_payment_rejects_too_many_quotes() {
1302        let quotes = (0..=CLOSE_GROUP_SIZE)
1303            .map(|i| payment_quote(i as u8, i as u64 + 1))
1304            .collect();
1305
1306        let err = SingleNodeQuotePayment::from_quotes(quotes)
1307            .expect_err("quote sets larger than the close group must remain invalid");
1308        assert!(
1309            err.to_string()
1310                .contains(&format!("requires 1..={CLOSE_GROUP_SIZE}")),
1311            "unexpected error: {err}"
1312        );
1313    }
1314
1315    #[test]
1316    fn payment_intent_from_single_chunk() {
1317        let chunk = make_prepared_chunk(300);
1318        let intent = PaymentIntent::from_prepared_chunks(&[chunk]);
1319
1320        assert_eq!(intent.payments.len(), 1, "only non-zero amounts");
1321        assert_eq!(intent.total_amount, Amount::from(300));
1322
1323        let (hash, addr, amt) = &intent.payments[0];
1324        assert_eq!(*hash, QuoteHash::from([MEDIAN_INDEX as u8 + 1; 32]));
1325        assert_eq!(*addr, RewardsAddress::new([MEDIAN_INDEX as u8 + 10; 20]));
1326        assert_eq!(*amt, Amount::from(300));
1327    }
1328
1329    #[test]
1330    fn payment_intent_from_multiple_chunks() {
1331        let c1 = make_prepared_chunk(100);
1332        let c2 = make_prepared_chunk(250);
1333        let intent = PaymentIntent::from_prepared_chunks(&[c1, c2]);
1334
1335        assert_eq!(intent.payments.len(), 2);
1336        assert_eq!(intent.total_amount, Amount::from(350));
1337    }
1338
1339    #[test]
1340    fn payment_intent_skips_all_zero_chunks() {
1341        let chunk = make_prepared_chunk(0);
1342        let intent = PaymentIntent::from_prepared_chunks(&[chunk]);
1343
1344        assert!(intent.payments.is_empty());
1345        assert_eq!(intent.total_amount, Amount::ZERO);
1346    }
1347
1348    #[test]
1349    fn payment_intent_empty_input() {
1350        let intent = PaymentIntent::from_prepared_chunks(&[]);
1351        assert!(intent.payments.is_empty());
1352        assert_eq!(intent.total_amount, Amount::ZERO);
1353    }
1354
1355    #[test]
1356    fn finalize_batch_payment_builds_proofs() {
1357        let chunk = make_prepared_chunk(500);
1358        let quote_hash = chunk.payment.quotes[MEDIAN_INDEX].quote_hash;
1359
1360        let mut tx_map = HashMap::new();
1361        tx_map.insert(quote_hash, TxHash::from([0xBB; 32]));
1362
1363        let paid = finalize_batch_payment(vec![chunk], &tx_map).unwrap();
1364
1365        assert_eq!(paid.len(), 1);
1366        assert!(!paid[0].proof_bytes.is_empty());
1367        assert_eq!(paid[0].address, [0u8; 32]);
1368    }
1369
1370    #[test]
1371    fn finalize_batch_payment_empty_input() {
1372        let paid = finalize_batch_payment(vec![], &HashMap::new()).unwrap();
1373        assert!(paid.is_empty());
1374    }
1375
1376    #[test]
1377    fn finalize_batch_payment_missing_tx_hash_errors() {
1378        // Missing tx hash for a non-zero-amount quote should error,
1379        // since the chunk would be rejected by the network without a valid proof.
1380        let chunk = make_prepared_chunk(500);
1381
1382        let result = finalize_batch_payment(vec![chunk], &HashMap::new());
1383        assert!(result.is_err());
1384        let err = result.unwrap_err().to_string();
1385        assert!(err.contains("Missing tx hash"), "got: {err}");
1386    }
1387
1388    #[test]
1389    fn finalize_batch_payment_multiple_chunks() {
1390        let c1 = make_prepared_chunk(100);
1391        let c2 = make_prepared_chunk(200);
1392        let q1 = c1.payment.quotes[MEDIAN_INDEX].quote_hash;
1393        let mut tx_map = HashMap::new();
1394        // Both chunks have the same quote_hash (same index/byte pattern)
1395        // so one tx_hash covers both
1396        tx_map.insert(q1, TxHash::from([0xCC; 32]));
1397
1398        let paid = finalize_batch_payment(vec![c1, c2], &tx_map).unwrap();
1399        assert_eq!(paid.len(), 2);
1400    }
1401
1402    // ---- prune_locally_expired_proofs ----
1403    //
1404    // Build synthetic ProofOfPayment instances with controlled
1405    // timestamps to verify the local pre-flight stale-proof check.
1406    // This is the "no remote text trust" replacement for the prior
1407    // substring-matching invalidation path. A bug here is a direct
1408    // wallet leak (drop-too-eager = re-pay; keep-too-long = doomed
1409    // PUT round trip but no payment loss).
1410
1411    fn make_proof_with_timestamps(timestamps: &[std::time::SystemTime]) -> ProofOfPayment {
1412        let peer_quotes = timestamps
1413            .iter()
1414            .enumerate()
1415            .map(|(i, ts)| {
1416                let quote = PaymentQuote {
1417                    content: xor_name::XorName([0u8; 32]),
1418                    timestamp: *ts,
1419                    price: Amount::from(1u64),
1420                    rewards_address: RewardsAddress::new([1u8; 20]),
1421                    pub_key: vec![],
1422                    signature: vec![],
1423                    committed_key_count: 0,
1424                    commitment_pin: None,
1425                };
1426                (EncodedPeerId::from([i as u8; 32]), quote)
1427            })
1428            .collect();
1429        ProofOfPayment { peer_quotes }
1430    }
1431
1432    fn default_max_future_skew() -> Duration {
1433        Duration::from_secs(CACHED_PROOF_FUTURE_SKEW_TOLERANCE_SECS)
1434    }
1435
1436    #[test]
1437    fn proof_is_safely_fresh_accepts_recent_quote() {
1438        let proof = make_proof_with_timestamps(&[std::time::SystemTime::now()]);
1439        assert!(proof_is_safely_fresh(
1440            &proof,
1441            std::time::SystemTime::now(),
1442            Duration::from_secs(CACHED_PROOF_MAX_AGE_SECS),
1443            default_max_future_skew(),
1444        ));
1445    }
1446
1447    #[test]
1448    fn proof_is_safely_fresh_rejects_quote_past_safe_window() {
1449        // 23h57m old: past the 24h - 5min safe-reuse threshold but
1450        // still within the storer's hard 24h limit. The whole point
1451        // of the safety margin is to drop these locally before
1452        // burning a doomed PUT round trip.
1453        let too_old = std::time::SystemTime::now() - Duration::from_secs(23 * 60 * 60 + 57 * 60);
1454        let proof = make_proof_with_timestamps(&[too_old]);
1455        let max_safe = Duration::from_secs(
1456            CACHED_PROOF_MAX_AGE_SECS.saturating_sub(CACHED_PROOF_SAFETY_MARGIN_SECS),
1457        );
1458        assert!(
1459            !proof_is_safely_fresh(
1460                &proof,
1461                std::time::SystemTime::now(),
1462                max_safe,
1463                default_max_future_skew(),
1464            ),
1465            "23h57m-old quote must fail safe-reuse check (limit is 24h - 5min margin)"
1466        );
1467    }
1468
1469    #[test]
1470    fn proof_is_safely_fresh_rejects_if_any_quote_is_stale() {
1471        // The storer rejects on a per-quote basis: a proof with even
1472        // one stale quote will fail on every retry. We must drop it.
1473        let now = std::time::SystemTime::now();
1474        let fresh = now;
1475        let stale = now - Duration::from_secs(CACHED_PROOF_MAX_AGE_SECS);
1476        let proof = make_proof_with_timestamps(&[fresh, fresh, stale, fresh]);
1477        let max_safe = Duration::from_secs(
1478            CACHED_PROOF_MAX_AGE_SECS.saturating_sub(CACHED_PROOF_SAFETY_MARGIN_SECS),
1479        );
1480        assert!(!proof_is_safely_fresh(
1481            &proof,
1482            now,
1483            max_safe,
1484            default_max_future_skew(),
1485        ));
1486    }
1487
1488    #[test]
1489    fn proof_is_safely_fresh_accepts_slight_future_skew_within_node_tolerance() {
1490        // Client clock 60s slow. Quote claims 60s in the future of
1491        // our local view. Node tolerates 300s forward skew, so the
1492        // storer would accept this quote — we must too, or we'd
1493        // wrongly prune fresh proofs and force re-payment.
1494        let now = std::time::SystemTime::now();
1495        let slight_future = now + Duration::from_secs(60);
1496        let proof = make_proof_with_timestamps(&[slight_future]);
1497        let max_safe = Duration::from_secs(CACHED_PROOF_MAX_AGE_SECS);
1498        assert!(
1499            proof_is_safely_fresh(&proof, now, max_safe, default_max_future_skew()),
1500            "60s-future quote must be accepted (within node's 300s skew tolerance)"
1501        );
1502    }
1503
1504    #[test]
1505    fn proof_is_safely_fresh_rejects_far_future_dated_quote() {
1506        // 1 hour in the future of our local clock. Exceeds the
1507        // node's 300s forward-skew tolerance and the storer would
1508        // reject it — we drop it locally to avoid a round trip.
1509        let now = std::time::SystemTime::now();
1510        let far_future = now + Duration::from_secs(3600);
1511        let proof = make_proof_with_timestamps(&[far_future]);
1512        let max_safe = Duration::from_secs(CACHED_PROOF_MAX_AGE_SECS);
1513        assert!(!proof_is_safely_fresh(
1514            &proof,
1515            now,
1516            max_safe,
1517            default_max_future_skew(),
1518        ));
1519    }
1520
1521    #[test]
1522    fn proof_is_safely_fresh_empty_quotes_is_vacuously_safe() {
1523        // No quotes = no storer-side timestamp check to fail. The
1524        // proof is structurally invalid for other reasons, but
1525        // this function's contract is "no stale timestamp present",
1526        // which is trivially true for an empty list.
1527        let proof = make_proof_with_timestamps(&[]);
1528        assert!(proof_is_safely_fresh(
1529            &proof,
1530            std::time::SystemTime::now(),
1531            Duration::from_secs(CACHED_PROOF_MAX_AGE_SECS),
1532            default_max_future_skew(),
1533        ));
1534    }
1535}