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