ant_node/replication/config.rs
1//! Tunable parameters for the replication subsystem.
2//!
3//! All values below are a reference profile used for logic validation.
4//! Parameter safety constraints (Section 4):
5//! 1. `1 <= QUORUM_THRESHOLD <= CLOSE_GROUP_SIZE`
6//! 2. Effective paid-list threshold is per-key dynamic:
7//! `ConfirmNeeded(K) = floor(PaidGroupSize(K)/2)+1`
8//! 3. If constraints are violated at runtime reconfiguration, node MUST reject
9//! the config.
10
11#![allow(clippy::module_name_repetitions)]
12
13use std::time::Duration;
14
15use rand::Rng;
16
17use crate::ant_protocol::{CLOSE_GROUP_SIZE, MAX_CHUNK_SIZE};
18
19// ---------------------------------------------------------------------------
20// Static constants (compile-time reference profile)
21// ---------------------------------------------------------------------------
22
23/// Maximum number of peers per k-bucket in the Kademlia routing table.
24pub const K_BUCKET_SIZE: usize = 20;
25
26/// Extra local-routing-table positions accepted for local chunk storage
27/// admission and stored-record pruning.
28///
29/// This margin absorbs small local RT disagreement between peers. It does not
30/// widen audit, quorum, or paid-list target sets; those remain strict
31/// `close_group_size` / paid-list group checks.
32pub const STORAGE_ADMISSION_MARGIN: usize = 2;
33
34/// Full-network target for required positive presence votes.
35///
36/// Effective per-key threshold is
37/// `QuorumNeeded(K) = min(QUORUM_THRESHOLD, floor(|QuorumTargets|/2)+1)`.
38pub const QUORUM_THRESHOLD: usize = 4; // floor(CLOSE_GROUP_SIZE / 2) + 1
39
40/// Maximum number of closest nodes tracking paid status for a key.
41pub const PAID_LIST_CLOSE_GROUP_SIZE: usize = 20;
42
43/// Number of closest peers to self eligible for neighbor sync.
44pub const NEIGHBOR_SYNC_SCOPE: usize = 20;
45
46/// Number of close-neighbor peers synced concurrently per round-robin repair
47/// round.
48pub const NEIGHBOR_SYNC_PEER_COUNT: usize = 4;
49
50/// Best-effort delivery retries for a fresh-replication push, per peer.
51///
52/// ADR-0003: on a transport/send failure the offer is retried up to this many
53/// times so a transient hiccup does not silently drop it. This is delivery
54/// assurance only — possession is judged separately by the delayed possession
55/// check, which still penalises a close peer that lacks the chunk even if the
56/// push never reached it.
57pub const FRESH_REPLICATION_DELIVERY_MAX_RETRIES: u32 = 2;
58
59const POSSESSION_CHECK_DELAY_MIN_SECS: u64 = 5 * 60;
60const POSSESSION_CHECK_DELAY_MAX_SECS: u64 = 15 * 60;
61
62/// Lower bound of the delay before a fresh-replication possession check runs
63/// (ADR-0003).
64///
65/// The delay lets replication settle so an honest peer still mid-store is not
66/// judged prematurely, and makes the check unpredictable to the peer.
67pub const POSSESSION_CHECK_DELAY_MIN: Duration =
68 Duration::from_secs(POSSESSION_CHECK_DELAY_MIN_SECS);
69
70/// Upper bound of the possession-check delay (ADR-0003).
71pub const POSSESSION_CHECK_DELAY_MAX: Duration =
72 Duration::from_secs(POSSESSION_CHECK_DELAY_MAX_SECS);
73
74// The possession probe reuses the `AuditChallenge` wire and the bandwidth-
75// calibrated `audit_response_timeout(1)` deadline, so it needs no bespoke
76// per-probe timeout or retry constants.
77
78/// Width used when deciding whether this node may locally store or retain a
79/// chunk.
80#[must_use]
81pub const fn storage_admission_width(close_group_size: usize) -> usize {
82 close_group_size.saturating_add(STORAGE_ADMISSION_MARGIN)
83}
84
85/// Minimum neighbor-sync cadence. Actual interval is randomized within
86/// `[min, max]`.
87const NEIGHBOR_SYNC_INTERVAL_MIN_SECS: u64 = 10 * 60;
88/// Maximum neighbor-sync cadence.
89const NEIGHBOR_SYNC_INTERVAL_MAX_SECS: u64 = 20 * 60;
90
91/// Neighbor sync cadence range (min).
92pub const NEIGHBOR_SYNC_INTERVAL_MIN: Duration =
93 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MIN_SECS);
94
95/// Neighbor sync cadence range (max).
96pub const NEIGHBOR_SYNC_INTERVAL_MAX: Duration =
97 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MAX_SECS);
98
99/// Per-peer minimum spacing between successive syncs with the same peer.
100const NEIGHBOR_SYNC_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
101/// Per-peer minimum spacing between successive syncs with the same peer.
102pub const NEIGHBOR_SYNC_COOLDOWN: Duration = Duration::from_secs(NEIGHBOR_SYNC_COOLDOWN_SECS);
103
104/// Minimum age for a replica repair hint before the hinted peer can be audited
105/// for that key.
106const REPAIR_HINT_MIN_AGE_SECS: u64 = 60 * 60; // 1 hour
107/// Minimum age for a replica repair hint before the hinted peer can be audited
108/// for that key.
109pub const REPAIR_HINT_MIN_AGE: Duration = Duration::from_secs(REPAIR_HINT_MIN_AGE_SECS);
110
111/// Minimum self-lookup cadence.
112const SELF_LOOKUP_INTERVAL_MIN_SECS: u64 = 5 * 60;
113/// Maximum self-lookup cadence.
114const SELF_LOOKUP_INTERVAL_MAX_SECS: u64 = 10 * 60;
115
116/// Periodic self-lookup cadence range (min) to keep close neighborhood
117/// current.
118pub const SELF_LOOKUP_INTERVAL_MIN: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MIN_SECS);
119
120/// Periodic self-lookup cadence range (max).
121pub const SELF_LOOKUP_INTERVAL_MAX: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MAX_SECS);
122
123/// Maximum number of concurrent outbound replication sends.
124///
125/// Caps how many fresh-replication chunk transfers can be in-flight at once
126/// across the entire replication engine. Prevents bandwidth saturation on
127/// home broadband connections when multiple chunks arrive simultaneously.
128/// Each send transfers up to 4 MB (`MAX_CHUNK_SIZE`), so a limit of 3 means
129/// at most ~12 MB queued for the upload link at any instant.
130pub const MAX_CONCURRENT_REPLICATION_SENDS: usize = 3;
131
132/// Maximum number of concurrent in-flight audit-responder tasks.
133///
134/// The responsible-chunk (audit #2), subtree (round 1), and byte (round 2)
135/// challenge handlers are all spawned off the serial replication message loop so
136/// their disk reads don't stall replication. This caps how many run at once
137/// across the engine, restoring backpressure: a peer flooding audit challenges
138/// cannot fan out unbounded `get_raw` reads or multi-MiB byte serves. When the
139/// cap is hit, the challenge is dropped and the caller's audit-specific timeout
140/// policy applies. The cap must therefore stay high enough for honest audit
141/// traffic while still throttling flooders.
142/// Sized to cover a handful of concurrent honest auditors (the per-peer
143/// gossip-audit cooldown is 30 min, so genuine concurrent audits are few) while
144/// bounding the byte round's worst-case resident bytes
145/// (`N × MAX_BYTE_CHALLENGE_KEYS × MAX_CHUNK_SIZE`).
146pub const MAX_CONCURRENT_AUDIT_RESPONSES: usize = 32;
147
148/// Maximum concurrent in-flight audit-responder tasks from any SINGLE peer.
149///
150/// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] ceiling alone is not
151/// flood-fair: one peer spamming challenges could occupy every slot and starve
152/// honest auditors (whose dropped challenges convert to audit failures or
153/// timeout verdicts on the challenged peers). This per-peer cap guarantees no
154/// source holds more than its share, so a flood self-throttles. Audits are
155/// cooldown-gated (one
156/// gossip-triggered audit per peer per 30 min), so 4 in-flight per peer leaves
157/// headroom beyond the legitimate round-1 + round-2 overlap.
158pub const MAX_AUDIT_RESPONSES_PER_PEER: u32 = 4;
159
160/// Concurrent fetches cap, derived from hardware thread count.
161///
162/// Uses `std::thread::available_parallelism()` so the node scales to the
163/// machine it runs on. Falls back to 4 if the OS query fails.
164const AVAILABLE_PARALLELISM_FALLBACK: usize = 4;
165
166/// Returns the number of hardware threads available, used as the fetch
167/// concurrency limit.
168#[allow(clippy::incompatible_msrv)] // NonZero::get is stable since 1.79; MSRV lint conflicts with redundant_closure
169pub fn max_parallel_fetch() -> usize {
170 std::thread::available_parallelism()
171 .map_or(AVAILABLE_PARALLELISM_FALLBACK, std::num::NonZero::get)
172}
173
174/// Minimum audit-scheduler cadence.
175const AUDIT_TICK_INTERVAL_MIN_SECS: u64 = 10 * 60;
176/// Maximum audit-scheduler cadence.
177const AUDIT_TICK_INTERVAL_MAX_SECS: u64 = 20 * 60;
178
179/// Audit scheduler cadence range (min).
180pub const AUDIT_TICK_INTERVAL_MIN: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MIN_SECS);
181
182/// Audit scheduler cadence range (max).
183pub const AUDIT_TICK_INTERVAL_MAX: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MAX_SECS);
184
185/// Floor on the audit response deadline (independent of challenge size).
186///
187/// Sized to absorb worst-case global RTT for the audit envelope
188/// (the request + response messages are KB-scale, not chunk-scale)
189/// plus scheduling jitter. Tokyo↔NY round-trip is ~150ms each way,
190/// so 4 seconds comfortably covers cross-continent communication
191/// for the round-1 proof, whose payload is hashes (KB-scale).
192const AUDIT_RESPONSE_FLOOR_SECS: u64 = 4;
193
194/// Floor on the round-2 BYTE-challenge deadline.
195///
196/// Unlike round 1 (KB of hashes), the byte challenge ships up to
197/// `MAX_BYTE_CHALLENGE_KEYS` full chunks (2 × 4 MiB = 8 MiB) back over the
198/// wire, so the envelope must also cover a cold QUIC handshake, the
199/// multi-MiB upload back to the auditor, and a busy honest peer's disk read.
200/// The round-1 4 s floor is still sized for a hashes-only reply; round 2 needs
201/// a larger base for the §4 byte-serving envelope. 5 s matches the
202/// cross-continent-RTT + handshake + 8 MiB transfer budget while keeping a relay
203/// that must fetch the bytes over a residential link outside it (the scaled
204/// term adds the per-byte estimate on top). Mirrors main's more generous
205/// byte-round base.
206const BYTE_AUDIT_RESPONSE_FLOOR_SECS: u64 = 5;
207
208/// Conservative honest-responder read throughput, in bytes per second.
209///
210/// Used to size the audit response deadline. An honest peer answers
211/// a k-key challenge by reading k chunks from local disk, computing
212/// BLAKE3 + path proofs, and signing the response. The bottleneck is
213/// disk read; BLAKE3 at ~3 GB/s + ML-DSA signing at ~3 ms are
214/// negligible.
215///
216/// Set conservatively below any modern SSD (typical: 500 MB/s+).
217/// At 50 MB/s, a k=10 sample at 4 MiB chunks reads in ~0.8s, well
218/// inside even an aggressive timeout. A relay attacker who must
219/// fetch the same 40 MB over the network at typical bandwidth
220/// (100 Mbps = 12.5 MB/s) takes 3+ seconds for the data alone, plus
221/// per-chunk network round-trips. At larger sample sizes the gap
222/// is exponential in the relay's disadvantage.
223const AUDIT_HONEST_READ_BPS: u64 = 50 * 1024 * 1024;
224
225/// Slack multiplier on the honest-read estimate.
226///
227/// Set so an honest peer that's slower than `HONEST_READ_BPS` (e.g. an
228/// HDD-backed node, or one under load) still answers within the
229/// timeout. 5× is generous; a relay peer fetching the same data over a
230/// residential link (~5-12 MB/s) sees ~10-100× higher latency than disk
231/// and misses the budget. This is an economic deterrent calibrated for
232/// residential bandwidth, NOT a hard cryptographic bound — a relay on a
233/// datacenter cross-connect could still fetch fast enough to answer in
234/// time (see the §7 note on `audit_response_timeout`).
235const AUDIT_RESPONSE_HONEST_MULTIPLIER: u64 = 5;
236
237/// Maximum duration a peer may claim bootstrap status before penalties apply.
238const BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS: u64 = 24 * 60 * 60; // 24 h
239/// Maximum duration a peer may claim bootstrap status before penalties apply.
240pub const BOOTSTRAP_CLAIM_GRACE_PERIOD: Duration =
241 Duration::from_secs(BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS);
242
243/// Minimum continuous out-of-range duration before pruning a key.
244const PRUNE_HYSTERESIS_DURATION_SECS: u64 = 3 * 24 * 60 * 60; // 3 days
245/// Minimum continuous out-of-range duration before pruning a key.
246pub const PRUNE_HYSTERESIS_DURATION: Duration = Duration::from_secs(PRUNE_HYSTERESIS_DURATION_SECS);
247
248/// Protocol identifier for replication operations.
249///
250/// Bumped to `v2` for the v12 storage-bound audit. That change extends the
251/// wire types (`NeighborSyncRequest`/`Response` carry an optional trailing
252/// `StorageCommitment`, and the gossip-triggered storage-commitment audit adds
253/// the `SubtreeAuditChallenge`/`SubtreeAuditResponse` and `SubtreeByteChallenge`/
254/// `SubtreeByteResponse` messages). The bump is for SEMANTIC interop, not
255/// decode failure: postcard tolerates the appended optional field (an old
256/// decoder reads the fields it knows and ignores the trailer — pinned by the
257/// `old_decoder_tolerates_new_neighbor_sync_*` tests in `protocol.rs`), but
258/// tolerating bytes is not interoperating. A v1 node cannot decode the NEW
259/// message variants at all (unknown enum discriminant) and never acts on a
260/// piggybacked commitment, so mixed-version replication would half-function —
261/// audit challenges unanswered, commitments silently dropped — and a v2 node
262/// could read that silence as misbehaviour. Rather than reason about each
263/// such case, we route v12 replication on a distinct protocol id: a node only
264/// delivers messages whose topic matches its own id (see the topic check in
265/// `mod.rs`), so v1 and v2 nodes simply do not exchange replication traffic
266/// during a mixed-version window. This is the rollout-safe behaviour: no
267/// half-interpreted exchange, no spurious eviction. Replication between
268/// matched-version peers is unaffected. (DHT routing/lookups are a separate
269/// protocol and continue to span both versions.)
270pub const REPLICATION_PROTOCOL_ID: &str = "autonomi.ant.replication.v2";
271
272/// 10 MiB — maximum replication wire message size (accommodates hint batches).
273const REPLICATION_MESSAGE_SIZE_MIB: usize = 10;
274/// Maximum replication wire message size.
275pub const MAX_REPLICATION_MESSAGE_SIZE: usize = REPLICATION_MESSAGE_SIZE_MIB * 1024 * 1024;
276
277/// Headroom reserved for the envelope (enum tags, ids, length prefixes) when
278/// sizing a round-2 byte-challenge batch against the wire cap.
279const BYTE_CHALLENGE_RESPONSE_HEADROOM: usize = 64 * 1024;
280
281/// Maximum keys per round-2 [`SubtreeByteChallenge`] (per-batch cap).
282///
283/// Sized so the WORST-CASE response (every requested chunk at
284/// `MAX_CHUNK_SIZE`) still encodes under [`MAX_REPLICATION_MESSAGE_SIZE`].
285/// The auditor splits its spot-check sample into batches of this size (one
286/// challenge per batch, same nonce/pin); the responder rejects any single
287/// challenge requesting more.
288///
289/// [`SubtreeByteChallenge`]: crate::replication::protocol::SubtreeByteChallenge
290pub const MAX_BYTE_CHALLENGE_KEYS: usize =
291 (MAX_REPLICATION_MESSAGE_SIZE - BYTE_CHALLENGE_RESPONSE_HEADROOM) / MAX_CHUNK_SIZE;
292const _: () = assert!(
293 MAX_BYTE_CHALLENGE_KEYS >= 1,
294 "wire cap must fit at least one max-size chunk per byte-challenge response"
295);
296
297/// Rollout gate for ADR-0004 quote-arithmetic enforcement.
298///
299/// When `true`, the payment verifier rejects any quote whose signed price does
300/// not lie exactly on the public pricing curve, i.e. there is no integer
301/// `key_count` for which `calculate_price(key_count) == quote.price`. The check
302/// is exact recomputation against the curve, never price-inversion (which
303/// rounds), per ADR-0004's "never by inverting the price" rule.
304///
305/// When `false`, the check still runs and logs every would-be rejection, but
306/// does not reject — matching the ADR-0004 rollout: ship observe-only first,
307/// enforce only once the fleet has upgraded. Off-curve quotes are honest
308/// errors, not signs of an old node (every honest implementation derives its
309/// price from the same public formula), so flipping this to `true` does not
310/// risk evicting un-upgraded peers; it only catches modified nodes that minted
311/// prices off the curve.
312///
313/// This is a reject-only gate: an off-curve quote produces no trust evidence
314/// and no audit, per ADR-0004 ("an off-curve quote is reject-only"). It does
315/// NOT gate the quote/commitment mismatch trust report — see
316/// [`QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED`] for that, kept separate because
317/// the two have different ADR-0004 contracts (this one rejects with no trust
318/// action; that one reports a deterministic contradiction to the trust engine).
319pub const QUOTE_ARITHMETIC_RECHECK_ENABLED: bool = false;
320
321/// Rollout gate for ADR-0004 quote/commitment **mismatch** trust reporting.
322///
323/// When a client-put quote's signed `committed_key_count` contradicts the
324/// `key_count` of the commitment it pinned (resolved from the gossip cache, a
325/// sidecar, or a fetch), that is two artifacts signed by the same key that
326/// contradict each other — a deterministic, first-occurrence misbehaviour. When
327/// `true`, the cross-check reports it to the trust engine as an
328/// `ApplicationFailure` (the same lane as a confirmed deterministic audit
329/// failure, NOT the timeout silence lane). When `false`, the cross-check only
330/// logs the would-be report (observe-only).
331///
332/// Kept independent of [`QUOTE_ARITHMETIC_RECHECK_ENABLED`] (which is
333/// reject-only with no trust action): a confirmed mismatch is not a mere
334/// off-curve price, so it deserves its own dial.
335pub const QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED: bool = false;
336
337/// Instant from which a merkle batch payment must carry the same 3x settlement
338/// multiplier the single-node path has always applied (ADR-0008). Unix seconds.
339///
340/// The single-node path settles a chunk at 3x the median quoted price. The
341/// merkle path submitted the bare quoted price as the on-chain payable amount,
342/// so the contract's `median16(amount) x 2^depth` came to 1x the median per
343/// padded leaf: the same chunk, stored and replicated identically, earned a
344/// third as much when it arrived in a batch.
345///
346/// **The rollout is client-first, and this constant is only its second half.**
347/// ant-client (ant-client#161) pays 3x immediately and unconditionally once
348/// released — no date, no flag — and un-upgraded nodes accept that, because 3x
349/// clears the 1x minimum they require. So the network is paid correctly from
350/// the moment the client ships. This instant is when upgraded nodes stop
351/// accepting anything less.
352///
353/// **Enforcement is on by default.** There is no shadow mode and no flag to
354/// flip later: a receipt stamped at or after this instant must settle at 3x or
355/// the store is refused. What the boundary buys is not a soft launch, it is
356/// compatibility with money that was already spent:
357///
358/// - A receipt stamped **before** the boundary is held to the historic 1x. It
359/// was paid in good faith under the old rule and the payer cannot get it
360/// back, so refusing it would destroy value rather than protect it.
361/// - Merkle receipts expire after `MERKLE_PAYMENT_EXPIRATION` (one week), and
362/// a receipt stamped in the future is refused outright. So once
363/// `boundary + one week` has passed, **every** still-valid receipt is
364/// necessarily stamped at or after the boundary and the 1x branch becomes
365/// unreachable. It retires itself; nobody has to remember to turn it off.
366/// - Backdating is **not** prevented during that week. The timestamp is
367/// client-chosen — it is a `payForMerkleTree` argument, the contract only
368/// rejects future and week-old stamps, and quoting nodes sign whatever stamp
369/// the request carries — so a modified client can stamp just before the
370/// boundary and keep paying 1x until such a stamp expires. Expiry is what
371/// closes the route, not detection, and it closes it at
372/// `boundary + one week`. The same branch protects honest in-flight receipts,
373/// so the window cannot be narrowed without also destroying those.
374///
375/// Set to 2026-08-04 15:00 UTC, after the client release with room for
376/// adoption. Two invariants when moving it: **it must never be earlier than the
377/// client release that pays 3x** (an earlier value refuses receipts bought
378/// under the previous rule, the one outcome this constant exists to avoid), and
379/// it must move forward if that **client** release slips — a node enforcing
380/// before clients pay fails every batch upload. A slip in *node* rollout needs
381/// no change: it only means fewer nodes enforce for a while.
382pub const MERKLE_PARITY_ENFORCED_FROM_UNIX: u64 = 1_785_855_600;
383
384/// ADR-0004: max unresolved quote pins to fetch per payment bundle.
385///
386/// A bundle has at most `CLOSE_GROUP_SIZE` quotes; capping fetches per bundle
387/// bounds the amplification a single malicious upload (many distinct unknown
388/// pins) can drive. Excess unresolved pins in one bundle are dropped (left
389/// unresolved, i.e. graced — the audit funnel still catches a serving cheater).
390pub const MAX_PIN_FETCHES_PER_BUNDLE: usize = 3;
391
392/// ADR-0004: capacity of the per-peer negative cache for unresolved pin fetches.
393///
394/// A pin that a peer answered `NotRetained` (or that timed out) is remembered so
395/// repeated bundles citing the same unknown pin don't re-fetch.
396pub const PIN_FETCH_NEGATIVE_CACHE_CAPACITY: usize = 4096;
397
398/// ADR-0004: timeout for a `GetCommitmentByPin` fetch.
399///
400/// Sized for a single small round-trip plus the responder's bounded in-memory
401/// lookup; a fetch is off the payment hot path, so this only bounds the
402/// background cross-check.
403pub const PIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
404
405/// Verification request timeout (per-batch).
406const VERIFICATION_REQUEST_TIMEOUT_SECS: u64 = 15;
407/// Verification request timeout (per-batch).
408pub const VERIFICATION_REQUEST_TIMEOUT: Duration =
409 Duration::from_secs(VERIFICATION_REQUEST_TIMEOUT_SECS);
410
411/// Fetch request timeout.
412const FETCH_REQUEST_TIMEOUT_SECS: u64 = 30;
413/// Fetch request timeout.
414pub const FETCH_REQUEST_TIMEOUT: Duration = Duration::from_secs(FETCH_REQUEST_TIMEOUT_SECS);
415
416/// Maximum age for pending-verification entries before stale eviction.
417const PENDING_VERIFY_MAX_AGE_SECS: u64 = 30 * 60;
418/// Maximum age for pending-verification entries before stale eviction.
419pub const PENDING_VERIFY_MAX_AGE: Duration = Duration::from_secs(PENDING_VERIFY_MAX_AGE_SECS);
420
421/// Trust event weight for confirmed audit failures.
422pub const AUDIT_FAILURE_TRUST_WEIGHT: f64 = 5.0;
423
424/// Probability of launching a subtree audit when a peer's *changed* commitment
425/// is ingested via gossip (ADR-0002). Keeps audits occasional surprise exams.
426pub const AUDIT_ON_GOSSIP_PROBABILITY: f64 = 0.2;
427
428/// Per-peer cooldown between gossip-triggered subtree audits (ADR-0002), in
429/// seconds. Bounds how often any one peer is audited regardless of gossip rate.
430pub const AUDIT_ON_GOSSIP_COOLDOWN_SECS: u64 = 30 * 60;
431
432/// ADR-0004: first-audit drainer retry cadence for cooldown-pending pins.
433///
434/// How often the drainer retries pins it kept pending because their peer was on
435/// cooldown. Finer than the cooldown itself so a monetized commitment is
436/// first-audited promptly after its peer's window reopens; the retry just
437/// re-checks a small per-peer map, so the tick is cheap.
438pub const FIRST_AUDIT_RETRY_INTERVAL: Duration = Duration::from_secs(60);
439
440/// Interval for the cumulative first-audit scheduler observability summary.
441///
442/// Deliberately low frequency: this is intended for fleet-level Elasticsearch
443/// aggregation without recreating the high-volume logging load it measures.
444pub const FIRST_AUDIT_SUMMARY_INTERVAL: Duration = Duration::from_secs(5 * 60);
445
446/// ADR-0004: max monetized-pin events the first-audit drainer drains from its
447/// channel per wake before it must run the audit-launch phase.
448///
449/// Bounds the synchronous `try_recv` batch so a sustained producer flood cannot
450/// starve audit launching by spinning in the drain loop forever. After this many
451/// events the drainer processes audits, then loops back to drain more.
452pub const FIRST_AUDIT_DRAIN_BATCH: usize = 64;
453
454/// ADR-0004 Amendment 2: token-bucket refill interval for monetized first-audit
455/// launches — one launch token per interval, per node.
456///
457/// This is the load-bearing bound: fleet-wide first-audit pressure becomes
458/// `nodes x (1 / interval)` regardless of upload volume, where the pre-amendment
459/// scheduler scaled with `uploads x pinned-quotes-per-proof x verifying-storers`
460/// (measured at ~110 storage-commitment audit events/hour/service in the
461/// DEV-01 staging run, with 77.7% of launches timing out in the DEV-03
462/// per-service-concurrency attempt). At 5 minutes the sustained rate is
463/// 12 launches/hour/node (a drained burst bucket adds at most
464/// [`FIRST_AUDIT_BUDGET_BURST`] more in the first hour); steady-state demand
465/// sits far below it because nomination is paid-pin-only and re-nominations
466/// are suppressed by [`FIRST_AUDIT_PEER_REAUDIT_INTERVAL`].
467pub const FIRST_AUDIT_LAUNCH_INTERVAL: Duration = Duration::from_secs(5 * 60);
468
469/// ADR-0004 Amendment 2: token-bucket capacity for monetized first-audit
470/// launches.
471///
472/// Lets a node absorb a small burst of NEW earning peers (several distinct
473/// paid pins verified back-to-back) without waiting a full refill interval per
474/// launch, while keeping the sustained rate pinned to
475/// [`FIRST_AUDIT_LAUNCH_INTERVAL`].
476pub const FIRST_AUDIT_BUDGET_BURST: u32 = 2;
477
478/// ADR-0004 Amendment 2: max concurrently in-flight monetized first audits per
479/// node.
480///
481/// A first audit can hold a slot for the full size-scaled two-round deadline,
482/// so without this cap a burst of slow/timing-out targets would pile up
483/// concurrent subtree audits even under the launch-rate budget. Deferral is
484/// penalty-free: the pin stays pending and is retried when a slot frees.
485pub const FIRST_AUDIT_MAX_INFLIGHT: u64 = 2;
486
487/// ADR-0004 Amendment 2: max uniform random delay applied before sending a
488/// monetized first-audit challenge.
489///
490/// Every storer of a chunk verifies the same payment at the same instant, so
491/// unjittered first audits from the whole close group would hit the paid peer
492/// simultaneously and trip its per-peer responder admission cap (drops that
493/// auditors then record as Timeout). The jitter decorrelates the observers.
494pub const FIRST_AUDIT_LAUNCH_JITTER_MAX: Duration = Duration::from_secs(30);
495
496/// ADR-0004 Amendment 2: per-peer suppression window between monetized first
497/// audits, across commitment rotations.
498///
499/// Pin-level dedup alone is defeated by the hourly commitment rotation (every
500/// rotation mints a fresh pin, re-arming every observer). After a first audit
501/// LAUNCHES at a peer, further monetized nominations for that peer are dropped
502/// for this window — unless the new pin's committed key count exceeds the
503/// audited one by more than [`FIRST_AUDIT_COUNT_JUMP_NUM`]/
504/// [`FIRST_AUDIT_COUNT_JUMP_DEN`] (a peer that passes an audit on an honest
505/// count and then mints a much larger commitment must be re-nominated
506/// immediately: inflated SIDECAR-ONLY pins are visible to payment verifiers
507/// only, so no gossip-lottery audit can ever cover them). Kept comfortably
508/// inside the 3h answerability TTL so a re-nomination after the window still
509/// lands in-window. Gossip-lottery re-audits are unaffected.
510pub const FIRST_AUDIT_PEER_REAUDIT_INTERVAL: Duration = Duration::from_secs(2 * 3600);
511
512/// ADR-0004 Amendment 2: committed-count jump that overrides the per-peer
513/// re-audit window, as a ratio (`new > old * NUM / DEN`, integer math).
514///
515/// 3/2: a >1.5x growth in claimed committed keys within the suppression window
516/// re-nominates the peer despite a recent first audit.
517pub const FIRST_AUDIT_COUNT_JUMP_NUM: u64 = 3;
518/// Denominator of the count-jump override ratio. See
519/// [`FIRST_AUDIT_COUNT_JUMP_NUM`].
520pub const FIRST_AUDIT_COUNT_JUMP_DEN: u64 = 2;
521
522/// ADR-0004 Amendment 2: capacity of the bounded verifier-to-drainer
523/// monetized-pin channel.
524///
525/// Nominations are gated behind SETTLED on-chain payments, so legitimate
526/// ingress is tiny; the drainer drains every wake (batched at
527/// [`FIRST_AUDIT_DRAIN_BATCH`]) and coalesces newest-per-peer, so a backlog
528/// this deep implies the drainer is starved, not that work is arriving fast.
529/// Producers `try_send` and drop on full: a dropped nomination is
530/// penalty-free; the peer's gossiped commitments stay lottery-covered and
531/// its next settled payment re-nominates the paid pin.
532pub const FIRST_AUDIT_INGRESS_CAPACITY: usize = 1024;
533
534/// Number of subtree leaves spot-checked against real chunk bytes per audit
535/// (ADR-0002 real-bytes layer).
536///
537/// The auditor clamps this to its 3..=5 band (`BYTE_SPOTCHECK_MIN..=MAX` in
538/// `storage_commitment_audit`), so this is the effective MAXIMUM — set it
539/// within the band rather than advertising a sample size the auditor never
540/// requests.
541pub const AUDIT_SPOTCHECK_COUNT: u32 = 5;
542
543/// Conservative leaf-count hint for sizing the subtree-audit response deadline.
544///
545/// The deadline is set before the proof arrives, so we size for the largest
546/// legal store: `sqrt(MAX_COMMITMENT_KEY_COUNT) = 1000`. Honest small stores
547/// finish well within it.
548pub const SUBTREE_AUDIT_TIMEOUT_LEAF_HINT: usize = 1000;
549
550/// Maximum number of prune-confirmation audit challenges sent per prune pass.
551pub const MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS: usize = 64;
552
553/// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before proceeding
554/// with bootstrap sync. Covers bootstrap nodes with no peers to connect to.
555const BOOTSTRAP_COMPLETE_TIMEOUT_SECS: u64 = 60;
556
557// ---------------------------------------------------------------------------
558// Runtime-configurable wrapper
559// ---------------------------------------------------------------------------
560
561/// Runtime-configurable replication parameters.
562///
563/// Validated on construction — node rejects invalid configs.
564#[derive(Debug, Clone)]
565pub struct ReplicationConfig {
566 /// Close-group width and target holder count per key.
567 pub close_group_size: usize,
568 /// Required positive presence votes for quorum.
569 pub quorum_threshold: usize,
570 /// Maximum closest nodes tracking paid status for a key.
571 pub paid_list_close_group_size: usize,
572 /// Number of closest peers to self eligible for neighbor sync.
573 pub neighbor_sync_scope: usize,
574 /// Peers synced concurrently per round-robin repair round.
575 pub neighbor_sync_peer_count: usize,
576 /// Neighbor sync cadence range (min).
577 pub neighbor_sync_interval_min: Duration,
578 /// Neighbor sync cadence range (max).
579 pub neighbor_sync_interval_max: Duration,
580 /// Minimum spacing between successive syncs with the same peer.
581 pub neighbor_sync_cooldown: Duration,
582 /// Self-lookup cadence range (min).
583 pub self_lookup_interval_min: Duration,
584 /// Self-lookup cadence range (max).
585 pub self_lookup_interval_max: Duration,
586 /// Audit scheduler cadence range (min).
587 pub audit_tick_interval_min: Duration,
588 /// Audit scheduler cadence range (max).
589 pub audit_tick_interval_max: Duration,
590 /// Floor on the audit response deadline. Covers global RTT for
591 /// the small request/response envelope plus scheduling jitter.
592 /// See `AUDIT_RESPONSE_FLOOR_SECS` for sizing.
593 pub audit_response_floor: Duration,
594 /// Conservative honest-responder read throughput (bytes/sec).
595 /// Used to scale the audit response deadline against the size of
596 /// the challenge. Slow enough that even an HDD-backed honest peer
597 /// fits inside the budget; fast enough that a relay attacker who
598 /// must fetch bytes over the network falls outside.
599 pub audit_honest_read_bps: u64,
600 /// Slack multiplier on the honest-read estimate before
601 /// declaring an audit timed out.
602 pub audit_response_honest_multiplier: u64,
603 /// Maximum duration a peer may claim bootstrap status.
604 pub bootstrap_claim_grace_period: Duration,
605 /// Minimum continuous out-of-range duration before pruning a key.
606 pub prune_hysteresis_duration: Duration,
607 /// Verification request timeout (per-batch).
608 pub verification_request_timeout: Duration,
609 /// Fetch request timeout.
610 pub fetch_request_timeout: Duration,
611 /// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before
612 /// proceeding with bootstrap sync (covers bootstrap nodes with no peers).
613 pub bootstrap_complete_timeout_secs: u64,
614 /// Lower bound of the delay before a fresh-replication possession check
615 /// runs (ADR-0003). Defaults to [`POSSESSION_CHECK_DELAY_MIN`]; tests
616 /// shorten it so the scheduled check fires quickly.
617 pub possession_check_delay_min: Duration,
618 /// Upper bound of the possession-check delay window (ADR-0003). Defaults
619 /// to [`POSSESSION_CHECK_DELAY_MAX`].
620 pub possession_check_delay_max: Duration,
621}
622
623impl Default for ReplicationConfig {
624 fn default() -> Self {
625 Self {
626 close_group_size: CLOSE_GROUP_SIZE,
627 quorum_threshold: QUORUM_THRESHOLD,
628 paid_list_close_group_size: PAID_LIST_CLOSE_GROUP_SIZE,
629 neighbor_sync_scope: NEIGHBOR_SYNC_SCOPE,
630 neighbor_sync_peer_count: NEIGHBOR_SYNC_PEER_COUNT,
631 neighbor_sync_interval_min: NEIGHBOR_SYNC_INTERVAL_MIN,
632 neighbor_sync_interval_max: NEIGHBOR_SYNC_INTERVAL_MAX,
633 neighbor_sync_cooldown: NEIGHBOR_SYNC_COOLDOWN,
634 self_lookup_interval_min: SELF_LOOKUP_INTERVAL_MIN,
635 self_lookup_interval_max: SELF_LOOKUP_INTERVAL_MAX,
636 audit_tick_interval_min: AUDIT_TICK_INTERVAL_MIN,
637 audit_tick_interval_max: AUDIT_TICK_INTERVAL_MAX,
638 audit_response_floor: Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
639 audit_honest_read_bps: AUDIT_HONEST_READ_BPS,
640 audit_response_honest_multiplier: AUDIT_RESPONSE_HONEST_MULTIPLIER,
641 bootstrap_claim_grace_period: BOOTSTRAP_CLAIM_GRACE_PERIOD,
642 prune_hysteresis_duration: PRUNE_HYSTERESIS_DURATION,
643 verification_request_timeout: VERIFICATION_REQUEST_TIMEOUT,
644 fetch_request_timeout: FETCH_REQUEST_TIMEOUT,
645 bootstrap_complete_timeout_secs: BOOTSTRAP_COMPLETE_TIMEOUT_SECS,
646 possession_check_delay_min: POSSESSION_CHECK_DELAY_MIN,
647 possession_check_delay_max: POSSESSION_CHECK_DELAY_MAX,
648 }
649 }
650}
651
652impl ReplicationConfig {
653 /// Validate safety constraints. Returns `Err` with a description if any
654 /// constraint is violated.
655 ///
656 /// # Errors
657 ///
658 /// Returns a human-readable message describing the first violated
659 /// constraint.
660 pub fn validate(&self) -> Result<(), String> {
661 if self.close_group_size == 0 {
662 return Err("close_group_size must be >= 1".to_string());
663 }
664 if self.quorum_threshold == 0 || self.quorum_threshold > self.close_group_size {
665 return Err(format!(
666 "quorum_threshold ({}) must satisfy 1 <= quorum_threshold <= close_group_size ({})",
667 self.quorum_threshold, self.close_group_size,
668 ));
669 }
670 if self.close_group_size > MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS {
671 return Err(format!(
672 "close_group_size ({}) must be <= MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS ({})",
673 self.close_group_size, MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS,
674 ));
675 }
676 if self.paid_list_close_group_size == 0 {
677 return Err("paid_list_close_group_size must be >= 1".to_string());
678 }
679 if self.neighbor_sync_interval_min > self.neighbor_sync_interval_max {
680 return Err(format!(
681 "neighbor_sync_interval_min ({:?}) must be <= neighbor_sync_interval_max ({:?})",
682 self.neighbor_sync_interval_min, self.neighbor_sync_interval_max,
683 ));
684 }
685 if self.audit_tick_interval_min > self.audit_tick_interval_max {
686 return Err(format!(
687 "audit_tick_interval_min ({:?}) must be <= audit_tick_interval_max ({:?})",
688 self.audit_tick_interval_min, self.audit_tick_interval_max,
689 ));
690 }
691 if self.self_lookup_interval_min > self.self_lookup_interval_max {
692 return Err(format!(
693 "self_lookup_interval_min ({:?}) must be <= self_lookup_interval_max ({:?})",
694 self.self_lookup_interval_min, self.self_lookup_interval_max,
695 ));
696 }
697 if self.neighbor_sync_peer_count == 0 {
698 return Err("neighbor_sync_peer_count must be >= 1".to_string());
699 }
700 if self.neighbor_sync_scope == 0 {
701 return Err("neighbor_sync_scope must be >= 1".to_string());
702 }
703 if self.neighbor_sync_scope > K_BUCKET_SIZE {
704 return Err(format!(
705 "neighbor_sync_scope ({}) must be <= K_BUCKET_SIZE ({})",
706 self.neighbor_sync_scope, K_BUCKET_SIZE,
707 ));
708 }
709 Ok(())
710 }
711
712 /// Effective quorum votes required for a key given the number of
713 /// reachable quorum targets.
714 ///
715 /// `min(self.quorum_threshold, floor(quorum_targets_count / 2) + 1)`
716 #[must_use]
717 pub fn quorum_needed(&self, quorum_targets_count: usize) -> usize {
718 if quorum_targets_count == 0 {
719 return 0;
720 }
721 let majority = quorum_targets_count / 2 + 1;
722 self.quorum_threshold.min(majority)
723 }
724
725 /// Confirmations required for paid-list consensus given the number of
726 /// peers in the paid-list close group for a key.
727 ///
728 /// `floor(paid_group_size / 2) + 1`
729 #[must_use]
730 pub fn confirm_needed(paid_group_size: usize) -> usize {
731 paid_group_size / 2 + 1
732 }
733
734 /// Returns a random duration in `[neighbor_sync_interval_min,
735 /// neighbor_sync_interval_max]`.
736 #[must_use]
737 pub fn random_neighbor_sync_interval(&self) -> Duration {
738 random_duration_in_range(
739 self.neighbor_sync_interval_min,
740 self.neighbor_sync_interval_max,
741 )
742 }
743
744 /// Compute the number of keys to sample for an audit round, scaled
745 /// dynamically by the total number of locally stored keys.
746 ///
747 /// Formula: `max(floor(sqrt(total_keys)), 1)`, capped at `total_keys`.
748 #[must_use]
749 pub fn audit_sample_count(total_keys: usize) -> usize {
750 #[allow(
751 clippy::cast_possible_truncation,
752 clippy::cast_sign_loss,
753 clippy::cast_precision_loss
754 )]
755 let sqrt = (total_keys as f64).sqrt() as usize;
756 sqrt.max(1).min(total_keys)
757 }
758
759 /// Maximum number of keys this node should send in one responsible-chunk
760 /// [`AuditChallenge`].
761 ///
762 /// This is the sender-side limit used by the normal responsible audit path:
763 /// one challenge samples at most `sqrt(local_stored_keys)` keys. Other paths
764 /// that reuse the same `AuditChallenge` wire message, such as
765 /// prune-confirmation audits, should chunk to this same limit instead of
766 /// inventing a larger batch size.
767 ///
768 /// [`AuditChallenge`]: crate::replication::protocol::AuditChallenge
769 #[must_use]
770 pub fn responsible_audit_key_limit(local_stored_keys: usize) -> usize {
771 Self::audit_sample_count(local_stored_keys)
772 }
773
774 /// Maximum number of keys to accept in an incoming audit challenge.
775 ///
776 /// Scales dynamically from the same responsible-audit sender limit, with a
777 /// 2x margin to account for the challenger having a larger local store than
778 /// us and therefore sampling more keys.
779 #[must_use]
780 pub fn max_incoming_audit_keys(stored_chunks: usize) -> usize {
781 // Allow at least 1 key so a newly-joined node can still be audited.
782 (2 * Self::responsible_audit_key_limit(stored_chunks)).max(1)
783 }
784
785 /// Compute the audit response timeout for a challenge with
786 /// `challenged_key_count` keys, **sized to be tight enough that a
787 /// relay attacker that must fetch the chunk bytes from elsewhere
788 /// falls outside the budget**.
789 ///
790 /// Formula:
791 /// `floor + (challenged_bytes / honest_read_bps) × multiplier`
792 ///
793 /// Where `challenged_bytes = k × MAX_CHUNK_SIZE`. An honest peer
794 /// reads `k × 4 MiB` from local disk at `honest_read_bps` (set
795 /// conservatively at 50 MB/s — well below modern SSDs); the
796 /// multiplier of 5 absorbs jitter, BLAKE3, ML-DSA, and slow disks.
797 ///
798 /// A relay attacker on a residential link (~5-12 MB/s) who must
799 /// fetch the same `k × 4 MiB` over the network sees ~10-100× higher
800 /// latency than disk for the data alone, plus per-chunk round-trips,
801 /// and misses the budget. In the periodic responsible-chunk
802 /// `AuditChallenge`, prune-confirmation, and ADR-0003 possession-check paths
803 /// that timeout is an immediate audit failure. The heavier subtree audit
804 /// still graces timeouts separately.
805 ///
806 /// This is an economic deterrent for the §7 relay limit calibrated
807 /// for residential bandwidth, NOT a hard bound: a relay on a
808 /// datacenter cross-connect (≥1 Gbps) can fetch `k × 4 MiB` fast
809 /// enough to answer in time. It raises the relay's cost (bandwidth
810 /// per audit) without claiming to make relaying impossible. The
811 /// cryptographic guarantee remains commitment-binding (the relay
812 /// must still hold or fetch the exact committed bytes); the timeout
813 /// only attacks the economics.
814 #[must_use]
815 pub fn audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
816 let bytes_per_key = u64::try_from(crate::ant_protocol::MAX_CHUNK_SIZE).unwrap_or(u64::MAX);
817 let keys = u64::try_from(challenged_key_count).unwrap_or(u64::MAX);
818 let total_bytes = bytes_per_key.saturating_mul(keys);
819 let bps = self.audit_honest_read_bps.max(1);
820 // Apply the multiplier BEFORE integer-dividing by bps so each
821 // chunk contributes a fractional second rather than rounding
822 // down to zero. Otherwise k in 1..=12 would all collapse to the
823 // floor (~40 MiB / 50 MB/s = 0 secs in integer arithmetic), and
824 // an honest HDD-backed peer at sqrt(N)=10 stored chunks could
825 // miss the budget under load.
826 let multiplied = total_bytes.saturating_mul(self.audit_response_honest_multiplier);
827 // Resolve the scaled term in MILLISECONDS, not seconds: at the
828 // byte-round sizes (MAX_BYTE_CHALLENGE_KEYS = 2 → 8 MiB) the per-second
829 // quotient `multiplied / bps` integer-truncates to 0, leaving only the
830 // floor. The §4 finding was that byte-serving challenges need the
831 // sub-second honest-read estimate (e.g. 8 MiB × 5 / 50 MB/s ≈ 840 ms)
832 // instead of dropping it.
833 let scaled_ms = multiplied.saturating_mul(1000) / bps;
834 // saturating_add avoids a panic if the floor plus the scaled term would
835 // overflow `Duration::MAX`.
836 self.audit_response_floor
837 .saturating_add(Duration::from_millis(scaled_ms))
838 }
839
840 /// Deadline for the round-2 BYTE challenge serving `challenged_key_count`
841 /// full chunks back to the auditor.
842 ///
843 /// Same per-byte scaling as [`Self::audit_response_timeout`] (so a relay
844 /// that must fetch the bytes over a residential link still blows it), but on
845 /// a higher floor (`BYTE_AUDIT_RESPONSE_FLOOR_SECS`) because the reply
846 /// carries up to
847 /// `MAX_BYTE_CHALLENGE_KEYS × MAX_CHUNK_SIZE` of chunk data — handshake +
848 /// multi-MiB upload + a busy honest disk read do not fit the hashes-only
849 /// round-1 floor (the §4 finding).
850 #[must_use]
851 pub fn byte_audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
852 let scaled = self
853 .audit_response_timeout(challenged_key_count)
854 .saturating_sub(self.audit_response_floor);
855 Duration::from_secs(BYTE_AUDIT_RESPONSE_FLOOR_SECS).saturating_add(scaled)
856 }
857
858 /// Number of subtree leaves to spot-check against real chunk bytes per
859 /// audit (ADR-0002 real-bytes layer). Faking a fraction `x` of nonced
860 /// leaves survives only `(1 - x)^k`.
861 #[must_use]
862 pub fn audit_spotcheck_count(&self) -> u32 {
863 AUDIT_SPOTCHECK_COUNT
864 }
865
866 /// Conservative leaf-count hint for sizing the subtree-audit response
867 /// deadline before the proof arrives.
868 ///
869 /// The selected subtree holds about `sqrt(key_count)` real leaves; sizing
870 /// for a large store keeps an honest peer with a big store from timing out.
871 #[must_use]
872 pub fn subtree_audit_timeout_leaf_hint(&self) -> usize {
873 SUBTREE_AUDIT_TIMEOUT_LEAF_HINT
874 }
875
876 /// Returns a random duration in `[audit_tick_interval_min,
877 /// audit_tick_interval_max]`.
878 #[must_use]
879 pub fn random_audit_tick_interval(&self) -> Duration {
880 random_duration_in_range(self.audit_tick_interval_min, self.audit_tick_interval_max)
881 }
882
883 /// Returns a random duration in `[self_lookup_interval_min,
884 /// self_lookup_interval_max]`.
885 #[must_use]
886 pub fn random_self_lookup_interval(&self) -> Duration {
887 random_duration_in_range(self.self_lookup_interval_min, self.self_lookup_interval_max)
888 }
889}
890
891/// Pick a random `Duration` uniformly in `[min, max]` at millisecond
892/// granularity.
893///
894/// When `min == max` the result is deterministic.
895fn random_duration_in_range(min: Duration, max: Duration) -> Duration {
896 if min == max {
897 return min;
898 }
899 // Our intervals are minutes/hours, well within u64 range. Saturate to
900 // u64::MAX on the impossible overflow path to avoid a lossy cast.
901 let to_u64_millis = |d: Duration| -> u64 { u64::try_from(d.as_millis()).unwrap_or(u64::MAX) };
902 let chosen = rand::thread_rng().gen_range(to_u64_millis(min)..=to_u64_millis(max));
903 Duration::from_millis(chosen)
904}
905
906// ---------------------------------------------------------------------------
907// Tests
908// ---------------------------------------------------------------------------
909
910#[cfg(test)]
911#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
912mod tests {
913 use super::*;
914
915 #[test]
916 fn defaults_pass_validation() {
917 let config = ReplicationConfig::default();
918 assert!(config.validate().is_ok(), "default config must be valid");
919 }
920
921 #[test]
922 fn default_prune_hysteresis_is_three_days() {
923 let config = ReplicationConfig::default();
924 assert_eq!(
925 config.prune_hysteresis_duration,
926 Duration::from_secs(3 * 24 * 60 * 60)
927 );
928 }
929
930 #[test]
931 fn storage_admission_width_adds_margin() {
932 const TEST_CLOSE_GROUP_SIZE: usize = 7;
933
934 assert_eq!(
935 storage_admission_width(TEST_CLOSE_GROUP_SIZE),
936 TEST_CLOSE_GROUP_SIZE + STORAGE_ADMISSION_MARGIN
937 );
938 assert_eq!(storage_admission_width(usize::MAX), usize::MAX);
939 }
940
941 #[test]
942 fn audit_failure_weight_is_five() {
943 assert!((AUDIT_FAILURE_TRUST_WEIGHT - 5.0).abs() <= f64::EPSILON);
944 }
945
946 #[test]
947 fn replication_protocol_id_is_v2() {
948 // The v12 storage-bound audit changes replication SEMANTICS. The
949 // protocol id MUST advance past v1 so v1 and v2 nodes never exchange
950 // replication traffic they can only half-interpret (rollout safety —
951 // see the const's doc). If this regresses to v1, mixed-version nodes
952 // would talk past each other and risk spurious penalties.
953 assert_eq!(REPLICATION_PROTOCOL_ID, "autonomi.ant.replication.v2");
954 }
955
956 #[test]
957 fn audit_response_timeout_floor_at_zero_keys() {
958 let config = ReplicationConfig::default();
959 assert_eq!(
960 config.audit_response_timeout(0),
961 Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
962 "zero-key challenge should yield the floor exactly"
963 );
964 }
965
966 #[test]
967 fn audit_response_timeout_scales_with_key_count() {
968 let config = ReplicationConfig::default();
969 let t1 = config.audit_response_timeout(1);
970 let t10 = config.audit_response_timeout(10);
971 let t100 = config.audit_response_timeout(100);
972 assert!(t1 <= t10 && t10 < t100, "timeout must not decrease with k");
973
974 // Scaling now resolves in MILLISECONDS so a sub-second honest read no
975 // longer truncates to zero (§4). For k=1:
976 // (4_194_304 × 5 × 1000) / 52_428_800 = 400 ms, + 4 s round-1 floor =
977 // 4.4 s.
978 assert_eq!(t1, Duration::from_millis(4400));
979
980 // For k=10: (10 × 4_194_304 × 5 × 1000) / 52_428_800 = 4000 ms scaled,
981 // + 4 s floor = 8 s. An HDD-backed honest peer at 20 MB/s reads 40 MiB
982 // in ~2 s, comfortably inside; a relay fetching 40 MiB at 5 MB/s
983 // residential bandwidth needs ~8 s for the data alone, outside.
984 assert_eq!(t10, Duration::from_secs(8));
985
986 // For k=100: (100 × 4_194_304 × 5 × 1000) / 52_428_800 = 40_000 ms
987 // scaled, + 4 s floor = 44 s.
988 assert_eq!(t100, Duration::from_secs(44));
989 }
990
991 #[test]
992 fn audit_response_timeout_fits_honest_hdd_at_typical_sample_size() {
993 // The canonical audit sample is sqrt(N) at N stored chunks.
994 // At N=100 stored chunks, sample is 10. An HDD-backed honest
995 // peer at the slowest realistic random-read throughput (20 MB/s,
996 // well below modern HDDs which sustain 80-150 MB/s sequential)
997 // reads 10 × 4 MiB = 40 MiB in ~2 s. Add 300 ms cross-continent
998 // RTT, ~10 ms scheduling, ~3 ms ML-DSA sign, and the honest
999 // envelope is ~2.3 s. The 8 s budget at k=10 leaves >5 s of
1000 // slack.
1001 let config = ReplicationConfig::default();
1002 let budget = config.audit_response_timeout(10);
1003 let realistic_hdd_bps: u64 = 20 * 1024 * 1024;
1004 let bytes: u64 = 10 * 4 * 1024 * 1024;
1005 let honest_envelope_secs = bytes / realistic_hdd_bps + 1; // +1 s for network/scheduling/sign
1006 assert!(
1007 Duration::from_secs(honest_envelope_secs) < budget,
1008 "honest HDD envelope ({honest_envelope_secs}s) must fit inside k=10 budget ({}s)",
1009 budget.as_secs(),
1010 );
1011 }
1012
1013 #[test]
1014 fn audit_response_timeout_relay_is_outside_envelope() {
1015 // The intended invariant: an honest peer with the SSD-class
1016 // read budget fits inside `audit_response_timeout(k)`, while a
1017 // relay attacker fetching k*4MiB over residential bandwidth
1018 // (≈ 5 MB/s realistic for sustained download) does NOT. Spot-
1019 // check this at k=100: honest budget is 44s, relay needs at
1020 // least 100 * 4 MiB / 5 MB/s = 80s for the data alone, which
1021 // exceeds the budget.
1022 let config = ReplicationConfig::default();
1023 let budget = config.audit_response_timeout(100);
1024 let relay_data_only = Duration::from_secs(100 * 4 * 1024 * 1024 / (5 * 1024 * 1024));
1025 assert!(
1026 relay_data_only > budget,
1027 "relay fetch ({}s) must exceed honest audit budget ({}s)",
1028 relay_data_only.as_secs(),
1029 budget.as_secs(),
1030 );
1031 }
1032
1033 #[test]
1034 fn audit_response_timeout_saturates_on_huge_k() {
1035 let config = ReplicationConfig::default();
1036 // Should not panic or overflow at extreme k values.
1037 let _ = config.audit_response_timeout(usize::MAX);
1038 }
1039
1040 #[test]
1041 fn quorum_threshold_zero_rejected() {
1042 let config = ReplicationConfig {
1043 quorum_threshold: 0,
1044 ..ReplicationConfig::default()
1045 };
1046 assert!(config.validate().is_err());
1047 }
1048
1049 #[test]
1050 fn quorum_threshold_exceeds_close_group_rejected() {
1051 let defaults = ReplicationConfig::default();
1052 let config = ReplicationConfig {
1053 quorum_threshold: defaults.close_group_size + 1,
1054 ..defaults
1055 };
1056 assert!(config.validate().is_err());
1057 }
1058
1059 #[test]
1060 fn close_group_size_zero_rejected() {
1061 let config = ReplicationConfig {
1062 close_group_size: 0,
1063 ..ReplicationConfig::default()
1064 };
1065 assert!(config.validate().is_err());
1066 }
1067
1068 #[test]
1069 fn close_group_size_exceeding_prune_audit_budget_rejected() {
1070 let config = ReplicationConfig {
1071 close_group_size: MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS + 1,
1072 quorum_threshold: QUORUM_THRESHOLD,
1073 ..ReplicationConfig::default()
1074 };
1075
1076 let err = config.validate().unwrap_err();
1077
1078 assert!(
1079 err.contains("MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS"),
1080 "error should mention prune audit budget: {err}"
1081 );
1082 }
1083
1084 #[test]
1085 fn paid_list_close_group_size_zero_rejected() {
1086 let config = ReplicationConfig {
1087 paid_list_close_group_size: 0,
1088 ..ReplicationConfig::default()
1089 };
1090 assert!(config.validate().is_err());
1091 }
1092
1093 #[test]
1094 fn neighbor_sync_interval_inverted_rejected() {
1095 let config = ReplicationConfig {
1096 neighbor_sync_interval_min: Duration::from_secs(100),
1097 neighbor_sync_interval_max: Duration::from_secs(50),
1098 ..ReplicationConfig::default()
1099 };
1100 assert!(config.validate().is_err());
1101 }
1102
1103 #[test]
1104 fn audit_tick_interval_inverted_rejected() {
1105 let config = ReplicationConfig {
1106 audit_tick_interval_min: Duration::from_secs(100),
1107 audit_tick_interval_max: Duration::from_secs(50),
1108 ..ReplicationConfig::default()
1109 };
1110 assert!(config.validate().is_err());
1111 }
1112
1113 #[test]
1114 fn self_lookup_interval_inverted_rejected() {
1115 let config = ReplicationConfig {
1116 self_lookup_interval_min: Duration::from_secs(100),
1117 self_lookup_interval_max: Duration::from_secs(50),
1118 ..ReplicationConfig::default()
1119 };
1120 assert!(config.validate().is_err());
1121 }
1122
1123 #[test]
1124 fn neighbor_sync_peer_count_zero_rejected() {
1125 let config = ReplicationConfig {
1126 neighbor_sync_peer_count: 0,
1127 ..ReplicationConfig::default()
1128 };
1129 assert!(config.validate().is_err());
1130 }
1131
1132 #[test]
1133 fn neighbor_sync_scope_exceeding_k_bucket_size_rejected() {
1134 let config = ReplicationConfig {
1135 neighbor_sync_scope: K_BUCKET_SIZE + 1,
1136 ..ReplicationConfig::default()
1137 };
1138 assert!(config.validate().is_err());
1139 }
1140
1141 #[test]
1142 fn audit_sample_count_scales_with_sqrt() {
1143 // Empty store
1144 assert_eq!(ReplicationConfig::audit_sample_count(0), 0);
1145
1146 // Single key
1147 assert_eq!(ReplicationConfig::audit_sample_count(1), 1);
1148
1149 // Small stores: sqrt(3)=1
1150 assert_eq!(ReplicationConfig::audit_sample_count(3), 1);
1151
1152 // sqrt scaling
1153 assert_eq!(ReplicationConfig::audit_sample_count(4), 2);
1154 assert_eq!(ReplicationConfig::audit_sample_count(25), 5);
1155 assert_eq!(ReplicationConfig::audit_sample_count(100), 10);
1156 assert_eq!(ReplicationConfig::audit_sample_count(1_000), 31);
1157 assert_eq!(ReplicationConfig::audit_sample_count(10_000), 100);
1158 assert_eq!(ReplicationConfig::audit_sample_count(1_000_000), 1_000);
1159 }
1160
1161 #[test]
1162 fn responsible_audit_key_limit_matches_audit_sample_count() {
1163 for stored_keys in [0, 1, 3, 4, 25, 100, 1_000, 10_000, 1_000_000] {
1164 assert_eq!(
1165 ReplicationConfig::responsible_audit_key_limit(stored_keys),
1166 ReplicationConfig::audit_sample_count(stored_keys),
1167 "responsible audit sender limit must stay identical to audit sample count"
1168 );
1169 }
1170 }
1171
1172 #[test]
1173 fn max_incoming_audit_keys_scales_dynamically() {
1174 // Empty store: at least 1 key accepted.
1175 assert_eq!(ReplicationConfig::max_incoming_audit_keys(0), 1);
1176
1177 // 1 chunk: 2 * responsible_audit_key_limit(1) = 2.
1178 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1), 2);
1179
1180 // 100 chunks: 2 * responsible_audit_key_limit(100) = 20.
1181 assert_eq!(ReplicationConfig::max_incoming_audit_keys(100), 20);
1182
1183 // 1M chunks: 2 * responsible_audit_key_limit(1_000_000) = 2_000.
1184 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1_000_000), 2_000);
1185
1186 // 5M chunks: 2 * responsible_audit_key_limit(5_000_000) = 4_472.
1187 assert_eq!(ReplicationConfig::max_incoming_audit_keys(5_000_000), 4_472);
1188 }
1189
1190 #[test]
1191 fn quorum_needed_uses_smaller_of_threshold_and_majority() {
1192 let config = ReplicationConfig::default();
1193
1194 // With 7 targets: majority = 7/2+1 = 4, threshold = 4 → min = 4
1195 assert_eq!(config.quorum_needed(7), 4);
1196
1197 // With 3 targets: majority = 3/2+1 = 2, threshold = 4 → min = 2
1198 assert_eq!(config.quorum_needed(3), 2);
1199
1200 // With 0 targets: quorum is impossible — returns 0
1201 assert_eq!(config.quorum_needed(0), 0);
1202
1203 // With 100 targets: majority = 51, threshold = 4 → min = 4
1204 assert_eq!(config.quorum_needed(100), 4);
1205 }
1206
1207 #[test]
1208 fn confirm_needed_is_strict_majority() {
1209 assert_eq!(ReplicationConfig::confirm_needed(1), 1);
1210 assert_eq!(ReplicationConfig::confirm_needed(2), 2);
1211 assert_eq!(ReplicationConfig::confirm_needed(3), 2);
1212 assert_eq!(ReplicationConfig::confirm_needed(4), 3);
1213 assert_eq!(ReplicationConfig::confirm_needed(20), 11);
1214 }
1215
1216 #[test]
1217 fn random_intervals_within_bounds() {
1218 let config = ReplicationConfig::default();
1219
1220 // Run several iterations to exercise randomness.
1221 let iterations = 50;
1222 for _ in 0..iterations {
1223 let ns = config.random_neighbor_sync_interval();
1224 assert!(ns >= config.neighbor_sync_interval_min);
1225 assert!(ns <= config.neighbor_sync_interval_max);
1226
1227 let at = config.random_audit_tick_interval();
1228 assert!(at >= config.audit_tick_interval_min);
1229 assert!(at <= config.audit_tick_interval_max);
1230
1231 let sl = config.random_self_lookup_interval();
1232 assert!(sl >= config.self_lookup_interval_min);
1233 assert!(sl <= config.self_lookup_interval_max);
1234 }
1235 }
1236
1237 #[test]
1238 fn random_interval_equal_bounds_is_deterministic() {
1239 let fixed = Duration::from_secs(42);
1240 let config = ReplicationConfig {
1241 neighbor_sync_interval_min: fixed,
1242 neighbor_sync_interval_max: fixed,
1243 ..ReplicationConfig::default()
1244 };
1245 assert_eq!(config.random_neighbor_sync_interval(), fixed);
1246 }
1247
1248 // -----------------------------------------------------------------------
1249 // Section 18 scenarios
1250 // -----------------------------------------------------------------------
1251
1252 /// Scenario 18: Invalid runtime config is rejected by `validate()`.
1253 #[test]
1254 fn scenario_18_invalid_config_rejected() {
1255 // quorum_threshold > close_group_size -> validation fails.
1256 let config = ReplicationConfig {
1257 quorum_threshold: 10,
1258 close_group_size: 7,
1259 ..ReplicationConfig::default()
1260 };
1261 let err = config.validate().unwrap_err();
1262 assert!(
1263 err.contains("quorum_threshold"),
1264 "error should mention quorum_threshold: {err}"
1265 );
1266
1267 // close_group_size = 0 -> validation fails.
1268 let config = ReplicationConfig {
1269 close_group_size: 0,
1270 ..ReplicationConfig::default()
1271 };
1272 let err = config.validate().unwrap_err();
1273 assert!(
1274 err.contains("close_group_size"),
1275 "error should mention close_group_size: {err}"
1276 );
1277
1278 // neighbor_sync interval min > max -> validation fails.
1279 let config = ReplicationConfig {
1280 neighbor_sync_interval_min: Duration::from_secs(200),
1281 neighbor_sync_interval_max: Duration::from_secs(100),
1282 ..ReplicationConfig::default()
1283 };
1284 let err = config.validate().unwrap_err();
1285 assert!(
1286 err.contains("neighbor_sync_interval"),
1287 "error should mention neighbor_sync_interval: {err}"
1288 );
1289
1290 // self_lookup interval min > max -> validation fails.
1291 let config = ReplicationConfig {
1292 self_lookup_interval_min: Duration::from_secs(999),
1293 self_lookup_interval_max: Duration::from_secs(1),
1294 ..ReplicationConfig::default()
1295 };
1296 let err = config.validate().unwrap_err();
1297 assert!(
1298 err.contains("self_lookup_interval"),
1299 "error should mention self_lookup_interval: {err}"
1300 );
1301
1302 // audit_tick interval min > max -> validation fails.
1303 let config = ReplicationConfig {
1304 audit_tick_interval_min: Duration::from_secs(500),
1305 audit_tick_interval_max: Duration::from_secs(10),
1306 ..ReplicationConfig::default()
1307 };
1308 let err = config.validate().unwrap_err();
1309 assert!(
1310 err.contains("audit_tick_interval"),
1311 "error should mention audit_tick_interval: {err}"
1312 );
1313 }
1314
1315 /// Scenario 26: Dynamic paid-list threshold for undersized set.
1316 /// With PaidGroupSize=8, `ConfirmNeeded` = floor(8/2)+1 = 5.
1317 #[test]
1318 fn scenario_26_dynamic_paid_threshold_undersized() {
1319 assert_eq!(ReplicationConfig::confirm_needed(8), 5, "floor(8/2)+1 = 5");
1320
1321 // Additional boundary checks for small paid groups.
1322 assert_eq!(
1323 ReplicationConfig::confirm_needed(1),
1324 1,
1325 "single peer requires 1 confirmation"
1326 );
1327 assert_eq!(
1328 ReplicationConfig::confirm_needed(2),
1329 2,
1330 "2 peers require 2 confirmations"
1331 );
1332 assert_eq!(
1333 ReplicationConfig::confirm_needed(3),
1334 2,
1335 "3 peers require 2 confirmations"
1336 );
1337 assert_eq!(
1338 ReplicationConfig::confirm_needed(0),
1339 1,
1340 "0 peers yields floor(0/2)+1 = 1 (degenerate case)"
1341 );
1342 }
1343
1344 /// Scenario 31: Consecutive audit ticks occur on randomized intervals
1345 /// bounded by the configured `[audit_tick_interval_min, audit_tick_interval_max]`
1346 /// window.
1347 #[test]
1348 fn scenario_31_audit_cadence_within_jitter_bounds() {
1349 let config = ReplicationConfig {
1350 audit_tick_interval_min: Duration::from_secs(600),
1351 audit_tick_interval_max: Duration::from_secs(1200),
1352 ..ReplicationConfig::default()
1353 };
1354
1355 // Sample many intervals and verify each is within bounds.
1356 let iterations = 100;
1357 let mut saw_different = false;
1358 let mut prev = Duration::ZERO;
1359
1360 for _ in 0..iterations {
1361 let interval = config.random_audit_tick_interval();
1362 assert!(
1363 interval >= config.audit_tick_interval_min,
1364 "interval {interval:?} below min {:?}",
1365 config.audit_tick_interval_min,
1366 );
1367 assert!(
1368 interval <= config.audit_tick_interval_max,
1369 "interval {interval:?} above max {:?}",
1370 config.audit_tick_interval_max,
1371 );
1372 if interval != prev && prev != Duration::ZERO {
1373 saw_different = true;
1374 }
1375 prev = interval;
1376 }
1377
1378 // With 100 samples from a 10-minute range, at least two should differ
1379 // (probabilistically near-certain).
1380 assert!(
1381 saw_different,
1382 "audit intervals should exhibit randomized jitter across samples"
1383 );
1384 }
1385}