Skip to main content

ant_node/replication/
admission.rs

1//! Neighbor-sync hint admission rules (Section 7).
2//!
3//! Per-key admission filtering before verification pipeline entry.
4//!
5//! When a neighbor sync hint arrives, each key must pass admission before
6//! entering verification. The admission rules check:
7//! 1. Sender is authenticated and in `LocalRT(self)` (checked before calling
8//!    this module).
9//! 2. Key is relevant to the receiver (checked here).
10
11use std::collections::HashSet;
12use std::sync::Arc;
13
14use saorsa_core::identity::PeerId;
15use saorsa_core::P2PNode;
16
17use crate::ant_protocol::XorName;
18use crate::replication::config::ReplicationConfig;
19use crate::replication::paid_list::PaidList;
20use crate::storage::ChunkStore;
21
22/// Result of admitting a set of hints from a neighbor sync.
23#[derive(Debug)]
24pub struct AdmissionResult {
25    /// Keys admitted into the replica-hint pipeline (fetch-eligible).
26    pub replica_keys: Vec<XorName>,
27    /// Keys admitted into the paid-hint-only pipeline (`PaidForList` update
28    /// only).
29    pub paid_only_keys: Vec<XorName>,
30    /// Keys rejected (not relevant to this node).
31    pub rejected_keys: Vec<XorName>,
32}
33
34/// Check if this node is within a caller-supplied closest-peer width for key
35/// `K`.
36///
37/// Returns `true` if `self_id` is among the `responsibility_width` nearest
38/// peers to `K` in `SelfInclusiveRT`.
39pub async fn is_responsible(
40    self_id: &PeerId,
41    key: &XorName,
42    p2p_node: &Arc<P2PNode>,
43    responsibility_width: usize,
44) -> bool {
45    let closest = p2p_node
46        .dht_manager()
47        .find_closest_nodes_local_with_self(key, responsibility_width)
48        .await;
49    closest.iter().any(|n| n.peer_id == *self_id)
50}
51
52/// Check if this node is in the `PaidCloseGroup` for key `K`.
53///
54/// `PaidCloseGroup` = `paid_list_close_group_size` nearest peers to `K` in
55/// `SelfInclusiveRT`.
56pub async fn is_in_paid_close_group(
57    self_id: &PeerId,
58    key: &XorName,
59    p2p_node: &Arc<P2PNode>,
60    paid_list_close_group_size: usize,
61) -> bool {
62    let closest = p2p_node
63        .dht_manager()
64        .find_closest_nodes_local_with_self(key, paid_list_close_group_size)
65        .await;
66    closest.iter().any(|n| n.peer_id == *self_id)
67}
68
69/// Is this key worth tracking at all?
70///
71/// One gate for every hint, whatever the sender labelled it. Admission asks
72/// only whether the key is relevant to us — whether we should learn that it
73/// exists and is paid for. That is the `PaidCloseGroup(K)` question, since
74/// `paid_list_close_group_size` is exactly the width across which nodes track
75/// payment validity.
76///
77/// Storage responsibility is a *different* question, asked later against live
78/// routing state at the point of download. Keeping the two apart is what makes
79/// the sender's replica/paid labelling unable to influence what we store.
80async fn is_relevant(
81    self_id: &PeerId,
82    key: &XorName,
83    p2p_node: &Arc<P2PNode>,
84    config: &ReplicationConfig,
85    storage: &Arc<ChunkStore>,
86    paid_list: &Arc<PaidList>,
87    pending_keys: &HashSet<XorName>,
88) -> bool {
89    // Fast paths: we already hold the key, already track it, or already know it
90    // is paid for. Each means the relevance question is settled -- no
91    // routing-table lookup needed.
92    storage.exists(key).unwrap_or(false)
93        || pending_keys.contains(key)
94        || paid_list.contains(key).unwrap_or(false)
95        || is_in_paid_close_group(self_id, key, p2p_node, config.paid_list_close_group_size).await
96}
97
98/// Admit neighbor-sync hints per Section 7.1 rules.
99///
100/// Every key -- replica-hinted or paid-hinted -- passes the same `is_relevant`
101/// gate. The hint set a key arrived on decides only whether the sender is
102/// recorded as claiming possession, which makes it a candidate fetch source; it
103/// does not decide admission, and it does not decide storage.
104///
105/// - **Cross-set precedence**: a key in both sets is settled by the replica
106///   pass, so the paid pass skips it.
107///
108/// Returns an [`AdmissionResult`] with keys sorted into pipelines.
109#[allow(clippy::too_many_arguments, clippy::implicit_hasher)]
110pub async fn admit_hints(
111    self_id: &PeerId,
112    replica_hints: &[XorName],
113    paid_hints: &[XorName],
114    p2p_node: &Arc<P2PNode>,
115    config: &ReplicationConfig,
116    storage: &Arc<ChunkStore>,
117    paid_list: &Arc<PaidList>,
118    pending_keys: &HashSet<XorName>,
119) -> AdmissionResult {
120    let mut result = AdmissionResult {
121        replica_keys: Vec::new(),
122        paid_only_keys: Vec::new(),
123        rejected_keys: Vec::new(),
124    };
125
126    let mut seen_replica = HashSet::new();
127    for &key in replica_hints {
128        if !seen_replica.insert(key) {
129            continue;
130        }
131        if is_relevant(
132            self_id,
133            &key,
134            p2p_node,
135            config,
136            storage,
137            paid_list,
138            pending_keys,
139        )
140        .await
141        {
142            result.replica_keys.push(key);
143        } else {
144            result.rejected_keys.push(key);
145        }
146    }
147
148    let mut seen_paid = HashSet::new();
149    for &key in paid_hints {
150        if !seen_paid.insert(key) {
151            continue;
152        }
153        // Cross-set precedence: the replica pass already ruled on this key,
154        // under the same gate this pass would apply. Re-asking cannot change
155        // the answer, and re-recording it would double-count the rejection.
156        if seen_replica.contains(&key) {
157            continue;
158        }
159        if is_relevant(
160            self_id,
161            &key,
162            p2p_node,
163            config,
164            storage,
165            paid_list,
166            pending_keys,
167        )
168        .await
169        {
170            result.paid_only_keys.push(key);
171        } else {
172            result.rejected_keys.push(key);
173        }
174    }
175
176    result
177}
178
179// ---------------------------------------------------------------------------
180// Tests
181// ---------------------------------------------------------------------------
182
183#[cfg(test)]
184#[allow(clippy::unwrap_used, clippy::expect_used)]
185mod tests {
186    use super::*;
187    use crate::client::xor_distance;
188    use crate::replication::config::ReplicationConfig;
189
190    /// Build a `PeerId` from a single byte (zero-padded to 32 bytes).
191    fn peer_id_from_byte(b: u8) -> PeerId {
192        let mut bytes = [0u8; 32];
193        bytes[0] = b;
194        PeerId::from_bytes(bytes)
195    }
196
197    /// Build an `XorName` from a single byte (repeated to 32 bytes).
198    fn xor_name_from_byte(b: u8) -> XorName {
199        [b; 32]
200    }
201
202    // -----------------------------------------------------------------------
203    // AdmissionResult construction helpers for pure-logic tests
204    //
205    // The full `admit_hints` function requires a live DHT + LMDB backend.
206    // For unit tests we directly exercise:
207    //   1. Cross-set precedence logic
208    //   2. Deduplication logic
209    //   3. evaluate_key_evidence (in quorum.rs)
210    //
211    // Below we simulate admission by using the pure-logic portions.
212    // -----------------------------------------------------------------------
213
214    #[test]
215    fn cross_set_precedence_replica_wins() {
216        // When a key appears in both replica_hints and paid_hints, the
217        // paid_hints entry should be suppressed by cross-set precedence.
218        let key = xor_name_from_byte(0xAA);
219        let replica_set: HashSet<XorName> = std::iter::once(key).collect();
220
221        // Simulating the paid-hint loop: key is in replica_set, so it should
222        // be skipped.
223        assert!(
224            replica_set.contains(&key),
225            "paid-hint key present in replica set should be skipped"
226        );
227    }
228
229    #[test]
230    fn deduplication_within_replica_hints() {
231        // Duplicate keys in replica_hints should only appear once.
232        let key_a = xor_name_from_byte(0x01);
233        let key_b = xor_name_from_byte(0x02);
234        let hints = vec![key_a, key_b, key_a, key_a, key_b];
235
236        let mut seen = HashSet::new();
237        let mut unique = Vec::new();
238        for &key in &hints {
239            if seen.insert(key) {
240                unique.push(key);
241            }
242        }
243
244        assert_eq!(unique.len(), 2);
245        assert_eq!(unique[0], key_a);
246        assert_eq!(unique[1], key_b);
247    }
248
249    #[test]
250    fn deduplication_across_sets() {
251        // If a key appears in replica_hints AND paid_hints and the replica
252        // side is admitted, the paid entry is skipped because the stronger
253        // replica pipeline already covers paid-list convergence.
254        let key = xor_name_from_byte(0xFF);
255        let replica_hints = vec![key];
256        let paid_hints = vec![key];
257
258        let mut admitted_replica: HashSet<XorName> = HashSet::new();
259
260        for &k in &replica_hints {
261            admitted_replica.insert(k);
262        }
263
264        let mut paid_admitted = Vec::new();
265        for &k in &paid_hints {
266            if admitted_replica.contains(&k) {
267                continue; // cross-set precedence
268            }
269            paid_admitted.push(k);
270        }
271
272        assert!(
273            paid_admitted.is_empty(),
274            "paid-hint should be suppressed when key is also a replica hint"
275        );
276    }
277
278    #[test]
279    fn admission_result_empty_inputs() {
280        let result = AdmissionResult {
281            replica_keys: Vec::new(),
282            paid_only_keys: Vec::new(),
283            rejected_keys: Vec::new(),
284        };
285
286        assert!(
287            result.replica_keys.is_empty(),
288            "expected no replica keys, got {:?}",
289            result.replica_keys
290        );
291        assert!(
292            result.paid_only_keys.is_empty(),
293            "expected no paid-only keys, got {:?}",
294            result.paid_only_keys
295        );
296        assert!(
297            result.rejected_keys.is_empty(),
298            "expected no rejected keys, got {:?}",
299            result.rejected_keys
300        );
301    }
302
303    #[test]
304    fn out_of_range_keys_rejected_by_distance() {
305        // Simulate rejection: a key whose XOR distance from self is large
306        // should not appear in a close-group of size 3 when there are closer
307        // peers.
308        let _self_id = peer_id_from_byte(0x00);
309        let key = xor_name_from_byte(0xFF);
310        let _config = ReplicationConfig::default();
311
312        // Distance from self (0x00...) to key (0xFF...):
313        let self_xor: XorName = [0u8; 32];
314        let dist = xor_distance(&self_xor, &key);
315
316        // A very far key would have high distance -- this proves the concept.
317        assert_eq!(dist[0], 0xFF, "distance first byte should be 0xFF");
318
319        // Meanwhile a close key would have a small distance.
320        let close_key = xor_name_from_byte(0x01);
321        let close_dist = xor_distance(&self_xor, &close_key);
322        assert_eq!(
323            close_dist[0], 0x01,
324            "close distance first byte should be 0x01"
325        );
326
327        assert!(
328            dist > close_dist,
329            "far key should have greater distance than close key"
330        );
331    }
332
333    #[test]
334    fn config_close_group_sizes_are_valid() {
335        let config = ReplicationConfig::default();
336        assert!(
337            config.close_group_size > 0,
338            "close_group_size must be positive"
339        );
340        assert!(
341            config.paid_list_close_group_size > 0,
342            "paid_list_close_group_size must be positive"
343        );
344        assert!(
345            config.paid_list_close_group_size >= config.close_group_size,
346            "paid_list_close_group_size should be >= close_group_size"
347        );
348    }
349
350    // -----------------------------------------------------------------------
351    // Section 18 scenarios
352    // -----------------------------------------------------------------------
353
354    /// Scenario 5: Unauthorized sync peer — hints from peers not in
355    /// `LocalRT(self)` are dropped and do not enter verification.
356    ///
357    /// Two layers enforce this:
358    /// (a) `handle_sync_request` in `neighbor_sync.rs` returns
359    ///     `sender_in_rt = false` when the sender is not in `LocalRT`.
360    ///     The caller (`handle_neighbor_sync_request` in `mod.rs`) returns
361    ///     early without processing ANY inbound hints. This is the primary
362    ///     gate tested at the e2e level (scenario 17 tests the positive
363    ///     case).
364    /// (b) Even if a sender IS in `LocalRT`, the per-key relevance check
365    ///     (`is_relevant`, i.e. `is_in_paid_close_group`) in `admit_hints`
366    ///     still applies. Sender identity does not grant key admission.
367    ///
368    /// This test exercises layer (b): the admission pipeline's dedup,
369    /// cross-set precedence, and relevance filtering using the same logic
370    /// that `admit_hints` performs — without the `P2PNode` dependency
371    /// needed for the actual `is_in_paid_close_group` DHT lookup.
372    #[test]
373    fn scenario_5_sender_does_not_grant_key_relevance() {
374        let key_pending = xor_name_from_byte(0xB0);
375        let key_not_pending = xor_name_from_byte(0xB1);
376        let key_paid_existing = xor_name_from_byte(0xB2);
377        let _sender = peer_id_from_byte(0x01);
378
379        // Simulate local state: only key_pending is in the pending set,
380        // key_paid_existing is in the paid list.
381        let pending: HashSet<XorName> = std::iter::once(key_pending).collect();
382        let paid_set: HashSet<XorName> = std::iter::once(key_paid_existing).collect();
383
384        // Trace through admit_hints logic for replica hints:
385        let replica_hints = [key_pending, key_not_pending];
386        let replica_set: HashSet<XorName> = replica_hints.iter().copied().collect();
387        let mut seen = HashSet::new();
388        let mut admitted_replica = Vec::new();
389        let mut rejected = Vec::new();
390
391        for &key in &replica_hints {
392            if !seen.insert(key) {
393                continue; // dedup
394            }
395            // Fast path: already pending -> admitted.
396            if pending.contains(&key) {
397                admitted_replica.push(key);
398                continue;
399            }
400            // key_not_pending: not pending, not local, not paid -> needs the
401            // paid-close-group relevance check. Simulate it returning false.
402            let is_relevant = false;
403            if is_relevant {
404                admitted_replica.push(key);
405            } else {
406                rejected.push(key);
407            }
408        }
409
410        // Trace through paid hints:
411        let paid_hints = [key_paid_existing, key_pending]; // key_pending overlaps with replica
412        let mut admitted_paid = Vec::new();
413
414        for &key in &paid_hints {
415            if !seen.insert(key) {
416                continue; // dedup: key_pending already seen
417            }
418            if replica_set.contains(&key) {
419                continue; // cross-set precedence
420            }
421            // Fast path: already in paid list -> admitted.
422            if paid_set.contains(&key) {
423                admitted_paid.push(key);
424                continue;
425            }
426            rejected.push(key);
427        }
428
429        // Verify outcomes:
430        assert_eq!(
431            admitted_replica,
432            vec![key_pending],
433            "only the pending key should be admitted as replica"
434        );
435        assert_eq!(
436            rejected,
437            vec![key_not_pending],
438            "non-pending, non-responsible key must be rejected"
439        );
440        assert_eq!(
441            admitted_paid,
442            vec![key_paid_existing],
443            "existing paid-list key should be admitted via fast path"
444        );
445
446        // Cross-set precedence: key_pending appeared in both replica and
447        // paid hints — it was processed as replica only, paid duplicate
448        // was deduped.
449        assert!(
450            !admitted_paid.contains(&key_pending),
451            "key in both hint sets must be processed as replica only"
452        );
453    }
454
455    /// Scenario 7: Out-of-range key hint rejected regardless of quorum.
456    ///
457    /// A key whose XOR distance from self is much larger than the distance of
458    /// the paid-close-group members fails the `is_relevant` check in
459    /// `admit_hints`. The key never enters the verification pipeline, so quorum
460    /// is irrelevant.
461    ///
462    /// This test exercises the distance-based reasoning that `admit_hints`
463    /// uses, tracing through the same logic path. Full `is_in_paid_close_group`
464    /// requires a `P2PNode` for DHT lookups; here we verify the distance
465    /// comparison and admission outcome for both close and far keys.
466    #[test]
467    fn scenario_7_out_of_range_key_rejected() {
468        let self_xor: XorName = [0u8; 32];
469
470        // -- Distance proof: far key vs close key --
471
472        let far_key = xor_name_from_byte(0xFF);
473        let close_key = xor_name_from_byte(0x01);
474        let far_dist = xor_distance(&self_xor, &far_key);
475        let close_dist = xor_distance(&self_xor, &close_key);
476
477        assert_eq!(far_dist[0], 0xFF, "far_key distance should be maximal");
478        assert_eq!(close_dist[0], 0x01, "close_key distance should be small");
479        assert!(far_dist > close_dist, "far key is further than close key");
480
481        // -- Simulate admit_hints for these keys --
482        //
483        // When the paid-close-group peers are all closer to far_key than self,
484        // `is_in_paid_close_group(self, far_key)` returns false. The key is
485        // rejected without entering verification or quorum.
486
487        let pending: HashSet<XorName> = HashSet::new();
488        let replica_hints = [far_key, close_key];
489        let mut seen = HashSet::new();
490        let mut admitted = Vec::new();
491        let mut rejected = Vec::new();
492
493        for &key in &replica_hints {
494            if !seen.insert(key) {
495                continue;
496            }
497            // Not pending, not local.
498            if pending.contains(&key) {
499                admitted.push(key);
500                continue;
501            }
502            // Simulate is_in_paid_close_group: self (0x00) has the full
503            // paid close group closer to far_key (0xFF) than itself. For
504            // close_key (0x01), self is very close -> relevant.
505            let distance = xor_distance(&self_xor, &key);
506            let simulated_relevant = distance[0] < 0x80;
507            if simulated_relevant {
508                admitted.push(key);
509            } else {
510                rejected.push(key);
511            }
512        }
513
514        assert_eq!(
515            admitted,
516            vec![close_key],
517            "only close key should be admitted"
518        );
519        assert_eq!(
520            rejected,
521            vec![far_key],
522            "far key should be rejected regardless of quorum — it never enters verification"
523        );
524
525        // Verify the key doesn't sneak in via paid hints either.
526        // far_key was already seen (deduped), so paid processing skips it.
527        let paid_hints = [far_key];
528        let replica_set: HashSet<XorName> = replica_hints.iter().copied().collect();
529        let mut paid_admitted = Vec::new();
530
531        for &key in &paid_hints {
532            if !seen.insert(key) {
533                continue; // already seen from replica processing
534            }
535            if replica_set.contains(&key) {
536                continue; // cross-set precedence
537            }
538            paid_admitted.push(key);
539        }
540
541        assert!(
542            paid_admitted.is_empty(),
543            "far key already processed as replica (and rejected) should not re-enter via paid hints"
544        );
545    }
546}