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.
28//!
29//! Requests go only to peers that have sent a pointer message themselves (see
30//! [`PointerReplication::is_capable`]). A peer built before pointers cannot
31//! decode them, and saorsa-core counts an unanswered request against the peer
32//! it was sent to; asking only capable peers keeps older peers out of it. Every
33//! neighbour-sync round pushes hints, empty or not, so capability is learned
34//! within a cycle.
35
36use std::collections::{HashMap, HashSet};
37use std::sync::Arc;
38use std::time::{Duration, Instant};
39
40use ant_protocol::pointer::{Pointer, PointerState, POINTER_WIRE_LEN};
41use futures::stream::{self, StreamExt};
42use parking_lot::Mutex;
43use rand::Rng;
44use saorsa_core::identity::PeerId;
45use saorsa_core::{P2PNode, TrustEvent};
46use tokio::sync::{mpsc, OwnedSemaphorePermit, RwLock, Semaphore};
47use tokio::task::{spawn_blocking, JoinHandle};
48use tokio_util::sync::CancellationToken;
49use tokio_util::task::TaskTracker;
50
51use crate::ant_protocol::XorName;
52use crate::logging::{debug, info, warn};
53use crate::payment::{
54    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
55    MIN_PAYMENT_PROOF_SIZE_BYTES,
56};
57use crate::pointer::store::{Inspected, PointerStore};
58use crate::replication::admission;
59use crate::replication::commitment_state::ResponderCommitmentState;
60use crate::replication::config::{
61    storage_admission_width, ReplicationConfig, FRESH_REPLICATION_DELIVERY_MAX_RETRIES,
62    REPLICATION_PROTOCOL_ID,
63};
64use crate::replication::protocol::{
65    PointerFetchRequest, PointerFetchResponse, PointerFreshOffer, PointerHints,
66    PointerStateRequest, PointerStateResponse, PointerStateSummary, ReplicationMessage,
67    ReplicationMessageBody, MAX_POINTER_HINTS_PER_MESSAGE, MAX_POINTER_STATE_REQUEST_ADDRESSES,
68};
69use crate::replication::pruning::prune_proofs_needed;
70use crate::storage::{CapacityVerdict, ChunkStore};
71
72use super::REPLICATION_TRUST_WEIGHT;
73
74/// Inbound fresh offers verified at once. An offer costs a signature check and
75/// an on-chain payment lookup, so a flood is dropped rather than queued; one
76/// that is dropped is repaired by the next neighbour-sync round.
77const MAX_CONCURRENT_OFFERS: usize = 16;
78
79/// Fetch and state requests served at once.
80const MAX_CONCURRENT_SERVES: usize = 32;
81
82/// Fetch and state requests admitted at once, served or waiting to be. Past
83/// it a request is dropped at admission rather than queued, as a chunk fetch
84/// is, so a flood costs a bounded number of tasks.
85const MAX_SERVES_OUTSTANDING: usize = MAX_CONCURRENT_SERVES * 4;
86
87/// Of those, how many one peer may have: twice the [`MAX_REQUESTS_PER_PEER`]
88/// an honest node lets itself have outstanding at any one peer, so its
89/// requests are never dropped, even those arriving before the reply to the
90/// last has released its place here, while one flooding peer cannot take the
91/// room every other peer's requests need.
92const MAX_SERVES_OUTSTANDING_PER_PEER: u32 = 16;
93
94/// Pointer requests this node has outstanding at any one peer, across repair,
95/// possession checks and pruning together. As many as a repair asks at once,
96/// so repair is not slowed; the rest wait their turn rather than go out and
97/// be dropped by the peer's per-peer allowance, which would make an honest
98/// peer look as though it had not answered.
99const MAX_REQUESTS_PER_PEER: usize = VERIFICATION_CONCURRENCY;
100
101// An honest node's requests to one peer, repair included, never exceed what
102// that peer admits from it, with room for a reply still releasing its place.
103const _: () = assert!(
104    MAX_SERVES_OUTSTANDING_PER_PEER as usize >= 2 * MAX_REQUESTS_PER_PEER,
105    "a peer's serve allowance must cover what an honest node asks of it"
106);
107
108/// Most peers remembered as speaking pointers. Only routed peers are, and a
109/// routing table removal forgets one, so this only bounds what removals missed
110/// (a lagging event stream) could leave behind. Capability forgotten this way
111/// is learned again from the peer's next hint push.
112const MAX_CAPABLE_PEERS: usize = 4096;
113
114/// Most hint pushes answering peers' sync requests at once. Each scans every
115/// pointer this node holds, so a peer's sync request that finds them all
116/// running gets no hints this time, and the next sync round delivers them.
117const MAX_CONCURRENT_SYNC_ANSWERS: usize = 8;
118
119/// Most peers remembered as having been answered with hints. Only routing-table
120/// peers are answered, so this only bounds what a lagging table could leave
121/// behind; past it the peer answered longest ago is forgotten, never a new one
122/// refused.
123const MAX_ANSWERED_SYNC_PEERS: usize = 4096;
124
125/// How often the pending hints are looked at.
126const VERIFICATION_TICK: Duration = Duration::from_millis(500);
127
128/// Most addresses awaiting verification at once, so a hint flood cannot grow
129/// memory without bound. A hint dropped here comes back next round.
130const MAX_PENDING: usize = 65_536;
131
132/// Most addresses verified per tick.
133const MAX_VERIFICATIONS_PER_TICK: usize = 256;
134
135/// Verifications and fetches in flight at once within a tick.
136const VERIFICATION_CONCURRENCY: usize = 8;
137
138/// Undecided rounds an address gets before it is dropped. It comes back with
139/// the next hint.
140const MAX_UNDECIDED_ROUNDS: u32 = 5;
141
142/// Wait before retrying an undecided address, doubled each round.
143const UNDECIDED_BACKOFF: Duration = Duration::from_secs(30);
144
145/// Most prune candidates examined per pass.
146const MAX_PRUNE_CANDIDATES_PER_PASS: usize = 256;
147
148/// One peer's answer about one address: the state it holds there, if any.
149type StateAnswer = ((PeerId, XorName), Option<PointerState>);
150
151/// A pointer state this node accepted from a paying client, to be offered to
152/// the rest of its close group.
153pub struct PointerFreshWrite {
154    /// The record, in its canonical encoding.
155    pub record: Vec<u8>,
156    /// The proof that paid for its state.
157    pub payment_proof: Vec<u8>,
158}
159
160/// A state this node was told about and has not yet verified.
161#[derive(Debug, Clone)]
162struct Pending {
163    /// The best state hinted so far.
164    wanted: PointerState,
165    /// Undecided rounds so far.
166    attempts: u32,
167    /// Not to be looked at again before this.
168    not_before: Instant,
169}
170
171/// What a verification round decided for one address.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub(crate) enum Verdict {
174    /// A quorum of the close group hold this state and it beats what is held
175    /// here: fetch it from one of `holders`.
176    Adopt {
177        /// The state to fetch.
178        state: PointerState,
179        /// The peers that said they hold exactly it.
180        holders: Vec<PeerId>,
181    },
182    /// Nothing reached quorum, but the peers that did not answer could still
183    /// make one. Ask again later.
184    Undecided,
185    /// No state that beats what is held can reach quorum.
186    Refused,
187}
188
189/// Decide what a round of answers supports.
190///
191/// `group_size` is the whole close group this node would ask, capable or not:
192/// a peer that cannot be asked counts as unanswered, not as a vote. The quorum
193/// is therefore the one a chunk would need, and a network where few peers
194/// understand pointers yet cannot repair on the word of those few.
195pub(crate) fn evaluate(
196    held: Option<&PointerState>,
197    group_size: usize,
198    answers: &[(PeerId, Option<PointerState>)],
199    quorum_needed: usize,
200) -> Verdict {
201    if group_size == 0 || quorum_needed == 0 {
202        return Verdict::Undecided;
203    }
204    let mut by_state: Vec<(PointerState, Vec<PeerId>)> = Vec::new();
205    for (peer, answer) in answers {
206        let Some(state) = answer else { continue };
207        match by_state
208            .iter_mut()
209            .find(|(known, _)| known.state_id == state.state_id)
210        {
211            Some((_, holders)) => holders.push(*peer),
212            None => by_state.push((*state, vec![*peer])),
213        }
214    }
215    let beats_held = |state: &PointerState| held.is_none_or(|held| state.replaces(held));
216
217    let best = by_state
218        .iter()
219        .filter(|(state, holders)| holders.len() >= quorum_needed && beats_held(state))
220        .fold(
221            None::<&(PointerState, Vec<PeerId>)>,
222            |best, candidate| match best {
223                Some(current) if !candidate.0.replaces(&current.0) => Some(current),
224                _ => Some(candidate),
225            },
226        );
227    if let Some((state, holders)) = best {
228        return Verdict::Adopt {
229            state: *state,
230            holders: holders.clone(),
231        };
232    }
233
234    let unanswered = group_size.saturating_sub(answers.len());
235    let largest = by_state
236        .iter()
237        .filter(|(state, _)| beats_held(state))
238        .map(|(_, holders)| holders.len())
239        .max()
240        .unwrap_or(0);
241    if largest.saturating_add(unanswered) >= quorum_needed {
242        Verdict::Undecided
243    } else {
244        Verdict::Refused
245    }
246}
247
248/// What asking a peer for a pointer record came to.
249enum Fetched {
250    /// A record that verifies and belongs at the address.
251    Record(Pointer),
252    /// A record that does not, which the peer has already been penalised for.
253    Invalid,
254    /// No record: no answer, an empty one, or one about another address.
255    Nothing,
256    /// A record this node could not check, or a request it never sent, for a
257    /// reason of its own.
258    LocalFailure,
259}
260
261/// What asking a peer came to (see [`PointerReplication::ask`]).
262enum Asked {
263    /// The peer's answer.
264    Answered(ReplicationMessageBody),
265    /// Sent, and no usable answer came back.
266    Silent,
267    /// Never sent: this node is shutting down, or its own requests to the
268    /// peer stayed busy for the whole timeout.
269    NotSent,
270}
271
272/// One of `permits`, if one comes free within `timeout` and before
273/// `shutdown`. Shutdown wins when both are ready at once.
274async fn acquire_or_give_up(
275    permits: Arc<Semaphore>,
276    timeout: Duration,
277    shutdown: &CancellationToken,
278) -> Option<OwnedSemaphorePermit> {
279    let permit = tokio::select! {
280        biased;
281        () = shutdown.cancelled() => None,
282        permit = tokio::time::timeout(timeout, permits.acquire_owned()) => permit.ok()?.ok(),
283    }?;
284    (!shutdown.is_cancelled()).then_some(permit)
285}
286
287/// What a possession check makes of one peer's answer about `fresh`.
288#[derive(Debug, PartialEq, Eq)]
289enum Possession {
290    /// The peer served `fresh` or a state that replaces it.
291    Holds,
292    /// The peer could not produce `fresh` or anything newer.
293    Missing,
294    /// Nothing to judge the peer on: it served a record that does not verify,
295    /// which the fetch has already charged it for, or this node could not
296    /// check what it served.
297    NotJudged,
298}
299
300/// Judge one peer's answer in a possession check for `fresh`.
301fn judge_possession(fetched: Fetched, fresh: &PointerState) -> Possession {
302    match fetched {
303        Fetched::Record(record) => {
304            let state = record.state();
305            if state.state_id == fresh.state_id || state.replaces(fresh) {
306                Possession::Holds
307            } else {
308                Possession::Missing
309            }
310        }
311        Fetched::Nothing => Possession::Missing,
312        Fetched::Invalid | Fetched::LocalFailure => Possession::NotJudged,
313    }
314}
315
316/// Whether nothing but the map holds a peer's outbound permits.
317///
318/// Every holder, a request waiting for a permit or one holding it, has a
319/// clone, and clones are only made under the map's lock. So an entry nothing
320/// else holds can be dropped without a later request getting a second set of
321/// permits beside one still in use, which would let this node exceed
322/// [`MAX_REQUESTS_PER_PEER`] at that peer.
323fn outbound_idle(permits: &Arc<Semaphore>) -> bool {
324    Arc::strong_count(permits) == 1
325}
326
327/// How many members a repair counts its quorum over: the whole close group,
328/// however few of them this node can see (ADR-0016). A member it cannot see is
329/// unanswered, so a thin routing table leaves a repair undecided instead of
330/// shrinking the quorum to what little it can see.
331fn repair_width(seen: usize, close_group_size: usize) -> usize {
332    seen.max(close_group_size)
333}
334
335/// Pointer replication for one node. See the module documentation.
336pub struct PointerReplication {
337    store: PointerStore,
338    chunks: Arc<ChunkStore>,
339    p2p: Arc<P2PNode>,
340    payments: Arc<PaymentVerifier>,
341    config: Arc<ReplicationConfig>,
342    is_bootstrapping: Arc<RwLock<bool>>,
343    /// Outbound record transfers, shared with chunk replication.
344    send_semaphore: Arc<Semaphore>,
345    offer_permits: Arc<Semaphore>,
346    serve_permits: Arc<Semaphore>,
347    /// Admission ahead of `serve_permits`: see [`MAX_SERVES_OUTSTANDING`].
348    serve_admission: Arc<Semaphore>,
349    /// Requests each peer has admitted and not yet had answered.
350    serve_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
351    /// This node's own requests outstanding at each peer (see
352    /// [`MAX_REQUESTS_PER_PEER`]).
353    outbound: Mutex<HashMap<PeerId, Arc<Semaphore>>>,
354    /// Peers that have sent a pointer message: the only ones asked anything.
355    capable: Mutex<HashSet<PeerId>>,
356    /// Hinted states awaiting verification, by address.
357    pending: Mutex<HashMap<XorName, Pending>>,
358    /// When each held address was first seen continuously out of range.
359    out_of_range: Mutex<HashMap<XorName, Instant>>,
360    /// Hint pushes answering sync requests that may run at once.
361    sync_answers: Arc<Semaphore>,
362    /// When each peer was last answered with hints.
363    answered_syncs: Mutex<AnsweredSyncs>,
364    shutdown: CancellationToken,
365    tracker: TaskTracker,
366}
367
368/// When each peer was last sent hints in answer to its own sync request.
369#[derive(Default)]
370struct AnsweredSyncs {
371    at: HashMap<PeerId, Instant>,
372}
373
374impl AnsweredSyncs {
375    /// Whether `peer` may be answered at `now`, and if so note it: not if it
376    /// was answered less than `spacing` ago. A full map forgets the peers
377    /// answered longest ago rather than refuse anyone new.
378    fn admit(&mut self, peer: PeerId, now: Instant, spacing: Duration) -> bool {
379        let recent = |at: &Instant| now.saturating_duration_since(*at) < spacing;
380        if self.at.get(&peer).is_some_and(recent) {
381            return false;
382        }
383        if self.at.len() >= MAX_ANSWERED_SYNC_PEERS && !self.at.contains_key(&peer) {
384            self.at.retain(|_, at| recent(at));
385        }
386        if self.at.len() >= MAX_ANSWERED_SYNC_PEERS && !self.at.contains_key(&peer) {
387            let oldest = self
388                .at
389                .iter()
390                .min_by_key(|(_, at)| **at)
391                .map(|(peer, _)| *peer);
392            if let Some(oldest) = oldest {
393                self.at.remove(&oldest);
394            }
395        }
396        self.at.insert(peer, now);
397        true
398    }
399}
400
401impl PointerReplication {
402    /// Pointer replication over `store`, sharing the engine's resources.
403    #[allow(clippy::too_many_arguments)]
404    pub(crate) fn new(
405        store: PointerStore,
406        chunks: Arc<ChunkStore>,
407        p2p: Arc<P2PNode>,
408        payments: Arc<PaymentVerifier>,
409        config: Arc<ReplicationConfig>,
410        is_bootstrapping: Arc<RwLock<bool>>,
411        send_semaphore: Arc<Semaphore>,
412        shutdown: CancellationToken,
413        tracker: TaskTracker,
414    ) -> Self {
415        Self {
416            store,
417            chunks,
418            p2p,
419            payments,
420            config,
421            is_bootstrapping,
422            send_semaphore,
423            offer_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_OFFERS)),
424            serve_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_SERVES)),
425            serve_admission: Arc::new(Semaphore::new(MAX_SERVES_OUTSTANDING)),
426            serve_inflight: Arc::new(RwLock::new(HashMap::new())),
427            outbound: Mutex::new(HashMap::new()),
428            capable: Mutex::new(HashSet::new()),
429            pending: Mutex::new(HashMap::new()),
430            out_of_range: Mutex::new(HashMap::new()),
431            sync_answers: Arc::new(Semaphore::new(MAX_CONCURRENT_SYNC_ANSWERS)),
432            answered_syncs: Mutex::new(AnsweredSyncs::default()),
433            shutdown,
434            tracker,
435        }
436    }
437
438    /// The pointer store this replication serves from.
439    pub(crate) fn store(&self) -> &PointerStore {
440        &self.store
441    }
442
443    // -----------------------------------------------------------------------
444    // Capability
445    // -----------------------------------------------------------------------
446
447    /// Remember that `peer` speaks pointers, if it is in the routing table.
448    ///
449    /// Only a routed peer is remembered: it is the only kind this node ever
450    /// asks, and the routing table's removals are what forget it again, so the
451    /// set cannot outgrow the table however many identities send a message.
452    async fn mark_capable(&self, peer: &PeerId) {
453        if !self.p2p.dht_manager().is_in_routing_table(peer).await {
454            return;
455        }
456        let mut capable = self.capable.lock();
457        if capable.len() >= MAX_CAPABLE_PEERS && !capable.contains(peer) {
458            if let Some(evicted) = capable.iter().next().copied() {
459                capable.remove(&evicted);
460            }
461        }
462        capable.insert(*peer);
463    }
464
465    /// Whether `peer` has sent a pointer message, and may therefore be asked.
466    pub fn is_capable(&self, peer: &PeerId) -> bool {
467        self.capable.lock().contains(peer)
468    }
469
470    /// Forget a peer that left the routing table.
471    pub(crate) fn forget_peer(&self, peer: &PeerId) {
472        self.capable.lock().remove(peer);
473        let mut outbound = self.outbound.lock();
474        if outbound.get(peer).is_some_and(outbound_idle) {
475            outbound.remove(peer);
476        }
477    }
478
479    /// The permits bounding this node's requests to `peer`.
480    fn outbound_permits(&self, peer: &PeerId) -> Arc<Semaphore> {
481        let mut outbound = self.outbound.lock();
482        if outbound.len() >= MAX_CAPABLE_PEERS && !outbound.contains_key(peer) {
483            // Peers nothing is outstanding at hold no state worth keeping.
484            outbound.retain(|_, permits| !outbound_idle(permits));
485        }
486        Arc::clone(
487            outbound
488                .entry(*peer)
489                .or_insert_with(|| Arc::new(Semaphore::new(MAX_REQUESTS_PER_PEER))),
490        )
491    }
492
493    /// Addresses currently awaiting verification. Tests only.
494    #[cfg(any(test, feature = "test-utils"))]
495    #[must_use]
496    pub fn pending_len(&self) -> usize {
497        self.pending.lock().len()
498    }
499
500    // -----------------------------------------------------------------------
501    // Messaging
502    // -----------------------------------------------------------------------
503
504    async fn send_one_way(&self, peer: &PeerId, body: ReplicationMessageBody) -> bool {
505        let msg = ReplicationMessage {
506            request_id: rand::thread_rng().gen::<u64>(),
507            body,
508        };
509        let Ok(bytes) = msg.encode() else {
510            warn!("Failed to encode a pointer replication message");
511            return false;
512        };
513        self.p2p
514            .send_message(peer, REPLICATION_PROTOCOL_ID, bytes, &[])
515            .await
516            .is_ok()
517    }
518
519    async fn request(
520        &self,
521        peer: &PeerId,
522        body: ReplicationMessageBody,
523        timeout: Duration,
524    ) -> Option<ReplicationMessageBody> {
525        match self.ask(peer, body, timeout).await {
526            Asked::Answered(body) => Some(body),
527            Asked::Silent | Asked::NotSent => None,
528        }
529    }
530
531    /// Ask `peer`, saying whether a missing answer was the peer's silence or
532    /// this node never sending the request at all.
533    ///
534    /// The request waits for one of this node's own permits for `peer` first,
535    /// but no longer than `timeout` and not past shutdown: a request that
536    /// could not be sent in that time is dropped as not sent, never left
537    /// waiting, and never held against the peer.
538    async fn ask(&self, peer: &PeerId, body: ReplicationMessageBody, timeout: Duration) -> Asked {
539        let Some(_permit) =
540            acquire_or_give_up(self.outbound_permits(peer), timeout, &self.shutdown).await
541        else {
542            return Asked::NotSent;
543        };
544        let msg = ReplicationMessage {
545            request_id: rand::thread_rng().gen::<u64>(),
546            body,
547        };
548        let Ok(bytes) = msg.encode() else {
549            return Asked::NotSent;
550        };
551        let Ok(response) = self
552            .p2p
553            .send_request(peer, REPLICATION_PROTOCOL_ID, bytes, timeout)
554            .await
555        else {
556            return Asked::Silent;
557        };
558        ReplicationMessage::decode(&response.data)
559            .map_or(Asked::Silent, |msg| Asked::Answered(msg.body))
560    }
561
562    async fn penalise(&self, peer: &PeerId) {
563        self.p2p
564            .report_trust_event(
565                peer,
566                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
567            )
568            .await;
569    }
570
571    /// Ask `peer` for the record it holds at `address`, and check what comes
572    /// back: a valid signature and the right address. Anything else counts
573    /// against the peer.
574    async fn fetch_record(&self, peer: &PeerId, address: &XorName) -> Option<Pointer> {
575        match self.fetch_outcome(peer, address).await {
576            Fetched::Record(record) => Some(record),
577            Fetched::Invalid | Fetched::Nothing | Fetched::LocalFailure => None,
578        }
579    }
580
581    /// [`Self::fetch_record`], saying whether a failure was a record that did
582    /// not verify, which has already cost the peer, or no record at all.
583    async fn fetch_outcome(&self, peer: &PeerId, address: &XorName) -> Fetched {
584        let body = match self
585            .ask(
586                peer,
587                ReplicationMessageBody::PointerFetchRequest(PointerFetchRequest {
588                    address: *address,
589                }),
590                self.config.fetch_request_timeout,
591            )
592            .await
593        {
594            Asked::Answered(body) => body,
595            Asked::Silent => return Fetched::Nothing,
596            // Never asked: nothing to judge the peer on.
597            Asked::NotSent => return Fetched::LocalFailure,
598        };
599        let ReplicationMessageBody::PointerFetchResponse(response) = body else {
600            return Fetched::Nothing;
601        };
602        if response.address != *address {
603            return Fetched::Nothing;
604        }
605        let Some(bytes) = response.record else {
606            return Fetched::Nothing;
607        };
608        // Parsing verifies the ML-DSA signature, milliseconds of CPU a peer
609        // can demand once per record it serves: off the async executor, as
610        // every other pointer signature check is (ADR-0016).
611        let Ok(parsed) = spawn_blocking(move || Pointer::from_bytes(&bytes)).await else {
612            // The check itself failed here, which says nothing about the peer.
613            warn!(
614                "Could not verify the pointer record {peer} served for {}",
615                hex::encode(address)
616            );
617            return Fetched::LocalFailure;
618        };
619        match parsed {
620            Ok(record) if record.address() == *address => Fetched::Record(record),
621            Ok(_) | Err(_) => {
622                debug!(
623                    "Peer {peer} served an invalid pointer record for {}",
624                    hex::encode(address)
625                );
626                self.penalise(peer).await;
627                Fetched::Invalid
628            }
629        }
630    }
631
632    // -----------------------------------------------------------------------
633    // Hints
634    // -----------------------------------------------------------------------
635
636    /// Push hints to `peers` in the background: for each, the states this
637    /// node holds whose close group, in this node's view, includes that peer.
638    ///
639    /// Every peer gets at least one message, empty or not. That is how a peer
640    /// learns this node understands pointers.
641    pub(crate) fn push_hints_detached(self: &Arc<Self>, peers: Vec<PeerId>) {
642        if peers.is_empty() {
643            return;
644        }
645        let this = Arc::clone(self);
646        self.tracker
647            .spawn(async move { this.push_hints(&peers).await });
648    }
649
650    /// Answer a peer's sync request, admitted and still fresh, with this
651    /// node's pointer hints, in the background: how a peer, including one
652    /// still bootstrapping, learns the pointers it should hold.
653    ///
654    /// Each answer scans every pointer held, so only a routing-table peer is
655    /// answered, at most once per shortest sync interval, which an honest
656    /// peer never syncs faster than, and at most
657    /// [`MAX_CONCURRENT_SYNC_ANSWERS`] answers run at once. A request that
658    /// finds them all busy gets no hints this time; the next sync round sends
659    /// them anyway.
660    pub(crate) fn answer_sync_with_hints(self: &Arc<Self>, peer: PeerId) {
661        let Ok(permit) = Arc::clone(&self.sync_answers).try_acquire_owned() else {
662            debug!("Not answering {peer}'s sync with pointer hints: too many answers running");
663            return;
664        };
665        let this = Arc::clone(self);
666        self.tracker.spawn(async move {
667            let _permit = permit;
668            if !this.p2p.dht_manager().is_in_routing_table(&peer).await {
669                return;
670            }
671            let admitted = this.answered_syncs.lock().admit(
672                peer,
673                Instant::now(),
674                this.config.neighbor_sync_interval_min,
675            );
676            if admitted {
677                this.push_hints(&[peer]).await;
678            }
679        });
680    }
681
682    /// Push hints to `peers` and wait until they are sent. This is what each
683    /// neighbour-sync round runs in the background; tests call it to drive a
684    /// round.
685    pub async fn push_hints(&self, peers: &[PeerId]) {
686        let self_id = *self.p2p.peer_id();
687        let mut by_peer: HashMap<PeerId, Vec<PointerStateSummary>> =
688            peers.iter().map(|peer| (*peer, Vec::new())).collect();
689        for state in self.store.held_states() {
690            if self.shutdown.is_cancelled() {
691                return;
692            }
693            let group = self
694                .p2p
695                .dht_manager()
696                .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
697                .await;
698            for node in group {
699                if node.peer_id == self_id {
700                    continue;
701                }
702                if let Some(hints) = by_peer.get_mut(&node.peer_id) {
703                    hints.push(state.into());
704                }
705            }
706        }
707        for (peer, hints) in by_peer {
708            let batches: Vec<Vec<PointerStateSummary>> = if hints.is_empty() {
709                vec![Vec::new()]
710            } else {
711                hints
712                    .chunks(MAX_POINTER_HINTS_PER_MESSAGE)
713                    .map(<[PointerStateSummary]>::to_vec)
714                    .collect()
715            };
716            for hints in batches {
717                self.send_one_way(
718                    &peer,
719                    ReplicationMessageBody::PointerHints(PointerHints { hints }),
720                )
721                .await;
722            }
723        }
724    }
725
726    /// Take in hints from `source`: queue each hinted state this node should
727    /// hold and lacks, or holds an older state than.
728    pub(crate) async fn handle_hints(&self, source: PeerId, hints: Vec<PointerStateSummary>) {
729        self.mark_capable(&source).await;
730        if hints.is_empty() {
731            return;
732        }
733        // As for chunks: only a peer in our own routing table may tell us what
734        // to hold.
735        if !self.p2p.dht_manager().is_in_routing_table(&source).await {
736            debug!("Dropping pointer hints from {source}: not in the routing table");
737            return;
738        }
739        let self_id = *self.p2p.peer_id();
740        let width = storage_admission_width(self.config.close_group_size);
741        for summary in hints.into_iter().take(MAX_POINTER_HINTS_PER_MESSAGE) {
742            let hinted = PointerState::from(summary);
743            match self.store.state(&hinted.address) {
744                Some(held) => {
745                    if held.state_id == hinted.state_id || !hinted.replaces(&held) {
746                        continue;
747                    }
748                }
749                None => {
750                    if !admission::is_responsible(&self_id, &hinted.address, &self.p2p, width).await
751                    {
752                        continue;
753                    }
754                }
755            }
756            self.enqueue(hinted);
757        }
758    }
759
760    fn enqueue(&self, hinted: PointerState) {
761        let mut pending = self.pending.lock();
762        let len = pending.len();
763        match pending.get_mut(&hinted.address) {
764            Some(entry) => {
765                if hinted.replaces(&entry.wanted) {
766                    entry.wanted = hinted;
767                    entry.attempts = 0;
768                    entry.not_before = Instant::now();
769                }
770            }
771            None if len < MAX_PENDING => {
772                pending.insert(
773                    hinted.address,
774                    Pending {
775                        wanted: hinted,
776                        attempts: 0,
777                        not_before: Instant::now(),
778                    },
779                );
780            }
781            None => {}
782        }
783    }
784
785    // -----------------------------------------------------------------------
786    // Verification and fetch
787    // -----------------------------------------------------------------------
788
789    /// Start the loop that verifies and fetches hinted states.
790    pub(crate) fn start_verification_loop(self: &Arc<Self>) -> JoinHandle<()> {
791        let this = Arc::clone(self);
792        tokio::spawn(async move {
793            loop {
794                tokio::select! {
795                    () = this.shutdown.cancelled() => break,
796                    () = tokio::time::sleep(VERIFICATION_TICK) => this.verify_due().await,
797                }
798            }
799        })
800    }
801
802    /// Whether this node should look for anything to repair now.
803    async fn may_repair(&self) -> bool {
804        // As for chunks (ADR-0011): a node that cannot store what it would
805        // fetch does not spend the network's time finding it. The hints wait,
806        // and come back each round if they are dropped meanwhile.
807        if self.chunks.capacity_verdict() == CapacityVerdict::Full {
808            return false;
809        }
810        // A node still bootstrapping sees too little of its close group to
811        // judge what a quorum of it holds. The hints wait for it.
812        !*self.is_bootstrapping.read().await
813    }
814
815    /// Verify and fetch whatever is due now. Also the tests' way to drive it.
816    pub async fn verify_due(&self) {
817        if !self.may_repair().await {
818            return;
819        }
820        let now = Instant::now();
821        let due: Vec<(XorName, PointerState)> = self
822            .pending
823            .lock()
824            .iter()
825            .filter(|(_, entry)| entry.not_before <= now)
826            .take(MAX_VERIFICATIONS_PER_TICK)
827            .map(|(address, entry)| (*address, entry.wanted))
828            .collect();
829        if due.is_empty() {
830            return;
831        }
832
833        let self_id = *self.p2p.peer_id();
834        let mut groups: HashMap<XorName, Vec<PeerId>> = HashMap::new();
835        let mut asked: HashMap<PeerId, Vec<XorName>> = HashMap::new();
836        for (address, _) in &due {
837            let group: Vec<PeerId> = self
838                .p2p
839                .dht_manager()
840                .find_closest_nodes_local(address, self.config.close_group_size)
841                .await
842                .into_iter()
843                .map(|node| node.peer_id)
844                .filter(|peer| *peer != self_id)
845                .collect();
846            for peer in group.iter().filter(|peer| self.is_capable(peer)) {
847                asked.entry(*peer).or_default().push(*address);
848            }
849            groups.insert(*address, group);
850        }
851
852        let answers = self.ask_states(asked).await;
853
854        let decisions: Vec<(XorName, Verdict)> = due
855            .iter()
856            .map(|(address, _)| {
857                let group = groups.get(address).map_or(&[][..], Vec::as_slice);
858                let answered: Vec<(PeerId, Option<PointerState>)> = group
859                    .iter()
860                    .filter_map(|peer| {
861                        answers
862                            .get(&(*peer, *address))
863                            .map(|answer| (*peer, *answer))
864                    })
865                    .collect();
866                let held = self.store.state(address);
867                // The quorum is counted over the whole close group, as
868                // ADR-0016 has it: a member this node cannot see, because its
869                // routing table is thin, counts as unanswered, never as a
870                // smaller group. Otherwise one peer in a thin view could vote
871                // alone for an owner-signed state nobody paid to store.
872                let width = repair_width(group.len(), self.config.close_group_size);
873                let verdict = evaluate(
874                    held.as_ref(),
875                    width,
876                    &answered,
877                    self.config.quorum_needed(width),
878                );
879                (*address, verdict)
880            })
881            .collect();
882
883        let outcomes: Vec<(XorName, bool)> = stream::iter(decisions)
884            .map(|(address, verdict)| async move {
885                match verdict {
886                    Verdict::Adopt { state, holders } => {
887                        let stored = self.fetch_and_store(address, state, &holders).await;
888                        (address, stored)
889                    }
890                    Verdict::Undecided => (address, false),
891                    Verdict::Refused => {
892                        info!(
893                            "No quorum backs a newer state for pointer {}",
894                            hex::encode(address)
895                        );
896                        self.pending.lock().remove(&address);
897                        (address, true)
898                    }
899                }
900            })
901            .buffer_unordered(VERIFICATION_CONCURRENCY)
902            .collect()
903            .await;
904
905        let now = Instant::now();
906        let mut pending = self.pending.lock();
907        for (address, settled) in outcomes {
908            if settled {
909                pending.remove(&address);
910                continue;
911            }
912            if let Some(entry) = pending.get_mut(&address) {
913                entry.attempts = entry.attempts.saturating_add(1);
914                if entry.attempts >= MAX_UNDECIDED_ROUNDS {
915                    pending.remove(&address);
916                } else {
917                    let backoff = UNDECIDED_BACKOFF
918                        .saturating_mul(2u32.saturating_pow(entry.attempts.saturating_sub(1)));
919                    entry.not_before = now + backoff;
920                }
921            }
922        }
923    }
924
925    /// Ask each peer which state it holds at the addresses listed for it.
926    async fn ask_states(
927        &self,
928        asked: HashMap<PeerId, Vec<XorName>>,
929    ) -> HashMap<(PeerId, XorName), Option<PointerState>> {
930        let requests: Vec<(PeerId, Vec<XorName>)> = asked
931            .into_iter()
932            .flat_map(|(peer, addresses)| {
933                addresses
934                    .chunks(MAX_POINTER_STATE_REQUEST_ADDRESSES)
935                    .map(|chunk| (peer, chunk.to_vec()))
936                    .collect::<Vec<_>>()
937            })
938            .collect();
939        let replies: Vec<Vec<StateAnswer>> = stream::iter(requests)
940            .map(|(peer, addresses)| async move {
941                let body = self
942                    .request(
943                        &peer,
944                        ReplicationMessageBody::PointerStateRequest(PointerStateRequest {
945                            addresses: addresses.clone(),
946                        }),
947                        self.config.verification_request_timeout,
948                    )
949                    .await;
950                let Some(ReplicationMessageBody::PointerStateResponse(response)) = body else {
951                    return Vec::new();
952                };
953                addresses
954                    .iter()
955                    .zip(response.states)
956                    .map(|(address, summary)| {
957                        // An answer about a different address is no answer.
958                        let state = summary
959                            .filter(|summary| summary.address == *address)
960                            .map(PointerState::from);
961                        ((peer, *address), state)
962                    })
963                    .collect()
964            })
965            .buffer_unordered(VERIFICATION_CONCURRENCY)
966            .collect()
967            .await;
968        replies.into_iter().flatten().collect()
969    }
970
971    /// Fetch `wanted` from one of `holders` and store it. Whether it is now
972    /// held, or nothing further can come of this round.
973    async fn fetch_and_store(
974        &self,
975        address: XorName,
976        wanted: PointerState,
977        holders: &[PeerId],
978    ) -> bool {
979        for holder in holders {
980            let Some(record) = self.fetch_record(holder, &address).await else {
981                continue;
982            };
983            // The quorum backed this state. A holder that has moved on since
984            // serves a different one, which that quorum says nothing about.
985            if record.state_id() != wanted.state_id {
986                continue;
987            }
988            match self.store_verified(record, None).await {
989                Ok(_) => return true,
990                Err(e) => {
991                    warn!(
992                        "Could not store replicated pointer {}: {e}",
993                        hex::encode(address)
994                    );
995                    return false;
996                }
997            }
998        }
999        false
1000    }
1001
1002    /// Store a record whose signature has been checked, if it still belongs
1003    /// here and beats what is held.
1004    async fn store_verified(
1005        &self,
1006        record: Pointer,
1007        width: Option<usize>,
1008    ) -> crate::error::Result<bool> {
1009        let state = record.state();
1010        let self_id = *self.p2p.peer_id();
1011        let width = width.unwrap_or_else(|| storage_admission_width(self.config.close_group_size));
1012        let held = self.store.state(&state.address).is_some();
1013        if !held && !admission::is_responsible(&self_id, &state.address, &self.p2p, width).await {
1014            return Ok(false);
1015        }
1016        if !self.store.admits(&state) {
1017            return Ok(false);
1018        }
1019        let reservation = self.chunks.reserve(POINTER_WIRE_LEN as u64)?;
1020        self.store.commit(record, Some(reservation)).await?;
1021        Ok(true)
1022    }
1023
1024    // -----------------------------------------------------------------------
1025    // Serving
1026    // -----------------------------------------------------------------------
1027
1028    /// Admit a fetch or state request from `source`, or drop it.
1029    ///
1030    /// Admitted before a task exists, fairly across peers, as a chunk fetch
1031    /// is: each admitted request would otherwise be a task waiting on a serve
1032    /// permit with nothing bounding how many, and one peer could take every
1033    /// place.
1034    async fn admit_serve(&self, source: &PeerId, kind: &str) -> Option<super::ResponderGuard> {
1035        match super::admit_bounded_responder(
1036            &self.serve_admission,
1037            &self.serve_inflight,
1038            source,
1039            MAX_SERVES_OUTSTANDING,
1040            MAX_SERVES_OUTSTANDING_PER_PEER,
1041        )
1042        .await
1043        {
1044            Ok(guard) => Some(guard),
1045            Err(failure) => {
1046                debug!("Dropping a pointer {kind} request from {source}: {failure}");
1047                None
1048            }
1049        }
1050    }
1051
1052    /// Answer a fetch request in the background.
1053    pub(crate) async fn serve_fetch_detached(
1054        self: &Arc<Self>,
1055        source: PeerId,
1056        request: PointerFetchRequest,
1057        request_id: u64,
1058        rr_message_id: Option<String>,
1059    ) {
1060        let Some(guard) = self.admit_serve(&source, "fetch").await else {
1061            return;
1062        };
1063        let this = Arc::clone(self);
1064        self.tracker.spawn(async move {
1065            let _guard = guard;
1066            // Shutting down ends the wait, and the work behind it.
1067            let permit = tokio::select! {
1068                biased;
1069                () = this.shutdown.cancelled() => return,
1070                permit = this.serve_permits.acquire() => permit,
1071            };
1072            let Ok(_permit) = permit else {
1073                return;
1074            };
1075            if this.shutdown.is_cancelled() {
1076                return;
1077            }
1078            this.mark_capable(&source).await;
1079            // `get` verifies the signature before serving, so a record damaged
1080            // on this disk is never handed on.
1081            let record = match this.store.get(&request.address).await {
1082                Ok(Some(record)) => Some(record.to_bytes()),
1083                Ok(None) | Err(_) => None,
1084            };
1085            super::send_replication_response(
1086                &source,
1087                &this.p2p,
1088                request_id,
1089                ReplicationMessageBody::PointerFetchResponse(PointerFetchResponse {
1090                    address: request.address,
1091                    record,
1092                }),
1093                rr_message_id.as_deref(),
1094            )
1095            .await;
1096        });
1097    }
1098
1099    /// Answer a state request in the background, from the index.
1100    pub(crate) async fn serve_state_detached(
1101        self: &Arc<Self>,
1102        source: PeerId,
1103        request: PointerStateRequest,
1104        request_id: u64,
1105        rr_message_id: Option<String>,
1106    ) {
1107        // An honest peer never asks about more than this at once. The decoded
1108        // request would otherwise be held by its task for as long as it waits,
1109        // and the wire allows one far larger.
1110        if request.addresses.len() > MAX_POINTER_STATE_REQUEST_ADDRESSES {
1111            debug!(
1112                "Dropping a pointer state request from {source}: {} addresses",
1113                request.addresses.len()
1114            );
1115            return;
1116        }
1117        let Some(guard) = self.admit_serve(&source, "state").await else {
1118            return;
1119        };
1120        let this = Arc::clone(self);
1121        self.tracker.spawn(async move {
1122            let _guard = guard;
1123            let permit = tokio::select! {
1124                biased;
1125                () = this.shutdown.cancelled() => return,
1126                permit = this.serve_permits.acquire() => permit,
1127            };
1128            let Ok(_permit) = permit else {
1129                return;
1130            };
1131            if this.shutdown.is_cancelled() {
1132                return;
1133            }
1134            this.mark_capable(&source).await;
1135            let states = request
1136                .addresses
1137                .iter()
1138                .take(MAX_POINTER_STATE_REQUEST_ADDRESSES)
1139                .map(|address| this.store.state(address).map(PointerStateSummary::from))
1140                .collect();
1141            super::send_replication_response(
1142                &source,
1143                &this.p2p,
1144                request_id,
1145                ReplicationMessageBody::PointerStateResponse(PointerStateResponse { states }),
1146                rr_message_id.as_deref(),
1147            )
1148            .await;
1149        });
1150    }
1151
1152    // -----------------------------------------------------------------------
1153    // Fresh replication
1154    // -----------------------------------------------------------------------
1155
1156    /// Start the loop that offers freshly paid states to their close groups.
1157    pub(crate) fn start_fresh_drainer(
1158        self: &Arc<Self>,
1159        mut writes: mpsc::UnboundedReceiver<PointerFreshWrite>,
1160    ) -> JoinHandle<()> {
1161        let this = Arc::clone(self);
1162        tokio::spawn(async move {
1163            loop {
1164                tokio::select! {
1165                    () = this.shutdown.cancelled() => break,
1166                    write = writes.recv() => match write {
1167                        Some(write) => this.replicate_fresh(write).await,
1168                        None => break,
1169                    },
1170                }
1171            }
1172        })
1173    }
1174
1175    /// Offer a freshly paid state to the rest of its close group, and schedule
1176    /// the check that they took it.
1177    pub async fn replicate_fresh(self: &Arc<Self>, write: PointerFreshWrite) {
1178        let Ok(state) = PointerState::parse(&write.record) else {
1179            warn!("A fresh pointer write did not parse; not replicating it");
1180            return;
1181        };
1182        let self_id = *self.p2p.peer_id();
1183        let targets: Vec<PeerId> = self
1184            .p2p
1185            .dht_manager()
1186            .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
1187            .await
1188            .into_iter()
1189            .map(|node| node.peer_id)
1190            .filter(|peer| *peer != self_id)
1191            .collect();
1192
1193        let msg = ReplicationMessage {
1194            request_id: rand::thread_rng().gen::<u64>(),
1195            body: ReplicationMessageBody::PointerFreshOffer(PointerFreshOffer {
1196                record: write.record,
1197                proof_of_payment: write.payment_proof,
1198            }),
1199        };
1200        let Ok(encoded) = msg.encode() else {
1201            warn!(
1202                "Failed to encode a fresh pointer offer for {}",
1203                hex::encode(state.address)
1204            );
1205            return;
1206        };
1207        let encoded = Arc::new(encoded);
1208        for peer in &targets {
1209            let p2p = Arc::clone(&self.p2p);
1210            let bytes = Arc::clone(&encoded);
1211            let semaphore = Arc::clone(&self.send_semaphore);
1212            let peer = *peer;
1213            self.tracker.spawn(async move {
1214                let Ok(_permit) = semaphore.acquire().await else {
1215                    return;
1216                };
1217                for attempt in 0..=FRESH_REPLICATION_DELIVERY_MAX_RETRIES {
1218                    match p2p
1219                        .send_message(&peer, REPLICATION_PROTOCOL_ID, bytes.as_ref().clone(), &[])
1220                        .await
1221                    {
1222                        Ok(()) => break,
1223                        Err(e) => debug!(
1224                            "Fresh pointer offer to {peer} failed (attempt {}): {e}",
1225                            attempt + 1
1226                        ),
1227                    }
1228                }
1229            });
1230        }
1231        debug!(
1232            "Fresh pointer {} offered to {} peers",
1233            hex::encode(state.address),
1234            targets.len()
1235        );
1236        self.schedule_possession_check(state, targets);
1237    }
1238
1239    /// Take a fresh offer from `source` in the background, unless too many are
1240    /// already being verified.
1241    pub(crate) fn accept_offer_detached(
1242        self: &Arc<Self>,
1243        source: PeerId,
1244        offer: PointerFreshOffer,
1245    ) {
1246        let Ok(permit) = Arc::clone(&self.offer_permits).try_acquire_owned() else {
1247            info!("Dropping a fresh pointer offer from {source}: too many in flight");
1248            return;
1249        };
1250        let this = Arc::clone(self);
1251        self.tracker.spawn(async move {
1252            let _permit = permit;
1253            this.mark_capable(&source).await;
1254            this.accept_offer(source, offer).await;
1255        });
1256    }
1257
1258    /// Verify and store a fresh offer. Cheapest checks first; the signature and
1259    /// the on-chain payment lookup only for a state that would change something
1260    /// here and that this node is responsible for.
1261    async fn accept_offer(&self, source: PeerId, offer: PointerFreshOffer) {
1262        if offer.record.len() != POINTER_WIRE_LEN
1263            || !(MIN_PAYMENT_PROOF_SIZE_BYTES..=MAX_PAYMENT_PROOF_SIZE_BYTES)
1264                .contains(&offer.proof_of_payment.len())
1265        {
1266            debug!("Dropping a malformed fresh pointer offer from {source}");
1267            self.penalise(&source).await;
1268            return;
1269        }
1270        let parsed = match self.store.inspect(&offer.record).await {
1271            Ok(Inspected::Candidate(parsed)) => parsed,
1272            Ok(Inspected::Unchanged(_) | Inspected::Stale(_)) => return,
1273            Err(e) => {
1274                debug!("Dropping an unparseable fresh pointer offer from {source}: {e}");
1275                self.penalise(&source).await;
1276                return;
1277            }
1278        };
1279        let state = *parsed.state();
1280        let self_id = *self.p2p.peer_id();
1281        // As for a chunk: a fresh offer is taken across the wider paid width.
1282        if !admission::is_responsible(
1283            &self_id,
1284            &state.address,
1285            &self.p2p,
1286            self.config.paid_list_close_group_size,
1287        )
1288        .await
1289        {
1290            return;
1291        }
1292        if !self.store.admits(&state)
1293            || self
1294                .chunks
1295                .check_capacity_for(POINTER_WIRE_LEN as u64)
1296                .is_err()
1297        {
1298            return;
1299        }
1300        let record = match self.store.verify(parsed).await {
1301            Ok(record) => record,
1302            Err(e) => {
1303                debug!("Fresh pointer offer from {source} does not verify: {e}");
1304                self.penalise(&source).await;
1305                return;
1306            }
1307        };
1308        if let Err(e) = self
1309            .payments
1310            .verify_pointer_payment_in(
1311                &state.address,
1312                &state.state_id,
1313                &offer.proof_of_payment,
1314                VerificationContext::FreshReplication,
1315            )
1316            .await
1317        {
1318            info!(
1319                "Fresh pointer offer for {} from {source} is not paid for: {e}",
1320                hex::encode(state.address)
1321            );
1322            return;
1323        }
1324        match self
1325            .store_verified(record, Some(self.config.paid_list_close_group_size))
1326            .await
1327        {
1328            Ok(true) => debug!(
1329                "Stored fresh pointer {} from {source}",
1330                hex::encode(state.address)
1331            ),
1332            Ok(false) => {}
1333            Err(e) => warn!(
1334                "Could not store fresh pointer {}: {e}",
1335                hex::encode(state.address)
1336            ),
1337        }
1338    }
1339
1340    // -----------------------------------------------------------------------
1341    // Possession
1342    // -----------------------------------------------------------------------
1343
1344    fn schedule_possession_check(self: &Arc<Self>, fresh: PointerState, peers: Vec<PeerId>) {
1345        if peers.is_empty() {
1346            return;
1347        }
1348        let min = self.config.possession_check_delay_min;
1349        let max = self.config.possession_check_delay_max.max(min);
1350        let delay = if max > min {
1351            rand::thread_rng().gen_range(min..=max)
1352        } else {
1353            min
1354        };
1355        let this = Arc::clone(self);
1356        self.tracker.spawn(async move {
1357            tokio::select! {
1358                () = this.shutdown.cancelled() => return,
1359                () = tokio::time::sleep(delay) => {}
1360            }
1361            this.check_possession(fresh, &peers).await;
1362        });
1363    }
1364
1365    /// Ask each peer for the record, and penalise any still responsible for it
1366    /// that cannot produce `fresh` or a state that replaces it.
1367    pub async fn check_possession(&self, fresh: PointerState, peers: &[PeerId]) {
1368        let self_id = *self.p2p.peer_id();
1369        for peer in peers {
1370            // A peer that has left the group owes nothing, and one that cannot
1371            // be asked is never judged on its silence.
1372            if *peer == self_id || !self.owes(peer, &fresh.address).await {
1373                continue;
1374            }
1375            let fetched = self.fetch_outcome(peer, &fresh.address).await;
1376            if judge_possession(fetched, &fresh) != Possession::Missing {
1377                continue;
1378            }
1379            // Asking can wait on this peer's other requests and on the peers
1380            // before it, and it may have left the group meanwhile. It is
1381            // judged on what it owes now, not on what it owed when this began.
1382            if !self.owes(peer, &fresh.address).await {
1383                continue;
1384            }
1385            warn!(
1386                "Peer {peer} does not hold pointer {} it was offered",
1387                hex::encode(fresh.address)
1388            );
1389            self.penalise(peer).await;
1390        }
1391    }
1392
1393    /// Whether `peer` is responsible for `address` in this node's view, and
1394    /// can be asked about it.
1395    async fn owes(&self, peer: &PeerId, address: &XorName) -> bool {
1396        self.is_capable(peer)
1397            && self
1398                .p2p
1399                .dht_manager()
1400                .find_closest_nodes_local_with_self(address, self.config.close_group_size)
1401                .await
1402                .iter()
1403                .any(|node| node.peer_id == *peer)
1404    }
1405
1406    // -----------------------------------------------------------------------
1407    // Pruning
1408    // -----------------------------------------------------------------------
1409
1410    /// Delete records this node has been out of range of for the hysteresis
1411    /// period, where that is safe. Run when a neighbour-sync cycle completes.
1412    ///
1413    /// `allow_remote` is false while bootstrapping: candidacy is still tracked,
1414    /// but nothing that needs other peers' proof is decided.
1415    ///
1416    /// A record a retained storage commitment still commits to is never
1417    /// deleted, exactly as for a chunk: an auditor pinning that commitment may
1418    /// still open it, and a node that deleted it would fail that audit.
1419    pub async fn prune_pass(
1420        &self,
1421        allow_remote: bool,
1422        commitment_state: Option<&ResponderCommitmentState>,
1423    ) {
1424        // Replaced records kept for audits go when their retention does,
1425        // whether or not another update comes along to drop them.
1426        self.store.drop_expired_superseded();
1427        let committed = |address: &XorName| commitment_state.is_some_and(|cs| cs.is_held(address));
1428        let self_id = *self.p2p.peer_id();
1429        let retention = storage_admission_width(self.config.close_group_size);
1430        let now = Instant::now();
1431        let held = self.store.held_states();
1432
1433        let mut candidates = Vec::new();
1434        for state in &held {
1435            if admission::is_responsible(&self_id, &state.address, &self.p2p, retention).await {
1436                self.out_of_range.lock().remove(&state.address);
1437                continue;
1438            }
1439            let first_seen = *self.out_of_range.lock().entry(state.address).or_insert(now);
1440            if now.duration_since(first_seen) >= self.config.prune_hysteresis_duration {
1441                candidates.push(*state);
1442            }
1443        }
1444        {
1445            let held: HashSet<XorName> = held.iter().map(|state| state.address).collect();
1446            self.out_of_range
1447                .lock()
1448                .retain(|address, _| held.contains(address));
1449        }
1450
1451        let mut deleted = 0usize;
1452        for state in candidates.into_iter().take(MAX_PRUNE_CANDIDATES_PER_PASS) {
1453            if self.shutdown.is_cancelled() {
1454                return;
1455            }
1456            if committed(&state.address) {
1457                continue;
1458            }
1459            let wide = self
1460                .p2p
1461                .dht_manager()
1462                .find_closest_nodes_local_with_self(
1463                    &state.address,
1464                    self.config.paid_list_close_group_size,
1465                )
1466                .await;
1467            let far = wide.len() >= self.config.paid_list_close_group_size
1468                && !wide.iter().any(|node| node.peer_id == self_id);
1469            let confirmed = if far {
1470                true
1471            } else if allow_remote && !*self.is_bootstrapping.read().await {
1472                self.others_hold(&state).await
1473            } else {
1474                false
1475            };
1476            // Revalidate just before deleting: the group may have moved back.
1477            if confirmed
1478                && !committed(&state.address)
1479                && !admission::is_responsible(&self_id, &state.address, &self.p2p, retention).await
1480                && self.delete(&state.address).await
1481            {
1482                deleted += 1;
1483            }
1484        }
1485        if deleted > 0 {
1486            info!("Pruned {deleted} pointer records this node is no longer responsible for");
1487        }
1488    }
1489
1490    /// Whether all but one of the current close group prove they hold `ours`
1491    /// or a newer state, by returning a valid record.
1492    async fn others_hold(&self, ours: &PointerState) -> bool {
1493        let group: Vec<PeerId> = self
1494            .p2p
1495            .dht_manager()
1496            .find_closest_nodes_local(&ours.address, self.config.close_group_size)
1497            .await
1498            .into_iter()
1499            .map(|node| node.peer_id)
1500            .collect();
1501        let needed = prune_proofs_needed(group.len());
1502        if needed == 0 {
1503            return false;
1504        }
1505        let mut proofs = 0usize;
1506        for peer in group.iter().filter(|peer| self.is_capable(peer)) {
1507            let proves = self
1508                .fetch_record(peer, &ours.address)
1509                .await
1510                .is_some_and(|record| {
1511                    let state = record.state();
1512                    state.state_id == ours.state_id || state.replaces(ours)
1513                });
1514            if proves {
1515                proofs += 1;
1516                if proofs >= needed {
1517                    return true;
1518                }
1519            }
1520        }
1521        false
1522    }
1523
1524    async fn delete(&self, address: &XorName) -> bool {
1525        self.out_of_range.lock().remove(address);
1526        match self.store.delete(address).await {
1527            Ok(true) => {
1528                self.chunks.release(POINTER_WIRE_LEN as u64);
1529                true
1530            }
1531            Ok(false) => false,
1532            Err(e) => {
1533                warn!("Could not prune pointer {}: {e}", hex::encode(address));
1534                false
1535            }
1536        }
1537    }
1538}
1539
1540#[cfg(test)]
1541#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1542mod tests {
1543    use super::*;
1544    use ant_protocol::pointer::{PointerTarget, PointerTargetKind};
1545    use saorsa_pqc::api::sig::ml_dsa_65;
1546
1547    fn state(counter: u64, target: u8, id: u8) -> PointerState {
1548        PointerState {
1549            state_id: [id; 32],
1550            address: [7; 32],
1551            counter,
1552            target: PointerTarget::new(PointerTargetKind::Chunk, [target; 32]),
1553        }
1554    }
1555
1556    fn peer(byte: u8) -> PeerId {
1557        PeerId::from_bytes([byte; 32])
1558    }
1559
1560    fn answers(list: &[(u8, Option<PointerState>)]) -> Vec<(PeerId, Option<PointerState>)> {
1561        list.iter().map(|(p, s)| (peer(*p), *s)).collect()
1562    }
1563
1564    /// A peer's outbound permits are dropped only once nothing holds them, so
1565    /// a request in flight keeps the one set later requests share.
1566    fn record(counter: u64, target: u8) -> Pointer {
1567        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[3; 32]);
1568        let target = PointerTarget::new(PointerTargetKind::Chunk, [target; 32]);
1569        Pointer::sign(&sk, &pk, counter, target).expect("sign")
1570    }
1571
1572    #[tokio::test(start_paused = true)]
1573    async fn a_request_that_cannot_be_sent_in_time_is_given_up_not_queued() {
1574        let permits = Arc::new(Semaphore::new(1));
1575        let shutdown = CancellationToken::new();
1576        let held = acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
1577            .await
1578            .expect("a free permit is taken");
1579
1580        // Busy past the timeout: given up, not left waiting.
1581        assert!(
1582            acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
1583                .await
1584                .is_none()
1585        );
1586
1587        // Shutdown ends a wait at once, however long it could still run.
1588        shutdown.cancel();
1589        let waited = tokio::time::Instant::now();
1590        assert!(
1591            acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(3600), &shutdown)
1592                .await
1593                .is_none()
1594        );
1595        assert!(waited.elapsed() < Duration::from_secs(1));
1596        drop(held);
1597
1598        // With a permit free and shutdown already under way, nothing is sent,
1599        // every time.
1600        for _ in 0..64 {
1601            assert!(
1602                acquire_or_give_up(Arc::clone(&permits), Duration::from_secs(1), &shutdown)
1603                    .await
1604                    .is_none()
1605            );
1606        }
1607    }
1608
1609    #[test]
1610    fn a_possession_check_judges_each_answer_once() {
1611        let fresh = record(5, 1);
1612        let judge = |fetched| judge_possession(fetched, &fresh.state());
1613        assert_eq!(judge(Fetched::Record(fresh.clone())), Possession::Holds);
1614        assert_eq!(
1615            judge(Fetched::Record(record(6, 9))),
1616            Possession::Holds,
1617            "a newer state is as good"
1618        );
1619        assert_eq!(judge(Fetched::Record(record(4, 1))), Possession::Missing);
1620        assert_eq!(judge(Fetched::Nothing), Possession::Missing);
1621        // The fetch already charged the peer for an invalid record; charging
1622        // it again as missing would count one bad answer twice.
1623        assert_eq!(judge(Fetched::Invalid), Possession::NotJudged);
1624        // A failure on this node says nothing about the peer.
1625        assert_eq!(judge(Fetched::LocalFailure), Possession::NotJudged);
1626    }
1627
1628    #[test]
1629    fn a_peer_is_answered_with_hints_once_per_sync_interval() {
1630        let spacing = Duration::from_secs(600);
1631        let start = Instant::now();
1632        let mut answered = AnsweredSyncs::default();
1633        assert!(answered.admit(peer(1), start, spacing));
1634        assert!(
1635            !answered.admit(peer(1), start + Duration::from_secs(1), spacing),
1636            "a second request inside the interval gets no second scan"
1637        );
1638        assert!(
1639            answered.admit(peer(2), start, spacing),
1640            "other peers are not held up"
1641        );
1642        assert!(answered.admit(peer(1), start + spacing, spacing));
1643
1644        // A full map forgets the peer answered longest ago; a new peer is
1645        // never refused for it.
1646        let mut full = AnsweredSyncs::default();
1647        let mut first = None;
1648        for i in 0..MAX_ANSWERED_SYNC_PEERS {
1649            let id = u32::try_from(i).expect("fits");
1650            let mut bytes = [0u8; 32];
1651            if let Some(prefix) = bytes.get_mut(..4) {
1652                prefix.copy_from_slice(&id.to_be_bytes());
1653            }
1654            let at = start + Duration::from_millis(u64::from(id));
1655            let each = PeerId::from_bytes(bytes);
1656            first.get_or_insert(each);
1657            assert!(full.admit(each, at, spacing));
1658        }
1659        let late = start + Duration::from_secs(10);
1660        assert!(
1661            full.admit(peer(0xEE), late, spacing),
1662            "a new peer is answered"
1663        );
1664        assert_eq!(full.at.len(), MAX_ANSWERED_SYNC_PEERS);
1665        let first = first.expect("one was admitted");
1666        assert!(!full.at.contains_key(&first), "the oldest was forgotten");
1667    }
1668
1669    #[tokio::test]
1670    async fn outbound_permits_in_use_are_never_dropped() {
1671        let permits = Arc::new(Semaphore::new(MAX_REQUESTS_PER_PEER));
1672        assert!(outbound_idle(&permits));
1673        let held = Arc::clone(&permits)
1674            .acquire_owned()
1675            .await
1676            .expect("a permit");
1677        assert!(!outbound_idle(&permits), "a held permit keeps the set");
1678        drop(held);
1679        assert!(outbound_idle(&permits));
1680    }
1681
1682    /// A node that sees one member of the close group, as one still filling
1683    /// its routing table does, cannot adopt a state on that member's word: the
1684    /// members it cannot see count as unanswered.
1685    #[test]
1686    fn a_thin_view_of_the_group_cannot_adopt_on_one_vote() {
1687        let config = ReplicationConfig::default();
1688        let unpaid = state(9, 1, 90);
1689        let width = repair_width(1, config.close_group_size);
1690        let got = evaluate(
1691            None,
1692            width,
1693            &answers(&[(1, Some(unpaid))]),
1694            config.quorum_needed(width),
1695        );
1696        assert!(
1697            matches!(got, Verdict::Undecided),
1698            "one visible peer must not decide, got {got:?}"
1699        );
1700        assert_eq!(
1701            repair_width(9, config.close_group_size),
1702            9,
1703            "a view wider than the configured group is counted as it is"
1704        );
1705    }
1706
1707    #[test]
1708    fn a_state_a_quorum_holds_is_adopted_from_its_holders() {
1709        let newer = state(3, 1, 30);
1710        let got = evaluate(
1711            None,
1712            7,
1713            &answers(&[
1714                (1, Some(newer)),
1715                (2, Some(newer)),
1716                (3, Some(newer)),
1717                (4, Some(newer)),
1718                (5, None),
1719            ]),
1720            4,
1721        );
1722        match got {
1723            Verdict::Adopt { state, holders } => {
1724                assert_eq!(state.state_id, newer.state_id);
1725                assert_eq!(holders.len(), 4);
1726            }
1727            other => panic!("expected Adopt, got {other:?}"),
1728        }
1729    }
1730
1731    #[test]
1732    fn a_state_below_quorum_is_never_adopted() {
1733        // One peer, or three, holding a state is not the network's word.
1734        let lone = state(9, 1, 90);
1735        let got = evaluate(
1736            None,
1737            7,
1738            &answers(&[
1739                (1, Some(lone)),
1740                (2, Some(lone)),
1741                (3, Some(lone)),
1742                (4, None),
1743                (5, None),
1744                (6, None),
1745                (7, None),
1746            ]),
1747            4,
1748        );
1749        assert_eq!(got, Verdict::Refused);
1750
1751        // With one peer silent, three holders plus that peer could still make
1752        // four: undecided, not refused.
1753        let got = evaluate(
1754            None,
1755            7,
1756            &answers(&[
1757                (1, Some(lone)),
1758                (2, Some(lone)),
1759                (3, Some(lone)),
1760                (4, None),
1761                (5, None),
1762                (6, None),
1763            ]),
1764            4,
1765        );
1766        assert_eq!(got, Verdict::Undecided);
1767    }
1768
1769    #[test]
1770    fn silence_is_not_a_vote_so_an_unanswered_group_stays_undecided() {
1771        let newer = state(3, 1, 30);
1772        let got = evaluate(None, 7, &answers(&[(1, Some(newer)), (2, Some(newer))]), 4);
1773        assert_eq!(got, Verdict::Undecided);
1774    }
1775
1776    #[test]
1777    fn nothing_older_than_what_is_held_is_adopted() {
1778        let held = state(5, 1, 50);
1779        let older = state(4, 1, 40);
1780        let got = evaluate(
1781            Some(&held),
1782            7,
1783            &answers(&[
1784                (1, Some(older)),
1785                (2, Some(older)),
1786                (3, Some(older)),
1787                (4, Some(older)),
1788                (5, Some(older)),
1789            ]),
1790            4,
1791        );
1792        assert_eq!(got, Verdict::Refused);
1793    }
1794
1795    #[test]
1796    fn of_two_states_with_quorum_the_merge_winner_is_adopted() {
1797        let lower = state(2, 9, 20);
1798        let winner = state(2, 1, 21);
1799        assert!(winner.replaces(&lower));
1800        let got = evaluate(
1801            None,
1802            8,
1803            &answers(&[
1804                (1, Some(lower)),
1805                (2, Some(lower)),
1806                (3, Some(lower)),
1807                (4, Some(lower)),
1808                (5, Some(winner)),
1809                (6, Some(winner)),
1810                (7, Some(winner)),
1811                (8, Some(winner)),
1812            ]),
1813            4,
1814        );
1815        match got {
1816            Verdict::Adopt { state, .. } => assert_eq!(state.state_id, winner.state_id),
1817            other => panic!("expected the winner, got {other:?}"),
1818        }
1819    }
1820
1821    #[test]
1822    fn a_group_nobody_can_be_asked_in_is_undecided() {
1823        assert_eq!(evaluate(None, 0, &[], 0), Verdict::Undecided);
1824    }
1825}