Skip to main content

ant_node/replication/
pointer.rs

1//! Pointer replication (ADR-0016).
2//!
3//! Pointers ride the same replication machinery chunks do — the same close
4//! groups, the same neighbour-sync rounds and churn triggers, the same quorum,
5//! pruning and possession rules — but not the chunk pipeline itself. That
6//! pipeline assumes a record never changes and that its key is the hash of its
7//! bytes. A pointer's address is stable while its state changes, and two honest
8//! replicas may hold different valid signatures over one state. So a pointer is
9//! replicated by *state*:
10//!
11//! - **Fresh.** A node that accepts a paid state from a client forwards the
12//!   record, with the proof that paid for it, to the rest of the close group.
13//!   Each receiver checks the signature, its own responsibility and the payment
14//!   itself before storing it.
15//! - **Repair.** Every neighbour-sync round pushes hints: the states the sender
16//!   holds that the receiver should hold. A receiver that lacks a hinted state,
17//!   or holds an older one, asks the close group which state each holds, adopts
18//!   the best state a quorum of them hold exactly, and fetches it from one of
19//!   them. The record verifies itself; the quorum stands in for the payment
20//!   proof, as presence quorum does for a chunk.
21//! - **Pruning.** A record this node has been out of range of for the
22//!   hysteresis period is eligible to be erased, never due (ADR-0028): while
23//!   the disk has room it is kept and nobody is asked. Under disk pressure it
24//!   is erased only once all but one of the current close group prove they
25//!   hold that state or a newer one by returning a valid record, however far
26//!   outside the group the node has moved. Each pass tries candidates farthest
27//!   from this node first, then those whose proof failed, oldest failure
28//!   first, and asks each one's group at once, so candidates nobody can prove
29//!   yet never keep the rest from a turn. A record whose group has too few
30//!   capable members to prove it is kept until it has enough.
31//! - **Possession.** Some minutes after offering a fresh state, the node asks
32//!   each close-group member for the record. A member that is still responsible
33//!   and cannot produce that state or a newer one is penalised — unless it holds
34//!   a *different final* state, which is a fork its owner made and not a failure
35//!   to store.
36//! - **Finality.** Before taking a final state it does not hold, from a client
37//!   or a fresh offer, a node asks the close group whether a different final
38//!   state is already held, and refuses if a peer proves one with the signed
39//!   record (ADR-0018). See [`PointerReplication::check_final`].
40//!
41//! Requests go only to peers that have sent a pointer message themselves (see
42//! [`PointerReplication::is_capable`]). A peer built before pointers cannot
43//! decode them, and saorsa-core counts an unanswered request against the peer
44//! it was sent to; asking only capable peers keeps older peers out of it. Every
45//! neighbour-sync round pushes hints, empty or not, so capability is learned
46//! within a cycle.
47
48use std::collections::{HashMap, HashSet, VecDeque};
49use std::future::Future;
50use std::sync::Arc;
51use std::time::{Duration, Instant, SystemTime};
52
53use ant_protocol::pointer::{Pointer, PointerState, POINTER_WIRE_LEN};
54use futures::future::{join_all, BoxFuture};
55use futures::stream::{self, StreamExt};
56use parking_lot::Mutex;
57use rand::Rng;
58use saorsa_core::identity::PeerId;
59use saorsa_core::{P2PNode, TrustEvent};
60use tokio::sync::{mpsc, OwnedSemaphorePermit, RwLock, Semaphore};
61use tokio::task::{spawn_blocking, JoinHandle};
62use tokio::time::Instant as TokioInstant;
63use tokio_util::sync::CancellationToken;
64use tokio_util::task::TaskTracker;
65
66use crate::ant_protocol::XorName;
67use crate::logging::{debug, info, warn};
68use crate::payment::{
69    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
70    MIN_PAYMENT_PROOF_SIZE_BYTES,
71};
72use crate::pointer::store::{Inspected, PointerStore, PutOutcome};
73use crate::pointer::{FinalStateWitness, FinalityCheck};
74use crate::replication::admission;
75use crate::replication::commitment_state::ResponderCommitmentState;
76use crate::replication::config::{
77    storage_admission_width, ReplicationConfig, FRESH_REPLICATION_DELIVERY_MAX_RETRIES,
78    REPLICATION_PROTOCOL_ID,
79};
80use crate::replication::out_of_range_clocks::{elapsed, OutOfRangeClocks};
81use crate::replication::protocol::{
82    PointerFetchRequest, PointerFetchResponse, PointerFreshOffer, PointerHints,
83    PointerStateRequest, PointerStateResponse, PointerStateSummary, ReplicationMessage,
84    ReplicationMessageBody, MAX_POINTER_HINTS_PER_MESSAGE, MAX_POINTER_STATE_REQUEST_ADDRESSES,
85};
86use crate::replication::pruning::prune_proofs_needed;
87use crate::replication::retention::{DiskPressure, RecordKind};
88use crate::storage::{CapacityVerdict, ChunkStore};
89
90use super::REPLICATION_TRUST_WEIGHT;
91
92/// Inbound fresh offers verified at once. An offer costs a signature check and
93/// an on-chain payment lookup, so a flood is dropped rather than queued; one
94/// that is dropped is repaired by the next neighbour-sync round.
95const MAX_CONCURRENT_OFFERS: usize = 16;
96
97/// Fetch and state requests served at once.
98const MAX_CONCURRENT_SERVES: usize = 32;
99
100/// Fetch and state requests admitted at once, served or waiting to be. Past
101/// it a request is dropped at admission rather than queued, as a chunk fetch
102/// is, so a flood costs a bounded number of tasks.
103const MAX_SERVES_OUTSTANDING: usize = MAX_CONCURRENT_SERVES * 4;
104
105/// Of those, how many one peer may have: twice the [`MAX_REQUESTS_PER_PEER`]
106/// an honest node lets itself have outstanding at any one peer, so its
107/// requests are never dropped, even those arriving before the reply to the
108/// last has released its place here, while one flooding peer cannot take the
109/// room every other peer's requests need.
110const MAX_SERVES_OUTSTANDING_PER_PEER: u32 = 16;
111
112/// Pointer requests this node has outstanding at any one peer, across repair,
113/// possession checks and pruning together. As many as a repair asks at once,
114/// so repair is not slowed; the rest wait their turn rather than go out and
115/// be dropped by the peer's per-peer allowance, which would make an honest
116/// peer look as though it had not answered.
117const MAX_REQUESTS_PER_PEER: usize = VERIFICATION_CONCURRENCY;
118
119// An honest node's requests to one peer, repair included, never exceed what
120// that peer admits from it, with room for a reply still releasing its place.
121const _: () = assert!(
122    MAX_SERVES_OUTSTANDING_PER_PEER as usize >= 2 * MAX_REQUESTS_PER_PEER,
123    "a peer's serve allowance must cover what an honest node asks of it"
124);
125
126/// Most peers remembered as speaking pointers. Only routed peers are, and a
127/// routing table removal forgets one, so this only bounds what removals missed
128/// (a lagging event stream) could leave behind. Capability forgotten this way
129/// is learned again from the peer's next hint push.
130const MAX_CAPABLE_PEERS: usize = 4096;
131
132/// Most hint pushes answering peers' sync requests at once. Each scans every
133/// pointer this node holds, so a peer's sync request that finds them all
134/// running gets no hints this time, and the next sync round delivers them.
135const MAX_CONCURRENT_SYNC_ANSWERS: usize = 8;
136
137/// Most peers remembered as having been answered with hints. Only routing-table
138/// peers are answered, so this only bounds what a lagging table could leave
139/// behind; past it the peer answered longest ago is forgotten, never a new one
140/// refused.
141const MAX_ANSWERED_SYNC_PEERS: usize = 4096;
142
143/// How often the pending hints are looked at.
144const VERIFICATION_TICK: Duration = Duration::from_millis(500);
145
146/// Most addresses awaiting verification at once, so a hint flood cannot grow
147/// memory without bound. A hint dropped here comes back next round.
148const MAX_PENDING: usize = 65_536;
149
150/// Most addresses verified per tick.
151const MAX_VERIFICATIONS_PER_TICK: usize = 256;
152
153/// Verifications and fetches in flight at once within a tick.
154const VERIFICATION_CONCURRENCY: usize = 8;
155
156/// Undecided rounds an address gets before it is dropped. It comes back with
157/// the next hint.
158const MAX_UNDECIDED_ROUNDS: u32 = 5;
159
160/// Wait before retrying an undecided address, doubled each round.
161const UNDECIDED_BACKOFF: Duration = Duration::from_secs(30);
162
163/// Most prune candidates examined per pass.
164const MAX_PRUNE_CANDIDATES_PER_PASS: usize = 256;
165
166/// File beside the pointer store's directory holding saved out-of-range clocks.
167const OUT_OF_RANGE_CLOCKS_FILE: &str = "pointer_out_of_range.bin";
168
169/// Prune candidates proven at once: half of what this node may have
170/// outstanding at any one peer. Each candidate awaits every request it
171/// sends, so even when the candidates in flight share one group, pruning
172/// never queues behind its own requests, and repair and possession checks
173/// keep the other half of every peer's [`MAX_REQUESTS_PER_PEER`]. With
174/// [`PRUNE_PROOF_BUDGET`] for an answer, a pass takes about five minutes however
175/// many peers stay silent, and about eleven if each request also waits that long
176/// for one of this node's own slots.
177const PRUNE_CONCURRENCY: usize = MAX_REQUESTS_PER_PEER / 2;
178
179const _: () = assert!(
180    PRUNE_CONCURRENCY > 0,
181    "pruning must be able to prove at least one candidate at a time"
182);
183
184/// How long a prune proof request waits for a request slot, and again for
185/// its answer. A record is 5,303 bytes, so this is what a storage audit allows
186/// a peer for one small read over a cold connection (its round-two floor). A
187/// group slower than that keeps the record until a later pass.
188const PRUNE_PROOF_BUDGET: Duration = Duration::from_secs(5);
189
190/// How long a node spends asking its close group for a conflicting final
191/// state before taking one (ADR-0018).
192///
193/// It runs inside a client's PUT, after payment has been verified, so it adds
194/// to whatever that verification took; it is kept short so a PUT whose
195/// payment is quick stays inside the client's ten-second store timeout. A
196/// group that has not answered by then is taken to hold nothing that
197/// conflicts: silence is never a vote, here as anywhere else.
198pub const FINAL_STATE_CHECK_BUDGET: Duration = Duration::from_secs(4);
199
200/// How long a finality check waits for its turn before it gives up and
201/// answers [`FinalityCheck::Busy`].
202///
203/// With [`FINAL_STATE_CHECK_BUDGET`] after it, a check adds at most six
204/// seconds to a PUT after its payment is verified.
205pub const FINAL_STATE_CHECK_WAIT: Duration = Duration::from_secs(2);
206
207/// How many finality checks run at once.
208///
209/// Each runs on its own share of the address space. Two checks for one
210/// address never run together, so a burst of replays of one final state
211/// costs the group one round of questions.
212pub const FINAL_STATE_CHECK_STRIPES: usize = 64;
213
214/// How many addresses a node remembers proven final states for, oldest
215/// forgotten first.
216///
217/// A proof is a final state the close group was shown to hold, so it never
218/// goes stale; the cap only bounds memory, at most two states of about 200
219/// bytes each per address.
220const MAX_PROVEN_FINALS: usize = 16_384;
221
222/// Proven final states remembered per address. Two different ones are enough
223/// to refuse every final state there: each conflicts with the other, and any
224/// third with both.
225const MAX_PROOFS_PER_ADDRESS: usize = 2;
226
227/// How long a look that found no conflict answers again for the same final
228/// state without asking anyone.
229///
230/// As long as a replay queued behind it can have waited for its turn, and no
231/// longer, since a rival could reach the group after it. The answer is also
232/// forgotten as soon as the write it cleared fails.
233pub const FINAL_STATE_CLEAR_REUSE: Duration = FINAL_STATE_CHECK_WAIT;
234
235/// Most clear looks remembered for reuse. Each is at most
236/// [`FINAL_STATE_CLEAR_REUSE`] old, so this only bounds a burst.
237const MAX_CLEAR_LOOKS: usize = 4096;
238
239/// One peer's answer about one address: the state it holds there, if any.
240type StateAnswer = ((PeerId, XorName), Option<PointerState>);
241
242/// Whether `record` is exactly the state a quorum backed.
243///
244/// The whole state, not only its identifier: the backed state is built from
245/// peers' unauthenticated summaries, and a summary can pair a real state's
246/// identifier with some other counter or target.
247fn backs(record: &Pointer, wanted: &PointerState) -> bool {
248    record.state() == *wanted
249}
250
251/// One peer's state response, read against the addresses it was asked about.
252///
253/// An explicit "nothing held" is an answer. A summary about some other
254/// address is no answer at all, and is left out, so that it does not count as
255/// a peer that answered.
256fn read_state_answers(
257    peer: PeerId,
258    addresses: &[XorName],
259    states: Vec<Option<PointerStateSummary>>,
260) -> Vec<StateAnswer> {
261    addresses
262        .iter()
263        .zip(states)
264        .filter_map(|(address, summary)| match summary {
265            None => Some(((peer, *address), None)),
266            Some(summary) if summary.address == *address => {
267                Some(((peer, *address), Some(PointerState::from(summary))))
268            }
269            Some(_) => None,
270        })
271        .collect()
272}
273
274/// A pointer state this node accepted from a paying client, to be offered to
275/// the rest of its close group.
276pub struct PointerFreshWrite {
277    /// The record, in its canonical encoding.
278    pub record: Vec<u8>,
279    /// The proof that paid for its state.
280    pub payment_proof: Vec<u8>,
281}
282
283/// A state this node was told about and has not yet verified.
284#[derive(Debug, Clone)]
285struct Pending {
286    /// The best state hinted so far.
287    wanted: PointerState,
288    /// Undecided rounds so far.
289    attempts: u32,
290    /// Not to be looked at again before this.
291    not_before: Instant,
292}
293
294/// What a verification round decided for one address.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub(crate) enum Verdict {
297    /// A quorum of the close group hold this state and it beats what is held
298    /// here: fetch it from one of `holders`.
299    Adopt {
300        /// The state to fetch.
301        state: PointerState,
302        /// The peers that said they hold exactly it.
303        holders: Vec<PeerId>,
304    },
305    /// Nothing reached quorum, but the peers that did not answer could still
306    /// make one. Ask again later.
307    Undecided,
308    /// No state that beats what is held can reach quorum.
309    Refused,
310}
311
312/// Decide what a round of answers supports.
313///
314/// `group_size` is the whole close group this node would ask, capable or not:
315/// a peer that cannot be asked counts as unanswered, not as a vote. The quorum
316/// is therefore the one a chunk would need, and a network where few peers
317/// understand pointers yet cannot repair on the word of those few.
318pub(crate) fn evaluate(
319    held: Option<&PointerState>,
320    group_size: usize,
321    answers: &[(PeerId, Option<PointerState>)],
322    quorum_needed: usize,
323) -> Verdict {
324    if group_size == 0 || quorum_needed == 0 {
325        return Verdict::Undecided;
326    }
327    // Votes count together only for the same whole state. A summary is a
328    // peer's unauthenticated claim: one naming a real state's identifier with
329    // some other counter must not absorb, or reshape, the honest votes for it.
330    let mut by_state: Vec<(PointerState, Vec<PeerId>)> = Vec::new();
331    for (peer, answer) in answers {
332        let Some(state) = answer else { continue };
333        match by_state.iter_mut().find(|(known, _)| known == state) {
334            Some((_, holders)) => holders.push(*peer),
335            None => by_state.push((*state, vec![*peer])),
336        }
337    }
338    let beats_held = |state: &PointerState| held.is_none_or(|held| state.replaces(held));
339
340    // The merge winner, and between two final states — which the merge rule
341    // leaves unordered — the one more of the group holds. Only a group wider
342    // than twice the quorum can back two at once, and then arrival order must
343    // not be what decides.
344    let prefer = |candidate: &(PointerState, Vec<PeerId>),
345                  current: &(PointerState, Vec<PeerId>)| {
346        candidate.0.replaces(&current.0)
347            || (!current.0.replaces(&candidate.0) && candidate.1.len() > current.1.len())
348    };
349    let best = by_state
350        .iter()
351        .filter(|(state, holders)| holders.len() >= quorum_needed && beats_held(state))
352        .fold(
353            None::<&(PointerState, Vec<PeerId>)>,
354            |best, candidate| match best {
355                Some(current) if !prefer(candidate, current) => Some(current),
356                _ => Some(candidate),
357            },
358        );
359    let unanswered = group_size.saturating_sub(answers.len());
360    if let Some((state, holders)) = best {
361        // A final state is adopted only as the strictly larger side, counting
362        // every peer that did not answer for its rival: a final state is
363        // never replaced, so two repairing nodes that each saw part of a tie
364        // would otherwise adopt opposite sides for good. That covers a rival
365        // seen among the answers and one only silent peers could hold.
366        if state.is_terminal() {
367            let rival_could_match = by_state.iter().any(|(other, others)| {
368                other.state_id != state.state_id
369                    && beats_held(other)
370                    && !other.replaces(state)
371                    && !state.replaces(other)
372                    && others.len().saturating_add(unanswered) >= holders.len()
373            });
374            if rival_could_match || unanswered >= holders.len() {
375                return Verdict::Undecided;
376            }
377        }
378        return Verdict::Adopt {
379            state: *state,
380            holders: holders.clone(),
381        };
382    }
383
384    let largest = by_state
385        .iter()
386        .filter(|(state, _)| beats_held(state))
387        .map(|(_, holders)| holders.len())
388        .max()
389        .unwrap_or(0);
390    if largest.saturating_add(unanswered) >= quorum_needed {
391        Verdict::Undecided
392    } else {
393        Verdict::Refused
394    }
395}
396
397/// What asking a peer for a pointer record came to.
398enum Fetched {
399    /// A record that verifies and belongs at the address.
400    Record(Pointer),
401    /// A record that does not, which the peer has already been penalised for.
402    Invalid,
403    /// No record: no answer, an empty one, or one about another address.
404    Nothing,
405    /// A record this node could not check, or a request it never sent, for a
406    /// reason of its own.
407    LocalFailure,
408}
409
410/// What asking a peer came to (see [`PointerReplication::ask`]).
411enum Asked {
412    /// The peer's answer.
413    Answered(ReplicationMessageBody),
414    /// Sent, and no usable answer came back.
415    Silent,
416    /// Never sent: this node is shutting down, or its own requests to the
417    /// peer stayed busy for the whole timeout.
418    NotSent,
419}
420
421/// One of `permits`, if one comes free within `timeout` and before
422/// `shutdown`. Shutdown wins when both are ready at once.
423async fn acquire_or_give_up(
424    permits: Arc<Semaphore>,
425    timeout: Duration,
426    shutdown: &CancellationToken,
427) -> Option<OwnedSemaphorePermit> {
428    let permit = tokio::select! {
429        biased;
430        () = shutdown.cancelled() => None,
431        permit = tokio::time::timeout(timeout, permits.acquire_owned()) => permit.ok()?.ok(),
432    }?;
433    (!shutdown.is_cancelled()).then_some(permit)
434}
435
436/// What a possession check makes of one peer's answer about `fresh`.
437#[derive(Debug, PartialEq, Eq)]
438enum Possession {
439    /// The peer served `fresh` or a state that replaces it.
440    Holds,
441    /// The peer could not produce `fresh` or anything newer.
442    Missing,
443    /// The peer served a different final state, and `fresh` is final too: the
444    /// owner signed both, and each node kept the one it took first. Carries
445    /// the state the peer holds, so the fork can be named.
446    Forked(XorName),
447    /// Nothing to judge the peer on: it served a record that does not verify,
448    /// which the fetch has already charged it for, or this node could not
449    /// check what it served.
450    NotJudged,
451}
452
453/// Judge one peer's answer in a possession check for `fresh`.
454fn judge_possession(fetched: Fetched, fresh: &PointerState) -> Possession {
455    match fetched {
456        Fetched::Record(record) => {
457            let state = record.state();
458            if state.state_id == fresh.state_id || state.replaces(fresh) {
459                Possession::Holds
460            } else if state.is_terminal() && fresh.is_terminal() {
461                Possession::Forked(state.state_id)
462            } else {
463                Possession::Missing
464            }
465        }
466        Fetched::Nothing => Possession::Missing,
467        Fetched::Invalid | Fetched::LocalFailure => Possession::NotJudged,
468    }
469}
470
471/// Whether nothing but the map holds a peer's outbound permits.
472///
473/// Every holder, a request waiting for a permit or one holding it, has a
474/// clone, and clones are only made under the map's lock. So an entry nothing
475/// else holds can be dropped without a later request getting a second set of
476/// permits beside one still in use, which would let this node exceed
477/// [`MAX_REQUESTS_PER_PEER`] at that peer.
478fn outbound_idle(permits: &Arc<Semaphore>) -> bool {
479    Arc::strong_count(permits) == 1
480}
481
482/// How many members a repair counts its quorum over: the whole close group,
483/// however few of them this node can see (ADR-0016). A member it cannot see is
484/// unanswered, so a thin routing table leaves a repair undecided instead of
485/// shrinking the quorum to what little it can see.
486fn repair_width(seen: usize, close_group_size: usize) -> usize {
487    seen.max(close_group_size)
488}
489
490/// Pointer replication for one node. See the module documentation.
491pub struct PointerReplication {
492    store: PointerStore,
493    chunks: Arc<ChunkStore>,
494    p2p: Arc<P2PNode>,
495    payments: Arc<PaymentVerifier>,
496    config: Arc<ReplicationConfig>,
497    is_bootstrapping: Arc<RwLock<bool>>,
498    /// Outbound record transfers, shared with chunk replication.
499    send_semaphore: Arc<Semaphore>,
500    offer_permits: Arc<Semaphore>,
501    serve_permits: Arc<Semaphore>,
502    /// Admission ahead of `serve_permits`: see [`MAX_SERVES_OUTSTANDING`].
503    serve_admission: Arc<Semaphore>,
504    /// Requests each peer has admitted and not yet had answered.
505    serve_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
506    /// This node's own requests outstanding at each peer (see
507    /// [`MAX_REQUESTS_PER_PEER`]).
508    outbound: Mutex<HashMap<PeerId, Arc<Semaphore>>>,
509    /// Peers that have sent a pointer message: the only ones asked anything.
510    capable: Mutex<HashSet<PeerId>>,
511    /// Hinted states awaiting verification, by address.
512    pending: Mutex<HashMap<XorName, Pending>>,
513    /// When each held address was first seen continuously out of range.
514    /// Restored on start, and saved after each prune pass's classification.
515    out_of_range: OutOfRangeClocks,
516    /// Hint pushes answering sync requests that may run at once.
517    sync_answers: Arc<Semaphore>,
518    /// When each peer was last answered with hints.
519    answered_syncs: Mutex<AnsweredSyncs>,
520    /// The bounds on looks before a final state (ADR-0018).
521    finality: FinalityLooks,
522    shutdown: CancellationToken,
523    tracker: TaskTracker,
524}
525
526/// When each peer was last sent hints in answer to its own sync request.
527#[derive(Default)]
528struct AnsweredSyncs {
529    at: HashMap<PeerId, Instant>,
530}
531
532impl AnsweredSyncs {
533    /// Whether `peer` may be answered at `now`, and if so note it: not if it
534    /// was answered less than `spacing` ago. A full map forgets the peers
535    /// answered longest ago rather than refuse anyone new.
536    fn admit(&mut self, peer: PeerId, now: Instant, spacing: Duration) -> bool {
537        let recent = |at: &Instant| now.saturating_duration_since(*at) < spacing;
538        if self.at.get(&peer).is_some_and(recent) {
539            return false;
540        }
541        if self.at.len() >= MAX_ANSWERED_SYNC_PEERS && !self.at.contains_key(&peer) {
542            self.at.retain(|_, at| recent(at));
543        }
544        if self.at.len() >= MAX_ANSWERED_SYNC_PEERS && !self.at.contains_key(&peer) {
545            let oldest = self
546                .at
547                .iter()
548                .min_by_key(|(_, at)| **at)
549                .map(|(peer, _)| *peer);
550            if let Some(oldest) = oldest {
551                self.at.remove(&oldest);
552            }
553        }
554        self.at.insert(peer, now);
555        true
556    }
557}
558
559/// Final states a finality check proved the close group holds, remembered so
560/// that a paid final state which lost to one is refused again without asking
561/// anyone.
562#[derive(Default)]
563struct ProvenFinals {
564    /// Up to [`MAX_PROOFS_PER_ADDRESS`] different proven states per address.
565    by_address: HashMap<XorName, Vec<PointerState>>,
566    /// Addresses in the order they were first proven, oldest first.
567    order: VecDeque<XorName>,
568}
569
570impl ProvenFinals {
571    /// A proven final state at `state.address` other than `state`.
572    fn conflict(&self, state: &PointerState) -> Option<PointerState> {
573        self.by_address
574            .get(&state.address)?
575            .iter()
576            .find(|proven| proven.state_id != state.state_id)
577            .copied()
578    }
579
580    /// Remember `proven` beside what is already proven at its address, never
581    /// in place of it: a proof replaced would let the state it disproved in.
582    /// Forgets the oldest addresses past the cap.
583    fn remember(&mut self, proven: PointerState) {
584        if let Some(states) = self.by_address.get_mut(&proven.address) {
585            let known = states.iter().any(|state| state.state_id == proven.state_id);
586            if !known && states.len() < MAX_PROOFS_PER_ADDRESS {
587                states.push(proven);
588            }
589        } else {
590            self.by_address.insert(proven.address, vec![proven]);
591            self.order.push_back(proven.address);
592        }
593        while self.by_address.len() > MAX_PROVEN_FINALS {
594            let Some(oldest) = self.order.pop_front() else {
595                break;
596            };
597            self.by_address.remove(&oldest);
598        }
599    }
600}
601
602/// The bounds on looks before a final state (ADR-0018), apart from the
603/// network so they can be tested without one.
604///
605/// A look's answer is kept either way: a proof for good, a clear look briefly.
606/// Looks for one address take turns, so replays queued behind a look find its
607/// answer rather than asking again; at most [`FINAL_STATE_CHECK_STRIPES`]
608/// run at once.
609struct FinalityLooks {
610    proven: Mutex<ProvenFinals>,
611    /// When each final state was last looked for and found clear, on the
612    /// runtime's clock, which the look's own time bounds use as well.
613    clear: Mutex<HashMap<(XorName, XorName), TokioInstant>>,
614    /// One turn per share of the address space.
615    turns: Vec<tokio::sync::Mutex<()>>,
616}
617
618impl FinalityLooks {
619    fn new() -> Self {
620        Self {
621            proven: Mutex::new(ProvenFinals::default()),
622            clear: Mutex::new(HashMap::new()),
623            turns: (0..FINAL_STATE_CHECK_STRIPES)
624                .map(|_| tokio::sync::Mutex::new(()))
625                .collect(),
626        }
627    }
628
629    /// A proven final state that conflicts with `state`, asking nobody.
630    fn proven_conflict(&self, state: &PointerState) -> Option<PointerState> {
631        self.proven.lock().conflict(state)
632    }
633
634    /// Whether a look found `state` clear recently enough to answer again.
635    fn recently_clear(&self, state: &PointerState, now: TokioInstant) -> bool {
636        self.clear
637            .lock()
638            .get(&(state.address, state.state_id))
639            .is_some_and(|at| now.saturating_duration_since(*at) < FINAL_STATE_CLEAR_REUSE)
640    }
641
642    /// Forget a clear look for `state`: the write it cleared did not land, so
643    /// a retry must look again.
644    fn forget_clear(&self, state: &PointerState) {
645        self.clear.lock().remove(&(state.address, state.state_id));
646    }
647
648    fn note_clear(&self, state: &PointerState, now: TokioInstant) {
649        let mut clear = self.clear.lock();
650        if clear.len() >= MAX_CLEAR_LOOKS {
651            clear.retain(|_, at| now.saturating_duration_since(*at) < FINAL_STATE_CLEAR_REUSE);
652        }
653        if clear.len() < MAX_CLEAR_LOOKS {
654            clear.insert((state.address, state.state_id), now);
655        }
656    }
657
658    /// Answer whether `state` may be taken, running `look` only when neither
659    /// a proof nor a recent clear look answers it already.
660    async fn check<Look, Fut>(&self, state: &PointerState, look: Look) -> FinalityCheck
661    where
662        Look: FnOnce() -> Fut + Send,
663        Fut: Future<Output = Option<Pointer>> + Send,
664    {
665        if !state.is_terminal() {
666            return FinalityCheck::Clear;
667        }
668        if let Some(conflict) = self.proven_conflict(state) {
669            return FinalityCheck::Conflict(conflict);
670        }
671        // By the last byte: the addresses one node is responsible for share
672        // their leading bits, so the first byte would put them all on one turn.
673        let stripe = usize::from(state.address.last().copied().unwrap_or_default())
674            % FINAL_STATE_CHECK_STRIPES;
675        let Some(turn) = self.turns.get(stripe) else {
676            return FinalityCheck::Busy;
677        };
678        let Ok(_turn) = tokio::time::timeout(FINAL_STATE_CHECK_WAIT, turn.lock()).await else {
679            return FinalityCheck::Busy;
680        };
681        // A look that held the turn may have answered this meanwhile.
682        if let Some(conflict) = self.proven_conflict(state) {
683            return FinalityCheck::Conflict(conflict);
684        }
685        if self.recently_clear(state, TokioInstant::now()) {
686            return FinalityCheck::Clear;
687        }
688        match tokio::time::timeout(FINAL_STATE_CHECK_BUDGET, look()).await {
689            Ok(Some(record)) => {
690                let conflict = record.state();
691                self.proven.lock().remember(conflict);
692                FinalityCheck::Conflict(conflict)
693            }
694            Ok(None) => {
695                self.note_clear(state, TokioInstant::now());
696                FinalityCheck::Clear
697            }
698            // Silence proves nothing, and is not kept for reuse either: the
699            // next look may be answered.
700            Err(_) => {
701                debug!(
702                    "Close group of pointer {} did not answer the finality check in time",
703                    hex::encode(state.address)
704                );
705                FinalityCheck::Clear
706            }
707        }
708    }
709}
710
711impl PointerReplication {
712    /// Pointer replication over `store`, sharing the engine's resources.
713    #[allow(clippy::too_many_arguments)]
714    pub(crate) fn new(
715        store: PointerStore,
716        chunks: Arc<ChunkStore>,
717        p2p: Arc<P2PNode>,
718        payments: Arc<PaymentVerifier>,
719        config: Arc<ReplicationConfig>,
720        is_bootstrapping: Arc<RwLock<bool>>,
721        send_semaphore: Arc<Semaphore>,
722        shutdown: CancellationToken,
723        tracker: TaskTracker,
724    ) -> Self {
725        let out_of_range =
726            OutOfRangeClocks::load(store.dir().with_file_name(OUT_OF_RANGE_CLOCKS_FILE));
727        Self {
728            store,
729            chunks,
730            p2p,
731            payments,
732            config,
733            is_bootstrapping,
734            send_semaphore,
735            offer_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_OFFERS)),
736            serve_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_SERVES)),
737            serve_admission: Arc::new(Semaphore::new(MAX_SERVES_OUTSTANDING)),
738            serve_inflight: Arc::new(RwLock::new(HashMap::new())),
739            outbound: Mutex::new(HashMap::new()),
740            capable: Mutex::new(HashSet::new()),
741            pending: Mutex::new(HashMap::new()),
742            out_of_range,
743            sync_answers: Arc::new(Semaphore::new(MAX_CONCURRENT_SYNC_ANSWERS)),
744            answered_syncs: Mutex::new(AnsweredSyncs::default()),
745            finality: FinalityLooks::new(),
746            shutdown,
747            tracker,
748        }
749    }
750
751    /// The pointer store this replication serves from.
752    pub(crate) fn store(&self) -> &PointerStore {
753        &self.store
754    }
755
756    // -----------------------------------------------------------------------
757    // Capability
758    // -----------------------------------------------------------------------
759
760    /// Remember that `peer` speaks pointers, if it is in the routing table.
761    ///
762    /// Only a routed peer is remembered: it is the only kind this node ever
763    /// asks, and the routing table's removals are what forget it again, so the
764    /// set cannot outgrow the table however many identities send a message.
765    async fn mark_capable(&self, peer: &PeerId) {
766        if !self.p2p.dht_manager().is_in_routing_table(peer).await {
767            return;
768        }
769        let mut capable = self.capable.lock();
770        if capable.len() >= MAX_CAPABLE_PEERS && !capable.contains(peer) {
771            if let Some(evicted) = capable.iter().next().copied() {
772                capable.remove(&evicted);
773            }
774        }
775        capable.insert(*peer);
776    }
777
778    /// Whether `peer` has sent a pointer message, and may therefore be asked.
779    pub fn is_capable(&self, peer: &PeerId) -> bool {
780        self.capable.lock().contains(peer)
781    }
782
783    /// Forget a peer that left the routing table.
784    pub(crate) fn forget_peer(&self, peer: &PeerId) {
785        self.capable.lock().remove(peer);
786        let mut outbound = self.outbound.lock();
787        if outbound.get(peer).is_some_and(outbound_idle) {
788            outbound.remove(peer);
789        }
790    }
791
792    /// The permits bounding this node's requests to `peer`.
793    fn outbound_permits(&self, peer: &PeerId) -> Arc<Semaphore> {
794        let mut outbound = self.outbound.lock();
795        if outbound.len() >= MAX_CAPABLE_PEERS && !outbound.contains_key(peer) {
796            // Peers nothing is outstanding at hold no state worth keeping.
797            outbound.retain(|_, permits| !outbound_idle(permits));
798        }
799        Arc::clone(
800            outbound
801                .entry(*peer)
802                .or_insert_with(|| Arc::new(Semaphore::new(MAX_REQUESTS_PER_PEER))),
803        )
804    }
805
806    /// Addresses currently awaiting verification. Tests only.
807    #[cfg(any(test, feature = "test-utils"))]
808    #[must_use]
809    pub fn pending_len(&self) -> usize {
810        self.pending.lock().len()
811    }
812
813    // -----------------------------------------------------------------------
814    // Messaging
815    // -----------------------------------------------------------------------
816
817    async fn send_one_way(&self, peer: &PeerId, body: ReplicationMessageBody) -> bool {
818        let msg = ReplicationMessage {
819            request_id: rand::thread_rng().gen::<u64>(),
820            body,
821        };
822        let Ok(bytes) = msg.encode() else {
823            warn!("Failed to encode a pointer replication message");
824            return false;
825        };
826        self.p2p
827            .send_message(peer, REPLICATION_PROTOCOL_ID, bytes, &[])
828            .await
829            .is_ok()
830    }
831
832    async fn request(
833        &self,
834        peer: &PeerId,
835        body: ReplicationMessageBody,
836        timeout: Duration,
837    ) -> Option<ReplicationMessageBody> {
838        match self.ask(peer, body, timeout).await {
839            Asked::Answered(body) => Some(body),
840            Asked::Silent | Asked::NotSent => None,
841        }
842    }
843
844    /// Ask `peer`, saying whether a missing answer was the peer's silence or
845    /// this node never sending the request at all.
846    ///
847    /// The request waits for one of this node's own permits for `peer` first,
848    /// but no longer than `timeout` and not past shutdown: a request that
849    /// could not be sent in that time is dropped as not sent, never left
850    /// waiting, and never held against the peer.
851    async fn ask(&self, peer: &PeerId, body: ReplicationMessageBody, timeout: Duration) -> Asked {
852        let Some(_permit) =
853            acquire_or_give_up(self.outbound_permits(peer), timeout, &self.shutdown).await
854        else {
855            return Asked::NotSent;
856        };
857        let msg = ReplicationMessage {
858            request_id: rand::thread_rng().gen::<u64>(),
859            body,
860        };
861        let Ok(bytes) = msg.encode() else {
862            return Asked::NotSent;
863        };
864        let Ok(response) = self
865            .p2p
866            .send_request(peer, REPLICATION_PROTOCOL_ID, bytes, timeout)
867            .await
868        else {
869            return Asked::Silent;
870        };
871        ReplicationMessage::decode(&response.data)
872            .map_or(Asked::Silent, |msg| Asked::Answered(msg.body))
873    }
874
875    async fn penalise(&self, peer: &PeerId) {
876        self.p2p
877            .report_trust_event(
878                peer,
879                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
880            )
881            .await;
882    }
883
884    /// Ask `peer` for the record it holds at `address`, and check what comes
885    /// back: a valid signature and the right address. Anything else counts
886    /// against the peer.
887    async fn fetch_record(&self, peer: &PeerId, address: &XorName) -> Option<Pointer> {
888        self.fetch_record_within(peer, address, self.config.fetch_request_timeout)
889            .await
890    }
891
892    /// [`Self::fetch_record`], waiting at most `timeout` for a request slot and
893    /// again for the answer.
894    async fn fetch_record_within(
895        &self,
896        peer: &PeerId,
897        address: &XorName,
898        timeout: Duration,
899    ) -> Option<Pointer> {
900        match self.fetch_outcome(peer, address, timeout).await {
901            Fetched::Record(record) => Some(record),
902            Fetched::Invalid | Fetched::Nothing | Fetched::LocalFailure => None,
903        }
904    }
905
906    /// [`Self::fetch_record_within`], saying whether a failure was a record
907    /// that did not verify, which has already cost the peer, or no record at
908    /// all.
909    async fn fetch_outcome(&self, peer: &PeerId, address: &XorName, timeout: Duration) -> Fetched {
910        let body = match self
911            .ask(
912                peer,
913                ReplicationMessageBody::PointerFetchRequest(PointerFetchRequest {
914                    address: *address,
915                }),
916                timeout,
917            )
918            .await
919        {
920            Asked::Answered(body) => body,
921            Asked::Silent => return Fetched::Nothing,
922            // Never asked: nothing to judge the peer on.
923            Asked::NotSent => return Fetched::LocalFailure,
924        };
925        let ReplicationMessageBody::PointerFetchResponse(response) = body else {
926            return Fetched::Nothing;
927        };
928        if response.address != *address {
929            return Fetched::Nothing;
930        }
931        let Some(bytes) = response.record else {
932            return Fetched::Nothing;
933        };
934        // Parsing verifies the ML-DSA signature, milliseconds of CPU a peer
935        // can demand once per record it serves: off the async executor, as
936        // every other pointer signature check is (ADR-0016).
937        let Ok(parsed) = spawn_blocking(move || Pointer::from_bytes(&bytes)).await else {
938            // The check itself failed here, which says nothing about the peer.
939            warn!(
940                "Could not verify the pointer record {peer} served for {}",
941                hex::encode(address)
942            );
943            return Fetched::LocalFailure;
944        };
945        match parsed {
946            Ok(record) if record.address() == *address => Fetched::Record(record),
947            Ok(_) | Err(_) => {
948                debug!(
949                    "Peer {peer} served an invalid pointer record for {}",
950                    hex::encode(address)
951                );
952                self.penalise(peer).await;
953                Fetched::Invalid
954            }
955        }
956    }
957
958    // -----------------------------------------------------------------------
959    // Hints
960    // -----------------------------------------------------------------------
961
962    /// Push hints to `peers` in the background: for each, the states this
963    /// node holds whose close group, in this node's view, includes that peer.
964    ///
965    /// Every peer gets at least one message, empty or not. That is how a peer
966    /// learns this node understands pointers.
967    pub(crate) fn push_hints_detached(self: &Arc<Self>, peers: Vec<PeerId>) {
968        if peers.is_empty() {
969            return;
970        }
971        let this = Arc::clone(self);
972        self.tracker
973            .spawn(async move { this.push_hints(&peers).await });
974    }
975
976    /// Answer a peer's sync request, admitted and still fresh, with this
977    /// node's pointer hints, in the background: how a peer, including one
978    /// still bootstrapping, learns the pointers it should hold.
979    ///
980    /// Each answer scans every pointer held, so only a routing-table peer is
981    /// answered, at most once per shortest sync interval, which an honest
982    /// peer never syncs faster than, and at most
983    /// [`MAX_CONCURRENT_SYNC_ANSWERS`] answers run at once. A request that
984    /// finds them all busy gets no hints this time; the next sync round sends
985    /// them anyway.
986    pub(crate) fn answer_sync_with_hints(self: &Arc<Self>, peer: PeerId) {
987        let Ok(permit) = Arc::clone(&self.sync_answers).try_acquire_owned() else {
988            debug!("Not answering {peer}'s sync with pointer hints: too many answers running");
989            return;
990        };
991        let this = Arc::clone(self);
992        self.tracker.spawn(async move {
993            let _permit = permit;
994            if !this.p2p.dht_manager().is_in_routing_table(&peer).await {
995                return;
996            }
997            let admitted = this.answered_syncs.lock().admit(
998                peer,
999                Instant::now(),
1000                this.config.neighbor_sync_interval_min,
1001            );
1002            if admitted {
1003                this.push_hints(&[peer]).await;
1004            }
1005        });
1006    }
1007
1008    /// Push hints to `peers` and wait until they are sent. This is what each
1009    /// neighbour-sync round runs in the background; tests call it to drive a
1010    /// round.
1011    pub async fn push_hints(&self, peers: &[PeerId]) {
1012        let self_id = *self.p2p.peer_id();
1013        let mut by_peer: HashMap<PeerId, Vec<PointerStateSummary>> =
1014            peers.iter().map(|peer| (*peer, Vec::new())).collect();
1015        for state in self.store.held_states() {
1016            if self.shutdown.is_cancelled() {
1017                return;
1018            }
1019            let group = self
1020                .p2p
1021                .dht_manager()
1022                .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
1023                .await;
1024            for node in group {
1025                if node.peer_id == self_id {
1026                    continue;
1027                }
1028                if let Some(hints) = by_peer.get_mut(&node.peer_id) {
1029                    hints.push(state.into());
1030                }
1031            }
1032        }
1033        for (peer, hints) in by_peer {
1034            let batches: Vec<Vec<PointerStateSummary>> = if hints.is_empty() {
1035                vec![Vec::new()]
1036            } else {
1037                hints
1038                    .chunks(MAX_POINTER_HINTS_PER_MESSAGE)
1039                    .map(<[PointerStateSummary]>::to_vec)
1040                    .collect()
1041            };
1042            for hints in batches {
1043                self.send_one_way(
1044                    &peer,
1045                    ReplicationMessageBody::PointerHints(PointerHints { hints }),
1046                )
1047                .await;
1048            }
1049        }
1050    }
1051
1052    /// Take in hints from `source`: queue each hinted state this node should
1053    /// hold and lacks, or holds an older state than.
1054    pub(crate) async fn handle_hints(&self, source: PeerId, hints: Vec<PointerStateSummary>) {
1055        self.mark_capable(&source).await;
1056        if hints.is_empty() {
1057            return;
1058        }
1059        // As for chunks: only a peer in our own routing table may tell us what
1060        // to hold.
1061        if !self.p2p.dht_manager().is_in_routing_table(&source).await {
1062            debug!("Dropping pointer hints from {source}: not in the routing table");
1063            return;
1064        }
1065        let self_id = *self.p2p.peer_id();
1066        let width = storage_admission_width(self.config.close_group_size);
1067        for summary in hints.into_iter().take(MAX_POINTER_HINTS_PER_MESSAGE) {
1068            let hinted = PointerState::from(summary);
1069            match self.store.state(&hinted.address) {
1070                Some(held) => {
1071                    if held.state_id == hinted.state_id || !hinted.replaces(&held) {
1072                        continue;
1073                    }
1074                }
1075                None => {
1076                    if !admission::is_responsible(&self_id, &hinted.address, &self.p2p, width).await
1077                    {
1078                        continue;
1079                    }
1080                }
1081            }
1082            self.enqueue(hinted);
1083        }
1084    }
1085
1086    fn enqueue(&self, hinted: PointerState) {
1087        let mut pending = self.pending.lock();
1088        let len = pending.len();
1089        match pending.get_mut(&hinted.address) {
1090            Some(entry) => {
1091                if hinted.replaces(&entry.wanted) {
1092                    entry.wanted = hinted;
1093                    entry.attempts = 0;
1094                    entry.not_before = Instant::now();
1095                }
1096            }
1097            None if len < MAX_PENDING => {
1098                pending.insert(
1099                    hinted.address,
1100                    Pending {
1101                        wanted: hinted,
1102                        attempts: 0,
1103                        not_before: Instant::now(),
1104                    },
1105                );
1106            }
1107            None => {}
1108        }
1109    }
1110
1111    // -----------------------------------------------------------------------
1112    // Verification and fetch
1113    // -----------------------------------------------------------------------
1114
1115    /// Start the loop that verifies and fetches hinted states.
1116    pub(crate) fn start_verification_loop(self: &Arc<Self>) -> JoinHandle<()> {
1117        let this = Arc::clone(self);
1118        tokio::spawn(async move {
1119            loop {
1120                tokio::select! {
1121                    () = this.shutdown.cancelled() => break,
1122                    () = tokio::time::sleep(VERIFICATION_TICK) => this.verify_due().await,
1123                }
1124            }
1125        })
1126    }
1127
1128    /// Whether this node should look for anything to repair now.
1129    async fn may_repair(&self) -> bool {
1130        // As for chunks (ADR-0011): a node that cannot store what it would
1131        // fetch does not spend the network's time finding it. The hints wait,
1132        // and come back each round if they are dropped meanwhile.
1133        if self.chunks.capacity_verdict() == CapacityVerdict::Full {
1134            return false;
1135        }
1136        // A node still bootstrapping sees too little of its close group to
1137        // judge what a quorum of it holds. The hints wait for it.
1138        !*self.is_bootstrapping.read().await
1139    }
1140
1141    /// Verify and fetch whatever is due now. Also the tests' way to drive it.
1142    pub async fn verify_due(&self) {
1143        if !self.may_repair().await {
1144            return;
1145        }
1146        let now = Instant::now();
1147        let due: Vec<(XorName, PointerState)> = self
1148            .pending
1149            .lock()
1150            .iter()
1151            .filter(|(_, entry)| entry.not_before <= now)
1152            .take(MAX_VERIFICATIONS_PER_TICK)
1153            .map(|(address, entry)| (*address, entry.wanted))
1154            .collect();
1155        if due.is_empty() {
1156            return;
1157        }
1158
1159        let self_id = *self.p2p.peer_id();
1160        let mut groups: HashMap<XorName, Vec<PeerId>> = HashMap::new();
1161        let mut asked: HashMap<PeerId, Vec<XorName>> = HashMap::new();
1162        for (address, _) in &due {
1163            let group: Vec<PeerId> = self
1164                .p2p
1165                .dht_manager()
1166                .find_closest_nodes_local(address, self.config.close_group_size)
1167                .await
1168                .into_iter()
1169                .map(|node| node.peer_id)
1170                .filter(|peer| *peer != self_id)
1171                .collect();
1172            for peer in group.iter().filter(|peer| self.is_capable(peer)) {
1173                asked.entry(*peer).or_default().push(*address);
1174            }
1175            groups.insert(*address, group);
1176        }
1177
1178        let answers = self.ask_states(asked).await;
1179
1180        let decisions: Vec<(XorName, Verdict)> = due
1181            .iter()
1182            .map(|(address, _)| {
1183                let group = groups.get(address).map_or(&[][..], Vec::as_slice);
1184                let answered: Vec<(PeerId, Option<PointerState>)> = group
1185                    .iter()
1186                    .filter_map(|peer| {
1187                        answers
1188                            .get(&(*peer, *address))
1189                            .map(|answer| (*peer, *answer))
1190                    })
1191                    .collect();
1192                let held = self.store.state(address);
1193                // The quorum is counted over the whole close group, as
1194                // ADR-0016 has it: a member this node cannot see, because its
1195                // routing table is thin, counts as unanswered, never as a
1196                // smaller group. Otherwise one peer in a thin view could vote
1197                // alone for an owner-signed state nobody paid to store.
1198                let width = repair_width(group.len(), self.config.close_group_size);
1199                let verdict = evaluate(
1200                    held.as_ref(),
1201                    width,
1202                    &answered,
1203                    self.config.quorum_needed(width),
1204                );
1205                (*address, verdict)
1206            })
1207            .collect();
1208
1209        let outcomes: Vec<(XorName, bool)> = stream::iter(decisions)
1210            .map(|(address, verdict)| async move {
1211                match verdict {
1212                    Verdict::Adopt { state, holders } => {
1213                        let stored = self.fetch_and_store(address, state, &holders).await;
1214                        (address, stored)
1215                    }
1216                    Verdict::Undecided => (address, false),
1217                    Verdict::Refused => {
1218                        info!(
1219                            "No quorum backs a newer state for pointer {}",
1220                            hex::encode(address)
1221                        );
1222                        self.pending.lock().remove(&address);
1223                        (address, true)
1224                    }
1225                }
1226            })
1227            .buffer_unordered(VERIFICATION_CONCURRENCY)
1228            .collect()
1229            .await;
1230
1231        let now = Instant::now();
1232        let mut pending = self.pending.lock();
1233        for (address, settled) in outcomes {
1234            if settled {
1235                pending.remove(&address);
1236                continue;
1237            }
1238            if let Some(entry) = pending.get_mut(&address) {
1239                entry.attempts = entry.attempts.saturating_add(1);
1240                if entry.attempts >= MAX_UNDECIDED_ROUNDS {
1241                    pending.remove(&address);
1242                } else {
1243                    let backoff = UNDECIDED_BACKOFF
1244                        .saturating_mul(2u32.saturating_pow(entry.attempts.saturating_sub(1)));
1245                    entry.not_before = now + backoff;
1246                }
1247            }
1248        }
1249    }
1250
1251    /// Ask each peer which state it holds at the addresses listed for it.
1252    async fn ask_states(
1253        &self,
1254        asked: HashMap<PeerId, Vec<XorName>>,
1255    ) -> HashMap<(PeerId, XorName), Option<PointerState>> {
1256        let requests: Vec<(PeerId, Vec<XorName>)> = asked
1257            .into_iter()
1258            .flat_map(|(peer, addresses)| {
1259                addresses
1260                    .chunks(MAX_POINTER_STATE_REQUEST_ADDRESSES)
1261                    .map(|chunk| (peer, chunk.to_vec()))
1262                    .collect::<Vec<_>>()
1263            })
1264            .collect();
1265        let replies: Vec<Vec<StateAnswer>> = stream::iter(requests)
1266            .map(|(peer, addresses)| async move {
1267                let body = self
1268                    .request(
1269                        &peer,
1270                        ReplicationMessageBody::PointerStateRequest(PointerStateRequest {
1271                            addresses: addresses.clone(),
1272                        }),
1273                        self.config.verification_request_timeout,
1274                    )
1275                    .await;
1276                let Some(ReplicationMessageBody::PointerStateResponse(response)) = body else {
1277                    return Vec::new();
1278                };
1279                read_state_answers(peer, &addresses, response.states)
1280            })
1281            .buffer_unordered(VERIFICATION_CONCURRENCY)
1282            .collect()
1283            .await;
1284        replies.into_iter().flatten().collect()
1285    }
1286
1287    /// Fetch `wanted` from one of `holders` and store it. Whether it is now
1288    /// held, or nothing further can come of this round.
1289    async fn fetch_and_store(
1290        &self,
1291        address: XorName,
1292        wanted: PointerState,
1293        holders: &[PeerId],
1294    ) -> bool {
1295        for holder in holders {
1296            let Some(record) = self.fetch_record(holder, &address).await else {
1297                continue;
1298            };
1299            // The quorum backed this state, exactly. A holder that has moved
1300            // on since serves a different one, which that quorum says nothing
1301            // about.
1302            if !backs(&record, &wanted) {
1303                continue;
1304            }
1305            match self.store_verified(record, None).await {
1306                Ok(_) => return true,
1307                Err(e) => {
1308                    warn!(
1309                        "Could not store replicated pointer {}: {e}",
1310                        hex::encode(address)
1311                    );
1312                    return false;
1313                }
1314            }
1315        }
1316        false
1317    }
1318
1319    /// Store a record whose signature has been checked, if it still belongs
1320    /// here and beats what is held.
1321    async fn store_verified(
1322        &self,
1323        record: Pointer,
1324        width: Option<usize>,
1325    ) -> crate::error::Result<bool> {
1326        let state = record.state();
1327        let self_id = *self.p2p.peer_id();
1328        let width = width.unwrap_or_else(|| storage_admission_width(self.config.close_group_size));
1329        let held = self.store.state(&state.address).is_some();
1330        if !held && !admission::is_responsible(&self_id, &state.address, &self.p2p, width).await {
1331            return Ok(false);
1332        }
1333        if !self.store.admits(&state) {
1334            return Ok(false);
1335        }
1336        let reservation = self.chunks.reserve(POINTER_WIRE_LEN as u64)?;
1337        // Held now, whether this wrote it or it was already here; a commit
1338        // that found a state it loses to is not.
1339        let outcome = self.store.commit(record, Some(reservation)).await?;
1340        Ok(!matches!(outcome, PutOutcome::Stale))
1341    }
1342
1343    // -----------------------------------------------------------------------
1344    // Serving
1345    // -----------------------------------------------------------------------
1346
1347    /// Admit a fetch or state request from `source`, or drop it.
1348    ///
1349    /// Admitted before a task exists, fairly across peers, as a chunk fetch
1350    /// is: each admitted request would otherwise be a task waiting on a serve
1351    /// permit with nothing bounding how many, and one peer could take every
1352    /// place.
1353    async fn admit_serve(&self, source: &PeerId, kind: &str) -> Option<super::ResponderGuard> {
1354        match super::admit_bounded_responder(
1355            &self.serve_admission,
1356            &self.serve_inflight,
1357            source,
1358            MAX_SERVES_OUTSTANDING,
1359            MAX_SERVES_OUTSTANDING_PER_PEER,
1360        )
1361        .await
1362        {
1363            Ok(guard) => Some(guard),
1364            Err(failure) => {
1365                debug!("Dropping a pointer {kind} request from {source}: {failure}");
1366                None
1367            }
1368        }
1369    }
1370
1371    /// Answer a fetch request in the background.
1372    pub(crate) async fn serve_fetch_detached(
1373        self: &Arc<Self>,
1374        source: PeerId,
1375        request: PointerFetchRequest,
1376        request_id: u64,
1377        rr_message_id: Option<String>,
1378    ) {
1379        let Some(guard) = self.admit_serve(&source, "fetch").await else {
1380            return;
1381        };
1382        let this = Arc::clone(self);
1383        self.tracker.spawn(async move {
1384            let _guard = guard;
1385            // Shutting down ends the wait, and the work behind it.
1386            let permit = tokio::select! {
1387                biased;
1388                () = this.shutdown.cancelled() => return,
1389                permit = this.serve_permits.acquire() => permit,
1390            };
1391            let Ok(_permit) = permit else {
1392                return;
1393            };
1394            if this.shutdown.is_cancelled() {
1395                return;
1396            }
1397            this.mark_capable(&source).await;
1398            // `get` verifies the signature before serving, so a record damaged
1399            // on this disk is never handed on.
1400            let record = match this.store.get(&request.address).await {
1401                Ok(Some(record)) => Some(record.to_bytes()),
1402                Ok(None) | Err(_) => None,
1403            };
1404            super::send_replication_response(
1405                &source,
1406                &this.p2p,
1407                request_id,
1408                ReplicationMessageBody::PointerFetchResponse(PointerFetchResponse {
1409                    address: request.address,
1410                    record,
1411                }),
1412                rr_message_id.as_deref(),
1413            )
1414            .await;
1415        });
1416    }
1417
1418    /// Answer a state request in the background, from the index.
1419    pub(crate) async fn serve_state_detached(
1420        self: &Arc<Self>,
1421        source: PeerId,
1422        request: PointerStateRequest,
1423        request_id: u64,
1424        rr_message_id: Option<String>,
1425    ) {
1426        // An honest peer never asks about more than this at once. The decoded
1427        // request would otherwise be held by its task for as long as it waits,
1428        // and the wire allows one far larger.
1429        if request.addresses.len() > MAX_POINTER_STATE_REQUEST_ADDRESSES {
1430            debug!(
1431                "Dropping a pointer state request from {source}: {} addresses",
1432                request.addresses.len()
1433            );
1434            return;
1435        }
1436        let Some(guard) = self.admit_serve(&source, "state").await else {
1437            return;
1438        };
1439        let this = Arc::clone(self);
1440        self.tracker.spawn(async move {
1441            let _guard = guard;
1442            let permit = tokio::select! {
1443                biased;
1444                () = this.shutdown.cancelled() => return,
1445                permit = this.serve_permits.acquire() => permit,
1446            };
1447            let Ok(_permit) = permit else {
1448                return;
1449            };
1450            if this.shutdown.is_cancelled() {
1451                return;
1452            }
1453            this.mark_capable(&source).await;
1454            let states = request
1455                .addresses
1456                .iter()
1457                .take(MAX_POINTER_STATE_REQUEST_ADDRESSES)
1458                .map(|address| this.store.state(address).map(PointerStateSummary::from))
1459                .collect();
1460            super::send_replication_response(
1461                &source,
1462                &this.p2p,
1463                request_id,
1464                ReplicationMessageBody::PointerStateResponse(PointerStateResponse { states }),
1465                rr_message_id.as_deref(),
1466            )
1467            .await;
1468        });
1469    }
1470
1471    // -----------------------------------------------------------------------
1472    // Fresh replication
1473    // -----------------------------------------------------------------------
1474
1475    /// Start the loop that offers freshly paid states to their close groups.
1476    pub(crate) fn start_fresh_drainer(
1477        self: &Arc<Self>,
1478        mut writes: mpsc::UnboundedReceiver<PointerFreshWrite>,
1479    ) -> JoinHandle<()> {
1480        let this = Arc::clone(self);
1481        tokio::spawn(async move {
1482            loop {
1483                tokio::select! {
1484                    () = this.shutdown.cancelled() => break,
1485                    write = writes.recv() => match write {
1486                        Some(write) => this.replicate_fresh(write).await,
1487                        None => break,
1488                    },
1489                }
1490            }
1491        })
1492    }
1493
1494    /// Offer a freshly paid state to the rest of its close group, and schedule
1495    /// the check that they took it.
1496    pub async fn replicate_fresh(self: &Arc<Self>, write: PointerFreshWrite) {
1497        let Ok(state) = PointerState::parse(&write.record) else {
1498            warn!("A fresh pointer write did not parse; not replicating it");
1499            return;
1500        };
1501        let self_id = *self.p2p.peer_id();
1502        let targets: Vec<PeerId> = self
1503            .p2p
1504            .dht_manager()
1505            .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
1506            .await
1507            .into_iter()
1508            .map(|node| node.peer_id)
1509            .filter(|peer| *peer != self_id)
1510            .collect();
1511
1512        let msg = ReplicationMessage {
1513            request_id: rand::thread_rng().gen::<u64>(),
1514            body: ReplicationMessageBody::PointerFreshOffer(PointerFreshOffer {
1515                record: write.record,
1516                proof_of_payment: write.payment_proof,
1517            }),
1518        };
1519        let Ok(encoded) = msg.encode() else {
1520            warn!(
1521                "Failed to encode a fresh pointer offer for {}",
1522                hex::encode(state.address)
1523            );
1524            return;
1525        };
1526        let encoded = Arc::new(encoded);
1527        for peer in &targets {
1528            let p2p = Arc::clone(&self.p2p);
1529            let bytes = Arc::clone(&encoded);
1530            let semaphore = Arc::clone(&self.send_semaphore);
1531            let peer = *peer;
1532            self.tracker.spawn(async move {
1533                let Ok(_permit) = semaphore.acquire().await else {
1534                    return;
1535                };
1536                for attempt in 0..=FRESH_REPLICATION_DELIVERY_MAX_RETRIES {
1537                    match p2p
1538                        .send_message(&peer, REPLICATION_PROTOCOL_ID, bytes.as_ref().clone(), &[])
1539                        .await
1540                    {
1541                        Ok(()) => break,
1542                        Err(e) => debug!(
1543                            "Fresh pointer offer to {peer} failed (attempt {}): {e}",
1544                            attempt + 1
1545                        ),
1546                    }
1547                }
1548            });
1549        }
1550        debug!(
1551            "Fresh pointer {} offered to {} peers",
1552            hex::encode(state.address),
1553            targets.len()
1554        );
1555        self.schedule_possession_check(state, targets);
1556    }
1557
1558    /// Take a fresh offer from `source` in the background, unless too many are
1559    /// already being verified.
1560    pub(crate) fn accept_offer_detached(
1561        self: &Arc<Self>,
1562        source: PeerId,
1563        offer: PointerFreshOffer,
1564    ) {
1565        let Ok(permit) = Arc::clone(&self.offer_permits).try_acquire_owned() else {
1566            info!("Dropping a fresh pointer offer from {source}: too many in flight");
1567            return;
1568        };
1569        let this = Arc::clone(self);
1570        self.tracker.spawn(async move {
1571            let _permit = permit;
1572            this.mark_capable(&source).await;
1573            this.accept_offer(source, offer).await;
1574        });
1575    }
1576
1577    /// Verify and store a fresh offer. Cheapest checks first; the signature and
1578    /// the on-chain payment lookup only for a state that would change something
1579    /// here and that this node is responsible for.
1580    async fn accept_offer(&self, source: PeerId, offer: PointerFreshOffer) {
1581        if offer.record.len() != POINTER_WIRE_LEN
1582            || !(MIN_PAYMENT_PROOF_SIZE_BYTES..=MAX_PAYMENT_PROOF_SIZE_BYTES)
1583                .contains(&offer.proof_of_payment.len())
1584        {
1585            debug!("Dropping a malformed fresh pointer offer from {source}");
1586            self.penalise(&source).await;
1587            return;
1588        }
1589        let parsed = match self.store.inspect(&offer.record).await {
1590            Ok(Inspected::Candidate(parsed)) => parsed,
1591            Ok(Inspected::Unchanged(_) | Inspected::Stale(_)) => return,
1592            Err(e) => {
1593                debug!("Dropping an unparseable fresh pointer offer from {source}: {e}");
1594                self.penalise(&source).await;
1595                return;
1596            }
1597        };
1598        let state = *parsed.state();
1599        let self_id = *self.p2p.peer_id();
1600        // As for a chunk: a fresh offer is taken across the wider paid width.
1601        if !admission::is_responsible(
1602            &self_id,
1603            &state.address,
1604            &self.p2p,
1605            self.config.paid_list_close_group_size,
1606        )
1607        .await
1608        {
1609            return;
1610        }
1611        if !self.store.admits(&state)
1612            || self
1613                .chunks
1614                .check_capacity_for(POINTER_WIRE_LEN as u64)
1615                .is_err()
1616        {
1617            return;
1618        }
1619        // A final state already proven to have lost is dropped before it
1620        // buys a signature check.
1621        let needs_final_check = state.is_terminal()
1622            && !self
1623                .store
1624                .remembered(&state.address)
1625                .is_some_and(|known| known.is_terminal());
1626        if needs_final_check && self.finality.proven_conflict(&state).is_some() {
1627            return;
1628        }
1629        let record = match self.store.verify(parsed).await {
1630            Ok(record) => record,
1631            Err(e) => {
1632                debug!("Fresh pointer offer from {source} does not verify: {e}");
1633                self.penalise(&source).await;
1634                return;
1635            }
1636        };
1637        if let Err(e) = self
1638            .payments
1639            .verify_pointer_payment_in(
1640                &state.address,
1641                &state.state_id,
1642                &offer.proof_of_payment,
1643                VerificationContext::FreshReplication,
1644            )
1645            .await
1646        {
1647            info!(
1648                "Fresh pointer offer for {} from {source} is not paid for: {e}",
1649                hex::encode(state.address)
1650            );
1651            return;
1652        }
1653        // A final state this node neither holds nor remembers is looked for
1654        // in the group first, exactly as a client PUT of one is: the peer
1655        // offering it may simply be the side of a race this node has not
1656        // heard the other side of. A node that lost its own final state is
1657        // admitted only that state, so restoring it asks nobody.
1658        if needs_final_check && !self.offered_final_is_clear(&source, &state).await {
1659            return;
1660        }
1661        let stored = self
1662            .store_verified(record, Some(self.config.paid_list_close_group_size))
1663            .await;
1664        if !matches!(stored, Ok(true)) && needs_final_check {
1665            self.finality.forget_clear(&state);
1666        }
1667        match stored {
1668            Ok(true) => debug!(
1669                "Stored fresh pointer {} from {source}",
1670                hex::encode(state.address)
1671            ),
1672            Ok(false) => {}
1673            Err(e) => warn!(
1674                "Could not store fresh pointer {}: {e}",
1675                hex::encode(state.address)
1676            ),
1677        }
1678    }
1679
1680    // -----------------------------------------------------------------------
1681    // Finality
1682    // -----------------------------------------------------------------------
1683
1684    /// Whether a freshly offered final state may be taken: no peer proved a
1685    /// different one, and the look was not too busy to run.
1686    async fn offered_final_is_clear(&self, source: &PeerId, state: &PointerState) -> bool {
1687        match self.check_final(state).await {
1688            FinalityCheck::Clear => true,
1689            FinalityCheck::Conflict(conflict) => {
1690                info!(
1691                    "Refusing fresh final pointer state {} at {} from {source}: the close \
1692                     group already holds final state {}",
1693                    hex::encode(state.state_id),
1694                    hex::encode(state.address),
1695                    hex::encode(conflict.state_id)
1696                );
1697                false
1698            }
1699            FinalityCheck::Busy => {
1700                debug!(
1701                    "Dropping fresh final pointer state {} at {} from {source}: too many \
1702                     finality checks running",
1703                    hex::encode(state.state_id),
1704                    hex::encode(state.address)
1705                );
1706                false
1707            }
1708        }
1709    }
1710
1711    /// Ask the close group whether a final state at `state.address`, other
1712    /// than `state`, is already held, and have a peer that says so prove it
1713    /// by serving the signed record.
1714    ///
1715    /// Asked before this node takes a final state it does not hold. A final
1716    /// state is replaced by nothing, so a node that took a second one would
1717    /// hold it for good; asking first is what keeps a former owner from
1718    /// finalizing an address again on a node that had not yet heard it was
1719    /// final, such as one that joined the group since.
1720    ///
1721    /// A peer's word is not enough to refuse: a state summary is a claim
1722    /// anyone can make, and one dishonest peer could otherwise block every
1723    /// handover. A signed record is not a claim. Only the owner can sign a
1724    /// final state, so one that verifies is the owner's own proof that it
1725    /// finalized the pointer before.
1726    ///
1727    /// A proof is remembered, beside any other for the address, so the same
1728    /// loser is refused again without a question; a clear look is reused for
1729    /// the same state for [`FINAL_STATE_CLEAR_REUSE`]. Checks for one address
1730    /// wait their turn, so a burst of replays queued behind a look costs that
1731    /// one round, and at most [`FINAL_STATE_CHECK_STRIPES`] run at once; one
1732    /// that cannot start within [`FINAL_STATE_CHECK_WAIT`] answers `Busy`.
1733    /// Once started it is bounded by [`FINAL_STATE_CHECK_BUDGET`], and only
1734    /// peers that have sent a pointer message are asked. A group that cannot
1735    /// be asked in time finds nothing, and the write goes ahead on the merge
1736    /// rule alone: a race is a fork the client detects, not one this can
1737    /// prevent.
1738    pub async fn check_final(&self, state: &PointerState) -> FinalityCheck {
1739        self.finality
1740            .check(state, || self.find_conflicting_final(state))
1741            .await
1742    }
1743
1744    /// The body of [`Self::check_final`], without its bounds.
1745    async fn find_conflicting_final(&self, state: &PointerState) -> Option<Pointer> {
1746        let self_id = *self.p2p.peer_id();
1747        let address = state.address;
1748        let peers: Vec<PeerId> = self
1749            .p2p
1750            .dht_manager()
1751            .find_closest_nodes_local(&address, self.config.close_group_size)
1752            .await
1753            .into_iter()
1754            .map(|node| node.peer_id)
1755            .filter(|peer| *peer != self_id && self.is_capable(peer))
1756            .collect();
1757        first_proven_final(
1758            peers,
1759            state,
1760            |peer| async move { self.ask_state(&peer, &address).await },
1761            |peer| async move { self.fetch_record(&peer, &address).await },
1762        )
1763        .await
1764    }
1765
1766    /// Ask one peer which state it holds at `address`.
1767    async fn ask_state(&self, peer: &PeerId, address: &XorName) -> Option<PointerState> {
1768        let body = self
1769            .request(
1770                peer,
1771                ReplicationMessageBody::PointerStateRequest(PointerStateRequest {
1772                    addresses: vec![*address],
1773                }),
1774                FINAL_STATE_CHECK_BUDGET,
1775            )
1776            .await?;
1777        let ReplicationMessageBody::PointerStateResponse(response) = body else {
1778            return None;
1779        };
1780        // An answer about a different address is no answer.
1781        response
1782            .states
1783            .into_iter()
1784            .next()
1785            .flatten()
1786            .filter(|summary| summary.address == *address)
1787            .map(PointerState::from)
1788    }
1789
1790    // -----------------------------------------------------------------------
1791    // Possession
1792    // -----------------------------------------------------------------------
1793
1794    fn schedule_possession_check(self: &Arc<Self>, fresh: PointerState, peers: Vec<PeerId>) {
1795        if peers.is_empty() {
1796            return;
1797        }
1798        let min = self.config.possession_check_delay_min;
1799        let max = self.config.possession_check_delay_max.max(min);
1800        let delay = if max > min {
1801            rand::thread_rng().gen_range(min..=max)
1802        } else {
1803            min
1804        };
1805        let this = Arc::clone(self);
1806        self.tracker.spawn(async move {
1807            tokio::select! {
1808                () = this.shutdown.cancelled() => return,
1809                () = tokio::time::sleep(delay) => {}
1810            }
1811            this.check_possession(fresh, &peers).await;
1812        });
1813    }
1814
1815    /// Ask each peer for the record, and penalise any still responsible for it
1816    /// that cannot produce `fresh` or a state that replaces it.
1817    pub async fn check_possession(&self, fresh: PointerState, peers: &[PeerId]) {
1818        let self_id = *self.p2p.peer_id();
1819        for peer in peers {
1820            // A peer that has left the group owes nothing, and one that cannot
1821            // be asked is never judged on its silence.
1822            if *peer == self_id || !self.owes(peer, &fresh.address).await {
1823                continue;
1824            }
1825            let fetched = self
1826                .fetch_outcome(peer, &fresh.address, self.config.fetch_request_timeout)
1827                .await;
1828            match judge_possession(fetched, &fresh) {
1829                Possession::Missing => {}
1830                // Two different final states: the owner signed both and each
1831                // node kept the one it took first, as this one did. The peer
1832                // is holding what the merge rule told it to hold, so it is not
1833                // penalised for the owner's fork. Said loudly, because a read
1834                // of this pointer now depends on which side most of the group
1835                // is on.
1836                Possession::Forked(held) => {
1837                    warn!(
1838                        "Pointer {} is forked: peer {peer} holds final state {}, this node \
1839                         offered final state {}",
1840                        hex::encode(fresh.address),
1841                        hex::encode(held),
1842                        hex::encode(fresh.state_id)
1843                    );
1844                    continue;
1845                }
1846                Possession::Holds | Possession::NotJudged => continue,
1847            }
1848            // Asking can wait on this peer's other requests and on the peers
1849            // before it, and it may have left the group meanwhile. It is
1850            // judged on what it owes now, not on what it owed when this began.
1851            if !self.owes(peer, &fresh.address).await {
1852                continue;
1853            }
1854            warn!(
1855                "Peer {peer} does not hold pointer {} it was offered",
1856                hex::encode(fresh.address)
1857            );
1858            self.penalise(peer).await;
1859        }
1860    }
1861
1862    /// Whether `peer` is responsible for `address` in this node's view, and
1863    /// can be asked about it.
1864    async fn owes(&self, peer: &PeerId, address: &XorName) -> bool {
1865        self.is_capable(peer)
1866            && self
1867                .p2p
1868                .dht_manager()
1869                .find_closest_nodes_local_with_self(address, self.config.close_group_size)
1870                .await
1871                .iter()
1872                .any(|node| node.peer_id == *peer)
1873    }
1874
1875    // -----------------------------------------------------------------------
1876    // Pruning
1877    // -----------------------------------------------------------------------
1878
1879    /// Delete records this node has been out of range of for the hysteresis
1880    /// period, where that is safe. Run when a neighbour-sync cycle completes.
1881    ///
1882    /// `allow_remote` is false while bootstrapping: candidacy is still tracked,
1883    /// but nothing that needs other peers' proof is decided.
1884    ///
1885    /// Being out of range makes a record eligible, never due (ADR-0028): while
1886    /// `disk_pressure` reports room on the disk, every candidate is kept and no
1887    /// group is asked. Under pressure, candidates are tried farthest from this
1888    /// node first, those whose group failed to prove them in this spell last.
1889    ///
1890    /// A record a retained storage commitment still commits to is never
1891    /// deleted, exactly as for a chunk: an auditor pinning that commitment may
1892    /// still open it, and a node that deleted it would fail that audit.
1893    pub async fn prune_pass(
1894        &self,
1895        allow_remote: bool,
1896        disk_pressure: &DiskPressure,
1897        commitment_state: Option<&ResponderCommitmentState>,
1898    ) {
1899        // Replaced records kept for audits go when their retention does,
1900        // whether or not another update comes along to drop them.
1901        self.store.drop_expired_superseded();
1902        let committed = |address: &XorName| commitment_state.is_some_and(|cs| cs.is_held(address));
1903        let self_id = *self.p2p.peer_id();
1904        let retention = storage_admission_width(self.config.close_group_size);
1905        let now = SystemTime::now();
1906        let held = self.store.held_states();
1907
1908        let mut candidates = Vec::new();
1909        for state in &held {
1910            if admission::is_responsible(&self_id, &state.address, &self.p2p, retention).await {
1911                // Until bootstrap has drained the routing table may still be
1912                // filling, and a node that knows few peers looks in range for
1913                // everything. The clocks restored after a restart have to
1914                // survive that.
1915                if allow_remote {
1916                    self.out_of_range.clear(&state.address);
1917                }
1918                continue;
1919            }
1920            let first_seen = self.out_of_range.start(&state.address, now);
1921            if elapsed(first_seen, now) >= self.config.prune_hysteresis_duration
1922                && !committed(&state.address)
1923            {
1924                candidates.push(*state);
1925            }
1926        }
1927        {
1928            let held: HashSet<XorName> = held.iter().map(|state| state.address).collect();
1929            self.out_of_range.retain(|address| held.contains(address));
1930        }
1931        self.out_of_range.save().await;
1932
1933        // However far outside the group this node has moved, only the close
1934        // group's proof makes a copy safe to drop: distance says who is
1935        // closer, not that any of them holds the record.
1936        if !allow_remote || *self.is_bootstrapping.read().await || candidates.is_empty() {
1937            return;
1938        }
1939        if !disk_pressure.observe_store(&self.chunks) {
1940            debug!(
1941                "Keeping {} out-of-range pointer records: the disk has room",
1942                candidates.len()
1943            );
1944            return;
1945        }
1946        let batch = disk_pressure.erasure_order(
1947            RecordKind::Pointer,
1948            &self_id,
1949            candidates,
1950            MAX_PRUNE_CANDIDATES_PER_PASS,
1951            |state| state.address,
1952        );
1953        let deleted = stream::iter(batch)
1954            .map(|state| self.prune_candidate(state, &committed, disk_pressure))
1955            .buffer_unordered(PRUNE_CONCURRENCY)
1956            .filter(|deleted| std::future::ready(*deleted))
1957            .count()
1958            .await;
1959        if deleted > 0 {
1960            info!("Pruned {deleted} pointer records this node is no longer responsible for");
1961        }
1962    }
1963
1964    /// Delete `state`'s record if its close group proves it holds that state
1965    /// or a newer one, and this node is still out of range, uncommitted and
1966    /// under disk pressure once it has.
1967    ///
1968    /// Pressure is checked before the group is asked too: once earlier
1969    /// deletions have ended it, a proof could no longer lead to a deletion.
1970    async fn prune_candidate(
1971        &self,
1972        state: PointerState,
1973        committed: &(impl Fn(&XorName) -> bool + Sync),
1974        disk_pressure: &DiskPressure,
1975    ) -> bool {
1976        if self.shutdown.is_cancelled() || !disk_pressure.observe_store(&self.chunks) {
1977            return false;
1978        }
1979        if !self.others_hold(&state).await {
1980            disk_pressure.demote(RecordKind::Pointer, state.address);
1981            return false;
1982        }
1983        // Revalidate just before deleting: the group may have moved back, and
1984        // earlier deletions may have ended the pressure.
1985        let retention = storage_admission_width(self.config.close_group_size);
1986        !committed(&state.address)
1987            && !admission::is_responsible(self.p2p.peer_id(), &state.address, &self.p2p, retention)
1988                .await
1989            && disk_pressure.observe_store(&self.chunks)
1990            && self.delete(&state.address).await
1991    }
1992
1993    /// Whether all but one of the current close group prove they hold `ours`
1994    /// or a newer state, by returning a valid record within
1995    /// [`PRUNE_PROOF_BUDGET`].
1996    ///
1997    /// Only capable members are asked, so a group with too few of them is
1998    /// not asked at all and the record is kept.
1999    async fn others_hold(&self, ours: &PointerState) -> bool {
2000        let group: Vec<PeerId> = self
2001            .p2p
2002            .dht_manager()
2003            .find_closest_nodes_local(&ours.address, self.config.close_group_size)
2004            .await
2005            .into_iter()
2006            .map(|node| node.peer_id)
2007            .collect();
2008        let needed = prune_proofs_needed(group.len());
2009        let capable: Vec<PeerId> = group
2010            .into_iter()
2011            .filter(|peer| self.is_capable(peer))
2012            .collect();
2013        enough_prove(capable, needed, |peer| async move {
2014            self.fetch_record_within(&peer, &ours.address, PRUNE_PROOF_BUDGET)
2015                .await
2016                .is_some_and(|record| {
2017                    let state = record.state();
2018                    state.state_id == ours.state_id || state.replaces(ours)
2019                })
2020        })
2021        .await
2022    }
2023
2024    async fn delete(&self, address: &XorName) -> bool {
2025        self.out_of_range.clear(address);
2026        match self.store.delete(address).await {
2027            Ok(true) => {
2028                self.chunks.release(POINTER_WIRE_LEN as u64);
2029                true
2030            }
2031            Ok(false) => false,
2032            Err(e) => {
2033                warn!("Could not prune pointer {}: {e}", hex::encode(address));
2034                false
2035            }
2036        }
2037    }
2038}
2039
2040impl FinalStateWitness for PointerReplication {
2041    fn check_final<'a>(&'a self, state: &'a PointerState) -> BoxFuture<'a, FinalityCheck> {
2042        Box::pin(Self::check_final(self, state))
2043    }
2044
2045    fn proven_conflict(&self, state: &PointerState) -> Option<PointerState> {
2046        self.finality.proven_conflict(state)
2047    }
2048
2049    fn forget_clear(&self, state: &PointerState) {
2050        self.finality.forget_clear(state);
2051    }
2052}
2053
2054/// The first final state other than `state` that one of `peers` claims with
2055/// `ask` and then proves with `fetch`.
2056///
2057/// Each peer's question and fetch run as one pipeline, all of them at once,
2058/// and the first proof wins. A peer that claims a rival and then stalls its
2059/// fetch holds up nobody else's proof: were the fetches made one at a time
2060/// after the claims, that one peer would hold the check until its budget ran
2061/// out, and a finality check that runs out finds nothing.
2062async fn first_proven_final<Ask, AskFut, Fetch, FetchFut>(
2063    peers: Vec<PeerId>,
2064    state: &PointerState,
2065    ask: Ask,
2066    fetch: Fetch,
2067) -> Option<Pointer>
2068where
2069    Ask: Fn(PeerId) -> AskFut + Sync,
2070    AskFut: Future<Output = Option<PointerState>> + Send,
2071    Fetch: Fn(PeerId) -> FetchFut + Sync,
2072    FetchFut: Future<Output = Option<Pointer>> + Send,
2073{
2074    let rival = |held: &PointerState| held.is_terminal() && held.state_id != state.state_id;
2075    let (ask, fetch, rival) = (&ask, &fetch, &rival);
2076    let width = peers.len().max(1);
2077    let mut proofs = stream::iter(peers)
2078        .map(|peer| async move {
2079            let held = ask(peer).await?;
2080            if !rival(&held) {
2081                return None;
2082            }
2083            let record = fetch(peer).await?;
2084            // The record must be the state the peer claimed: a claim the
2085            // served record does not back is no proof, even if what it serves
2086            // is some other rival.
2087            (backs(&record, &held) && rival(&record.state())).then_some(record)
2088        })
2089        .buffer_unordered(width);
2090    while let Some(proof) = proofs.next().await {
2091        if proof.is_some() {
2092            return proof;
2093        }
2094    }
2095    None
2096}
2097
2098/// Whether at least `needed` of `peers` prove possession with `prove`.
2099///
2100/// Every peer is asked at once and every answer is awaited, so no request
2101/// outlives the check. A group too small to reach `needed` is never asked.
2102async fn enough_prove<Prove, ProveFut>(peers: Vec<PeerId>, needed: usize, prove: Prove) -> bool
2103where
2104    Prove: Fn(PeerId) -> ProveFut,
2105    ProveFut: Future<Output = bool>,
2106{
2107    if needed == 0 || peers.len() < needed {
2108        return false;
2109    }
2110    let proofs = join_all(peers.into_iter().map(prove)).await;
2111    proofs.into_iter().filter(|proves| *proves).count() >= needed
2112}
2113
2114#[cfg(test)]
2115#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2116mod tests {
2117    use super::*;
2118    use ant_protocol::pointer::{PointerTarget, PointerTargetKind, FINAL_COUNTER};
2119    use saorsa_pqc::api::sig::ml_dsa_65;
2120    use std::sync::atomic::{AtomicUsize, Ordering};
2121
2122    fn state(counter: u64, target: u8, id: u8) -> PointerState {
2123        PointerState {
2124            state_id: [id; 32],
2125            address: [7; 32],
2126            counter,
2127            target: PointerTarget::new(PointerTargetKind::Chunk, [target; 32]),
2128        }
2129    }
2130
2131    fn peer(byte: u8) -> PeerId {
2132        PeerId::from_bytes([byte; 32])
2133    }
2134
2135    fn answers(list: &[(u8, Option<PointerState>)]) -> Vec<(PeerId, Option<PointerState>)> {
2136        list.iter().map(|(p, s)| (peer(*p), *s)).collect()
2137    }
2138
2139    /// A peer's outbound permits are dropped only once nothing holds them, so
2140    /// a request in flight keeps the one set later requests share.
2141    fn record(counter: u64, target: u8) -> Pointer {
2142        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[3; 32]);
2143        let target = PointerTarget::new(PointerTargetKind::Chunk, [target; 32]);
2144        Pointer::sign(&sk, &pk, counter, target).expect("sign")
2145    }
2146
2147    #[tokio::test(start_paused = true)]
2148    async fn a_request_that_cannot_be_sent_in_time_is_given_up_not_queued() {
2149        let permits = Arc::new(Semaphore::new(1));
2150        let shutdown = CancellationToken::new();
2151        let held = acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
2152            .await
2153            .expect("a free permit is taken");
2154
2155        // Busy past the timeout: given up, not left waiting.
2156        assert!(
2157            acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
2158                .await
2159                .is_none()
2160        );
2161
2162        // Shutdown ends a wait at once, however long it could still run.
2163        shutdown.cancel();
2164        let waited = tokio::time::Instant::now();
2165        assert!(
2166            acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(3600), &shutdown)
2167                .await
2168                .is_none()
2169        );
2170        assert!(waited.elapsed() < Duration::from_secs(1));
2171        drop(held);
2172
2173        // With a permit free and shutdown already under way, nothing is sent,
2174        // every time.
2175        for _ in 0..64 {
2176            assert!(
2177                acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
2178                    .await
2179                    .is_none()
2180            );
2181        }
2182    }
2183
2184    #[test]
2185    fn a_possession_check_judges_each_answer_once() {
2186        let fresh = record(5, 1);
2187        let judge = |fetched| judge_possession(fetched, &fresh.state());
2188        assert_eq!(judge(Fetched::Record(fresh.clone())), Possession::Holds);
2189        assert_eq!(
2190            judge(Fetched::Record(record(6, 9))),
2191            Possession::Holds,
2192            "a newer state is as good"
2193        );
2194        assert_eq!(judge(Fetched::Record(record(4, 1))), Possession::Missing);
2195        assert_eq!(judge(Fetched::Nothing), Possession::Missing);
2196        // The fetch already charged the peer for an invalid record; charging
2197        // it again as missing would count one bad answer twice.
2198        assert_eq!(judge(Fetched::Invalid), Possession::NotJudged);
2199        // A failure on this node says nothing about the peer.
2200        assert_eq!(judge(Fetched::LocalFailure), Possession::NotJudged);
2201    }
2202
2203    #[test]
2204    fn a_peer_is_answered_with_hints_once_per_sync_interval() {
2205        let spacing = Duration::from_secs(600);
2206        let start = Instant::now();
2207        let mut answered = AnsweredSyncs::default();
2208        assert!(answered.admit(peer(1), start, spacing));
2209        assert!(
2210            !answered.admit(peer(1), start + Duration::from_secs(1), spacing),
2211            "a second request inside the interval gets no second scan"
2212        );
2213        assert!(
2214            answered.admit(peer(2), start, spacing),
2215            "other peers are not held up"
2216        );
2217        assert!(answered.admit(peer(1), start + spacing, spacing));
2218
2219        // A full map forgets the peer answered longest ago; a new peer is
2220        // never refused for it.
2221        let mut full = AnsweredSyncs::default();
2222        let mut first = None;
2223        for i in 0..MAX_ANSWERED_SYNC_PEERS {
2224            let id = u32::try_from(i).expect("fits");
2225            let mut bytes = [0u8; 32];
2226            if let Some(prefix) = bytes.get_mut(..4) {
2227                prefix.copy_from_slice(&id.to_be_bytes());
2228            }
2229            let at = start + Duration::from_millis(u64::from(id));
2230            let each = PeerId::from_bytes(bytes);
2231            first.get_or_insert(each);
2232            assert!(full.admit(each, at, spacing));
2233        }
2234        let late = start + Duration::from_secs(10);
2235        assert!(
2236            full.admit(peer(0xEE), late, spacing),
2237            "a new peer is answered"
2238        );
2239        assert_eq!(full.at.len(), MAX_ANSWERED_SYNC_PEERS);
2240        let first = first.expect("one was admitted");
2241        assert!(!full.at.contains_key(&first), "the oldest was forgotten");
2242    }
2243
2244    #[tokio::test]
2245    async fn outbound_permits_in_use_are_never_dropped() {
2246        let permits = Arc::new(Semaphore::new(MAX_REQUESTS_PER_PEER));
2247        assert!(outbound_idle(&permits));
2248        let held = Arc::clone(&permits)
2249            .acquire_owned()
2250            .await
2251            .expect("a permit");
2252        assert!(!outbound_idle(&permits), "a held permit keeps the set");
2253        drop(held);
2254        assert!(outbound_idle(&permits));
2255    }
2256
2257    /// A node that sees one member of the close group, as one still filling
2258    /// its routing table does, cannot adopt a state on that member's word: the
2259    /// members it cannot see count as unanswered.
2260    #[test]
2261    fn a_thin_view_of_the_group_cannot_adopt_on_one_vote() {
2262        let config = ReplicationConfig::default();
2263        let unpaid = state(9, 1, 90);
2264        let width = repair_width(1, config.close_group_size);
2265        let got = evaluate(
2266            None,
2267            width,
2268            &answers(&[(1, Some(unpaid))]),
2269            config.quorum_needed(width),
2270        );
2271        assert!(
2272            matches!(got, Verdict::Undecided),
2273            "one visible peer must not decide, got {got:?}"
2274        );
2275        assert_eq!(
2276            repair_width(9, config.close_group_size),
2277            9,
2278            "a view wider than the configured group is counted as it is"
2279        );
2280    }
2281
2282    #[test]
2283    fn a_state_a_quorum_holds_is_adopted_from_its_holders() {
2284        let newer = state(3, 1, 30);
2285        let got = evaluate(
2286            None,
2287            7,
2288            &answers(&[
2289                (1, Some(newer)),
2290                (2, Some(newer)),
2291                (3, Some(newer)),
2292                (4, Some(newer)),
2293                (5, None),
2294            ]),
2295            4,
2296        );
2297        match got {
2298            Verdict::Adopt { state, holders } => {
2299                assert_eq!(state.state_id, newer.state_id);
2300                assert_eq!(holders.len(), 4);
2301            }
2302            other => panic!("expected Adopt, got {other:?}"),
2303        }
2304    }
2305
2306    #[test]
2307    fn a_state_below_quorum_is_never_adopted() {
2308        // One peer, or three, holding a state is not the network's word.
2309        let lone = state(9, 1, 90);
2310        let got = evaluate(
2311            None,
2312            7,
2313            &answers(&[
2314                (1, Some(lone)),
2315                (2, Some(lone)),
2316                (3, Some(lone)),
2317                (4, None),
2318                (5, None),
2319                (6, None),
2320                (7, None),
2321            ]),
2322            4,
2323        );
2324        assert_eq!(got, Verdict::Refused);
2325
2326        // With one peer silent, three holders plus that peer could still make
2327        // four: undecided, not refused.
2328        let got = evaluate(
2329            None,
2330            7,
2331            &answers(&[
2332                (1, Some(lone)),
2333                (2, Some(lone)),
2334                (3, Some(lone)),
2335                (4, None),
2336                (5, None),
2337                (6, None),
2338            ]),
2339            4,
2340        );
2341        assert_eq!(got, Verdict::Undecided);
2342    }
2343
2344    #[test]
2345    fn silence_is_not_a_vote_so_an_unanswered_group_stays_undecided() {
2346        let newer = state(3, 1, 30);
2347        let got = evaluate(None, 7, &answers(&[(1, Some(newer)), (2, Some(newer))]), 4);
2348        assert_eq!(got, Verdict::Undecided);
2349    }
2350
2351    #[test]
2352    fn nothing_older_than_what_is_held_is_adopted() {
2353        let held = state(5, 1, 50);
2354        let older = state(4, 1, 40);
2355        let got = evaluate(
2356            Some(&held),
2357            7,
2358            &answers(&[
2359                (1, Some(older)),
2360                (2, Some(older)),
2361                (3, Some(older)),
2362                (4, Some(older)),
2363                (5, Some(older)),
2364            ]),
2365            4,
2366        );
2367        assert_eq!(got, Verdict::Refused);
2368    }
2369
2370    #[test]
2371    fn of_two_states_with_quorum_the_merge_winner_is_adopted() {
2372        let lower = state(2, 9, 20);
2373        let winner = state(2, 1, 21);
2374        assert!(winner.replaces(&lower));
2375        let got = evaluate(
2376            None,
2377            8,
2378            &answers(&[
2379                (1, Some(lower)),
2380                (2, Some(lower)),
2381                (3, Some(lower)),
2382                (4, Some(lower)),
2383                (5, Some(winner)),
2384                (6, Some(winner)),
2385                (7, Some(winner)),
2386                (8, Some(winner)),
2387            ]),
2388            4,
2389        );
2390        match got {
2391            Verdict::Adopt { state, .. } => assert_eq!(state.state_id, winner.state_id),
2392            other => panic!("expected the winner, got {other:?}"),
2393        }
2394    }
2395
2396    #[test]
2397    fn a_node_holding_a_final_state_adopts_nothing_else() {
2398        // Not even another final state the whole group holds: the merge rule
2399        // replaces a final state with nothing, and repair is the merge rule
2400        // applied to what the group says.
2401        let held = state(u64::MAX, 9, 90);
2402        let other = state(u64::MAX, 1, 91);
2403        let got = evaluate(
2404            Some(&held),
2405            7,
2406            &answers(&[
2407                (1, Some(other)),
2408                (2, Some(other)),
2409                (3, Some(other)),
2410                (4, Some(other)),
2411                (5, Some(other)),
2412            ]),
2413            4,
2414        );
2415        assert_eq!(got, Verdict::Refused);
2416    }
2417
2418    #[test]
2419    fn of_two_final_states_with_quorum_the_one_more_hold_is_adopted() {
2420        // Two final states are unordered, so only a group wide enough to back
2421        // both can get here. Arrival order must not pick; the larger side does.
2422        let fewer = state(u64::MAX, 1, 70);
2423        let more = state(u64::MAX, 9, 71);
2424        for order in [[fewer, more], [more, fewer]] {
2425            let mut list = Vec::new();
2426            let mut next = 1u8;
2427            for candidate in order {
2428                let holders = if candidate.state_id == more.state_id {
2429                    5
2430                } else {
2431                    4
2432                };
2433                for _ in 0..holders {
2434                    list.push((next, Some(candidate)));
2435                    next += 1;
2436                }
2437            }
2438            // Everyone answered, so the four cannot become five.
2439            match evaluate(None, 9, &answers(&list), 4) {
2440                Verdict::Adopt { state, holders } => {
2441                    assert_eq!(state.state_id, more.state_id);
2442                    assert_eq!(holders.len(), 5);
2443                }
2444                other => panic!("expected the larger side, got {other:?}"),
2445            }
2446        }
2447    }
2448
2449    #[test]
2450    fn a_silent_peer_that_could_tie_two_final_states_blocks_adoption() {
2451        // Eight peers, quorum four: four hold one final state, three another,
2452        // one is silent. The silent one could hold the second, making a tie,
2453        // so neither side is adopted, whichever answered first.
2454        let four = state(u64::MAX, 1, 90);
2455        let three = state(u64::MAX, 9, 91);
2456        for order in [[four, three], [three, four]] {
2457            let mut list = Vec::new();
2458            let mut next = 1u8;
2459            for candidate in order {
2460                let count = if candidate.state_id == four.state_id {
2461                    4
2462                } else {
2463                    3
2464                };
2465                for _ in 0..count {
2466                    list.push((next, Some(candidate)));
2467                    next += 1;
2468                }
2469            }
2470            assert_eq!(evaluate(None, 8, &answers(&list), 4), Verdict::Undecided);
2471        }
2472
2473        // A lone final state with quorum, and as many silent peers as hold
2474        // it, could meet an unseen rival: undecided too. One fewer silent
2475        // peer and it is adopted.
2476        let alone = state(u64::MAX, 5, 92);
2477        let held: Vec<(u8, Option<PointerState>)> = (1..=4).map(|p| (p, Some(alone))).collect();
2478        assert_eq!(evaluate(None, 8, &answers(&held), 4), Verdict::Undecided);
2479        assert!(matches!(
2480            evaluate(None, 7, &answers(&held), 4),
2481            Verdict::Adopt { .. }
2482        ));
2483    }
2484
2485    #[test]
2486    fn two_final_states_backed_equally_are_adopted_by_neither_order() {
2487        // A group of eight with a quorum of four can back two final states
2488        // four to four. Whichever answered first must not decide.
2489        let one = state(u64::MAX, 1, 80);
2490        let other = state(u64::MAX, 9, 81);
2491        for order in [[one, other], [other, one]] {
2492            let mut list = Vec::new();
2493            let mut next = 1u8;
2494            for candidate in order {
2495                for _ in 0..4 {
2496                    list.push((next, Some(candidate)));
2497                    next += 1;
2498                }
2499            }
2500            assert_eq!(evaluate(None, 8, &answers(&list), 4), Verdict::Undecided);
2501        }
2502    }
2503
2504    #[test]
2505    fn a_forged_summary_does_not_absorb_the_votes_for_a_final_state() {
2506        // One peer names final state A's identifier with a lower counter. It
2507        // must stand alone, not carry A's three honest votes as a non-final
2508        // state of four and so slip past the guard for final states.
2509        let a = state(u64::MAX, 1, 93);
2510        let forged = PointerState {
2511            counter: u64::MAX - 1,
2512            ..a
2513        };
2514        let b = state(u64::MAX, 9, 94);
2515        let mut list = vec![(1u8, Some(forged))];
2516        list.extend((2..=4).map(|p| (p, Some(a))));
2517        list.extend((5..=7).map(|p| (p, Some(b))));
2518        assert!(!matches!(
2519            evaluate(None, 8, &answers(&list), 4),
2520            Verdict::Adopt { .. }
2521        ));
2522    }
2523
2524    #[tokio::test]
2525    async fn a_claim_that_names_a_rival_with_another_target_proves_nothing() {
2526        // The claim reuses a real rival's identifier with some other target;
2527        // the peer then serves the real rival. The record is not what was
2528        // claimed, so it is no proof.
2529        let taking = final_record(18, 0x01);
2530        let rival = final_record(18, 0xAA);
2531        let mut claim = rival.state();
2532        claim.target = PointerTarget::new(PointerTargetKind::Chunk, [0xCC; 32]);
2533        let found = first_proven_final(
2534            vec![peer(1)],
2535            &taking.state(),
2536            |_| async move { Some(claim) },
2537            |_| {
2538                let record = rival.clone();
2539                async move { Some(record) }
2540            },
2541        )
2542        .await;
2543        assert!(found.is_none());
2544    }
2545
2546    #[test]
2547    fn a_record_backs_only_the_whole_state_a_quorum_named() {
2548        let record = final_record(17, 0x01);
2549        assert!(backs(&record, &record.state()));
2550        let forged = PointerState {
2551            counter: 7,
2552            ..record.state()
2553        };
2554        assert!(
2555            !backs(&record, &forged),
2556            "a summary pairing the record's identifier with another counter is not backed"
2557        );
2558    }
2559
2560    #[test]
2561    fn a_summary_for_another_address_is_no_answer_at_all() {
2562        let (a, b, c) = ([1u8; 32], [2u8; 32], [3u8; 32]);
2563        let mut elsewhere = state(3, 1, 95);
2564        elsewhere.address = [9u8; 32];
2565        let mut here = state(3, 1, 96);
2566        here.address = c;
2567        let read = read_state_answers(
2568            peer(1),
2569            &[a, b, c],
2570            vec![None, Some(elsewhere.into()), Some(here.into())],
2571        );
2572        assert_eq!(read, vec![((peer(1), a), None), ((peer(1), c), Some(here))]);
2573    }
2574
2575    #[test]
2576    fn a_group_nobody_can_be_asked_in_is_undecided() {
2577        assert_eq!(evaluate(None, 0, &[], 0), Verdict::Undecided);
2578    }
2579
2580    fn final_record(seed: u8, target: u8) -> Pointer {
2581        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[seed; 32]);
2582        let target = PointerTarget::new(PointerTargetKind::Pointer, [target; 32]);
2583        Pointer::sign(&sk, &pk, FINAL_COUNTER, target).expect("sign")
2584    }
2585
2586    #[tokio::test(start_paused = true)]
2587    async fn a_claimant_that_stalls_its_fetch_does_not_hide_a_rival_another_peer_proves() {
2588        // One peer claims a rival final state first and then never serves
2589        // it; an honest peer claims the same rival a moment later and serves
2590        // it at once. The honest proof must land inside the budget.
2591        let taking = final_record(9, 0x01);
2592        let rival = final_record(9, 0xAA);
2593        let (staller, honest) = (peer(1), peer(2));
2594        let found = tokio::time::timeout(
2595            FINAL_STATE_CHECK_BUDGET,
2596            first_proven_final(
2597                vec![staller, honest],
2598                &taking.state(),
2599                |asked| {
2600                    let claim = rival.state();
2601                    async move {
2602                        if asked == honest {
2603                            tokio::time::sleep(Duration::from_millis(100)).await;
2604                        }
2605                        Some(claim)
2606                    }
2607                },
2608                |asked| {
2609                    let record = rival.clone();
2610                    async move {
2611                        if asked == staller {
2612                            std::future::pending::<()>().await;
2613                        }
2614                        Some(record)
2615                    }
2616                },
2617            ),
2618        )
2619        .await;
2620        assert_eq!(
2621            found.ok().flatten().map(|record| record.state_id()),
2622            Some(rival.state_id()),
2623            "the honest peer's proof was hidden behind the stalled fetch"
2624        );
2625    }
2626
2627    #[tokio::test]
2628    async fn only_a_different_final_state_that_is_served_is_a_proof() {
2629        let taking = final_record(10, 0x01);
2630        let rival = final_record(10, 0xAA);
2631        let (same, unbacked, open) = (peer(1), peer(2), peer(3));
2632        let found = first_proven_final(
2633            vec![same, unbacked, open],
2634            &taking.state(),
2635            |asked| {
2636                let claim = if asked == same {
2637                    taking.state()
2638                } else if asked == unbacked {
2639                    rival.state()
2640                } else {
2641                    state(3, 1, 1)
2642                };
2643                async move { Some(claim) }
2644            },
2645            // The peer claiming a rival serves the state being taken instead.
2646            |_| {
2647                let record = taking.clone();
2648                async move { Some(record) }
2649            },
2650        )
2651        .await;
2652        assert!(
2653            found.is_none(),
2654            "a claim the record does not back is no proof"
2655        );
2656    }
2657
2658    #[tokio::test]
2659    async fn a_peer_that_serves_a_different_rival_than_it_claimed_proves_nothing() {
2660        let taking = final_record(16, 0x01);
2661        let claimed = final_record(16, 0xAA);
2662        let served = final_record(16, 0xBB);
2663        let found = first_proven_final(
2664            vec![peer(1)],
2665            &taking.state(),
2666            |_| {
2667                let claim = claimed.state();
2668                async move { Some(claim) }
2669            },
2670            |_| {
2671                let record = served.clone();
2672                async move { Some(record) }
2673            },
2674        )
2675        .await;
2676        assert!(found.is_none());
2677    }
2678
2679    #[test]
2680    fn a_proven_final_state_refuses_others_and_forgets_the_oldest_past_the_cap() {
2681        let mut proven = ProvenFinals::default();
2682        let held = final_record(11, 0xAA).state();
2683        let other = final_record(11, 0x01).state();
2684        proven.remember(held);
2685        assert_eq!(proven.conflict(&other), Some(held));
2686        assert_eq!(
2687            proven.conflict(&held),
2688            None,
2689            "a proof is no conflict with itself"
2690        );
2691
2692        for i in 0..MAX_PROVEN_FINALS {
2693            let mut filler = held;
2694            filler.address = [0; 32];
2695            if let Some(slot) = filler.address.get_mut(..8) {
2696                slot.copy_from_slice(&(i as u64 + 1).to_be_bytes());
2697            }
2698            proven.remember(filler);
2699        }
2700        assert_eq!(proven.by_address.len(), MAX_PROVEN_FINALS);
2701        assert_eq!(proven.order.len(), MAX_PROVEN_FINALS);
2702        assert_eq!(
2703            proven.conflict(&other),
2704            None,
2705            "the oldest proof is forgotten first"
2706        );
2707    }
2708
2709    #[test]
2710    fn a_second_proof_never_replaces_the_first() {
2711        // Both sides of a fork proven at one address: each is refused by the
2712        // other, so a later look that proved the other side cannot let back
2713        // in the state the first look disproved.
2714        let mut proven = ProvenFinals::default();
2715        let a = final_record(12, 0xAA).state();
2716        let b = final_record(12, 0xBB).state();
2717        let c = final_record(12, 0xCC).state();
2718        proven.remember(a);
2719        proven.remember(b);
2720        proven.remember(c);
2721        assert_eq!(proven.conflict(&b), Some(a));
2722        assert_eq!(proven.conflict(&a), Some(b));
2723        assert!(proven.conflict(&c).is_some(), "a third is refused by both");
2724        assert_eq!(
2725            proven.by_address.get(&a.address).map(Vec::len),
2726            Some(MAX_PROOFS_PER_ADDRESS)
2727        );
2728    }
2729
2730    #[tokio::test(start_paused = true)]
2731    async fn looks_for_addresses_sharing_leading_bits_run_side_by_side() {
2732        // The addresses a node is responsible for share their leading bits.
2733        // Two such looks, each longer than a check waits for its turn, must
2734        // both run rather than one wait and come back Busy.
2735        let looks = FinalityLooks::new();
2736        let mut first = final_record(14, 0x01).state();
2737        let mut second = final_record(15, 0x01).state();
2738        first.address = [0xAB; 32];
2739        second.address = [0xAB; 32];
2740        if let Some(last) = second.address.last_mut() {
2741            *last = 0xAC;
2742        }
2743        let slow = || async {
2744            tokio::time::sleep(FINAL_STATE_CHECK_WAIT + Duration::from_secs(1)).await;
2745            None
2746        };
2747        let (a, b) = tokio::join!(looks.check(&first, slow), looks.check(&second, slow));
2748        assert_eq!(a, FinalityCheck::Clear);
2749        assert_eq!(b, FinalityCheck::Clear, "the second look was held up");
2750    }
2751
2752    #[tokio::test(start_paused = true)]
2753    async fn replays_queued_behind_a_look_reuse_its_answer() {
2754        let looks = FinalityLooks::new();
2755        let taking = final_record(13, 0x01);
2756        let asked = AtomicUsize::new(0);
2757        let look = || {
2758            asked.fetch_add(1, Ordering::SeqCst);
2759            async {
2760                tokio::time::sleep(Duration::from_millis(500)).await;
2761                None
2762            }
2763        };
2764        let state = taking.state();
2765        let checks = (0..8).map(|_| looks.check(&state, look));
2766        let answers = futures::future::join_all(checks).await;
2767        assert!(answers.iter().all(|answer| *answer == FinalityCheck::Clear));
2768        assert_eq!(asked.load(Ordering::SeqCst), 1, "eight replays, one look");
2769
2770        // Past the reuse window the group is asked again.
2771        tokio::time::sleep(FINAL_STATE_CLEAR_REUSE).await;
2772        assert_eq!(looks.check(&state, look).await, FinalityCheck::Clear);
2773        assert_eq!(asked.load(Ordering::SeqCst), 2);
2774
2775        // A proof answers every replay of the loser without a look.
2776        let loser = final_record(13, 0x02).state();
2777        let rival = final_record(13, 0xAA);
2778        let proved = looks.check(&loser, || async { Some(rival.clone()) }).await;
2779        assert_eq!(proved, FinalityCheck::Conflict(rival.state()));
2780        assert_eq!(
2781            looks.check(&loser, look).await,
2782            FinalityCheck::Conflict(rival.state())
2783        );
2784        assert_eq!(asked.load(Ordering::SeqCst), 2);
2785    }
2786
2787    #[tokio::test]
2788    async fn all_but_one_of_the_group_must_prove() {
2789        let group: Vec<PeerId> = (1..=7).map(peer).collect();
2790        let one_missing = peer(1);
2791        let two_missing = [peer(1), peer(2)];
2792
2793        let proven = enough_prove(group.clone(), prune_proofs_needed(7), |asked| async move {
2794            asked != one_missing
2795        })
2796        .await;
2797        assert!(proven, "six of seven prove");
2798
2799        let proven = enough_prove(group, prune_proofs_needed(7), |asked| async move {
2800            !two_missing.contains(&asked)
2801        })
2802        .await;
2803        assert!(!proven, "five of seven fall short");
2804    }
2805
2806    #[tokio::test]
2807    async fn a_group_too_small_to_reach_the_threshold_is_never_asked() {
2808        // Five capable members of a seven-member group cannot give six proofs.
2809        let asked = AtomicUsize::new(0);
2810        let capable: Vec<PeerId> = (1..=5).map(peer).collect();
2811        let proven = enough_prove(capable, prune_proofs_needed(7), |_| {
2812            asked.fetch_add(1, Ordering::SeqCst);
2813            async { true }
2814        })
2815        .await;
2816        assert!(!proven);
2817        assert_eq!(asked.load(Ordering::SeqCst), 0, "a lost cause was asked");
2818    }
2819}