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, RwLock, Semaphore};
47use tokio::task::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/// How often the pending hints are looked at.
83const VERIFICATION_TICK: Duration = Duration::from_millis(500);
84
85/// Most addresses awaiting verification at once, so a hint flood cannot grow
86/// memory without bound. A hint dropped here comes back next round.
87const MAX_PENDING: usize = 65_536;
88
89/// Most addresses verified per tick.
90const MAX_VERIFICATIONS_PER_TICK: usize = 256;
91
92/// Verifications and fetches in flight at once within a tick.
93const VERIFICATION_CONCURRENCY: usize = 8;
94
95/// Undecided rounds an address gets before it is dropped. It comes back with
96/// the next hint.
97const MAX_UNDECIDED_ROUNDS: u32 = 5;
98
99/// Wait before retrying an undecided address, doubled each round.
100const UNDECIDED_BACKOFF: Duration = Duration::from_secs(30);
101
102/// Most prune candidates examined per pass.
103const MAX_PRUNE_CANDIDATES_PER_PASS: usize = 256;
104
105/// One peer's answer about one address: the state it holds there, if any.
106type StateAnswer = ((PeerId, XorName), Option<PointerState>);
107
108/// A pointer state this node accepted from a paying client, to be offered to
109/// the rest of its close group.
110pub struct PointerFreshWrite {
111    /// The record, in its canonical encoding.
112    pub record: Vec<u8>,
113    /// The proof that paid for its state.
114    pub payment_proof: Vec<u8>,
115}
116
117/// A state this node was told about and has not yet verified.
118#[derive(Debug, Clone)]
119struct Pending {
120    /// The best state hinted so far.
121    wanted: PointerState,
122    /// Undecided rounds so far.
123    attempts: u32,
124    /// Not to be looked at again before this.
125    not_before: Instant,
126}
127
128/// What a verification round decided for one address.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub(crate) enum Verdict {
131    /// A quorum of the close group hold this state and it beats what is held
132    /// here: fetch it from one of `holders`.
133    Adopt {
134        /// The state to fetch.
135        state: PointerState,
136        /// The peers that said they hold exactly it.
137        holders: Vec<PeerId>,
138    },
139    /// Nothing reached quorum, but the peers that did not answer could still
140    /// make one. Ask again later.
141    Undecided,
142    /// No state that beats what is held can reach quorum.
143    Refused,
144}
145
146/// Decide what a round of answers supports.
147///
148/// `group_size` is the whole close group this node would ask, capable or not:
149/// a peer that cannot be asked counts as unanswered, not as a vote. The quorum
150/// is therefore the one a chunk would need, and a network where few peers
151/// understand pointers yet cannot repair on the word of those few.
152pub(crate) fn evaluate(
153    held: Option<&PointerState>,
154    group_size: usize,
155    answers: &[(PeerId, Option<PointerState>)],
156    quorum_needed: usize,
157) -> Verdict {
158    if group_size == 0 || quorum_needed == 0 {
159        return Verdict::Undecided;
160    }
161    let mut by_state: Vec<(PointerState, Vec<PeerId>)> = Vec::new();
162    for (peer, answer) in answers {
163        let Some(state) = answer else { continue };
164        match by_state
165            .iter_mut()
166            .find(|(known, _)| known.state_id == state.state_id)
167        {
168            Some((_, holders)) => holders.push(*peer),
169            None => by_state.push((*state, vec![*peer])),
170        }
171    }
172    let beats_held = |state: &PointerState| held.is_none_or(|held| state.replaces(held));
173
174    let best = by_state
175        .iter()
176        .filter(|(state, holders)| holders.len() >= quorum_needed && beats_held(state))
177        .fold(
178            None::<&(PointerState, Vec<PeerId>)>,
179            |best, candidate| match best {
180                Some(current) if !candidate.0.replaces(&current.0) => Some(current),
181                _ => Some(candidate),
182            },
183        );
184    if let Some((state, holders)) = best {
185        return Verdict::Adopt {
186            state: *state,
187            holders: holders.clone(),
188        };
189    }
190
191    let unanswered = group_size.saturating_sub(answers.len());
192    let largest = by_state
193        .iter()
194        .filter(|(state, _)| beats_held(state))
195        .map(|(_, holders)| holders.len())
196        .max()
197        .unwrap_or(0);
198    if largest.saturating_add(unanswered) >= quorum_needed {
199        Verdict::Undecided
200    } else {
201        Verdict::Refused
202    }
203}
204
205/// Pointer replication for one node. See the module documentation.
206pub struct PointerReplication {
207    store: PointerStore,
208    chunks: Arc<ChunkStore>,
209    p2p: Arc<P2PNode>,
210    payments: Arc<PaymentVerifier>,
211    config: Arc<ReplicationConfig>,
212    is_bootstrapping: Arc<RwLock<bool>>,
213    /// Outbound record transfers, shared with chunk replication.
214    send_semaphore: Arc<Semaphore>,
215    offer_permits: Arc<Semaphore>,
216    serve_permits: Arc<Semaphore>,
217    /// Peers that have sent a pointer message: the only ones asked anything.
218    capable: Mutex<HashSet<PeerId>>,
219    /// Hinted states awaiting verification, by address.
220    pending: Mutex<HashMap<XorName, Pending>>,
221    /// When each held address was first seen continuously out of range.
222    out_of_range: Mutex<HashMap<XorName, Instant>>,
223    shutdown: CancellationToken,
224    tracker: TaskTracker,
225}
226
227impl PointerReplication {
228    /// Pointer replication over `store`, sharing the engine's resources.
229    #[allow(clippy::too_many_arguments)]
230    pub(crate) fn new(
231        store: PointerStore,
232        chunks: Arc<ChunkStore>,
233        p2p: Arc<P2PNode>,
234        payments: Arc<PaymentVerifier>,
235        config: Arc<ReplicationConfig>,
236        is_bootstrapping: Arc<RwLock<bool>>,
237        send_semaphore: Arc<Semaphore>,
238        shutdown: CancellationToken,
239        tracker: TaskTracker,
240    ) -> Self {
241        Self {
242            store,
243            chunks,
244            p2p,
245            payments,
246            config,
247            is_bootstrapping,
248            send_semaphore,
249            offer_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_OFFERS)),
250            serve_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_SERVES)),
251            capable: Mutex::new(HashSet::new()),
252            pending: Mutex::new(HashMap::new()),
253            out_of_range: Mutex::new(HashMap::new()),
254            shutdown,
255            tracker,
256        }
257    }
258
259    /// The pointer store this replication serves from.
260    pub(crate) fn store(&self) -> &PointerStore {
261        &self.store
262    }
263
264    // -----------------------------------------------------------------------
265    // Capability
266    // -----------------------------------------------------------------------
267
268    fn mark_capable(&self, peer: &PeerId) {
269        self.capable.lock().insert(*peer);
270    }
271
272    /// Whether `peer` has sent a pointer message, and may therefore be asked.
273    pub fn is_capable(&self, peer: &PeerId) -> bool {
274        self.capable.lock().contains(peer)
275    }
276
277    /// Forget a peer that left the routing table.
278    pub(crate) fn forget_peer(&self, peer: &PeerId) {
279        self.capable.lock().remove(peer);
280    }
281
282    /// Addresses currently awaiting verification. Tests only.
283    #[cfg(any(test, feature = "test-utils"))]
284    #[must_use]
285    pub fn pending_len(&self) -> usize {
286        self.pending.lock().len()
287    }
288
289    // -----------------------------------------------------------------------
290    // Messaging
291    // -----------------------------------------------------------------------
292
293    async fn send_one_way(&self, peer: &PeerId, body: ReplicationMessageBody) -> bool {
294        let msg = ReplicationMessage {
295            request_id: rand::thread_rng().gen::<u64>(),
296            body,
297        };
298        let Ok(bytes) = msg.encode() else {
299            warn!("Failed to encode a pointer replication message");
300            return false;
301        };
302        self.p2p
303            .send_message(peer, REPLICATION_PROTOCOL_ID, bytes, &[])
304            .await
305            .is_ok()
306    }
307
308    async fn request(
309        &self,
310        peer: &PeerId,
311        body: ReplicationMessageBody,
312        timeout: Duration,
313    ) -> Option<ReplicationMessageBody> {
314        let msg = ReplicationMessage {
315            request_id: rand::thread_rng().gen::<u64>(),
316            body,
317        };
318        let bytes = msg.encode().ok()?;
319        let response = self
320            .p2p
321            .send_request(peer, REPLICATION_PROTOCOL_ID, bytes, timeout)
322            .await
323            .ok()?;
324        ReplicationMessage::decode(&response.data)
325            .ok()
326            .map(|msg| msg.body)
327    }
328
329    async fn penalise(&self, peer: &PeerId) {
330        self.p2p
331            .report_trust_event(
332                peer,
333                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
334            )
335            .await;
336    }
337
338    /// Ask `peer` for the record it holds at `address`, and check what comes
339    /// back: a valid signature and the right address. Anything else counts
340    /// against the peer.
341    async fn fetch_record(&self, peer: &PeerId, address: &XorName) -> Option<Pointer> {
342        let body = self
343            .request(
344                peer,
345                ReplicationMessageBody::PointerFetchRequest(PointerFetchRequest {
346                    address: *address,
347                }),
348                self.config.fetch_request_timeout,
349            )
350            .await?;
351        let ReplicationMessageBody::PointerFetchResponse(response) = body else {
352            return None;
353        };
354        if response.address != *address {
355            return None;
356        }
357        let bytes = response.record?;
358        match Pointer::from_bytes(&bytes) {
359            Ok(record) if record.address() == *address => Some(record),
360            Ok(_) | Err(_) => {
361                debug!(
362                    "Peer {peer} served an invalid pointer record for {}",
363                    hex::encode(address)
364                );
365                self.penalise(peer).await;
366                None
367            }
368        }
369    }
370
371    // -----------------------------------------------------------------------
372    // Hints
373    // -----------------------------------------------------------------------
374
375    /// Push hints to `peers` in the background: for each, the states this
376    /// node holds whose close group, in this node's view, includes that peer.
377    ///
378    /// Every peer gets at least one message, empty or not. That is how a peer
379    /// learns this node understands pointers.
380    pub(crate) fn push_hints_detached(self: &Arc<Self>, peers: Vec<PeerId>) {
381        if peers.is_empty() {
382            return;
383        }
384        let this = Arc::clone(self);
385        self.tracker
386            .spawn(async move { this.push_hints(&peers).await });
387    }
388
389    /// Push hints to `peers` and wait until they are sent. This is what each
390    /// neighbour-sync round runs in the background; tests call it to drive a
391    /// round.
392    pub async fn push_hints(&self, peers: &[PeerId]) {
393        let self_id = *self.p2p.peer_id();
394        let mut by_peer: HashMap<PeerId, Vec<PointerStateSummary>> =
395            peers.iter().map(|peer| (*peer, Vec::new())).collect();
396        for state in self.store.held_states() {
397            if self.shutdown.is_cancelled() {
398                return;
399            }
400            let group = self
401                .p2p
402                .dht_manager()
403                .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
404                .await;
405            for node in group {
406                if node.peer_id == self_id {
407                    continue;
408                }
409                if let Some(hints) = by_peer.get_mut(&node.peer_id) {
410                    hints.push(state.into());
411                }
412            }
413        }
414        for (peer, hints) in by_peer {
415            let batches: Vec<Vec<PointerStateSummary>> = if hints.is_empty() {
416                vec![Vec::new()]
417            } else {
418                hints
419                    .chunks(MAX_POINTER_HINTS_PER_MESSAGE)
420                    .map(<[PointerStateSummary]>::to_vec)
421                    .collect()
422            };
423            for hints in batches {
424                self.send_one_way(
425                    &peer,
426                    ReplicationMessageBody::PointerHints(PointerHints { hints }),
427                )
428                .await;
429            }
430        }
431    }
432
433    /// Take in hints from `source`: queue each hinted state this node should
434    /// hold and lacks, or holds an older state than.
435    pub(crate) async fn handle_hints(&self, source: PeerId, hints: Vec<PointerStateSummary>) {
436        self.mark_capable(&source);
437        if hints.is_empty() {
438            return;
439        }
440        // As for chunks: only a peer in our own routing table may tell us what
441        // to hold.
442        if !self.p2p.dht_manager().is_in_routing_table(&source).await {
443            debug!("Dropping pointer hints from {source}: not in the routing table");
444            return;
445        }
446        let self_id = *self.p2p.peer_id();
447        let width = storage_admission_width(self.config.close_group_size);
448        for summary in hints.into_iter().take(MAX_POINTER_HINTS_PER_MESSAGE) {
449            let hinted = PointerState::from(summary);
450            match self.store.state(&hinted.address) {
451                Some(held) => {
452                    if held.state_id == hinted.state_id || !hinted.replaces(&held) {
453                        continue;
454                    }
455                }
456                None => {
457                    if !admission::is_responsible(&self_id, &hinted.address, &self.p2p, width).await
458                    {
459                        continue;
460                    }
461                }
462            }
463            self.enqueue(hinted);
464        }
465    }
466
467    fn enqueue(&self, hinted: PointerState) {
468        let mut pending = self.pending.lock();
469        let len = pending.len();
470        match pending.get_mut(&hinted.address) {
471            Some(entry) => {
472                if hinted.replaces(&entry.wanted) {
473                    entry.wanted = hinted;
474                    entry.attempts = 0;
475                    entry.not_before = Instant::now();
476                }
477            }
478            None if len < MAX_PENDING => {
479                pending.insert(
480                    hinted.address,
481                    Pending {
482                        wanted: hinted,
483                        attempts: 0,
484                        not_before: Instant::now(),
485                    },
486                );
487            }
488            None => {}
489        }
490    }
491
492    // -----------------------------------------------------------------------
493    // Verification and fetch
494    // -----------------------------------------------------------------------
495
496    /// Start the loop that verifies and fetches hinted states.
497    pub(crate) fn start_verification_loop(self: &Arc<Self>) -> JoinHandle<()> {
498        let this = Arc::clone(self);
499        tokio::spawn(async move {
500            loop {
501                tokio::select! {
502                    () = this.shutdown.cancelled() => break,
503                    () = tokio::time::sleep(VERIFICATION_TICK) => this.verify_due().await,
504                }
505            }
506        })
507    }
508
509    /// Verify and fetch whatever is due now. Also the tests' way to drive it.
510    pub async fn verify_due(&self) {
511        // As for chunks (ADR-0011): a node that cannot store what it would
512        // fetch does not spend the network's time finding it. The hints wait,
513        // and come back each round if they are dropped meanwhile.
514        if self.chunks.capacity_verdict() == CapacityVerdict::Full {
515            return;
516        }
517        let now = Instant::now();
518        let due: Vec<(XorName, PointerState)> = self
519            .pending
520            .lock()
521            .iter()
522            .filter(|(_, entry)| entry.not_before <= now)
523            .take(MAX_VERIFICATIONS_PER_TICK)
524            .map(|(address, entry)| (*address, entry.wanted))
525            .collect();
526        if due.is_empty() {
527            return;
528        }
529
530        let self_id = *self.p2p.peer_id();
531        let mut groups: HashMap<XorName, Vec<PeerId>> = HashMap::new();
532        let mut asked: HashMap<PeerId, Vec<XorName>> = HashMap::new();
533        for (address, _) in &due {
534            let group: Vec<PeerId> = self
535                .p2p
536                .dht_manager()
537                .find_closest_nodes_local(address, self.config.close_group_size)
538                .await
539                .into_iter()
540                .map(|node| node.peer_id)
541                .filter(|peer| *peer != self_id)
542                .collect();
543            for peer in group.iter().filter(|peer| self.is_capable(peer)) {
544                asked.entry(*peer).or_default().push(*address);
545            }
546            groups.insert(*address, group);
547        }
548
549        let answers = self.ask_states(asked).await;
550
551        let decisions: Vec<(XorName, Verdict)> = due
552            .iter()
553            .map(|(address, _)| {
554                let group = groups.get(address).map_or(&[][..], Vec::as_slice);
555                let answered: Vec<(PeerId, Option<PointerState>)> = group
556                    .iter()
557                    .filter_map(|peer| {
558                        answers
559                            .get(&(*peer, *address))
560                            .map(|answer| (*peer, *answer))
561                    })
562                    .collect();
563                let held = self.store.state(address);
564                let verdict = evaluate(
565                    held.as_ref(),
566                    group.len(),
567                    &answered,
568                    self.config.quorum_needed(group.len()),
569                );
570                (*address, verdict)
571            })
572            .collect();
573
574        let outcomes: Vec<(XorName, bool)> = stream::iter(decisions)
575            .map(|(address, verdict)| async move {
576                match verdict {
577                    Verdict::Adopt { state, holders } => {
578                        let stored = self.fetch_and_store(address, state, &holders).await;
579                        (address, stored)
580                    }
581                    Verdict::Undecided => (address, false),
582                    Verdict::Refused => {
583                        info!(
584                            "No quorum backs a newer state for pointer {}",
585                            hex::encode(address)
586                        );
587                        self.pending.lock().remove(&address);
588                        (address, true)
589                    }
590                }
591            })
592            .buffer_unordered(VERIFICATION_CONCURRENCY)
593            .collect()
594            .await;
595
596        let now = Instant::now();
597        let mut pending = self.pending.lock();
598        for (address, settled) in outcomes {
599            if settled {
600                pending.remove(&address);
601                continue;
602            }
603            if let Some(entry) = pending.get_mut(&address) {
604                entry.attempts = entry.attempts.saturating_add(1);
605                if entry.attempts >= MAX_UNDECIDED_ROUNDS {
606                    pending.remove(&address);
607                } else {
608                    let backoff = UNDECIDED_BACKOFF
609                        .saturating_mul(2u32.saturating_pow(entry.attempts.saturating_sub(1)));
610                    entry.not_before = now + backoff;
611                }
612            }
613        }
614    }
615
616    /// Ask each peer which state it holds at the addresses listed for it.
617    async fn ask_states(
618        &self,
619        asked: HashMap<PeerId, Vec<XorName>>,
620    ) -> HashMap<(PeerId, XorName), Option<PointerState>> {
621        let requests: Vec<(PeerId, Vec<XorName>)> = asked
622            .into_iter()
623            .flat_map(|(peer, addresses)| {
624                addresses
625                    .chunks(MAX_POINTER_STATE_REQUEST_ADDRESSES)
626                    .map(|chunk| (peer, chunk.to_vec()))
627                    .collect::<Vec<_>>()
628            })
629            .collect();
630        let replies: Vec<Vec<StateAnswer>> = stream::iter(requests)
631            .map(|(peer, addresses)| async move {
632                let body = self
633                    .request(
634                        &peer,
635                        ReplicationMessageBody::PointerStateRequest(PointerStateRequest {
636                            addresses: addresses.clone(),
637                        }),
638                        self.config.verification_request_timeout,
639                    )
640                    .await;
641                let Some(ReplicationMessageBody::PointerStateResponse(response)) = body else {
642                    return Vec::new();
643                };
644                addresses
645                    .iter()
646                    .zip(response.states)
647                    .map(|(address, summary)| {
648                        // An answer about a different address is no answer.
649                        let state = summary
650                            .filter(|summary| summary.address == *address)
651                            .map(PointerState::from);
652                        ((peer, *address), state)
653                    })
654                    .collect()
655            })
656            .buffer_unordered(VERIFICATION_CONCURRENCY)
657            .collect()
658            .await;
659        replies.into_iter().flatten().collect()
660    }
661
662    /// Fetch `wanted` from one of `holders` and store it. Whether it is now
663    /// held, or nothing further can come of this round.
664    async fn fetch_and_store(
665        &self,
666        address: XorName,
667        wanted: PointerState,
668        holders: &[PeerId],
669    ) -> bool {
670        for holder in holders {
671            let Some(record) = self.fetch_record(holder, &address).await else {
672                continue;
673            };
674            // The quorum backed this state. A holder that has moved on since
675            // serves a different one, which that quorum says nothing about.
676            if record.state_id() != wanted.state_id {
677                continue;
678            }
679            match self.store_verified(record, None).await {
680                Ok(_) => return true,
681                Err(e) => {
682                    warn!(
683                        "Could not store replicated pointer {}: {e}",
684                        hex::encode(address)
685                    );
686                    return false;
687                }
688            }
689        }
690        false
691    }
692
693    /// Store a record whose signature has been checked, if it still belongs
694    /// here and beats what is held.
695    async fn store_verified(
696        &self,
697        record: Pointer,
698        width: Option<usize>,
699    ) -> crate::error::Result<bool> {
700        let state = record.state();
701        let self_id = *self.p2p.peer_id();
702        let width = width.unwrap_or_else(|| storage_admission_width(self.config.close_group_size));
703        let held = self.store.state(&state.address).is_some();
704        if !held && !admission::is_responsible(&self_id, &state.address, &self.p2p, width).await {
705            return Ok(false);
706        }
707        if !self.store.admits(&state) {
708            return Ok(false);
709        }
710        let reservation = self.chunks.reserve(POINTER_WIRE_LEN as u64)?;
711        self.store.commit(record, Some(reservation)).await?;
712        Ok(true)
713    }
714
715    // -----------------------------------------------------------------------
716    // Serving
717    // -----------------------------------------------------------------------
718
719    /// Answer a fetch request in the background.
720    pub(crate) fn serve_fetch_detached(
721        self: &Arc<Self>,
722        source: PeerId,
723        request: PointerFetchRequest,
724        request_id: u64,
725        rr_message_id: Option<String>,
726    ) {
727        self.mark_capable(&source);
728        let this = Arc::clone(self);
729        self.tracker.spawn(async move {
730            let Ok(_permit) = this.serve_permits.acquire().await else {
731                return;
732            };
733            // `get` verifies the signature before serving, so a record damaged
734            // on this disk is never handed on.
735            let record = match this.store.get(&request.address).await {
736                Ok(Some(record)) => Some(record.to_bytes()),
737                Ok(None) | Err(_) => None,
738            };
739            super::send_replication_response(
740                &source,
741                &this.p2p,
742                request_id,
743                ReplicationMessageBody::PointerFetchResponse(PointerFetchResponse {
744                    address: request.address,
745                    record,
746                }),
747                rr_message_id.as_deref(),
748            )
749            .await;
750        });
751    }
752
753    /// Answer a state request in the background, from the index.
754    pub(crate) fn serve_state_detached(
755        self: &Arc<Self>,
756        source: PeerId,
757        request: PointerStateRequest,
758        request_id: u64,
759        rr_message_id: Option<String>,
760    ) {
761        self.mark_capable(&source);
762        let this = Arc::clone(self);
763        self.tracker.spawn(async move {
764            let Ok(_permit) = this.serve_permits.acquire().await else {
765                return;
766            };
767            let states = request
768                .addresses
769                .iter()
770                .take(MAX_POINTER_STATE_REQUEST_ADDRESSES)
771                .map(|address| this.store.state(address).map(PointerStateSummary::from))
772                .collect();
773            super::send_replication_response(
774                &source,
775                &this.p2p,
776                request_id,
777                ReplicationMessageBody::PointerStateResponse(PointerStateResponse { states }),
778                rr_message_id.as_deref(),
779            )
780            .await;
781        });
782    }
783
784    // -----------------------------------------------------------------------
785    // Fresh replication
786    // -----------------------------------------------------------------------
787
788    /// Start the loop that offers freshly paid states to their close groups.
789    pub(crate) fn start_fresh_drainer(
790        self: &Arc<Self>,
791        mut writes: mpsc::UnboundedReceiver<PointerFreshWrite>,
792    ) -> JoinHandle<()> {
793        let this = Arc::clone(self);
794        tokio::spawn(async move {
795            loop {
796                tokio::select! {
797                    () = this.shutdown.cancelled() => break,
798                    write = writes.recv() => match write {
799                        Some(write) => this.replicate_fresh(write).await,
800                        None => break,
801                    },
802                }
803            }
804        })
805    }
806
807    /// Offer a freshly paid state to the rest of its close group, and schedule
808    /// the check that they took it.
809    pub async fn replicate_fresh(self: &Arc<Self>, write: PointerFreshWrite) {
810        let Ok(state) = PointerState::parse(&write.record) else {
811            warn!("A fresh pointer write did not parse; not replicating it");
812            return;
813        };
814        let self_id = *self.p2p.peer_id();
815        let targets: Vec<PeerId> = self
816            .p2p
817            .dht_manager()
818            .find_closest_nodes_local_with_self(&state.address, self.config.close_group_size)
819            .await
820            .into_iter()
821            .map(|node| node.peer_id)
822            .filter(|peer| *peer != self_id)
823            .collect();
824
825        let msg = ReplicationMessage {
826            request_id: rand::thread_rng().gen::<u64>(),
827            body: ReplicationMessageBody::PointerFreshOffer(PointerFreshOffer {
828                record: write.record,
829                proof_of_payment: write.payment_proof,
830            }),
831        };
832        let Ok(encoded) = msg.encode() else {
833            warn!(
834                "Failed to encode a fresh pointer offer for {}",
835                hex::encode(state.address)
836            );
837            return;
838        };
839        let encoded = Arc::new(encoded);
840        for peer in &targets {
841            let p2p = Arc::clone(&self.p2p);
842            let bytes = Arc::clone(&encoded);
843            let semaphore = Arc::clone(&self.send_semaphore);
844            let peer = *peer;
845            self.tracker.spawn(async move {
846                let Ok(_permit) = semaphore.acquire().await else {
847                    return;
848                };
849                for attempt in 0..=FRESH_REPLICATION_DELIVERY_MAX_RETRIES {
850                    match p2p
851                        .send_message(&peer, REPLICATION_PROTOCOL_ID, bytes.as_ref().clone(), &[])
852                        .await
853                    {
854                        Ok(()) => break,
855                        Err(e) => debug!(
856                            "Fresh pointer offer to {peer} failed (attempt {}): {e}",
857                            attempt + 1
858                        ),
859                    }
860                }
861            });
862        }
863        debug!(
864            "Fresh pointer {} offered to {} peers",
865            hex::encode(state.address),
866            targets.len()
867        );
868        self.schedule_possession_check(state, targets);
869    }
870
871    /// Take a fresh offer from `source` in the background, unless too many are
872    /// already being verified.
873    pub(crate) fn accept_offer_detached(
874        self: &Arc<Self>,
875        source: PeerId,
876        offer: PointerFreshOffer,
877    ) {
878        self.mark_capable(&source);
879        let Ok(permit) = Arc::clone(&self.offer_permits).try_acquire_owned() else {
880            info!("Dropping a fresh pointer offer from {source}: too many in flight");
881            return;
882        };
883        let this = Arc::clone(self);
884        self.tracker.spawn(async move {
885            let _permit = permit;
886            this.accept_offer(source, offer).await;
887        });
888    }
889
890    /// Verify and store a fresh offer. Cheapest checks first; the signature and
891    /// the on-chain payment lookup only for a state that would change something
892    /// here and that this node is responsible for.
893    async fn accept_offer(&self, source: PeerId, offer: PointerFreshOffer) {
894        if offer.record.len() != POINTER_WIRE_LEN
895            || !(MIN_PAYMENT_PROOF_SIZE_BYTES..=MAX_PAYMENT_PROOF_SIZE_BYTES)
896                .contains(&offer.proof_of_payment.len())
897        {
898            debug!("Dropping a malformed fresh pointer offer from {source}");
899            self.penalise(&source).await;
900            return;
901        }
902        let parsed = match self.store.inspect(&offer.record).await {
903            Ok(Inspected::Candidate(parsed)) => parsed,
904            Ok(Inspected::Unchanged(_) | Inspected::Stale(_)) => return,
905            Err(e) => {
906                debug!("Dropping an unparseable fresh pointer offer from {source}: {e}");
907                self.penalise(&source).await;
908                return;
909            }
910        };
911        let state = *parsed.state();
912        let self_id = *self.p2p.peer_id();
913        // As for a chunk: a fresh offer is taken across the wider paid width.
914        if !admission::is_responsible(
915            &self_id,
916            &state.address,
917            &self.p2p,
918            self.config.paid_list_close_group_size,
919        )
920        .await
921        {
922            return;
923        }
924        if !self.store.admits(&state)
925            || self
926                .chunks
927                .check_capacity_for(POINTER_WIRE_LEN as u64)
928                .is_err()
929        {
930            return;
931        }
932        let record = match self.store.verify(parsed).await {
933            Ok(record) => record,
934            Err(e) => {
935                debug!("Fresh pointer offer from {source} does not verify: {e}");
936                self.penalise(&source).await;
937                return;
938            }
939        };
940        if let Err(e) = self
941            .payments
942            .verify_pointer_payment_in(
943                &state.address,
944                &state.state_id,
945                &offer.proof_of_payment,
946                VerificationContext::FreshReplication,
947            )
948            .await
949        {
950            info!(
951                "Fresh pointer offer for {} from {source} is not paid for: {e}",
952                hex::encode(state.address)
953            );
954            return;
955        }
956        match self
957            .store_verified(record, Some(self.config.paid_list_close_group_size))
958            .await
959        {
960            Ok(true) => debug!(
961                "Stored fresh pointer {} from {source}",
962                hex::encode(state.address)
963            ),
964            Ok(false) => {}
965            Err(e) => warn!(
966                "Could not store fresh pointer {}: {e}",
967                hex::encode(state.address)
968            ),
969        }
970    }
971
972    // -----------------------------------------------------------------------
973    // Possession
974    // -----------------------------------------------------------------------
975
976    fn schedule_possession_check(self: &Arc<Self>, fresh: PointerState, peers: Vec<PeerId>) {
977        if peers.is_empty() {
978            return;
979        }
980        let min = self.config.possession_check_delay_min;
981        let max = self.config.possession_check_delay_max.max(min);
982        let delay = if max > min {
983            rand::thread_rng().gen_range(min..=max)
984        } else {
985            min
986        };
987        let this = Arc::clone(self);
988        self.tracker.spawn(async move {
989            tokio::select! {
990                () = this.shutdown.cancelled() => return,
991                () = tokio::time::sleep(delay) => {}
992            }
993            this.check_possession(fresh, &peers).await;
994        });
995    }
996
997    /// Ask each peer for the record, and penalise any still responsible for it
998    /// that cannot produce `fresh` or a state that replaces it.
999    pub async fn check_possession(&self, fresh: PointerState, peers: &[PeerId]) {
1000        let self_id = *self.p2p.peer_id();
1001        let group: HashSet<PeerId> = self
1002            .p2p
1003            .dht_manager()
1004            .find_closest_nodes_local_with_self(&fresh.address, self.config.close_group_size)
1005            .await
1006            .into_iter()
1007            .map(|node| node.peer_id)
1008            .collect();
1009        for peer in peers {
1010            // A peer that has left the group owes nothing, and one that cannot
1011            // be asked is never judged on its silence.
1012            if *peer == self_id || !group.contains(peer) || !self.is_capable(peer) {
1013                continue;
1014            }
1015            let holds = self
1016                .fetch_record(peer, &fresh.address)
1017                .await
1018                .is_some_and(|record| {
1019                    let state = record.state();
1020                    state.state_id == fresh.state_id || state.replaces(&fresh)
1021                });
1022            if !holds {
1023                warn!(
1024                    "Peer {peer} does not hold pointer {} it was offered",
1025                    hex::encode(fresh.address)
1026                );
1027                self.penalise(peer).await;
1028            }
1029        }
1030    }
1031
1032    // -----------------------------------------------------------------------
1033    // Pruning
1034    // -----------------------------------------------------------------------
1035
1036    /// Delete records this node has been out of range of for the hysteresis
1037    /// period, where that is safe. Run when a neighbour-sync cycle completes.
1038    ///
1039    /// `allow_remote` is false while bootstrapping: candidacy is still tracked,
1040    /// but nothing that needs other peers' proof is decided.
1041    ///
1042    /// A record a retained storage commitment still commits to is never
1043    /// deleted, exactly as for a chunk: an auditor pinning that commitment may
1044    /// still open it, and a node that deleted it would fail that audit.
1045    pub async fn prune_pass(
1046        &self,
1047        allow_remote: bool,
1048        commitment_state: Option<&ResponderCommitmentState>,
1049    ) {
1050        let committed = |address: &XorName| commitment_state.is_some_and(|cs| cs.is_held(address));
1051        let self_id = *self.p2p.peer_id();
1052        let retention = storage_admission_width(self.config.close_group_size);
1053        let now = Instant::now();
1054        let held = self.store.held_states();
1055
1056        let mut candidates = Vec::new();
1057        for state in &held {
1058            if admission::is_responsible(&self_id, &state.address, &self.p2p, retention).await {
1059                self.out_of_range.lock().remove(&state.address);
1060                continue;
1061            }
1062            let first_seen = *self.out_of_range.lock().entry(state.address).or_insert(now);
1063            if now.duration_since(first_seen) >= self.config.prune_hysteresis_duration {
1064                candidates.push(*state);
1065            }
1066        }
1067        {
1068            let held: HashSet<XorName> = held.iter().map(|state| state.address).collect();
1069            self.out_of_range
1070                .lock()
1071                .retain(|address, _| held.contains(address));
1072        }
1073
1074        let mut deleted = 0usize;
1075        for state in candidates.into_iter().take(MAX_PRUNE_CANDIDATES_PER_PASS) {
1076            if self.shutdown.is_cancelled() {
1077                return;
1078            }
1079            if committed(&state.address) {
1080                continue;
1081            }
1082            let wide = self
1083                .p2p
1084                .dht_manager()
1085                .find_closest_nodes_local_with_self(
1086                    &state.address,
1087                    self.config.paid_list_close_group_size,
1088                )
1089                .await;
1090            let far = wide.len() >= self.config.paid_list_close_group_size
1091                && !wide.iter().any(|node| node.peer_id == self_id);
1092            let confirmed = if far {
1093                true
1094            } else if allow_remote && !*self.is_bootstrapping.read().await {
1095                self.others_hold(&state).await
1096            } else {
1097                false
1098            };
1099            // Revalidate just before deleting: the group may have moved back.
1100            if confirmed
1101                && !committed(&state.address)
1102                && !admission::is_responsible(&self_id, &state.address, &self.p2p, retention).await
1103                && self.delete(&state.address).await
1104            {
1105                deleted += 1;
1106            }
1107        }
1108        if deleted > 0 {
1109            info!("Pruned {deleted} pointer records this node is no longer responsible for");
1110        }
1111    }
1112
1113    /// Whether all but one of the current close group prove they hold `ours`
1114    /// or a newer state, by returning a valid record.
1115    async fn others_hold(&self, ours: &PointerState) -> bool {
1116        let group: Vec<PeerId> = self
1117            .p2p
1118            .dht_manager()
1119            .find_closest_nodes_local(&ours.address, self.config.close_group_size)
1120            .await
1121            .into_iter()
1122            .map(|node| node.peer_id)
1123            .collect();
1124        let needed = prune_proofs_needed(group.len());
1125        if needed == 0 {
1126            return false;
1127        }
1128        let mut proofs = 0usize;
1129        for peer in group.iter().filter(|peer| self.is_capable(peer)) {
1130            let proves = self
1131                .fetch_record(peer, &ours.address)
1132                .await
1133                .is_some_and(|record| {
1134                    let state = record.state();
1135                    state.state_id == ours.state_id || state.replaces(ours)
1136                });
1137            if proves {
1138                proofs += 1;
1139                if proofs >= needed {
1140                    return true;
1141                }
1142            }
1143        }
1144        false
1145    }
1146
1147    async fn delete(&self, address: &XorName) -> bool {
1148        self.out_of_range.lock().remove(address);
1149        match self.store.delete(address).await {
1150            Ok(true) => {
1151                self.chunks.release(POINTER_WIRE_LEN as u64);
1152                true
1153            }
1154            Ok(false) => false,
1155            Err(e) => {
1156                warn!("Could not prune pointer {}: {e}", hex::encode(address));
1157                false
1158            }
1159        }
1160    }
1161}
1162
1163#[cfg(test)]
1164#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1165mod tests {
1166    use super::*;
1167    use ant_protocol::pointer::{PointerTarget, PointerTargetKind};
1168
1169    fn state(counter: u64, target: u8, id: u8) -> PointerState {
1170        PointerState {
1171            state_id: [id; 32],
1172            address: [7; 32],
1173            counter,
1174            target: PointerTarget::new(PointerTargetKind::Chunk, [target; 32]),
1175        }
1176    }
1177
1178    fn peer(byte: u8) -> PeerId {
1179        PeerId::from_bytes([byte; 32])
1180    }
1181
1182    fn answers(list: &[(u8, Option<PointerState>)]) -> Vec<(PeerId, Option<PointerState>)> {
1183        list.iter().map(|(p, s)| (peer(*p), *s)).collect()
1184    }
1185
1186    #[test]
1187    fn a_state_a_quorum_holds_is_adopted_from_its_holders() {
1188        let newer = state(3, 1, 30);
1189        let got = evaluate(
1190            None,
1191            7,
1192            &answers(&[
1193                (1, Some(newer)),
1194                (2, Some(newer)),
1195                (3, Some(newer)),
1196                (4, Some(newer)),
1197                (5, None),
1198            ]),
1199            4,
1200        );
1201        match got {
1202            Verdict::Adopt { state, holders } => {
1203                assert_eq!(state.state_id, newer.state_id);
1204                assert_eq!(holders.len(), 4);
1205            }
1206            other => panic!("expected Adopt, got {other:?}"),
1207        }
1208    }
1209
1210    #[test]
1211    fn a_state_below_quorum_is_never_adopted() {
1212        // One peer, or three, holding a state is not the network's word.
1213        let lone = state(9, 1, 90);
1214        let got = evaluate(
1215            None,
1216            7,
1217            &answers(&[
1218                (1, Some(lone)),
1219                (2, Some(lone)),
1220                (3, Some(lone)),
1221                (4, None),
1222                (5, None),
1223                (6, None),
1224                (7, None),
1225            ]),
1226            4,
1227        );
1228        assert_eq!(got, Verdict::Refused);
1229
1230        // With one peer silent, three holders plus that peer could still make
1231        // four: undecided, not refused.
1232        let got = evaluate(
1233            None,
1234            7,
1235            &answers(&[
1236                (1, Some(lone)),
1237                (2, Some(lone)),
1238                (3, Some(lone)),
1239                (4, None),
1240                (5, None),
1241                (6, None),
1242            ]),
1243            4,
1244        );
1245        assert_eq!(got, Verdict::Undecided);
1246    }
1247
1248    #[test]
1249    fn silence_is_not_a_vote_so_an_unanswered_group_stays_undecided() {
1250        let newer = state(3, 1, 30);
1251        let got = evaluate(None, 7, &answers(&[(1, Some(newer)), (2, Some(newer))]), 4);
1252        assert_eq!(got, Verdict::Undecided);
1253    }
1254
1255    #[test]
1256    fn nothing_older_than_what_is_held_is_adopted() {
1257        let held = state(5, 1, 50);
1258        let older = state(4, 1, 40);
1259        let got = evaluate(
1260            Some(&held),
1261            7,
1262            &answers(&[
1263                (1, Some(older)),
1264                (2, Some(older)),
1265                (3, Some(older)),
1266                (4, Some(older)),
1267                (5, Some(older)),
1268            ]),
1269            4,
1270        );
1271        assert_eq!(got, Verdict::Refused);
1272    }
1273
1274    #[test]
1275    fn of_two_states_with_quorum_the_merge_winner_is_adopted() {
1276        let lower = state(2, 9, 20);
1277        let winner = state(2, 1, 21);
1278        assert!(winner.replaces(&lower));
1279        let got = evaluate(
1280            None,
1281            8,
1282            &answers(&[
1283                (1, Some(lower)),
1284                (2, Some(lower)),
1285                (3, Some(lower)),
1286                (4, Some(lower)),
1287                (5, Some(winner)),
1288                (6, Some(winner)),
1289                (7, Some(winner)),
1290                (8, Some(winner)),
1291            ]),
1292            4,
1293        );
1294        match got {
1295            Verdict::Adopt { state, .. } => assert_eq!(state.state_id, winner.state_id),
1296            other => panic!("expected the winner, got {other:?}"),
1297        }
1298    }
1299
1300    #[test]
1301    fn a_group_nobody_can_be_asked_in_is_undecided() {
1302        assert_eq!(evaluate(None, 0, &[], 0), Verdict::Undecided);
1303    }
1304}