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