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 = 16;
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 2 in-flight per peer
157/// comfortably covers the legitimate round-1 + round-2 overlap.
158pub const MAX_AUDIT_RESPONSES_PER_PEER: u32 = 2;
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/// ADR-0004: max unresolved quote pins to fetch per payment bundle.
338///
339/// A bundle has at most `CLOSE_GROUP_SIZE` quotes; capping fetches per bundle
340/// bounds the amplification a single malicious upload (many distinct unknown
341/// pins) can drive. Excess unresolved pins in one bundle are dropped (left
342/// unresolved, i.e. graced — the audit funnel still catches a serving cheater).
343pub const MAX_PIN_FETCHES_PER_BUNDLE: usize = 3;
344
345/// ADR-0004: capacity of the per-peer negative cache for unresolved pin fetches.
346///
347/// A pin that a peer answered `NotRetained` (or that timed out) is remembered so
348/// repeated bundles citing the same unknown pin don't re-fetch.
349pub const PIN_FETCH_NEGATIVE_CACHE_CAPACITY: usize = 4096;
350
351/// ADR-0004: timeout for a `GetCommitmentByPin` fetch.
352///
353/// Sized for a single small round-trip plus the responder's bounded in-memory
354/// lookup; a fetch is off the payment hot path, so this only bounds the
355/// background cross-check.
356pub const PIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
357
358/// Verification request timeout (per-batch).
359const VERIFICATION_REQUEST_TIMEOUT_SECS: u64 = 15;
360/// Verification request timeout (per-batch).
361pub const VERIFICATION_REQUEST_TIMEOUT: Duration =
362 Duration::from_secs(VERIFICATION_REQUEST_TIMEOUT_SECS);
363
364/// Fetch request timeout.
365const FETCH_REQUEST_TIMEOUT_SECS: u64 = 30;
366/// Fetch request timeout.
367pub const FETCH_REQUEST_TIMEOUT: Duration = Duration::from_secs(FETCH_REQUEST_TIMEOUT_SECS);
368
369/// Maximum age for pending-verification entries before stale eviction.
370const PENDING_VERIFY_MAX_AGE_SECS: u64 = 30 * 60;
371/// Maximum age for pending-verification entries before stale eviction.
372pub const PENDING_VERIFY_MAX_AGE: Duration = Duration::from_secs(PENDING_VERIFY_MAX_AGE_SECS);
373
374/// Trust event weight for confirmed audit failures.
375pub const AUDIT_FAILURE_TRUST_WEIGHT: f64 = 5.0;
376
377/// Probability of launching a subtree audit when a peer's *changed* commitment
378/// is ingested via gossip (ADR-0002). Keeps audits occasional surprise exams.
379pub const AUDIT_ON_GOSSIP_PROBABILITY: f64 = 0.2;
380
381/// Per-peer cooldown between gossip-triggered subtree audits (ADR-0002), in
382/// seconds. Bounds how often any one peer is audited regardless of gossip rate.
383pub const AUDIT_ON_GOSSIP_COOLDOWN_SECS: u64 = 30 * 60;
384
385/// ADR-0004: first-audit drainer retry cadence for cooldown-pending pins.
386///
387/// How often the drainer retries pins it kept pending because their peer was on
388/// cooldown. Finer than the cooldown itself so a monetized commitment is
389/// first-audited promptly after its peer's window reopens; the retry just
390/// re-checks a small per-peer map, so the tick is cheap.
391pub const FIRST_AUDIT_RETRY_INTERVAL: Duration = Duration::from_secs(60);
392
393/// ADR-0004: max monetized-pin events the first-audit drainer drains from its
394/// channel per wake before it must run the audit-launch phase.
395///
396/// Bounds the synchronous `try_recv` batch so a sustained producer flood cannot
397/// starve audit launching by spinning in the drain loop forever. After this many
398/// events the drainer processes audits, then loops back to drain more.
399pub const FIRST_AUDIT_DRAIN_BATCH: usize = 64;
400
401/// Number of subtree leaves spot-checked against real chunk bytes per audit
402/// (ADR-0002 real-bytes layer).
403///
404/// The auditor clamps this to its 3..=5 band (`BYTE_SPOTCHECK_MIN..=MAX` in
405/// `storage_commitment_audit`), so this is the effective MAXIMUM — set it
406/// within the band rather than advertising a sample size the auditor never
407/// requests.
408pub const AUDIT_SPOTCHECK_COUNT: u32 = 5;
409
410/// Conservative leaf-count hint for sizing the subtree-audit response deadline.
411///
412/// The deadline is set before the proof arrives, so we size for the largest
413/// legal store: `sqrt(MAX_COMMITMENT_KEY_COUNT) = 1000`. Honest small stores
414/// finish well within it.
415pub const SUBTREE_AUDIT_TIMEOUT_LEAF_HINT: usize = 1000;
416
417/// Maximum number of prune-confirmation audit challenges sent per prune pass.
418pub const MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS: usize = 64;
419
420/// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before proceeding
421/// with bootstrap sync. Covers bootstrap nodes with no peers to connect to.
422const BOOTSTRAP_COMPLETE_TIMEOUT_SECS: u64 = 60;
423
424// ---------------------------------------------------------------------------
425// Runtime-configurable wrapper
426// ---------------------------------------------------------------------------
427
428/// Runtime-configurable replication parameters.
429///
430/// Validated on construction — node rejects invalid configs.
431#[derive(Debug, Clone)]
432pub struct ReplicationConfig {
433 /// Close-group width and target holder count per key.
434 pub close_group_size: usize,
435 /// Required positive presence votes for quorum.
436 pub quorum_threshold: usize,
437 /// Maximum closest nodes tracking paid status for a key.
438 pub paid_list_close_group_size: usize,
439 /// Number of closest peers to self eligible for neighbor sync.
440 pub neighbor_sync_scope: usize,
441 /// Peers synced concurrently per round-robin repair round.
442 pub neighbor_sync_peer_count: usize,
443 /// Neighbor sync cadence range (min).
444 pub neighbor_sync_interval_min: Duration,
445 /// Neighbor sync cadence range (max).
446 pub neighbor_sync_interval_max: Duration,
447 /// Minimum spacing between successive syncs with the same peer.
448 pub neighbor_sync_cooldown: Duration,
449 /// Self-lookup cadence range (min).
450 pub self_lookup_interval_min: Duration,
451 /// Self-lookup cadence range (max).
452 pub self_lookup_interval_max: Duration,
453 /// Audit scheduler cadence range (min).
454 pub audit_tick_interval_min: Duration,
455 /// Audit scheduler cadence range (max).
456 pub audit_tick_interval_max: Duration,
457 /// Floor on the audit response deadline. Covers global RTT for
458 /// the small request/response envelope plus scheduling jitter.
459 /// See `AUDIT_RESPONSE_FLOOR_SECS` for sizing.
460 pub audit_response_floor: Duration,
461 /// Conservative honest-responder read throughput (bytes/sec).
462 /// Used to scale the audit response deadline against the size of
463 /// the challenge. Slow enough that even an HDD-backed honest peer
464 /// fits inside the budget; fast enough that a relay attacker who
465 /// must fetch bytes over the network falls outside.
466 pub audit_honest_read_bps: u64,
467 /// Slack multiplier on the honest-read estimate before
468 /// declaring an audit timed out.
469 pub audit_response_honest_multiplier: u64,
470 /// Maximum duration a peer may claim bootstrap status.
471 pub bootstrap_claim_grace_period: Duration,
472 /// Minimum continuous out-of-range duration before pruning a key.
473 pub prune_hysteresis_duration: Duration,
474 /// Verification request timeout (per-batch).
475 pub verification_request_timeout: Duration,
476 /// Fetch request timeout.
477 pub fetch_request_timeout: Duration,
478 /// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before
479 /// proceeding with bootstrap sync (covers bootstrap nodes with no peers).
480 pub bootstrap_complete_timeout_secs: u64,
481 /// Lower bound of the delay before a fresh-replication possession check
482 /// runs (ADR-0003). Defaults to [`POSSESSION_CHECK_DELAY_MIN`]; tests
483 /// shorten it so the scheduled check fires quickly.
484 pub possession_check_delay_min: Duration,
485 /// Upper bound of the possession-check delay window (ADR-0003). Defaults
486 /// to [`POSSESSION_CHECK_DELAY_MAX`].
487 pub possession_check_delay_max: Duration,
488}
489
490impl Default for ReplicationConfig {
491 fn default() -> Self {
492 Self {
493 close_group_size: CLOSE_GROUP_SIZE,
494 quorum_threshold: QUORUM_THRESHOLD,
495 paid_list_close_group_size: PAID_LIST_CLOSE_GROUP_SIZE,
496 neighbor_sync_scope: NEIGHBOR_SYNC_SCOPE,
497 neighbor_sync_peer_count: NEIGHBOR_SYNC_PEER_COUNT,
498 neighbor_sync_interval_min: NEIGHBOR_SYNC_INTERVAL_MIN,
499 neighbor_sync_interval_max: NEIGHBOR_SYNC_INTERVAL_MAX,
500 neighbor_sync_cooldown: NEIGHBOR_SYNC_COOLDOWN,
501 self_lookup_interval_min: SELF_LOOKUP_INTERVAL_MIN,
502 self_lookup_interval_max: SELF_LOOKUP_INTERVAL_MAX,
503 audit_tick_interval_min: AUDIT_TICK_INTERVAL_MIN,
504 audit_tick_interval_max: AUDIT_TICK_INTERVAL_MAX,
505 audit_response_floor: Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
506 audit_honest_read_bps: AUDIT_HONEST_READ_BPS,
507 audit_response_honest_multiplier: AUDIT_RESPONSE_HONEST_MULTIPLIER,
508 bootstrap_claim_grace_period: BOOTSTRAP_CLAIM_GRACE_PERIOD,
509 prune_hysteresis_duration: PRUNE_HYSTERESIS_DURATION,
510 verification_request_timeout: VERIFICATION_REQUEST_TIMEOUT,
511 fetch_request_timeout: FETCH_REQUEST_TIMEOUT,
512 bootstrap_complete_timeout_secs: BOOTSTRAP_COMPLETE_TIMEOUT_SECS,
513 possession_check_delay_min: POSSESSION_CHECK_DELAY_MIN,
514 possession_check_delay_max: POSSESSION_CHECK_DELAY_MAX,
515 }
516 }
517}
518
519impl ReplicationConfig {
520 /// Validate safety constraints. Returns `Err` with a description if any
521 /// constraint is violated.
522 ///
523 /// # Errors
524 ///
525 /// Returns a human-readable message describing the first violated
526 /// constraint.
527 pub fn validate(&self) -> Result<(), String> {
528 if self.close_group_size == 0 {
529 return Err("close_group_size must be >= 1".to_string());
530 }
531 if self.quorum_threshold == 0 || self.quorum_threshold > self.close_group_size {
532 return Err(format!(
533 "quorum_threshold ({}) must satisfy 1 <= quorum_threshold <= close_group_size ({})",
534 self.quorum_threshold, self.close_group_size,
535 ));
536 }
537 if self.close_group_size > MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS {
538 return Err(format!(
539 "close_group_size ({}) must be <= MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS ({})",
540 self.close_group_size, MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS,
541 ));
542 }
543 if self.paid_list_close_group_size == 0 {
544 return Err("paid_list_close_group_size must be >= 1".to_string());
545 }
546 if self.neighbor_sync_interval_min > self.neighbor_sync_interval_max {
547 return Err(format!(
548 "neighbor_sync_interval_min ({:?}) must be <= neighbor_sync_interval_max ({:?})",
549 self.neighbor_sync_interval_min, self.neighbor_sync_interval_max,
550 ));
551 }
552 if self.audit_tick_interval_min > self.audit_tick_interval_max {
553 return Err(format!(
554 "audit_tick_interval_min ({:?}) must be <= audit_tick_interval_max ({:?})",
555 self.audit_tick_interval_min, self.audit_tick_interval_max,
556 ));
557 }
558 if self.self_lookup_interval_min > self.self_lookup_interval_max {
559 return Err(format!(
560 "self_lookup_interval_min ({:?}) must be <= self_lookup_interval_max ({:?})",
561 self.self_lookup_interval_min, self.self_lookup_interval_max,
562 ));
563 }
564 if self.neighbor_sync_peer_count == 0 {
565 return Err("neighbor_sync_peer_count must be >= 1".to_string());
566 }
567 if self.neighbor_sync_scope == 0 {
568 return Err("neighbor_sync_scope must be >= 1".to_string());
569 }
570 if self.neighbor_sync_scope > K_BUCKET_SIZE {
571 return Err(format!(
572 "neighbor_sync_scope ({}) must be <= K_BUCKET_SIZE ({})",
573 self.neighbor_sync_scope, K_BUCKET_SIZE,
574 ));
575 }
576 Ok(())
577 }
578
579 /// Effective quorum votes required for a key given the number of
580 /// reachable quorum targets.
581 ///
582 /// `min(self.quorum_threshold, floor(quorum_targets_count / 2) + 1)`
583 #[must_use]
584 pub fn quorum_needed(&self, quorum_targets_count: usize) -> usize {
585 if quorum_targets_count == 0 {
586 return 0;
587 }
588 let majority = quorum_targets_count / 2 + 1;
589 self.quorum_threshold.min(majority)
590 }
591
592 /// Confirmations required for paid-list consensus given the number of
593 /// peers in the paid-list close group for a key.
594 ///
595 /// `floor(paid_group_size / 2) + 1`
596 #[must_use]
597 pub fn confirm_needed(paid_group_size: usize) -> usize {
598 paid_group_size / 2 + 1
599 }
600
601 /// Returns a random duration in `[neighbor_sync_interval_min,
602 /// neighbor_sync_interval_max]`.
603 #[must_use]
604 pub fn random_neighbor_sync_interval(&self) -> Duration {
605 random_duration_in_range(
606 self.neighbor_sync_interval_min,
607 self.neighbor_sync_interval_max,
608 )
609 }
610
611 /// Compute the number of keys to sample for an audit round, scaled
612 /// dynamically by the total number of locally stored keys.
613 ///
614 /// Formula: `max(floor(sqrt(total_keys)), 1)`, capped at `total_keys`.
615 #[must_use]
616 pub fn audit_sample_count(total_keys: usize) -> usize {
617 #[allow(
618 clippy::cast_possible_truncation,
619 clippy::cast_sign_loss,
620 clippy::cast_precision_loss
621 )]
622 let sqrt = (total_keys as f64).sqrt() as usize;
623 sqrt.max(1).min(total_keys)
624 }
625
626 /// Maximum number of keys to accept in an incoming audit challenge.
627 ///
628 /// Scales dynamically: `2 * audit_sample_count(stored_chunks)`. The 2x
629 /// margin accounts for the challenger having a larger store than us and
630 /// therefore sampling more keys.
631 #[must_use]
632 pub fn max_incoming_audit_keys(stored_chunks: usize) -> usize {
633 // Allow at least 1 key so a newly-joined node can still be audited.
634 (2 * Self::audit_sample_count(stored_chunks)).max(1)
635 }
636
637 /// Compute the audit response timeout for a challenge with
638 /// `challenged_key_count` keys, **sized to be tight enough that a
639 /// relay attacker that must fetch the chunk bytes from elsewhere
640 /// falls outside the budget**.
641 ///
642 /// Formula:
643 /// `floor + (challenged_bytes / honest_read_bps) × multiplier`
644 ///
645 /// Where `challenged_bytes = k × MAX_CHUNK_SIZE`. An honest peer
646 /// reads `k × 4 MiB` from local disk at `honest_read_bps` (set
647 /// conservatively at 50 MB/s — well below modern SSDs); the
648 /// multiplier of 5 absorbs jitter, BLAKE3, ML-DSA, and slow disks.
649 ///
650 /// A relay attacker on a residential link (~5-12 MB/s) who must
651 /// fetch the same `k × 4 MiB` over the network sees ~10-100× higher
652 /// latency than disk for the data alone, plus per-chunk round-trips,
653 /// and misses the budget. In the periodic responsible-chunk
654 /// `AuditChallenge`, prune-confirmation, and ADR-0003 possession-check paths
655 /// that timeout is an immediate audit failure. The heavier subtree audit
656 /// still graces timeouts separately.
657 ///
658 /// This is an economic deterrent for the §7 relay limit calibrated
659 /// for residential bandwidth, NOT a hard bound: a relay on a
660 /// datacenter cross-connect (≥1 Gbps) can fetch `k × 4 MiB` fast
661 /// enough to answer in time. It raises the relay's cost (bandwidth
662 /// per audit) without claiming to make relaying impossible. The
663 /// cryptographic guarantee remains commitment-binding (the relay
664 /// must still hold or fetch the exact committed bytes); the timeout
665 /// only attacks the economics.
666 #[must_use]
667 pub fn audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
668 let bytes_per_key = u64::try_from(crate::ant_protocol::MAX_CHUNK_SIZE).unwrap_or(u64::MAX);
669 let keys = u64::try_from(challenged_key_count).unwrap_or(u64::MAX);
670 let total_bytes = bytes_per_key.saturating_mul(keys);
671 let bps = self.audit_honest_read_bps.max(1);
672 // Apply the multiplier BEFORE integer-dividing by bps so each
673 // chunk contributes a fractional second rather than rounding
674 // down to zero. Otherwise k in 1..=12 would all collapse to the
675 // floor (~40 MiB / 50 MB/s = 0 secs in integer arithmetic), and
676 // an honest HDD-backed peer at sqrt(N)=10 stored chunks could
677 // miss the budget under load.
678 let multiplied = total_bytes.saturating_mul(self.audit_response_honest_multiplier);
679 // Resolve the scaled term in MILLISECONDS, not seconds: at the
680 // byte-round sizes (MAX_BYTE_CHALLENGE_KEYS = 2 → 8 MiB) the per-second
681 // quotient `multiplied / bps` integer-truncates to 0, leaving only the
682 // floor. The §4 finding was that byte-serving challenges need the
683 // sub-second honest-read estimate (e.g. 8 MiB × 5 / 50 MB/s ≈ 840 ms)
684 // instead of dropping it.
685 let scaled_ms = multiplied.saturating_mul(1000) / bps;
686 // saturating_add avoids a panic if the floor plus the scaled term would
687 // overflow `Duration::MAX`.
688 self.audit_response_floor
689 .saturating_add(Duration::from_millis(scaled_ms))
690 }
691
692 /// Deadline for the round-2 BYTE challenge serving `challenged_key_count`
693 /// full chunks back to the auditor.
694 ///
695 /// Same per-byte scaling as [`Self::audit_response_timeout`] (so a relay
696 /// that must fetch the bytes over a residential link still blows it), but on
697 /// a higher floor (`BYTE_AUDIT_RESPONSE_FLOOR_SECS`) because the reply
698 /// carries up to
699 /// `MAX_BYTE_CHALLENGE_KEYS × MAX_CHUNK_SIZE` of chunk data — handshake +
700 /// multi-MiB upload + a busy honest disk read do not fit the hashes-only
701 /// round-1 floor (the §4 finding).
702 #[must_use]
703 pub fn byte_audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
704 let scaled = self
705 .audit_response_timeout(challenged_key_count)
706 .saturating_sub(self.audit_response_floor);
707 Duration::from_secs(BYTE_AUDIT_RESPONSE_FLOOR_SECS).saturating_add(scaled)
708 }
709
710 /// Number of subtree leaves to spot-check against real chunk bytes per
711 /// audit (ADR-0002 real-bytes layer). Faking a fraction `x` of nonced
712 /// leaves survives only `(1 - x)^k`.
713 #[must_use]
714 pub fn audit_spotcheck_count(&self) -> u32 {
715 AUDIT_SPOTCHECK_COUNT
716 }
717
718 /// Conservative leaf-count hint for sizing the subtree-audit response
719 /// deadline before the proof arrives.
720 ///
721 /// The selected subtree holds about `sqrt(key_count)` real leaves; sizing
722 /// for a large store keeps an honest peer with a big store from timing out.
723 #[must_use]
724 pub fn subtree_audit_timeout_leaf_hint(&self) -> usize {
725 SUBTREE_AUDIT_TIMEOUT_LEAF_HINT
726 }
727
728 /// Returns a random duration in `[audit_tick_interval_min,
729 /// audit_tick_interval_max]`.
730 #[must_use]
731 pub fn random_audit_tick_interval(&self) -> Duration {
732 random_duration_in_range(self.audit_tick_interval_min, self.audit_tick_interval_max)
733 }
734
735 /// Returns a random duration in `[self_lookup_interval_min,
736 /// self_lookup_interval_max]`.
737 #[must_use]
738 pub fn random_self_lookup_interval(&self) -> Duration {
739 random_duration_in_range(self.self_lookup_interval_min, self.self_lookup_interval_max)
740 }
741}
742
743/// Pick a random `Duration` uniformly in `[min, max]` at millisecond
744/// granularity.
745///
746/// When `min == max` the result is deterministic.
747fn random_duration_in_range(min: Duration, max: Duration) -> Duration {
748 if min == max {
749 return min;
750 }
751 // Our intervals are minutes/hours, well within u64 range. Saturate to
752 // u64::MAX on the impossible overflow path to avoid a lossy cast.
753 let to_u64_millis = |d: Duration| -> u64 { u64::try_from(d.as_millis()).unwrap_or(u64::MAX) };
754 let chosen = rand::thread_rng().gen_range(to_u64_millis(min)..=to_u64_millis(max));
755 Duration::from_millis(chosen)
756}
757
758// ---------------------------------------------------------------------------
759// Tests
760// ---------------------------------------------------------------------------
761
762#[cfg(test)]
763#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
764mod tests {
765 use super::*;
766
767 #[test]
768 fn defaults_pass_validation() {
769 let config = ReplicationConfig::default();
770 assert!(config.validate().is_ok(), "default config must be valid");
771 }
772
773 #[test]
774 fn default_prune_hysteresis_is_three_days() {
775 let config = ReplicationConfig::default();
776 assert_eq!(
777 config.prune_hysteresis_duration,
778 Duration::from_secs(3 * 24 * 60 * 60)
779 );
780 }
781
782 #[test]
783 fn storage_admission_width_adds_margin() {
784 const TEST_CLOSE_GROUP_SIZE: usize = 7;
785
786 assert_eq!(
787 storage_admission_width(TEST_CLOSE_GROUP_SIZE),
788 TEST_CLOSE_GROUP_SIZE + STORAGE_ADMISSION_MARGIN
789 );
790 assert_eq!(storage_admission_width(usize::MAX), usize::MAX);
791 }
792
793 #[test]
794 fn audit_failure_weight_is_five() {
795 assert!((AUDIT_FAILURE_TRUST_WEIGHT - 5.0).abs() <= f64::EPSILON);
796 }
797
798 #[test]
799 fn replication_protocol_id_is_v2() {
800 // The v12 storage-bound audit changes replication SEMANTICS. The
801 // protocol id MUST advance past v1 so v1 and v2 nodes never exchange
802 // replication traffic they can only half-interpret (rollout safety —
803 // see the const's doc). If this regresses to v1, mixed-version nodes
804 // would talk past each other and risk spurious penalties.
805 assert_eq!(REPLICATION_PROTOCOL_ID, "autonomi.ant.replication.v2");
806 }
807
808 #[test]
809 fn audit_response_timeout_floor_at_zero_keys() {
810 let config = ReplicationConfig::default();
811 assert_eq!(
812 config.audit_response_timeout(0),
813 Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
814 "zero-key challenge should yield the floor exactly"
815 );
816 }
817
818 #[test]
819 fn audit_response_timeout_scales_with_key_count() {
820 let config = ReplicationConfig::default();
821 let t1 = config.audit_response_timeout(1);
822 let t10 = config.audit_response_timeout(10);
823 let t100 = config.audit_response_timeout(100);
824 assert!(t1 <= t10 && t10 < t100, "timeout must not decrease with k");
825
826 // Scaling now resolves in MILLISECONDS so a sub-second honest read no
827 // longer truncates to zero (§4). For k=1:
828 // (4_194_304 × 5 × 1000) / 52_428_800 = 400 ms, + 4 s round-1 floor =
829 // 4.4 s.
830 assert_eq!(t1, Duration::from_millis(4400));
831
832 // For k=10: (10 × 4_194_304 × 5 × 1000) / 52_428_800 = 4000 ms scaled,
833 // + 4 s floor = 8 s. An HDD-backed honest peer at 20 MB/s reads 40 MiB
834 // in ~2 s, comfortably inside; a relay fetching 40 MiB at 5 MB/s
835 // residential bandwidth needs ~8 s for the data alone, outside.
836 assert_eq!(t10, Duration::from_secs(8));
837
838 // For k=100: (100 × 4_194_304 × 5 × 1000) / 52_428_800 = 40_000 ms
839 // scaled, + 4 s floor = 44 s.
840 assert_eq!(t100, Duration::from_secs(44));
841 }
842
843 #[test]
844 fn audit_response_timeout_fits_honest_hdd_at_typical_sample_size() {
845 // The canonical audit sample is sqrt(N) at N stored chunks.
846 // At N=100 stored chunks, sample is 10. An HDD-backed honest
847 // peer at the slowest realistic random-read throughput (20 MB/s,
848 // well below modern HDDs which sustain 80-150 MB/s sequential)
849 // reads 10 × 4 MiB = 40 MiB in ~2 s. Add 300 ms cross-continent
850 // RTT, ~10 ms scheduling, ~3 ms ML-DSA sign, and the honest
851 // envelope is ~2.3 s. The 8 s budget at k=10 leaves >5 s of
852 // slack.
853 let config = ReplicationConfig::default();
854 let budget = config.audit_response_timeout(10);
855 let realistic_hdd_bps: u64 = 20 * 1024 * 1024;
856 let bytes: u64 = 10 * 4 * 1024 * 1024;
857 let honest_envelope_secs = bytes / realistic_hdd_bps + 1; // +1 s for network/scheduling/sign
858 assert!(
859 Duration::from_secs(honest_envelope_secs) < budget,
860 "honest HDD envelope ({honest_envelope_secs}s) must fit inside k=10 budget ({}s)",
861 budget.as_secs(),
862 );
863 }
864
865 #[test]
866 fn audit_response_timeout_relay_is_outside_envelope() {
867 // The intended invariant: an honest peer with the SSD-class
868 // read budget fits inside `audit_response_timeout(k)`, while a
869 // relay attacker fetching k*4MiB over residential bandwidth
870 // (≈ 5 MB/s realistic for sustained download) does NOT. Spot-
871 // check this at k=100: honest budget is 44s, relay needs at
872 // least 100 * 4 MiB / 5 MB/s = 80s for the data alone, which
873 // exceeds the budget.
874 let config = ReplicationConfig::default();
875 let budget = config.audit_response_timeout(100);
876 let relay_data_only = Duration::from_secs(100 * 4 * 1024 * 1024 / (5 * 1024 * 1024));
877 assert!(
878 relay_data_only > budget,
879 "relay fetch ({}s) must exceed honest audit budget ({}s)",
880 relay_data_only.as_secs(),
881 budget.as_secs(),
882 );
883 }
884
885 #[test]
886 fn audit_response_timeout_saturates_on_huge_k() {
887 let config = ReplicationConfig::default();
888 // Should not panic or overflow at extreme k values.
889 let _ = config.audit_response_timeout(usize::MAX);
890 }
891
892 #[test]
893 fn quorum_threshold_zero_rejected() {
894 let config = ReplicationConfig {
895 quorum_threshold: 0,
896 ..ReplicationConfig::default()
897 };
898 assert!(config.validate().is_err());
899 }
900
901 #[test]
902 fn quorum_threshold_exceeds_close_group_rejected() {
903 let defaults = ReplicationConfig::default();
904 let config = ReplicationConfig {
905 quorum_threshold: defaults.close_group_size + 1,
906 ..defaults
907 };
908 assert!(config.validate().is_err());
909 }
910
911 #[test]
912 fn close_group_size_zero_rejected() {
913 let config = ReplicationConfig {
914 close_group_size: 0,
915 ..ReplicationConfig::default()
916 };
917 assert!(config.validate().is_err());
918 }
919
920 #[test]
921 fn close_group_size_exceeding_prune_audit_budget_rejected() {
922 let config = ReplicationConfig {
923 close_group_size: MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS + 1,
924 quorum_threshold: QUORUM_THRESHOLD,
925 ..ReplicationConfig::default()
926 };
927
928 let err = config.validate().unwrap_err();
929
930 assert!(
931 err.contains("MAX_PRUNE_AUDIT_CHALLENGES_PER_PASS"),
932 "error should mention prune audit budget: {err}"
933 );
934 }
935
936 #[test]
937 fn paid_list_close_group_size_zero_rejected() {
938 let config = ReplicationConfig {
939 paid_list_close_group_size: 0,
940 ..ReplicationConfig::default()
941 };
942 assert!(config.validate().is_err());
943 }
944
945 #[test]
946 fn neighbor_sync_interval_inverted_rejected() {
947 let config = ReplicationConfig {
948 neighbor_sync_interval_min: Duration::from_secs(100),
949 neighbor_sync_interval_max: Duration::from_secs(50),
950 ..ReplicationConfig::default()
951 };
952 assert!(config.validate().is_err());
953 }
954
955 #[test]
956 fn audit_tick_interval_inverted_rejected() {
957 let config = ReplicationConfig {
958 audit_tick_interval_min: Duration::from_secs(100),
959 audit_tick_interval_max: Duration::from_secs(50),
960 ..ReplicationConfig::default()
961 };
962 assert!(config.validate().is_err());
963 }
964
965 #[test]
966 fn self_lookup_interval_inverted_rejected() {
967 let config = ReplicationConfig {
968 self_lookup_interval_min: Duration::from_secs(100),
969 self_lookup_interval_max: Duration::from_secs(50),
970 ..ReplicationConfig::default()
971 };
972 assert!(config.validate().is_err());
973 }
974
975 #[test]
976 fn neighbor_sync_peer_count_zero_rejected() {
977 let config = ReplicationConfig {
978 neighbor_sync_peer_count: 0,
979 ..ReplicationConfig::default()
980 };
981 assert!(config.validate().is_err());
982 }
983
984 #[test]
985 fn neighbor_sync_scope_exceeding_k_bucket_size_rejected() {
986 let config = ReplicationConfig {
987 neighbor_sync_scope: K_BUCKET_SIZE + 1,
988 ..ReplicationConfig::default()
989 };
990 assert!(config.validate().is_err());
991 }
992
993 #[test]
994 fn audit_sample_count_scales_with_sqrt() {
995 // Empty store
996 assert_eq!(ReplicationConfig::audit_sample_count(0), 0);
997
998 // Single key
999 assert_eq!(ReplicationConfig::audit_sample_count(1), 1);
1000
1001 // Small stores: sqrt(3)=1
1002 assert_eq!(ReplicationConfig::audit_sample_count(3), 1);
1003
1004 // sqrt scaling
1005 assert_eq!(ReplicationConfig::audit_sample_count(4), 2);
1006 assert_eq!(ReplicationConfig::audit_sample_count(25), 5);
1007 assert_eq!(ReplicationConfig::audit_sample_count(100), 10);
1008 assert_eq!(ReplicationConfig::audit_sample_count(1_000), 31);
1009 assert_eq!(ReplicationConfig::audit_sample_count(10_000), 100);
1010 assert_eq!(ReplicationConfig::audit_sample_count(1_000_000), 1_000);
1011 }
1012
1013 #[test]
1014 fn max_incoming_audit_keys_scales_dynamically() {
1015 // Empty store: at least 1 key accepted.
1016 assert_eq!(ReplicationConfig::max_incoming_audit_keys(0), 1);
1017
1018 // 1 chunk: 2 * sqrt(1) = 2.
1019 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1), 2);
1020
1021 // 100 chunks: 2 * sqrt(100) = 20.
1022 assert_eq!(ReplicationConfig::max_incoming_audit_keys(100), 20);
1023
1024 // 1M chunks: 2 * sqrt(1_000_000) = 2_000.
1025 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1_000_000), 2_000);
1026
1027 // 5M chunks: 2 * sqrt(5_000_000) = 4_472.
1028 assert_eq!(ReplicationConfig::max_incoming_audit_keys(5_000_000), 4_472);
1029 }
1030
1031 #[test]
1032 fn quorum_needed_uses_smaller_of_threshold_and_majority() {
1033 let config = ReplicationConfig::default();
1034
1035 // With 7 targets: majority = 7/2+1 = 4, threshold = 4 → min = 4
1036 assert_eq!(config.quorum_needed(7), 4);
1037
1038 // With 3 targets: majority = 3/2+1 = 2, threshold = 4 → min = 2
1039 assert_eq!(config.quorum_needed(3), 2);
1040
1041 // With 0 targets: quorum is impossible — returns 0
1042 assert_eq!(config.quorum_needed(0), 0);
1043
1044 // With 100 targets: majority = 51, threshold = 4 → min = 4
1045 assert_eq!(config.quorum_needed(100), 4);
1046 }
1047
1048 #[test]
1049 fn confirm_needed_is_strict_majority() {
1050 assert_eq!(ReplicationConfig::confirm_needed(1), 1);
1051 assert_eq!(ReplicationConfig::confirm_needed(2), 2);
1052 assert_eq!(ReplicationConfig::confirm_needed(3), 2);
1053 assert_eq!(ReplicationConfig::confirm_needed(4), 3);
1054 assert_eq!(ReplicationConfig::confirm_needed(20), 11);
1055 }
1056
1057 #[test]
1058 fn random_intervals_within_bounds() {
1059 let config = ReplicationConfig::default();
1060
1061 // Run several iterations to exercise randomness.
1062 let iterations = 50;
1063 for _ in 0..iterations {
1064 let ns = config.random_neighbor_sync_interval();
1065 assert!(ns >= config.neighbor_sync_interval_min);
1066 assert!(ns <= config.neighbor_sync_interval_max);
1067
1068 let at = config.random_audit_tick_interval();
1069 assert!(at >= config.audit_tick_interval_min);
1070 assert!(at <= config.audit_tick_interval_max);
1071
1072 let sl = config.random_self_lookup_interval();
1073 assert!(sl >= config.self_lookup_interval_min);
1074 assert!(sl <= config.self_lookup_interval_max);
1075 }
1076 }
1077
1078 #[test]
1079 fn random_interval_equal_bounds_is_deterministic() {
1080 let fixed = Duration::from_secs(42);
1081 let config = ReplicationConfig {
1082 neighbor_sync_interval_min: fixed,
1083 neighbor_sync_interval_max: fixed,
1084 ..ReplicationConfig::default()
1085 };
1086 assert_eq!(config.random_neighbor_sync_interval(), fixed);
1087 }
1088
1089 // -----------------------------------------------------------------------
1090 // Section 18 scenarios
1091 // -----------------------------------------------------------------------
1092
1093 /// Scenario 18: Invalid runtime config is rejected by `validate()`.
1094 #[test]
1095 fn scenario_18_invalid_config_rejected() {
1096 // quorum_threshold > close_group_size -> validation fails.
1097 let config = ReplicationConfig {
1098 quorum_threshold: 10,
1099 close_group_size: 7,
1100 ..ReplicationConfig::default()
1101 };
1102 let err = config.validate().unwrap_err();
1103 assert!(
1104 err.contains("quorum_threshold"),
1105 "error should mention quorum_threshold: {err}"
1106 );
1107
1108 // close_group_size = 0 -> validation fails.
1109 let config = ReplicationConfig {
1110 close_group_size: 0,
1111 ..ReplicationConfig::default()
1112 };
1113 let err = config.validate().unwrap_err();
1114 assert!(
1115 err.contains("close_group_size"),
1116 "error should mention close_group_size: {err}"
1117 );
1118
1119 // neighbor_sync interval min > max -> validation fails.
1120 let config = ReplicationConfig {
1121 neighbor_sync_interval_min: Duration::from_secs(200),
1122 neighbor_sync_interval_max: Duration::from_secs(100),
1123 ..ReplicationConfig::default()
1124 };
1125 let err = config.validate().unwrap_err();
1126 assert!(
1127 err.contains("neighbor_sync_interval"),
1128 "error should mention neighbor_sync_interval: {err}"
1129 );
1130
1131 // self_lookup interval min > max -> validation fails.
1132 let config = ReplicationConfig {
1133 self_lookup_interval_min: Duration::from_secs(999),
1134 self_lookup_interval_max: Duration::from_secs(1),
1135 ..ReplicationConfig::default()
1136 };
1137 let err = config.validate().unwrap_err();
1138 assert!(
1139 err.contains("self_lookup_interval"),
1140 "error should mention self_lookup_interval: {err}"
1141 );
1142
1143 // audit_tick interval min > max -> validation fails.
1144 let config = ReplicationConfig {
1145 audit_tick_interval_min: Duration::from_secs(500),
1146 audit_tick_interval_max: Duration::from_secs(10),
1147 ..ReplicationConfig::default()
1148 };
1149 let err = config.validate().unwrap_err();
1150 assert!(
1151 err.contains("audit_tick_interval"),
1152 "error should mention audit_tick_interval: {err}"
1153 );
1154 }
1155
1156 /// Scenario 26: Dynamic paid-list threshold for undersized set.
1157 /// With PaidGroupSize=8, `ConfirmNeeded` = floor(8/2)+1 = 5.
1158 #[test]
1159 fn scenario_26_dynamic_paid_threshold_undersized() {
1160 assert_eq!(ReplicationConfig::confirm_needed(8), 5, "floor(8/2)+1 = 5");
1161
1162 // Additional boundary checks for small paid groups.
1163 assert_eq!(
1164 ReplicationConfig::confirm_needed(1),
1165 1,
1166 "single peer requires 1 confirmation"
1167 );
1168 assert_eq!(
1169 ReplicationConfig::confirm_needed(2),
1170 2,
1171 "2 peers require 2 confirmations"
1172 );
1173 assert_eq!(
1174 ReplicationConfig::confirm_needed(3),
1175 2,
1176 "3 peers require 2 confirmations"
1177 );
1178 assert_eq!(
1179 ReplicationConfig::confirm_needed(0),
1180 1,
1181 "0 peers yields floor(0/2)+1 = 1 (degenerate case)"
1182 );
1183 }
1184
1185 /// Scenario 31: Consecutive audit ticks occur on randomized intervals
1186 /// bounded by the configured `[audit_tick_interval_min, audit_tick_interval_max]`
1187 /// window.
1188 #[test]
1189 fn scenario_31_audit_cadence_within_jitter_bounds() {
1190 let config = ReplicationConfig {
1191 audit_tick_interval_min: Duration::from_secs(600),
1192 audit_tick_interval_max: Duration::from_secs(1200),
1193 ..ReplicationConfig::default()
1194 };
1195
1196 // Sample many intervals and verify each is within bounds.
1197 let iterations = 100;
1198 let mut saw_different = false;
1199 let mut prev = Duration::ZERO;
1200
1201 for _ in 0..iterations {
1202 let interval = config.random_audit_tick_interval();
1203 assert!(
1204 interval >= config.audit_tick_interval_min,
1205 "interval {interval:?} below min {:?}",
1206 config.audit_tick_interval_min,
1207 );
1208 assert!(
1209 interval <= config.audit_tick_interval_max,
1210 "interval {interval:?} above max {:?}",
1211 config.audit_tick_interval_max,
1212 );
1213 if interval != prev && prev != Duration::ZERO {
1214 saw_different = true;
1215 }
1216 prev = interval;
1217 }
1218
1219 // With 100 samples from a 10-minute range, at least two should differ
1220 // (probabilistically near-certain).
1221 assert!(
1222 saw_different,
1223 "audit intervals should exhibit randomized jitter across samples"
1224 );
1225 }
1226}