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;
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/// Maximum number of furthest paid-list close-group peers treated as churny
44/// edge voters.
45///
46/// Once the paid-list close group reaches [`PAID_LIST_CLOSE_GROUP_SIZE`], edge
47/// peers are queried, but a negative edge paid-list response does not count
48/// into the paid-list majority denominator. A positive edge response does
49/// count. This absorbs local routing-table disagreement at the boundary of the
50/// paid close group. Undersized groups keep their ordinary strict majority.
51///
52/// This is a **ceiling**, not a fixed width: the effective edge is scaled to
53/// the group by [`ReplicationConfig::paid_list_flex_edge_count`] so the discount stays
54/// proportionate. A fixed four peers is a fifth of the production width but
55/// would be four fifths of a configured width of five, collapsing the voting
56/// core to a single peer.
57pub const PAID_LIST_FLEX_EDGE_COUNT: usize = 4;
58
59/// Divisor fixing the edge as a proportion of the paid close group.
60///
61/// Five gives the production ratio: 20 / 5 = 4 edge voters, matching
62/// [`PAID_LIST_FLEX_EDGE_COUNT`] exactly, so default behaviour is unchanged.
63const PAID_LIST_FLEX_EDGE_DIVISOR: usize = 5;
64
65/// Minimum `Confirmed` paid-list votes required to authorize a key, whatever
66/// the flexible edge does to the denominator.
67///
68/// The edge discount shrinks the denominator, and with it the majority
69/// threshold. Without an absolute floor a sufficiently small or sufficiently
70/// silent group authorizes on a single confirmation — and `PaidListVerified`
71/// writes the paid list and enables repair fetches, so that is the gate
72/// deciding what a node fetches and retains. Three independent confirmations
73/// keeps a lone voter (honest or not) from being decisive; groups genuinely
74/// smaller than this fall back to their strict majority via the `min` in
75/// [`ReplicationConfig::paid_confirm_needed`], since a floor above the group
76/// size would make authorization impossible rather than merely strict.
77pub const PAID_LIST_ABSOLUTE_CONFIRM_FLOOR: usize = 3;
78
79/// Number of closest peers to self eligible for neighbor sync.
80pub const NEIGHBOR_SYNC_SCOPE: usize = 20;
81
82/// Number of close-neighbor peers synced concurrently per round-robin repair
83/// round.
84pub const NEIGHBOR_SYNC_PEER_COUNT: usize = 4;
85
86/// Best-effort delivery retries for a fresh-replication push, per peer.
87///
88/// ADR-0003: on a transport/send failure the offer is retried up to this many
89/// times so a transient hiccup does not silently drop it. This is delivery
90/// assurance only — possession is judged separately by the delayed possession
91/// check, which still penalises a close peer that lacks the chunk even if the
92/// push never reached it.
93pub const FRESH_REPLICATION_DELIVERY_MAX_RETRIES: u32 = 2;
94
95const POSSESSION_CHECK_DELAY_MIN_SECS: u64 = 5 * 60;
96const POSSESSION_CHECK_DELAY_MAX_SECS: u64 = 15 * 60;
97
98/// Lower bound of the delay before a fresh-replication possession check runs
99/// (ADR-0003).
100///
101/// The delay lets replication settle so an honest peer still mid-store is not
102/// judged prematurely, and makes the check unpredictable to the peer.
103pub const POSSESSION_CHECK_DELAY_MIN: Duration =
104 Duration::from_secs(POSSESSION_CHECK_DELAY_MIN_SECS);
105
106/// Upper bound of the possession-check delay (ADR-0003).
107pub const POSSESSION_CHECK_DELAY_MAX: Duration =
108 Duration::from_secs(POSSESSION_CHECK_DELAY_MAX_SECS);
109
110// The possession probe reuses the `AuditChallenge` wire and the bandwidth-
111// calibrated `audit_response_timeout(1)` deadline, so it needs no bespoke
112// per-probe timeout or retry constants.
113
114/// Width used when deciding whether this node may locally store or retain a
115/// chunk.
116#[must_use]
117pub const fn storage_admission_width(close_group_size: usize) -> usize {
118 close_group_size.saturating_add(STORAGE_ADMISSION_MARGIN)
119}
120
121/// Minimum neighbor-sync cadence. Actual interval is randomized within
122/// `[min, max]`.
123const NEIGHBOR_SYNC_INTERVAL_MIN_SECS: u64 = 10 * 60;
124/// Maximum neighbor-sync cadence.
125const NEIGHBOR_SYNC_INTERVAL_MAX_SECS: u64 = 20 * 60;
126
127/// Neighbor sync cadence range (min).
128pub const NEIGHBOR_SYNC_INTERVAL_MIN: Duration =
129 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MIN_SECS);
130
131/// Neighbor sync cadence range (max).
132pub const NEIGHBOR_SYNC_INTERVAL_MAX: Duration =
133 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MAX_SECS);
134
135/// Per-peer minimum spacing between successive syncs with the same peer.
136const NEIGHBOR_SYNC_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
137/// Per-peer minimum spacing between successive syncs with the same peer.
138pub const NEIGHBOR_SYNC_COOLDOWN: Duration = Duration::from_secs(NEIGHBOR_SYNC_COOLDOWN_SECS);
139
140/// Minimum age for a replica repair hint before the hinted peer can be audited
141/// for that key.
142const REPAIR_HINT_MIN_AGE_SECS: u64 = 60 * 60; // 1 hour
143/// Minimum age for a replica repair hint before the hinted peer can be audited
144/// for that key.
145pub const REPAIR_HINT_MIN_AGE: Duration = Duration::from_secs(REPAIR_HINT_MIN_AGE_SECS);
146
147/// Minimum self-lookup cadence.
148const SELF_LOOKUP_INTERVAL_MIN_SECS: u64 = 5 * 60;
149/// Maximum self-lookup cadence.
150const SELF_LOOKUP_INTERVAL_MAX_SECS: u64 = 10 * 60;
151
152/// Periodic self-lookup cadence range (min) to keep close neighborhood
153/// current.
154pub const SELF_LOOKUP_INTERVAL_MIN: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MIN_SECS);
155
156/// Periodic self-lookup cadence range (max).
157pub const SELF_LOOKUP_INTERVAL_MAX: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MAX_SECS);
158
159/// Maximum number of concurrent outbound replication sends.
160///
161/// Caps how many fresh-replication chunk transfers can be in-flight at once
162/// across the entire replication engine. Prevents bandwidth saturation on
163/// home broadband connections when multiple chunks arrive simultaneously.
164/// Each send transfers up to 4 MB (`MAX_CHUNK_SIZE`), so a limit of 3 means
165/// at most ~12 MB queued for the upload link at any instant.
166pub const MAX_CONCURRENT_REPLICATION_SENDS: usize = 3;
167
168/// Maximum number of concurrent in-flight audit-responder tasks.
169///
170/// The LIGHT audit-responder handlers — responsible-chunk audits and subtree
171/// slice (round 2) — are spawned off the serial replication message loop so their
172/// disk reads don't stall replication. (The HEAVY subtree round 1 has its own
173/// tighter pool, [`MAX_CONCURRENT_SUBTREE_ROUND1`].) This caps how many run at once
174/// across the engine, restoring backpressure: a peer flooding audit challenges
175/// cannot fan out unbounded `get_raw` reads. When the cap is hit, the challenge
176/// is dropped and the caller's audit-specific timeout policy applies. The cap
177/// must therefore stay high enough for honest audit traffic while still
178/// throttling flooders.
179/// Sized to cover a handful of concurrent honest auditors (the per-peer
180/// gossip-audit cooldown is 30 min, so genuine concurrent audits are few) while
181/// bounding the round-2 worst-case disk reads (each request reads at most
182/// `BYTE_SPOTCHECK_MAX` distinct chunks — the openings are coalesced and the
183/// distinct-key count is capped — to build its slice proofs).
184pub const MAX_CONCURRENT_AUDIT_RESPONSES: usize = 32;
185
186/// Maximum concurrent in-flight audit-responder tasks from any SINGLE peer.
187///
188/// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] ceiling alone is not
189/// flood-fair: one peer spamming challenges could occupy every slot and starve
190/// honest auditors (whose dropped challenges convert to audit failures or
191/// timeout verdicts on the challenged peers). This per-peer cap guarantees no
192/// source holds more than its share, so a flood self-throttles. Audits are
193/// cooldown-gated (one
194/// gossip-triggered audit per peer per 30 min), so 4 in-flight per peer leaves
195/// headroom beyond the legitimate round-1 + round-2 overlap.
196pub const MAX_AUDIT_RESPONSES_PER_PEER: u32 = 4;
197
198/// Maximum concurrent digest-only `AuditChallenge` responses from any single
199/// source peer.
200///
201/// Digest challenges are KB-scale replies: at most
202/// `max_incoming_audit_keys(stored_chunks)` bounded disk reads plus BLAKE3
203/// digests. A higher per-source allowance absorbs the three legitimate issuer
204/// subsystems (responsible-chunk audit, prune confirmation, and possession
205/// checks) from one auditor without weakening the existing subtree/byte audit
206/// budget. The multi-MiB subtree and byte challenge paths intentionally keep
207/// [`MAX_AUDIT_RESPONSES_PER_PEER`] exactly unchanged.
208pub const MAX_DIGEST_AUDIT_RESPONSES_PER_PEER: u32 = 8;
209
210/// Cadence of audit-responder capacity and slow-processing summaries.
211///
212/// Each window is reset after logging, so the ranked origins describe current
213/// testnet load rather than being permanently dominated by an old burst.
214pub const AUDIT_RESPONDER_SUMMARY_INTERVAL: Duration = Duration::from_secs(60);
215
216/// Number of busiest source peers included in each responder summary window.
217pub const AUDIT_RESPONDER_TOP_ORIGINS: usize = 10;
218
219/// Dedicated global concurrency cap for the HEAVY subtree-audit round 1.
220///
221/// Round 1 hashes every leaf of the selected `sqrt(key_count)` subtree (up to
222/// ~1000 chunks × `MAX_CHUNK_SIZE` for a maximal commitment), far heavier than a
223/// responsible-chunk or slice (round-2) response. Giving it its own tiny pool —
224/// rather than sharing [`MAX_CONCURRENT_AUDIT_RESPONSES`] — keeps a burst of
225/// round-1 proofs from starving the light audits, and bounds concurrent
226/// multi-gigabyte hashing to this many at once. Two allows overlap without
227/// admitting many simultaneous full-subtree hashes; there is little benefit in
228/// more concurrent large LMDB scans against one disk.
229pub const MAX_CONCURRENT_SUBTREE_ROUND1: usize = 2;
230
231/// Per-peer concurrency cap for the heavy subtree-audit round 1. One in-flight
232/// round-1 proof per source at a time (an honest auditor never needs more).
233pub const MAX_SUBTREE_ROUND1_PER_PEER: u32 = 1;
234
235/// Per-peer responder-side cooldown between heavy subtree round-1 proofs.
236///
237/// An honest auditor already self-limits to one gossip-triggered subtree audit
238/// per peer per 30 min, so matching that as a responder-side floor costs honest
239/// traffic nothing while bounding the sustained round-1 work a single identity
240/// can extract (a concurrency cap alone lets a peer refill its slot forever).
241pub const SUBTREE_ROUND1_RESPONDER_COOLDOWN: Duration = Duration::from_secs(30 * 60);
242
243/// Lifetime of a single-use round-1 → round-2 session.
244///
245/// A round-2 slice challenge is only served if the same peer completed a matching
246/// round 1 within this window. Long enough for the auditor to verify round 1 and
247/// send round 2, far shorter than commitment retention; ephemeral, so a loss
248/// across a restart just
249/// drops that round to the (graced) timeout lane.
250pub const SUBTREE_SESSION_TTL: Duration = Duration::from_secs(2 * 60);
251
252/// Capacity backstop on the live round-1 session map (bounds memory if many
253/// peers open sessions; oldest are evicted past this).
254pub const MAX_SUBTREE_SESSIONS: usize = 4 * MAX_CONCURRENT_SUBTREE_ROUND1 * 256;
255
256/// Sustained rate at which the responder-wide round-1 work budget refills, in
257/// bytes of chunk content per second.
258///
259/// [`MAX_CONCURRENT_SUBTREE_ROUND1`] bounds how many round-1 proofs run at once
260/// and [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] bounds how often one peer id may
261/// ask, but neither bounds sustained work: the cooldown is keyed by identity, so
262/// a party holding several identities refills its allowance by rotating between
263/// them and keeps the small pool permanently busy. This budget is keyed by
264/// nothing at all — it is charged for the bytes read and hashed no matter who
265/// asked — so identity count cannot buy more of it.
266///
267/// Sized to clear honest demand even at the worst commitment size, since
268/// starving honest audits would cost more than it saves. The 990-node run
269/// served about 24 audits per node per hour. At the `MAX_COMMITMENT_KEY_COUNT`
270/// cap one proof reads close to 4 GiB, so honest demand there is ~96 GiB/h,
271/// against the 225 GiB/h this allows — and a flooder is held to about twice
272/// honest load rather than to whatever the disk will bear. For the far more
273/// common mid-sized commitment, where a proof reads a few hundred MiB, the
274/// headroom is more than an order of magnitude.
275///
276/// Signed because the budget it refills carries debt when a proof costs more
277/// than is left.
278pub const SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC: i64 = 64 * 1024 * 1024;
279
280/// Burst capacity of the round-1 work budget, in bytes of chunk content.
281///
282/// Also its starting fill, so a freshly started node can serve audits at once.
283/// Two maximal proofs' worth, matching [`MAX_CONCURRENT_SUBTREE_ROUND1`], so a
284/// legitimate burst is never refused for arriving together — the budget limits
285/// the sustained rate, which is what a concurrency cap cannot do.
286pub const SUBTREE_ROUND1_WORK_BURST_BYTES: i64 = 8 * 1024 * 1024 * 1024;
287
288/// Floor charged against the round-1 work budget per leaf attempted, in bytes.
289///
290/// The budget counts content bytes, which is the right unit for the hashing but
291/// misses what a leaf costs before its size is known: an LMDB point lookup with
292/// its retries, and a `spawn_blocking` dispatch and join. Nothing bounds a
293/// chunk from below, so a commitment made of a million tiny records would run a
294/// full subtree of reads and task round-trips per audit while charging almost
295/// nothing, and a leaf that fails to read charged nothing at all. Since the
296/// per-peer cooldown is escapable by rotating identity, the budget is the only
297/// bound that applies, so it has to see that cost.
298///
299/// Charged at the attempt, then topped up by whatever the content exceeds it
300/// by, so a leaf costs `max(bytes, this)`. At 4 KiB an honest chunk is almost
301/// always above it and pays exactly its bytes, which leaves the sizing of the
302/// refill rate above unchanged.
303pub const SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES: i64 = 4 * 1024;
304
305/// Concurrent fetches cap, derived from hardware thread count.
306///
307/// Uses `std::thread::available_parallelism()` so the node scales to the
308/// machine it runs on. Falls back to 4 if the OS query fails.
309const AVAILABLE_PARALLELISM_FALLBACK: usize = 4;
310
311/// Returns the number of hardware threads available, used as the fetch
312/// concurrency limit.
313#[allow(clippy::incompatible_msrv)] // NonZero::get is stable since 1.79; MSRV lint conflicts with redundant_closure
314pub fn max_parallel_fetch() -> usize {
315 std::thread::available_parallelism()
316 .map_or(AVAILABLE_PARALLELISM_FALLBACK, std::num::NonZero::get)
317}
318
319/// Minimum audit-scheduler cadence.
320const AUDIT_TICK_INTERVAL_MIN_SECS: u64 = 10 * 60;
321/// Maximum audit-scheduler cadence.
322const AUDIT_TICK_INTERVAL_MAX_SECS: u64 = 20 * 60;
323
324/// Audit scheduler cadence range (min).
325pub const AUDIT_TICK_INTERVAL_MIN: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MIN_SECS);
326
327/// Audit scheduler cadence range (max).
328pub const AUDIT_TICK_INTERVAL_MAX: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MAX_SECS);
329
330/// Floor on the audit response deadline (independent of challenge size).
331///
332/// Sized to absorb worst-case global RTT for the audit envelope
333/// (the request + response messages are KB-scale, not chunk-scale)
334/// plus scheduling jitter. Tokyo↔NY round-trip is ~150ms each way,
335/// so 4 seconds comfortably covers cross-continent communication
336/// for the round-1 proof, whose payload is hashes (KB-scale).
337const AUDIT_RESPONSE_FLOOR_SECS: u64 = 4;
338
339/// Floor on the round-2 SLICE-challenge deadline.
340///
341/// The round-2 reply is only a few KB per opening (a 1 KiB block plus two short
342/// hash chains), but an honest responder still reads each opened chunk's full
343/// bytes from disk to build its Bao slice and nonced opening, so the floor must
344/// cover a cold QUIC handshake plus a busy honest peer's full-chunk disk read.
345/// The round-1 4 s floor is sized for a hashes-only reply; round 2 keeps a
346/// slightly larger 5 s base for the disk-read envelope, with the per-byte scaled
347/// term (one full chunk per opening) added on top.
348const BYTE_AUDIT_RESPONSE_FLOOR_SECS: u64 = 5;
349
350/// Conservative honest-responder read throughput, in bytes per second.
351///
352/// Used to size the audit response deadline. An honest peer answers
353/// a k-key challenge by reading k chunks from local disk, computing
354/// BLAKE3 + path proofs, and signing the response. The bottleneck is
355/// disk read; BLAKE3 at ~3 GB/s + ML-DSA signing at ~3 ms are
356/// negligible.
357///
358/// Set conservatively below any modern SSD (typical: 500 MB/s+).
359/// At 50 MB/s, a k=10 sample at 4 MiB chunks reads in ~0.8s, well
360/// inside even an aggressive timeout. A relay attacker who must
361/// fetch the same 40 MB over the network at typical bandwidth
362/// (100 Mbps = 12.5 MB/s) takes 3+ seconds for the data alone, plus
363/// per-chunk network round-trips. At larger sample sizes the gap
364/// is exponential in the relay's disadvantage.
365const AUDIT_HONEST_READ_BPS: u64 = 50 * 1024 * 1024;
366
367/// Slack multiplier on the honest-read estimate.
368///
369/// Set so an honest peer that's slower than `HONEST_READ_BPS` (e.g. an
370/// HDD-backed node, or one under load) still answers within the
371/// timeout. 5× is generous; a relay peer fetching the same data over a
372/// residential link (~5-12 MB/s) sees ~10-100× higher latency than disk
373/// and misses the budget. This is an economic deterrent calibrated for
374/// residential bandwidth, NOT a hard cryptographic bound — a relay on a
375/// datacenter cross-connect could still fetch fast enough to answer in
376/// time (see the §7 note on `audit_response_timeout`).
377const AUDIT_RESPONSE_HONEST_MULTIPLIER: u64 = 5;
378
379/// Maximum duration a peer may claim bootstrap status before penalties apply.
380const BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS: u64 = 24 * 60 * 60; // 24 h
381/// Maximum duration a peer may claim bootstrap status before penalties apply.
382pub const BOOTSTRAP_CLAIM_GRACE_PERIOD: Duration =
383 Duration::from_secs(BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS);
384
385/// Minimum continuous out-of-range duration before pruning a key.
386const PRUNE_HYSTERESIS_DURATION_SECS: u64 = 3 * 24 * 60 * 60; // 3 days
387/// Minimum continuous out-of-range duration before pruning a key.
388pub const PRUNE_HYSTERESIS_DURATION: Duration = Duration::from_secs(PRUNE_HYSTERESIS_DURATION_SECS);
389
390/// Protocol identifier for core replication operations, including the
391/// digest-based responsible-chunk, possession, and prune-confirmation audits.
392///
393/// Kept at `v2`: the V2-685 work changes only the subtree-audit wire family.
394/// Fresh replication, neighbour sync, fetch, repair, verification, and the
395/// digest-based audit lanes therefore continue interoperating on this id. A node
396/// filters inbound messages by exact topic match (see the dispatch in `mod.rs`).
397pub const REPLICATION_PROTOCOL_ID: &str = "autonomi.ant.replication.v2";
398
399/// Protocol identifier for the subtree storage-commitment audit (ADR-0002 /
400/// V2-685), both rounds: `SubtreeAuditChallenge`/`Response` (round 1) and
401/// `SubtreeSliceChallenge`/`Response` (round 2).
402///
403/// These are the only replication messages whose wire format changed for the
404/// slice audit (round 1's `SubtreeLeaf` now carries `content_len` + `nonced_root`
405/// instead of a flat `nonced_hash`; round 2 replaced full-byte responses with Bao
406/// verified slices). Routing them on their own id — instead of bumping the whole
407/// [`REPLICATION_PROTOCOL_ID`] — means a mixed-version fleet keeps doing fresh
408/// replication, neighbour sync, fetch and repair across versions; only
409/// cross-version subtree *audits* pause during the ~24 h auto-upgrade window.
410///
411/// Rollout effect is bounded, not zero: `saorsa-core`'s `send_request` records a
412/// unit trust failure on any unanswered request (before ant-node's graced-timeout
413/// policy), so a v3 auditor's subtree challenge to a still-v2 peer (and the
414/// reverse, where a v2 subtree audit is dropped by the id/body guard) each ding
415/// that peer's EMA trust once per 30-minute audit cooldown. Trust decays back to
416/// neutral (a worst-case dip recovers above the 0.35 routing-swap threshold in
417/// ~1 online day, and a successful audit after upgrade adds a unit success), and
418/// crossing 0.35 only makes a peer replaceable in a full bucket — it does not
419/// delete data or ban the peer. This is strictly milder than bumping the shared
420/// id, which would fail every cross-version request path (sync/quorum/prune/
421/// possession/repair/commitment-fetch) with no per-peer limiter. A truly
422/// zero-penalty rollout needs an upstream `send_request` that does not
423/// auto-report trust; tracked as a saorsa-core follow-up.
424pub const SUBTREE_AUDIT_PROTOCOL_ID: &str = "autonomi.ant.replication.subtree-audit.v1";
425
426/// 10 MiB — maximum replication wire message size (accommodates hint batches).
427const REPLICATION_MESSAGE_SIZE_MIB: usize = 10;
428/// Maximum replication wire message size.
429pub const MAX_REPLICATION_MESSAGE_SIZE: usize = REPLICATION_MESSAGE_SIZE_MIB * 1024 * 1024;
430
431/// Maximum wire size for a message in the subtree-audit protocol family.
432///
433/// The 10 MiB core ceiling is sized for hint batches, which no subtree-audit
434/// body carries. Applying it to the subtree family would let a peer make this node
435/// allocate and decode megabytes of attacker-shaped collection before any
436/// family, session or admission check has run — those checks all read fields of
437/// the decoded body, so they cannot come first. Checking the encoded length
438/// against a family-appropriate ceiling can, because it needs nothing but the
439/// byte count.
440///
441/// Sized against the largest legitimate audit body, the round-1
442/// `SubtreeAuditResponse::Proof`: at the `MAX_COMMITMENT_KEY_COUNT` cap a
443/// subtree is at most 1,024 leaves of ~100 bytes each, plus the sibling cut
444/// hashes and the signed commitment, so ~110 KiB. Every other subtree body is
445/// far smaller. This leaves roughly
446/// 4x headroom over the worst legitimate case while cutting the pre-admission
447/// allocation ceiling by a factor of 20.
448pub const MAX_SUBTREE_AUDIT_MESSAGE_SIZE: usize = 512 * 1024;
449const _: () = assert!(
450 MAX_SUBTREE_AUDIT_MESSAGE_SIZE < MAX_REPLICATION_MESSAGE_SIZE,
451 "the subtree-audit ceiling must be tighter than the core one, or it is pointless"
452);
453
454/// Maximum block openings per round-2 [`SubtreeSliceChallenge`].
455///
456/// Each opening is a Bao verified slice (a 1 KiB block plus O(log n) BLAKE3
457/// parent hashes) plus a nonced block-tree sibling chain — a few KB, so even
458/// this many openings encode far under [`MAX_REPLICATION_MESSAGE_SIZE`] with no
459/// batching. The auditor draws up to *two* openings per sampled leaf — one
460/// fresh-random block (possession) and one at the claimed final block (a length
461/// pin: opening the final block forces Bao's EOF validation, which authenticates
462/// the true content length and defeats a forged-short `content_len` that would
463/// otherwise shrink the challenge space). With at most `BYTE_SPOTCHECK_MAX`
464/// leaves that is `2 × BYTE_SPOTCHECK_MAX` openings; this cap sits just above
465/// that, and the responder rejects any challenge requesting more (a forged-
466/// auditor guard: each opening forces one full chunk read to build its proof).
467///
468/// [`SubtreeSliceChallenge`]: crate::replication::protocol::SubtreeSliceChallenge
469pub const MAX_SLICE_OPENINGS: usize = 10;
470const _: () = assert!(
471 MAX_SLICE_OPENINGS >= 1,
472 "at least one block opening must be allowed per slice challenge"
473);
474
475/// Rollout gate for ADR-0004 quote-arithmetic enforcement.
476///
477/// When `true`, the payment verifier rejects any quote whose signed price does
478/// not lie exactly on the public pricing curve, i.e. there is no integer
479/// `key_count` for which `calculate_price(key_count) == quote.price`. The check
480/// is exact recomputation against the curve, never price-inversion (which
481/// rounds), per ADR-0004's "never by inverting the price" rule.
482///
483/// When `false`, the check still runs and logs every would-be rejection, but
484/// does not reject — matching the ADR-0004 rollout: ship observe-only first,
485/// enforce only once the fleet has upgraded. Off-curve quotes are honest
486/// errors, not signs of an old node (every honest implementation derives its
487/// price from the same public formula), so flipping this to `true` does not
488/// risk evicting un-upgraded peers; it only catches modified nodes that minted
489/// prices off the curve.
490///
491/// This is a reject-only gate: an off-curve quote produces no trust evidence
492/// and no audit, per ADR-0004 ("an off-curve quote is reject-only"). It does
493/// NOT gate the quote/commitment mismatch trust report — see
494/// [`QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED`] for that, kept separate because
495/// the two have different ADR-0004 contracts (this one rejects with no trust
496/// action; that one reports a deterministic contradiction to the trust engine).
497pub const QUOTE_ARITHMETIC_RECHECK_ENABLED: bool = false;
498
499/// Rollout gate for ADR-0004 quote/commitment **mismatch** trust reporting.
500///
501/// When a client-put quote's signed `committed_key_count` contradicts the
502/// `key_count` of the commitment it pinned (resolved from the gossip cache, a
503/// sidecar, or a fetch), that is two artifacts signed by the same key that
504/// contradict each other — a deterministic, first-occurrence misbehaviour. When
505/// `true`, the cross-check reports it to the trust engine as an
506/// `ApplicationFailure` (the same lane as a confirmed deterministic audit
507/// failure, NOT the timeout silence lane). When `false`, the cross-check only
508/// logs the would-be report (observe-only).
509///
510/// Kept independent of [`QUOTE_ARITHMETIC_RECHECK_ENABLED`] (which is
511/// reject-only with no trust action): a confirmed mismatch is not a mere
512/// off-curve price, so it deserves its own dial.
513pub const QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED: bool = false;
514
515/// Instant from which a merkle batch payment must carry the same 3x settlement
516/// multiplier the single-node path has always applied (ADR-0008). Unix seconds.
517///
518/// The single-node path settles a chunk at 3x the median quoted price. The
519/// merkle path submitted the bare quoted price as the on-chain payable amount,
520/// so the contract's `median16(amount) x 2^depth` came to 1x the median per
521/// padded leaf: the same chunk, stored and replicated identically, earned a
522/// third as much when it arrived in a batch.
523///
524/// **The rollout is client-first, and this constant is only its second half.**
525/// ant-client (ant-client#161) pays 3x immediately and unconditionally once
526/// released — no date, no flag — and un-upgraded nodes accept that, because 3x
527/// clears the 1x minimum they require. So the network is paid correctly from
528/// the moment the client ships. This instant is when upgraded nodes stop
529/// accepting anything less.
530///
531/// **Enforcement is on by default.** There is no shadow mode and no flag to
532/// flip later: a receipt stamped at or after this instant must settle at 3x or
533/// the store is refused. What the boundary buys is not a soft launch, it is
534/// compatibility with money that was already spent:
535///
536/// - A receipt stamped **before** the boundary is held to the historic 1x. It
537/// was paid in good faith under the old rule and the payer cannot get it
538/// back, so refusing it would destroy value rather than protect it.
539/// - Merkle receipts expire after `MERKLE_PAYMENT_EXPIRATION` (one week), and
540/// a receipt stamped in the future is refused outright. So once
541/// `boundary + one week` has passed, **every** still-valid receipt is
542/// necessarily stamped at or after the boundary and the 1x branch becomes
543/// unreachable. It retires itself; nobody has to remember to turn it off.
544/// - Backdating is **not** prevented during that week. The timestamp is
545/// client-chosen — it is a `payForMerkleTree` argument, the contract only
546/// rejects future and week-old stamps, and quoting nodes sign whatever stamp
547/// the request carries — so a modified client can stamp just before the
548/// boundary and keep paying 1x until such a stamp expires. Expiry is what
549/// closes the route, not detection, and it closes it at
550/// `boundary + one week`. The same branch protects honest in-flight receipts,
551/// so the window cannot be narrowed without also destroying those.
552///
553/// Set to 2026-08-04 15:00 UTC, after the client release with room for
554/// adoption. Two invariants when moving it: **it must never be earlier than the
555/// client release that pays 3x** (an earlier value refuses receipts bought
556/// under the previous rule, the one outcome this constant exists to avoid), and
557/// it must move forward if that **client** release slips — a node enforcing
558/// before clients pay fails every batch upload. A slip in *node* rollout needs
559/// no change: it only means fewer nodes enforce for a while.
560pub const MERKLE_PARITY_ENFORCED_FROM_UNIX: u64 = 1_785_855_600;
561
562/// ADR-0004: max unresolved quote pins to fetch per payment bundle.
563///
564/// A bundle has at most `CLOSE_GROUP_SIZE` quotes; capping fetches per bundle
565/// bounds the amplification a single malicious upload (many distinct unknown
566/// pins) can drive. Excess unresolved pins in one bundle are dropped (left
567/// unresolved, i.e. graced — the audit funnel still catches a serving cheater).
568pub const MAX_PIN_FETCHES_PER_BUNDLE: usize = 3;
569
570/// ADR-0004: capacity of the per-peer negative cache for unresolved pin fetches.
571///
572/// A pin that a peer answered `NotRetained` (or that timed out) is remembered so
573/// repeated bundles citing the same unknown pin don't re-fetch.
574pub const PIN_FETCH_NEGATIVE_CACHE_CAPACITY: usize = 4096;
575
576/// ADR-0004: timeout for a `GetCommitmentByPin` fetch.
577///
578/// Sized for a single small round-trip plus the responder's bounded in-memory
579/// lookup; a fetch is off the payment hot path, so this only bounds the
580/// background cross-check.
581pub const PIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
582
583/// Verification request timeout (per-batch).
584const VERIFICATION_REQUEST_TIMEOUT_SECS: u64 = 15;
585/// Verification request timeout (per-batch).
586pub const VERIFICATION_REQUEST_TIMEOUT: Duration =
587 Duration::from_secs(VERIFICATION_REQUEST_TIMEOUT_SECS);
588
589/// Maximum ready hints processed by one verification cycle.
590///
591/// The pending queue may be much larger. Each cycle takes a sender-fair bounded
592/// sample, retaining corroboration/age priority within each sender's share.
593/// This value keeps today's roughly 6k-chunk average bootstrap within one cycle
594/// while preventing a full emergency-cap queue from creating one enormous
595/// verification round.
596pub const MAX_VERIFICATION_KEYS_PER_CYCLE: usize = 8_192;
597
598/// Maximum keys accepted in one incoming verification request.
599///
600/// Senders aggregate all keys for a peer into one request. Matching this limit
601/// to the cycle bound lets an honest round use one request per peer while still
602/// bounding the LMDB work performed on the responder's serial replication
603/// message path. Oversized requests are rejected as an empty, wire-compatible
604/// verification response.
605pub const MAX_INCOMING_VERIFICATION_KEYS: usize = MAX_VERIFICATION_KEYS_PER_CYCLE;
606
607/// Maximum simultaneous verification request/response exchanges.
608/// Larger rounds remain fully batched but wait for a permit instead of
609/// launching hundreds or thousands of network requests at once.
610pub const MAX_CONCURRENT_VERIFICATION_REQUESTS: usize = 32;
611
612/// Fetch request timeout.
613const FETCH_REQUEST_TIMEOUT_SECS: u64 = 30;
614/// Fetch request timeout.
615pub const FETCH_REQUEST_TIMEOUT: Duration = Duration::from_secs(FETCH_REQUEST_TIMEOUT_SECS);
616
617/// Maximum age for pending-verification entries before stale eviction.
618const PENDING_VERIFY_MAX_AGE_SECS: u64 = 30 * 60;
619/// Maximum age for pending-verification entries before stale eviction.
620pub const PENDING_VERIFY_MAX_AGE: Duration = Duration::from_secs(PENDING_VERIFY_MAX_AGE_SECS);
621
622/// Trust event weight for confirmed audit failures.
623pub const AUDIT_FAILURE_TRUST_WEIGHT: f64 = 5.0;
624
625/// Probability of launching a subtree audit when a peer's *changed* commitment
626/// is ingested via gossip (ADR-0002). Keeps audits occasional surprise exams.
627pub const AUDIT_ON_GOSSIP_PROBABILITY: f64 = 0.2;
628
629/// Per-peer cooldown between gossip-triggered subtree audits (ADR-0002), in
630/// seconds. Bounds how often any one peer is audited regardless of gossip rate.
631pub const AUDIT_ON_GOSSIP_COOLDOWN_SECS: u64 = 30 * 60;
632
633/// ADR-0004: first-audit drainer retry cadence for cooldown-pending pins.
634///
635/// How often the drainer retries pins it kept pending because their peer was on
636/// cooldown. Finer than the cooldown itself so a monetized commitment is
637/// first-audited promptly after its peer's window reopens; the retry just
638/// re-checks a small per-peer map, so the tick is cheap.
639pub const FIRST_AUDIT_RETRY_INTERVAL: Duration = Duration::from_secs(60);
640
641/// Interval for the cumulative first-audit scheduler observability summary.
642///
643/// Deliberately low frequency: this is intended for fleet-level Elasticsearch
644/// aggregation without recreating the high-volume logging load it measures.
645pub const FIRST_AUDIT_SUMMARY_INTERVAL: Duration = Duration::from_secs(5 * 60);
646
647/// ADR-0004: max monetized-pin events the first-audit drainer drains from its
648/// channel per wake before it must run the audit-launch phase.
649///
650/// Bounds the synchronous `try_recv` batch so a sustained producer flood cannot
651/// starve audit launching by spinning in the drain loop forever. After this many
652/// events the drainer processes audits, then loops back to drain more.
653pub const FIRST_AUDIT_DRAIN_BATCH: usize = 64;
654
655/// ADR-0004 Amendment 2: token-bucket refill interval for monetized first-audit
656/// launches — one launch token per interval, per node.
657///
658/// This is the load-bearing bound: fleet-wide first-audit pressure becomes
659/// `nodes x (1 / interval)` regardless of upload volume, where the pre-amendment
660/// scheduler scaled with `uploads x pinned-quotes-per-proof x verifying-storers`
661/// (measured at ~110 storage-commitment audit events/hour/service in the
662/// DEV-01 staging run, with 77.7% of launches timing out in the DEV-03
663/// per-service-concurrency attempt). At 5 minutes the sustained rate is
664/// 12 launches/hour/node (a drained burst bucket adds at most
665/// [`FIRST_AUDIT_BUDGET_BURST`] more in the first hour); steady-state demand
666/// sits far below it because nomination is paid-pin-only and re-nominations
667/// are suppressed by [`FIRST_AUDIT_PEER_REAUDIT_INTERVAL`].
668pub const FIRST_AUDIT_LAUNCH_INTERVAL: Duration = Duration::from_secs(5 * 60);
669
670/// ADR-0004 Amendment 2: token-bucket capacity for monetized first-audit
671/// launches.
672///
673/// Lets a node absorb a small burst of NEW earning peers (several distinct
674/// paid pins verified back-to-back) without waiting a full refill interval per
675/// launch, while keeping the sustained rate pinned to
676/// [`FIRST_AUDIT_LAUNCH_INTERVAL`].
677pub const FIRST_AUDIT_BUDGET_BURST: u32 = 2;
678
679/// ADR-0004 Amendment 2: max concurrently in-flight monetized first audits per
680/// node.
681///
682/// A first audit can hold a slot for the full size-scaled two-round deadline,
683/// so without this cap a burst of slow/timing-out targets would pile up
684/// concurrent subtree audits even under the launch-rate budget. Deferral is
685/// penalty-free: the pin stays pending and is retried when a slot frees.
686pub const FIRST_AUDIT_MAX_INFLIGHT: u64 = 2;
687
688/// ADR-0004 Amendment 2: max uniform random delay applied before sending a
689/// monetized first-audit challenge.
690///
691/// Every storer of a chunk verifies the same payment at the same instant, so
692/// unjittered first audits from the whole close group would hit the paid peer
693/// simultaneously and trip its per-peer responder admission cap (drops that
694/// auditors then record as Timeout). The jitter decorrelates the observers.
695pub const FIRST_AUDIT_LAUNCH_JITTER_MAX: Duration = Duration::from_secs(30);
696
697/// ADR-0004 Amendment 2: per-peer suppression window between monetized first
698/// audits, across commitment rotations.
699///
700/// Pin-level dedup alone is defeated by the hourly commitment rotation (every
701/// rotation mints a fresh pin, re-arming every observer). After a first audit
702/// LAUNCHES at a peer, further monetized nominations for that peer are dropped
703/// for this window — unless the new pin's committed key count exceeds the
704/// audited one by more than [`FIRST_AUDIT_COUNT_JUMP_NUM`]/
705/// [`FIRST_AUDIT_COUNT_JUMP_DEN`] (a peer that passes an audit on an honest
706/// count and then mints a much larger commitment must be re-nominated
707/// immediately: inflated SIDECAR-ONLY pins are visible to payment verifiers
708/// only, so no gossip-lottery audit can ever cover them). Kept comfortably
709/// inside the 3h answerability TTL so a re-nomination after the window still
710/// lands in-window. Gossip-lottery re-audits are unaffected.
711pub const FIRST_AUDIT_PEER_REAUDIT_INTERVAL: Duration = Duration::from_secs(2 * 3600);
712
713/// ADR-0004 Amendment 2: committed-count jump that overrides the per-peer
714/// re-audit window, as a ratio (`new > old * NUM / DEN`, integer math).
715///
716/// 3/2: a >1.5x growth in claimed committed keys within the suppression window
717/// re-nominates the peer despite a recent first audit.
718pub const FIRST_AUDIT_COUNT_JUMP_NUM: u64 = 3;
719/// Denominator of the count-jump override ratio. See
720/// [`FIRST_AUDIT_COUNT_JUMP_NUM`].
721pub const FIRST_AUDIT_COUNT_JUMP_DEN: u64 = 2;
722
723/// ADR-0004 Amendment 2: capacity of the bounded verifier-to-drainer
724/// monetized-pin channel.
725///
726/// Nominations are gated behind SETTLED on-chain payments, so legitimate
727/// ingress is tiny; the drainer drains every wake (batched at
728/// [`FIRST_AUDIT_DRAIN_BATCH`]) and coalesces newest-per-peer, so a backlog
729/// this deep implies the drainer is starved, not that work is arriving fast.
730/// Producers `try_send` and drop on full: a dropped nomination is
731/// penalty-free; the peer's gossiped commitments stay lottery-covered and
732/// its next settled payment re-nominates the paid pin.
733pub const FIRST_AUDIT_INGRESS_CAPACITY: usize = 1024;
734
735/// Number of subtree leaves spot-checked against real chunk bytes per audit
736/// (ADR-0002 real-bytes layer).
737///
738/// The auditor clamps this to its 3..=5 band (`BYTE_SPOTCHECK_MIN..=MAX` in
739/// `storage_commitment_audit`), so this is the effective MAXIMUM — set it
740/// within the band rather than advertising a sample size the auditor never
741/// requests.
742pub const AUDIT_SPOTCHECK_COUNT: u32 = 5;
743
744/// Conservative leaf-count hint for sizing the subtree-audit response deadline.
745///
746/// The deadline is set before the proof arrives, so we size for the largest
747/// legal store: `sqrt(MAX_COMMITMENT_KEY_COUNT) = 1000`. Honest small stores
748/// finish well within it.
749pub const SUBTREE_AUDIT_TIMEOUT_LEAF_HINT: usize = 1000;
750
751/// Maximum mature records selected for prune-confirmation auditing per pass.
752///
753/// This bounds local digest/proof bookkeeping independently from the number
754/// of network requests. Keys for the same peer are batched below.
755pub const MAX_PRUNE_AUDIT_CANDIDATES_PER_PASS: usize = 1024;
756
757/// Maximum initial prune-confirmation audit requests sent per pass.
758///
759/// A request may contain multiple keys. Keeping this separate from the
760/// candidate cap prevents the old candidate-to-peer-edge accounting from
761/// limiting a production pass to roughly nine records.
762pub const MAX_PRUNE_AUDIT_REQUESTS_PER_PASS: usize = 256;
763
764/// Maximum mature records deleted through the complete width-20 fast path per
765/// pass.
766pub const MAX_FAST_PRUNE_DELETIONS_PER_PASS: usize = 2048;
767
768/// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before proceeding
769/// with bootstrap sync. Covers bootstrap nodes with no peers to connect to.
770const BOOTSTRAP_COMPLETE_TIMEOUT_SECS: u64 = 60;
771
772// ---------------------------------------------------------------------------
773// Runtime-configurable wrapper
774// ---------------------------------------------------------------------------
775
776/// Runtime-configurable replication parameters.
777///
778/// Validated on construction — node rejects invalid configs.
779#[derive(Debug, Clone)]
780pub struct ReplicationConfig {
781 /// Close-group width and target holder count per key.
782 pub close_group_size: usize,
783 /// Required positive presence votes for quorum.
784 pub quorum_threshold: usize,
785 /// Maximum closest nodes tracking paid status for a key.
786 pub paid_list_close_group_size: usize,
787 /// Number of closest peers to self eligible for neighbor sync.
788 pub neighbor_sync_scope: usize,
789 /// Peers synced concurrently per round-robin repair round.
790 pub neighbor_sync_peer_count: usize,
791 /// Neighbor sync cadence range (min).
792 pub neighbor_sync_interval_min: Duration,
793 /// Neighbor sync cadence range (max).
794 pub neighbor_sync_interval_max: Duration,
795 /// Minimum spacing between successive syncs with the same peer.
796 pub neighbor_sync_cooldown: Duration,
797 /// Self-lookup cadence range (min).
798 pub self_lookup_interval_min: Duration,
799 /// Self-lookup cadence range (max).
800 pub self_lookup_interval_max: Duration,
801 /// Audit scheduler cadence range (min).
802 pub audit_tick_interval_min: Duration,
803 /// Audit scheduler cadence range (max).
804 pub audit_tick_interval_max: Duration,
805 /// Floor on the audit response deadline. Covers global RTT for
806 /// the small request/response envelope plus scheduling jitter.
807 /// See `AUDIT_RESPONSE_FLOOR_SECS` for sizing.
808 pub audit_response_floor: Duration,
809 /// Conservative honest-responder read throughput (bytes/sec).
810 /// Used to scale the audit response deadline against the size of
811 /// the challenge. Slow enough that even an HDD-backed honest peer
812 /// fits inside the budget; fast enough that a relay attacker who
813 /// must fetch bytes over the network falls outside.
814 pub audit_honest_read_bps: u64,
815 /// Slack multiplier on the honest-read estimate before
816 /// declaring an audit timed out.
817 pub audit_response_honest_multiplier: u64,
818 /// Maximum duration a peer may claim bootstrap status.
819 pub bootstrap_claim_grace_period: Duration,
820 /// Minimum continuous out-of-range duration before pruning a key.
821 pub prune_hysteresis_duration: Duration,
822 /// Verification request timeout (per-batch).
823 pub verification_request_timeout: Duration,
824 /// Fetch request timeout.
825 pub fetch_request_timeout: Duration,
826 /// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before
827 /// proceeding with bootstrap sync (covers bootstrap nodes with no peers).
828 pub bootstrap_complete_timeout_secs: u64,
829 /// Lower bound of the delay before a fresh-replication possession check
830 /// runs (ADR-0003). Defaults to [`POSSESSION_CHECK_DELAY_MIN`]; tests
831 /// shorten it so the scheduled check fires quickly.
832 pub possession_check_delay_min: Duration,
833 /// Upper bound of the possession-check delay window (ADR-0003). Defaults
834 /// to [`POSSESSION_CHECK_DELAY_MAX`].
835 pub possession_check_delay_max: Duration,
836 /// Per-peer responder-side cooldown between heavy subtree round-1 proofs.
837 /// Defaults to [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`]; tests set
838 /// it low so rapid back-to-back audits of one holder are not rate-dropped.
839 pub subtree_round1_responder_cooldown: Duration,
840 /// Global ceiling on concurrent heavy subtree round-1 proofs this node will
841 /// serve. Defaults to [`MAX_CONCURRENT_SUBTREE_ROUND1`].
842 ///
843 /// Exposed here rather than read straight from the constant because it is the
844 /// tightest bound the responder applies and the one with the least fleet
845 /// evidence behind its value: too low and honest auditors are capacity-dropped
846 /// (their audits land in the graced timeout lane, so coverage silently falls
847 /// without any peer being penalised), too high and concurrent full-subtree
848 /// hashing competes with serving real traffic. Making it configurable means a
849 /// fleet that lands on the wrong number can be retuned without cutting a
850 /// release. A value of 0 is clamped to 1 by
851 /// [`SubtreeRound1Limiter::new`](crate::replication) rather than disabling
852 /// round 1 outright.
853 pub subtree_round1_max_concurrent: usize,
854}
855
856impl Default for ReplicationConfig {
857 fn default() -> Self {
858 Self {
859 close_group_size: CLOSE_GROUP_SIZE,
860 quorum_threshold: QUORUM_THRESHOLD,
861 paid_list_close_group_size: PAID_LIST_CLOSE_GROUP_SIZE,
862 neighbor_sync_scope: NEIGHBOR_SYNC_SCOPE,
863 neighbor_sync_peer_count: NEIGHBOR_SYNC_PEER_COUNT,
864 neighbor_sync_interval_min: NEIGHBOR_SYNC_INTERVAL_MIN,
865 neighbor_sync_interval_max: NEIGHBOR_SYNC_INTERVAL_MAX,
866 neighbor_sync_cooldown: NEIGHBOR_SYNC_COOLDOWN,
867 self_lookup_interval_min: SELF_LOOKUP_INTERVAL_MIN,
868 self_lookup_interval_max: SELF_LOOKUP_INTERVAL_MAX,
869 audit_tick_interval_min: AUDIT_TICK_INTERVAL_MIN,
870 audit_tick_interval_max: AUDIT_TICK_INTERVAL_MAX,
871 audit_response_floor: Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
872 audit_honest_read_bps: AUDIT_HONEST_READ_BPS,
873 audit_response_honest_multiplier: AUDIT_RESPONSE_HONEST_MULTIPLIER,
874 bootstrap_claim_grace_period: BOOTSTRAP_CLAIM_GRACE_PERIOD,
875 prune_hysteresis_duration: PRUNE_HYSTERESIS_DURATION,
876 verification_request_timeout: VERIFICATION_REQUEST_TIMEOUT,
877 fetch_request_timeout: FETCH_REQUEST_TIMEOUT,
878 bootstrap_complete_timeout_secs: BOOTSTRAP_COMPLETE_TIMEOUT_SECS,
879 possession_check_delay_min: POSSESSION_CHECK_DELAY_MIN,
880 possession_check_delay_max: POSSESSION_CHECK_DELAY_MAX,
881 subtree_round1_responder_cooldown: SUBTREE_ROUND1_RESPONDER_COOLDOWN,
882 subtree_round1_max_concurrent: MAX_CONCURRENT_SUBTREE_ROUND1,
883 }
884 }
885}
886
887impl ReplicationConfig {
888 /// Validate safety constraints. Returns `Err` with a description if any
889 /// constraint is violated.
890 ///
891 /// # Errors
892 ///
893 /// Returns a human-readable message describing the first violated
894 /// constraint.
895 pub fn validate(&self) -> Result<(), String> {
896 if self.close_group_size == 0 {
897 return Err("close_group_size must be >= 1".to_string());
898 }
899 if self.quorum_threshold == 0 || self.quorum_threshold > self.close_group_size {
900 return Err(format!(
901 "quorum_threshold ({}) must satisfy 1 <= quorum_threshold <= close_group_size ({})",
902 self.quorum_threshold, self.close_group_size,
903 ));
904 }
905 if self.close_group_size > MAX_PRUNE_AUDIT_REQUESTS_PER_PASS {
906 return Err(format!(
907 "close_group_size ({}) must be <= MAX_PRUNE_AUDIT_REQUESTS_PER_PASS ({})",
908 self.close_group_size, MAX_PRUNE_AUDIT_REQUESTS_PER_PASS,
909 ));
910 }
911 if self.paid_list_close_group_size == 0 {
912 return Err("paid_list_close_group_size must be >= 1".to_string());
913 }
914 if self.neighbor_sync_interval_min > self.neighbor_sync_interval_max {
915 return Err(format!(
916 "neighbor_sync_interval_min ({:?}) must be <= neighbor_sync_interval_max ({:?})",
917 self.neighbor_sync_interval_min, self.neighbor_sync_interval_max,
918 ));
919 }
920 if self.audit_tick_interval_min > self.audit_tick_interval_max {
921 return Err(format!(
922 "audit_tick_interval_min ({:?}) must be <= audit_tick_interval_max ({:?})",
923 self.audit_tick_interval_min, self.audit_tick_interval_max,
924 ));
925 }
926 if self.self_lookup_interval_min > self.self_lookup_interval_max {
927 return Err(format!(
928 "self_lookup_interval_min ({:?}) must be <= self_lookup_interval_max ({:?})",
929 self.self_lookup_interval_min, self.self_lookup_interval_max,
930 ));
931 }
932 if self.neighbor_sync_peer_count == 0 {
933 return Err("neighbor_sync_peer_count must be >= 1".to_string());
934 }
935 if self.neighbor_sync_scope == 0 {
936 return Err("neighbor_sync_scope must be >= 1".to_string());
937 }
938 if self.neighbor_sync_scope > K_BUCKET_SIZE {
939 return Err(format!(
940 "neighbor_sync_scope ({}) must be <= K_BUCKET_SIZE ({})",
941 self.neighbor_sync_scope, K_BUCKET_SIZE,
942 ));
943 }
944 Ok(())
945 }
946
947 /// Effective quorum votes required for a key given the number of
948 /// reachable quorum targets.
949 ///
950 /// `min(self.quorum_threshold, floor(quorum_targets_count / 2) + 1)`
951 #[must_use]
952 pub fn quorum_needed(&self, quorum_targets_count: usize) -> usize {
953 if quorum_targets_count == 0 {
954 return 0;
955 }
956 let majority = quorum_targets_count / 2 + 1;
957 self.quorum_threshold.min(majority)
958 }
959
960 /// Confirmations required for paid-list consensus given the number of
961 /// peers in the paid-list close group for a key.
962 ///
963 /// `floor(paid_group_size / 2) + 1`
964 #[must_use]
965 pub fn confirm_needed(paid_group_size: usize) -> usize {
966 paid_group_size / 2 + 1
967 }
968
969 /// Confirmations required to authorize a key, given the edge-discounted
970 /// denominator and the true (undiscounted) group size.
971 ///
972 /// The strict majority of the discounted group, raised to
973 /// [`PAID_LIST_ABSOLUTE_CONFIRM_FLOOR`] so a shrunken denominator cannot
974 /// make a single voter decisive — but never above `full_group_size`, which
975 /// would demand more confirmations than there are peers to give them.
976 #[must_use]
977 pub fn paid_confirm_needed(effective_group_size: usize, full_group_size: usize) -> usize {
978 Self::confirm_needed(effective_group_size)
979 .max(PAID_LIST_ABSOLUTE_CONFIRM_FLOOR.min(full_group_size))
980 }
981
982 /// Number of furthest peers treated as churny edge voters for a paid close
983 /// group of `paid_group_size`, when the group is at full configured width.
984 ///
985 /// Scaled to the group so the discount stays proportionate at every
986 /// configured width, and capped at [`PAID_LIST_FLEX_EDGE_COUNT`]. Returns
987 /// `0` for an undersized group, which keeps its ordinary strict majority.
988 #[must_use]
989 pub fn paid_list_flex_edge_count(
990 paid_group_size: usize,
991 configured_group_size: usize,
992 ) -> usize {
993 if paid_group_size < configured_group_size {
994 return 0;
995 }
996 PAID_LIST_FLEX_EDGE_COUNT.min(configured_group_size / PAID_LIST_FLEX_EDGE_DIVISOR)
997 }
998
999 /// Returns a random duration in `[neighbor_sync_interval_min,
1000 /// neighbor_sync_interval_max]`.
1001 #[must_use]
1002 pub fn random_neighbor_sync_interval(&self) -> Duration {
1003 random_duration_in_range(
1004 self.neighbor_sync_interval_min,
1005 self.neighbor_sync_interval_max,
1006 )
1007 }
1008
1009 /// Maximum age of an outstanding bootstrap capacity-rejection record.
1010 ///
1011 /// A source is revisited only after the round-robin loop has advanced
1012 /// through every neighbor batch. Size the window from that full configured
1013 /// cycle (including one request deadline per peer), the peer cooldown, and
1014 /// one slow-cadence interval of slack. This prevents a live source near the
1015 /// end of a 20-peer cycle from being expired before it can legitimately
1016 /// re-deliver its rejected hints.
1017 #[must_use]
1018 pub fn capacity_rejected_max_age(&self) -> Duration {
1019 let batch_size = self.neighbor_sync_peer_count.max(1);
1020 let batch_count = self.neighbor_sync_scope.saturating_add(batch_size - 1) / batch_size;
1021 let batch_count = u32::try_from(batch_count).unwrap_or(u32::MAX);
1022 let peer_count = u32::try_from(self.neighbor_sync_scope).unwrap_or(u32::MAX);
1023 let full_cycle = self
1024 .neighbor_sync_interval_max
1025 .saturating_mul(batch_count)
1026 .saturating_add(self.verification_request_timeout.saturating_mul(peer_count));
1027
1028 full_cycle
1029 .max(self.neighbor_sync_cooldown)
1030 .saturating_add(self.neighbor_sync_interval_max)
1031 }
1032
1033 /// Compute the number of keys to sample for an audit round, scaled
1034 /// dynamically by the total number of locally stored keys.
1035 ///
1036 /// Formula: `max(floor(sqrt(total_keys)), 1)`, capped at `total_keys`.
1037 #[must_use]
1038 pub fn audit_sample_count(total_keys: usize) -> usize {
1039 #[allow(
1040 clippy::cast_possible_truncation,
1041 clippy::cast_sign_loss,
1042 clippy::cast_precision_loss
1043 )]
1044 let sqrt = (total_keys as f64).sqrt() as usize;
1045 sqrt.max(1).min(total_keys)
1046 }
1047
1048 /// Maximum number of keys this node should send in one responsible-chunk
1049 /// [`AuditChallenge`].
1050 ///
1051 /// This is the sender-side limit used by the normal responsible audit path:
1052 /// one challenge samples at most `sqrt(local_stored_keys)` keys. Other paths
1053 /// that reuse the same `AuditChallenge` wire message, such as
1054 /// prune-confirmation audits, should chunk to this same limit instead of
1055 /// inventing a larger batch size.
1056 ///
1057 /// [`AuditChallenge`]: crate::replication::protocol::AuditChallenge
1058 #[must_use]
1059 pub fn responsible_audit_key_limit(local_stored_keys: usize) -> usize {
1060 Self::audit_sample_count(local_stored_keys)
1061 }
1062
1063 /// Maximum number of keys to accept in an incoming audit challenge.
1064 ///
1065 /// Scales dynamically from the same responsible-audit sender limit, with a
1066 /// 2x margin to account for the challenger having a larger local store than
1067 /// us and therefore sampling more keys.
1068 #[must_use]
1069 pub fn max_incoming_audit_keys(stored_chunks: usize) -> usize {
1070 // Allow at least 1 key so a newly-joined node can still be audited.
1071 (2 * Self::responsible_audit_key_limit(stored_chunks)).max(1)
1072 }
1073
1074 /// Compute the audit response timeout for a challenge with
1075 /// `challenged_key_count` keys, **sized to be tight enough that a
1076 /// relay attacker that must fetch the chunk bytes from elsewhere
1077 /// falls outside the budget**.
1078 ///
1079 /// Formula:
1080 /// `floor + (challenged_bytes / honest_read_bps) × multiplier`
1081 ///
1082 /// Where `challenged_bytes = k × MAX_CHUNK_SIZE`. An honest peer
1083 /// reads `k × 4 MiB` from local disk at `honest_read_bps` (set
1084 /// conservatively at 50 MB/s — well below modern SSDs); the
1085 /// multiplier of 5 absorbs jitter, BLAKE3, ML-DSA, and slow disks.
1086 ///
1087 /// A relay attacker on a residential link (~5-12 MB/s) who must
1088 /// fetch the same `k × 4 MiB` over the network sees ~10-100× higher
1089 /// latency than disk for the data alone, plus per-chunk round-trips,
1090 /// and misses the budget. In the periodic responsible-chunk
1091 /// `AuditChallenge`, prune-confirmation, and ADR-0003 possession-check paths
1092 /// that timeout is an immediate audit failure. The heavier subtree audit
1093 /// still graces timeouts separately.
1094 ///
1095 /// This is an economic deterrent for the §7 relay limit calibrated
1096 /// for residential bandwidth, NOT a hard bound: a relay on a
1097 /// datacenter cross-connect (≥1 Gbps) can fetch `k × 4 MiB` fast
1098 /// enough to answer in time. It raises the relay's cost (bandwidth
1099 /// per audit) without claiming to make relaying impossible. The
1100 /// cryptographic guarantee remains commitment-binding (the relay
1101 /// must still hold or fetch the exact committed bytes); the timeout
1102 /// only attacks the economics.
1103 #[must_use]
1104 pub fn audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
1105 let bytes_per_key = u64::try_from(crate::ant_protocol::MAX_CHUNK_SIZE).unwrap_or(u64::MAX);
1106 let keys = u64::try_from(challenged_key_count).unwrap_or(u64::MAX);
1107 let total_bytes = bytes_per_key.saturating_mul(keys);
1108 let bps = self.audit_honest_read_bps.max(1);
1109 // Apply the multiplier BEFORE integer-dividing by bps so each
1110 // chunk contributes a fractional second rather than rounding
1111 // down to zero. Otherwise k in 1..=12 would all collapse to the
1112 // floor (~40 MiB / 50 MB/s = 0 secs in integer arithmetic), and
1113 // an honest HDD-backed peer at sqrt(N)=10 stored chunks could
1114 // miss the budget under load.
1115 let multiplied = total_bytes.saturating_mul(self.audit_response_honest_multiplier);
1116 // Resolve the scaled term in MILLISECONDS, not seconds: at small
1117 // sample sizes (e.g. a 2-key challenge → 8 MiB) the per-second quotient
1118 // `multiplied / bps` integer-truncates to 0, leaving only the floor.
1119 // Small challenges still need the sub-second honest-read estimate
1120 // (e.g. 8 MiB × 5 / 50 MB/s ≈ 840 ms) instead of dropping it.
1121 let scaled_ms = multiplied.saturating_mul(1000) / bps;
1122 // saturating_add avoids a panic if the floor plus the scaled term would
1123 // overflow `Duration::MAX`.
1124 self.audit_response_floor
1125 .saturating_add(Duration::from_millis(scaled_ms))
1126 }
1127
1128 /// Deadline for the round-2 SLICE challenge opening `openings` blocks.
1129 ///
1130 /// The reply itself is only a few KB per opening (a 1 KiB block plus two
1131 /// short hash chains), but an honest responder still reads each opened
1132 /// chunk's full bytes from disk to build its Bao slice and nonced opening. So
1133 /// the deadline is sized to that honest full-chunk disk read (the same
1134 /// per-byte scaling as [`Self::audit_response_timeout`], one full chunk per
1135 /// opening), on the `BYTE_AUDIT_RESPONSE_FLOOR_SECS` floor to absorb the
1136 /// handshake and a busy disk.
1137 ///
1138 /// The deadline is not a security parameter, and this is worth stating
1139 /// precisely because an earlier version of this comment claimed more than
1140 /// it should. The round-1 `nonced_root` is uncomputable without all the
1141 /// bytes under a fresh nonce, but that binds only that SOMEONE holding them
1142 /// computed it, not that the audited peer did: nonce, peer id and key are
1143 /// all public, so a backend holding one copy can compute roots and openings
1144 /// for any number of front-end identities, and only the compact proof
1145 /// crosses the link. The old full-byte round 2 did not prevent that either
1146 /// — it priced it, by forcing megabytes through the relay per audit, and a
1147 /// tight deadline was part of that price. Both are gone here. So the
1148 /// deadline exists only to bound how long the auditor waits for an honest
1149 /// reply, and non-delegability is not a property either design provides;
1150 /// see ADR-0009 for where that is left.
1151 #[must_use]
1152 pub fn slice_audit_response_timeout(&self, openings: usize) -> Duration {
1153 let scaled = self
1154 .audit_response_timeout(openings)
1155 .saturating_sub(self.audit_response_floor);
1156 Duration::from_secs(BYTE_AUDIT_RESPONSE_FLOOR_SECS).saturating_add(scaled)
1157 }
1158
1159 /// Number of subtree leaves to spot-check against real chunk bytes per
1160 /// audit (ADR-0002 real-bytes layer). Faking a fraction `x` of nonced
1161 /// leaves survives only `(1 - x)^k`.
1162 #[must_use]
1163 pub fn audit_spotcheck_count(&self) -> u32 {
1164 AUDIT_SPOTCHECK_COUNT
1165 }
1166
1167 /// Conservative leaf-count hint for sizing the subtree-audit response
1168 /// deadline before the proof arrives.
1169 ///
1170 /// The selected subtree holds about `sqrt(key_count)` real leaves; sizing
1171 /// for a large store keeps an honest peer with a big store from timing out.
1172 #[must_use]
1173 pub fn subtree_audit_timeout_leaf_hint(&self) -> usize {
1174 SUBTREE_AUDIT_TIMEOUT_LEAF_HINT
1175 }
1176
1177 /// Returns a random duration in `[audit_tick_interval_min,
1178 /// audit_tick_interval_max]`.
1179 #[must_use]
1180 pub fn random_audit_tick_interval(&self) -> Duration {
1181 random_duration_in_range(self.audit_tick_interval_min, self.audit_tick_interval_max)
1182 }
1183
1184 /// Returns a random duration in `[self_lookup_interval_min,
1185 /// self_lookup_interval_max]`.
1186 #[must_use]
1187 pub fn random_self_lookup_interval(&self) -> Duration {
1188 random_duration_in_range(self.self_lookup_interval_min, self.self_lookup_interval_max)
1189 }
1190}
1191
1192/// Pick a random `Duration` uniformly in `[min, max]` at millisecond
1193/// granularity.
1194///
1195/// When `min == max` the result is deterministic.
1196fn random_duration_in_range(min: Duration, max: Duration) -> Duration {
1197 if min == max {
1198 return min;
1199 }
1200 // Our intervals are minutes/hours, well within u64 range. Saturate to
1201 // u64::MAX on the impossible overflow path to avoid a lossy cast.
1202 let to_u64_millis = |d: Duration| -> u64 { u64::try_from(d.as_millis()).unwrap_or(u64::MAX) };
1203 let chosen = rand::thread_rng().gen_range(to_u64_millis(min)..=to_u64_millis(max));
1204 Duration::from_millis(chosen)
1205}
1206
1207// ---------------------------------------------------------------------------
1208// Tests
1209// ---------------------------------------------------------------------------
1210
1211#[cfg(test)]
1212#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1213mod tests {
1214 use super::*;
1215
1216 #[test]
1217 fn defaults_pass_validation() {
1218 let config = ReplicationConfig::default();
1219 assert!(config.validate().is_ok(), "default config must be valid");
1220 }
1221
1222 #[test]
1223 fn default_prune_hysteresis_is_three_days() {
1224 let config = ReplicationConfig::default();
1225 assert_eq!(
1226 config.prune_hysteresis_duration,
1227 Duration::from_secs(3 * 24 * 60 * 60)
1228 );
1229 }
1230
1231 #[test]
1232 fn storage_admission_width_adds_margin() {
1233 const TEST_CLOSE_GROUP_SIZE: usize = 7;
1234
1235 assert_eq!(
1236 storage_admission_width(TEST_CLOSE_GROUP_SIZE),
1237 TEST_CLOSE_GROUP_SIZE + STORAGE_ADMISSION_MARGIN
1238 );
1239 assert_eq!(storage_admission_width(usize::MAX), usize::MAX);
1240 }
1241
1242 #[test]
1243 fn audit_failure_weight_is_five() {
1244 assert!((AUDIT_FAILURE_TRUST_WEIGHT - 5.0).abs() <= f64::EPSILON);
1245 }
1246
1247 #[test]
1248 fn core_replication_id_stays_v2_and_subtree_rides_its_own_id() {
1249 // Core replication, including all digest audit lanes, stays on v2.
1250 // Only the subtree family changed and therefore receives a separate id.
1251 assert_eq!(REPLICATION_PROTOCOL_ID, "autonomi.ant.replication.v2");
1252 assert_eq!(
1253 SUBTREE_AUDIT_PROTOCOL_ID,
1254 "autonomi.ant.replication.subtree-audit.v1"
1255 );
1256 assert_ne!(REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID);
1257 }
1258
1259 #[test]
1260 fn audit_response_timeout_floor_at_zero_keys() {
1261 let config = ReplicationConfig::default();
1262 assert_eq!(
1263 config.audit_response_timeout(0),
1264 Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
1265 "zero-key challenge should yield the floor exactly"
1266 );
1267 }
1268
1269 #[test]
1270 fn audit_response_timeout_scales_with_key_count() {
1271 let config = ReplicationConfig::default();
1272 let t1 = config.audit_response_timeout(1);
1273 let t10 = config.audit_response_timeout(10);
1274 let t100 = config.audit_response_timeout(100);
1275 assert!(t1 <= t10 && t10 < t100, "timeout must not decrease with k");
1276
1277 // Scaling now resolves in MILLISECONDS so a sub-second honest read no
1278 // longer truncates to zero (§4). For k=1:
1279 // (4_194_304 × 5 × 1000) / 52_428_800 = 400 ms, + 4 s round-1 floor =
1280 // 4.4 s.
1281 assert_eq!(t1, Duration::from_millis(4400));
1282
1283 // For k=10: (10 × 4_194_304 × 5 × 1000) / 52_428_800 = 4000 ms scaled,
1284 // + 4 s floor = 8 s. An HDD-backed honest peer at 20 MB/s reads 40 MiB
1285 // in ~2 s, comfortably inside; a relay fetching 40 MiB at 5 MB/s
1286 // residential bandwidth needs ~8 s for the data alone, outside.
1287 assert_eq!(t10, Duration::from_secs(8));
1288
1289 // For k=100: (100 × 4_194_304 × 5 × 1000) / 52_428_800 = 40_000 ms
1290 // scaled, + 4 s floor = 44 s.
1291 assert_eq!(t100, Duration::from_secs(44));
1292 }
1293
1294 #[test]
1295 fn audit_response_timeout_fits_honest_hdd_at_typical_sample_size() {
1296 // The canonical audit sample is sqrt(N) at N stored chunks.
1297 // At N=100 stored chunks, sample is 10. An HDD-backed honest
1298 // peer at the slowest realistic random-read throughput (20 MB/s,
1299 // well below modern HDDs which sustain 80-150 MB/s sequential)
1300 // reads 10 × 4 MiB = 40 MiB in ~2 s. Add 300 ms cross-continent
1301 // RTT, ~10 ms scheduling, ~3 ms ML-DSA sign, and the honest
1302 // envelope is ~2.3 s. The 8 s budget at k=10 leaves >5 s of
1303 // slack.
1304 let config = ReplicationConfig::default();
1305 let budget = config.audit_response_timeout(10);
1306 let realistic_hdd_bps: u64 = 20 * 1024 * 1024;
1307 let bytes: u64 = 10 * 4 * 1024 * 1024;
1308 let honest_envelope_secs = bytes / realistic_hdd_bps + 1; // +1 s for network/scheduling/sign
1309 assert!(
1310 Duration::from_secs(honest_envelope_secs) < budget,
1311 "honest HDD envelope ({honest_envelope_secs}s) must fit inside k=10 budget ({}s)",
1312 budget.as_secs(),
1313 );
1314 }
1315
1316 #[test]
1317 fn audit_response_timeout_relay_is_outside_envelope() {
1318 // The intended invariant: an honest peer with the SSD-class
1319 // read budget fits inside `audit_response_timeout(k)`, while a
1320 // relay attacker fetching k*4MiB over residential bandwidth
1321 // (≈ 5 MB/s realistic for sustained download) does NOT. Spot-
1322 // check this at k=100: honest budget is 44s, relay needs at
1323 // least 100 * 4 MiB / 5 MB/s = 80s for the data alone, which
1324 // exceeds the budget.
1325 let config = ReplicationConfig::default();
1326 let budget = config.audit_response_timeout(100);
1327 let relay_data_only = Duration::from_secs(100 * 4 * 1024 * 1024 / (5 * 1024 * 1024));
1328 assert!(
1329 relay_data_only > budget,
1330 "relay fetch ({}s) must exceed honest audit budget ({}s)",
1331 relay_data_only.as_secs(),
1332 budget.as_secs(),
1333 );
1334 }
1335
1336 #[test]
1337 fn audit_response_timeout_saturates_on_huge_k() {
1338 let config = ReplicationConfig::default();
1339 // Should not panic or overflow at extreme k values.
1340 let _ = config.audit_response_timeout(usize::MAX);
1341 }
1342
1343 #[test]
1344 fn quorum_threshold_zero_rejected() {
1345 let config = ReplicationConfig {
1346 quorum_threshold: 0,
1347 ..ReplicationConfig::default()
1348 };
1349 assert!(config.validate().is_err());
1350 }
1351
1352 #[test]
1353 fn quorum_threshold_exceeds_close_group_rejected() {
1354 let defaults = ReplicationConfig::default();
1355 let config = ReplicationConfig {
1356 quorum_threshold: defaults.close_group_size + 1,
1357 ..defaults
1358 };
1359 assert!(config.validate().is_err());
1360 }
1361
1362 #[test]
1363 fn close_group_size_zero_rejected() {
1364 let config = ReplicationConfig {
1365 close_group_size: 0,
1366 ..ReplicationConfig::default()
1367 };
1368 assert!(config.validate().is_err());
1369 }
1370
1371 #[test]
1372 fn close_group_size_exceeding_prune_audit_request_budget_rejected() {
1373 let config = ReplicationConfig {
1374 close_group_size: MAX_PRUNE_AUDIT_REQUESTS_PER_PASS + 1,
1375 quorum_threshold: QUORUM_THRESHOLD,
1376 ..ReplicationConfig::default()
1377 };
1378
1379 let err = config.validate().unwrap_err();
1380
1381 assert!(
1382 err.contains("MAX_PRUNE_AUDIT_REQUESTS_PER_PASS"),
1383 "error should mention prune audit budget: {err}"
1384 );
1385 }
1386
1387 #[test]
1388 fn paid_list_close_group_size_zero_rejected() {
1389 let config = ReplicationConfig {
1390 paid_list_close_group_size: 0,
1391 ..ReplicationConfig::default()
1392 };
1393 assert!(config.validate().is_err());
1394 }
1395
1396 #[test]
1397 fn neighbor_sync_interval_inverted_rejected() {
1398 let config = ReplicationConfig {
1399 neighbor_sync_interval_min: Duration::from_secs(100),
1400 neighbor_sync_interval_max: Duration::from_secs(50),
1401 ..ReplicationConfig::default()
1402 };
1403 assert!(config.validate().is_err());
1404 }
1405
1406 #[test]
1407 fn capacity_rejection_expiry_covers_full_configured_sync_cycle() {
1408 let config = ReplicationConfig {
1409 // Keep the scope deliberately indivisible by the batch size so the
1410 // expectation verifies that the final partial batch is included.
1411 neighbor_sync_scope: 21,
1412 neighbor_sync_peer_count: 4,
1413 ..ReplicationConfig::default()
1414 };
1415 let batches = config
1416 .neighbor_sync_scope
1417 .div_ceil(config.neighbor_sync_peer_count);
1418 let cycle_cadence = config.neighbor_sync_interval_max * u32::try_from(batches).unwrap();
1419 let request_budget = config.verification_request_timeout
1420 * u32::try_from(config.neighbor_sync_scope).unwrap();
1421 let full_cycle = cycle_cadence + request_budget;
1422
1423 assert_eq!(
1424 config.capacity_rejected_max_age(),
1425 full_cycle + config.neighbor_sync_interval_max,
1426 );
1427 assert!(config.capacity_rejected_max_age() > Duration::from_secs(70 * 60));
1428 }
1429
1430 #[test]
1431 fn capacity_rejection_expiry_tracks_runtime_sync_configuration() {
1432 let config = ReplicationConfig {
1433 neighbor_sync_scope: 9,
1434 neighbor_sync_peer_count: 2,
1435 neighbor_sync_interval_max: Duration::from_secs(10),
1436 neighbor_sync_cooldown: Duration::from_secs(100),
1437 verification_request_timeout: Duration::from_secs(1),
1438 ..ReplicationConfig::default()
1439 };
1440
1441 // Five batches take 50s and their nine request budgets take 9s, so
1442 // the 100s cooldown dominates; one 10s cadence interval is slack.
1443 assert_eq!(config.capacity_rejected_max_age(), Duration::from_secs(110));
1444 }
1445
1446 #[test]
1447 fn audit_tick_interval_inverted_rejected() {
1448 let config = ReplicationConfig {
1449 audit_tick_interval_min: Duration::from_secs(100),
1450 audit_tick_interval_max: Duration::from_secs(50),
1451 ..ReplicationConfig::default()
1452 };
1453 assert!(config.validate().is_err());
1454 }
1455
1456 #[test]
1457 fn self_lookup_interval_inverted_rejected() {
1458 let config = ReplicationConfig {
1459 self_lookup_interval_min: Duration::from_secs(100),
1460 self_lookup_interval_max: Duration::from_secs(50),
1461 ..ReplicationConfig::default()
1462 };
1463 assert!(config.validate().is_err());
1464 }
1465
1466 #[test]
1467 fn neighbor_sync_peer_count_zero_rejected() {
1468 let config = ReplicationConfig {
1469 neighbor_sync_peer_count: 0,
1470 ..ReplicationConfig::default()
1471 };
1472 assert!(config.validate().is_err());
1473 }
1474
1475 #[test]
1476 fn neighbor_sync_scope_exceeding_k_bucket_size_rejected() {
1477 let config = ReplicationConfig {
1478 neighbor_sync_scope: K_BUCKET_SIZE + 1,
1479 ..ReplicationConfig::default()
1480 };
1481 assert!(config.validate().is_err());
1482 }
1483
1484 #[test]
1485 fn audit_sample_count_scales_with_sqrt() {
1486 // Empty store
1487 assert_eq!(ReplicationConfig::audit_sample_count(0), 0);
1488
1489 // Single key
1490 assert_eq!(ReplicationConfig::audit_sample_count(1), 1);
1491
1492 // Small stores: sqrt(3)=1
1493 assert_eq!(ReplicationConfig::audit_sample_count(3), 1);
1494
1495 // sqrt scaling
1496 assert_eq!(ReplicationConfig::audit_sample_count(4), 2);
1497 assert_eq!(ReplicationConfig::audit_sample_count(25), 5);
1498 assert_eq!(ReplicationConfig::audit_sample_count(100), 10);
1499 assert_eq!(ReplicationConfig::audit_sample_count(1_000), 31);
1500 assert_eq!(ReplicationConfig::audit_sample_count(7_000), 83);
1501 assert_eq!(ReplicationConfig::audit_sample_count(10_000), 100);
1502 assert_eq!(ReplicationConfig::audit_sample_count(1_000_000), 1_000);
1503 }
1504
1505 #[test]
1506 fn responsible_audit_key_limit_matches_audit_sample_count() {
1507 for stored_keys in [0, 1, 3, 4, 25, 100, 1_000, 7_000, 10_000, 1_000_000] {
1508 assert_eq!(
1509 ReplicationConfig::responsible_audit_key_limit(stored_keys),
1510 ReplicationConfig::audit_sample_count(stored_keys),
1511 "responsible audit sender limit must stay identical to audit sample count"
1512 );
1513 }
1514 }
1515
1516 #[test]
1517 fn max_incoming_audit_keys_scales_dynamically() {
1518 // Empty store: at least 1 key accepted.
1519 assert_eq!(ReplicationConfig::max_incoming_audit_keys(0), 1);
1520
1521 // 1 chunk: 2 * responsible_audit_key_limit(1) = 2.
1522 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1), 2);
1523
1524 // 100 chunks: 2 * responsible_audit_key_limit(100) = 20.
1525 assert_eq!(ReplicationConfig::max_incoming_audit_keys(100), 20);
1526
1527 // 1M chunks: 2 * responsible_audit_key_limit(1_000_000) = 2_000.
1528 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1_000_000), 2_000);
1529
1530 // 5M chunks: 2 * responsible_audit_key_limit(5_000_000) = 4_472.
1531 assert_eq!(ReplicationConfig::max_incoming_audit_keys(5_000_000), 4_472);
1532 }
1533
1534 #[test]
1535 fn quorum_needed_uses_smaller_of_threshold_and_majority() {
1536 let config = ReplicationConfig::default();
1537
1538 // With 7 targets: majority = 7/2+1 = 4, threshold = 4 → min = 4
1539 assert_eq!(config.quorum_needed(7), 4);
1540
1541 // With 3 targets: majority = 3/2+1 = 2, threshold = 4 → min = 2
1542 assert_eq!(config.quorum_needed(3), 2);
1543
1544 // With 0 targets: quorum is impossible — returns 0
1545 assert_eq!(config.quorum_needed(0), 0);
1546
1547 // With 100 targets: majority = 51, threshold = 4 → min = 4
1548 assert_eq!(config.quorum_needed(100), 4);
1549 }
1550
1551 #[test]
1552 fn confirm_needed_is_strict_majority() {
1553 assert_eq!(ReplicationConfig::confirm_needed(1), 1);
1554 assert_eq!(ReplicationConfig::confirm_needed(2), 2);
1555 assert_eq!(ReplicationConfig::confirm_needed(3), 2);
1556 assert_eq!(ReplicationConfig::confirm_needed(4), 3);
1557 assert_eq!(ReplicationConfig::confirm_needed(20), 11);
1558 }
1559
1560 /// The edge is a proportion of the group, not a fixed four peers.
1561 ///
1562 /// A fixed four is a fifth of the production width but four fifths of a
1563 /// configured width of five, which collapsed the voting core to one peer.
1564 #[test]
1565 fn flex_edge_scales_with_the_configured_group() {
1566 // Production width is unchanged: 20 / 5 == PAID_LIST_FLEX_EDGE_COUNT.
1567 assert_eq!(
1568 ReplicationConfig::paid_list_flex_edge_count(
1569 PAID_LIST_CLOSE_GROUP_SIZE,
1570 PAID_LIST_CLOSE_GROUP_SIZE
1571 ),
1572 PAID_LIST_FLEX_EDGE_COUNT,
1573 );
1574
1575 // Small widths keep a majority-sized core rather than a single peer.
1576 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(5, 5), 1);
1577 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(10, 10), 2);
1578 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(15, 15), 3);
1579
1580 // Never more than the ceiling, however wide the group is configured.
1581 assert_eq!(
1582 ReplicationConfig::paid_list_flex_edge_count(100, 100),
1583 PAID_LIST_FLEX_EDGE_COUNT,
1584 );
1585
1586 // An undersized group keeps its ordinary strict majority.
1587 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(19, 20), 0);
1588 }
1589
1590 /// A shrunken denominator must never make one voter decisive.
1591 #[test]
1592 fn paid_confirm_needed_applies_an_absolute_floor() {
1593 // The floor binds where the discounted majority would be trivial.
1594 assert_eq!(
1595 ReplicationConfig::paid_confirm_needed(1, 5),
1596 PAID_LIST_ABSOLUTE_CONFIRM_FLOOR
1597 );
1598 assert_eq!(
1599 ReplicationConfig::paid_confirm_needed(2, 5),
1600 PAID_LIST_ABSOLUTE_CONFIRM_FLOOR
1601 );
1602
1603 // Above the floor the strict majority governs, unchanged.
1604 assert_eq!(ReplicationConfig::paid_confirm_needed(16, 20), 9);
1605 assert_eq!(ReplicationConfig::paid_confirm_needed(20, 20), 11);
1606
1607 // The floor never demands more confirmations than there are peers.
1608 assert_eq!(ReplicationConfig::paid_confirm_needed(1, 1), 1);
1609 assert_eq!(ReplicationConfig::paid_confirm_needed(2, 2), 2);
1610 }
1611
1612 /// The reviewed collapse: at a configured width of five, four fixed edge
1613 /// voters left a core of one, so a single `Confirmed` authorized the key.
1614 #[test]
1615 fn small_configured_group_cannot_authorize_on_one_vote() {
1616 const SMALL_GROUP: usize = 5;
1617
1618 let edge = ReplicationConfig::paid_list_flex_edge_count(SMALL_GROUP, SMALL_GROUP);
1619 let core = SMALL_GROUP - edge;
1620 assert!(
1621 core > 1,
1622 "the voting core must not collapse to a single peer"
1623 );
1624 assert!(
1625 ReplicationConfig::paid_confirm_needed(core, SMALL_GROUP) > 1,
1626 "a lone confirmation must not authorize a key"
1627 );
1628 }
1629
1630 #[test]
1631 fn random_intervals_within_bounds() {
1632 let config = ReplicationConfig::default();
1633
1634 // Run several iterations to exercise randomness.
1635 let iterations = 50;
1636 for _ in 0..iterations {
1637 let ns = config.random_neighbor_sync_interval();
1638 assert!(ns >= config.neighbor_sync_interval_min);
1639 assert!(ns <= config.neighbor_sync_interval_max);
1640
1641 let at = config.random_audit_tick_interval();
1642 assert!(at >= config.audit_tick_interval_min);
1643 assert!(at <= config.audit_tick_interval_max);
1644
1645 let sl = config.random_self_lookup_interval();
1646 assert!(sl >= config.self_lookup_interval_min);
1647 assert!(sl <= config.self_lookup_interval_max);
1648 }
1649 }
1650
1651 #[test]
1652 fn random_interval_equal_bounds_is_deterministic() {
1653 let fixed = Duration::from_secs(42);
1654 let config = ReplicationConfig {
1655 neighbor_sync_interval_min: fixed,
1656 neighbor_sync_interval_max: fixed,
1657 ..ReplicationConfig::default()
1658 };
1659 assert_eq!(config.random_neighbor_sync_interval(), fixed);
1660 }
1661
1662 // -----------------------------------------------------------------------
1663 // Section 18 scenarios
1664 // -----------------------------------------------------------------------
1665
1666 /// Scenario 18: Invalid runtime config is rejected by `validate()`.
1667 #[test]
1668 fn scenario_18_invalid_config_rejected() {
1669 // quorum_threshold > close_group_size -> validation fails.
1670 let config = ReplicationConfig {
1671 quorum_threshold: 10,
1672 close_group_size: 7,
1673 ..ReplicationConfig::default()
1674 };
1675 let err = config.validate().unwrap_err();
1676 assert!(
1677 err.contains("quorum_threshold"),
1678 "error should mention quorum_threshold: {err}"
1679 );
1680
1681 // close_group_size = 0 -> validation fails.
1682 let config = ReplicationConfig {
1683 close_group_size: 0,
1684 ..ReplicationConfig::default()
1685 };
1686 let err = config.validate().unwrap_err();
1687 assert!(
1688 err.contains("close_group_size"),
1689 "error should mention close_group_size: {err}"
1690 );
1691
1692 // neighbor_sync interval min > max -> validation fails.
1693 let config = ReplicationConfig {
1694 neighbor_sync_interval_min: Duration::from_secs(200),
1695 neighbor_sync_interval_max: Duration::from_secs(100),
1696 ..ReplicationConfig::default()
1697 };
1698 let err = config.validate().unwrap_err();
1699 assert!(
1700 err.contains("neighbor_sync_interval"),
1701 "error should mention neighbor_sync_interval: {err}"
1702 );
1703
1704 // self_lookup interval min > max -> validation fails.
1705 let config = ReplicationConfig {
1706 self_lookup_interval_min: Duration::from_secs(999),
1707 self_lookup_interval_max: Duration::from_secs(1),
1708 ..ReplicationConfig::default()
1709 };
1710 let err = config.validate().unwrap_err();
1711 assert!(
1712 err.contains("self_lookup_interval"),
1713 "error should mention self_lookup_interval: {err}"
1714 );
1715
1716 // audit_tick interval min > max -> validation fails.
1717 let config = ReplicationConfig {
1718 audit_tick_interval_min: Duration::from_secs(500),
1719 audit_tick_interval_max: Duration::from_secs(10),
1720 ..ReplicationConfig::default()
1721 };
1722 let err = config.validate().unwrap_err();
1723 assert!(
1724 err.contains("audit_tick_interval"),
1725 "error should mention audit_tick_interval: {err}"
1726 );
1727 }
1728
1729 /// Scenario 26: Dynamic paid-list threshold for undersized set.
1730 /// With PaidGroupSize=8, `ConfirmNeeded` = floor(8/2)+1 = 5.
1731 #[test]
1732 fn scenario_26_dynamic_paid_threshold_undersized() {
1733 assert_eq!(ReplicationConfig::confirm_needed(8), 5, "floor(8/2)+1 = 5");
1734
1735 // Additional boundary checks for small paid groups.
1736 assert_eq!(
1737 ReplicationConfig::confirm_needed(1),
1738 1,
1739 "single peer requires 1 confirmation"
1740 );
1741 assert_eq!(
1742 ReplicationConfig::confirm_needed(2),
1743 2,
1744 "2 peers require 2 confirmations"
1745 );
1746 assert_eq!(
1747 ReplicationConfig::confirm_needed(3),
1748 2,
1749 "3 peers require 2 confirmations"
1750 );
1751 assert_eq!(
1752 ReplicationConfig::confirm_needed(0),
1753 1,
1754 "0 peers yields floor(0/2)+1 = 1 (degenerate case)"
1755 );
1756 }
1757
1758 /// Scenario 31: Consecutive audit ticks occur on randomized intervals
1759 /// bounded by the configured `[audit_tick_interval_min, audit_tick_interval_max]`
1760 /// window.
1761 #[test]
1762 fn scenario_31_audit_cadence_within_jitter_bounds() {
1763 let config = ReplicationConfig {
1764 audit_tick_interval_min: Duration::from_secs(600),
1765 audit_tick_interval_max: Duration::from_secs(1200),
1766 ..ReplicationConfig::default()
1767 };
1768
1769 // Sample many intervals and verify each is within bounds.
1770 let iterations = 100;
1771 let mut saw_different = false;
1772 let mut prev = Duration::ZERO;
1773
1774 for _ in 0..iterations {
1775 let interval = config.random_audit_tick_interval();
1776 assert!(
1777 interval >= config.audit_tick_interval_min,
1778 "interval {interval:?} below min {:?}",
1779 config.audit_tick_interval_min,
1780 );
1781 assert!(
1782 interval <= config.audit_tick_interval_max,
1783 "interval {interval:?} above max {:?}",
1784 config.audit_tick_interval_max,
1785 );
1786 if interval != prev && prev != Duration::ZERO {
1787 saw_different = true;
1788 }
1789 prev = interval;
1790 }
1791
1792 // With 100 samples from a 10-minute range, at least two should differ
1793 // (probabilistically near-certain).
1794 assert!(
1795 saw_different,
1796 "audit intervals should exhibit randomized jitter across samples"
1797 );
1798 }
1799}