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::LmdbStorage;
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<LmdbStorage>,
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<LmdbStorage>,
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!(result.replica_keys.is_empty());
287        assert!(result.paid_only_keys.is_empty());
288        assert!(result.rejected_keys.is_empty());
289    }
290
291    #[test]
292    fn out_of_range_keys_rejected_by_distance() {
293        // Simulate rejection: a key whose XOR distance from self is large
294        // should not appear in a close-group of size 3 when there are closer
295        // peers.
296        let _self_id = peer_id_from_byte(0x00);
297        let key = xor_name_from_byte(0xFF);
298        let _config = ReplicationConfig::default();
299
300        // Distance from self (0x00...) to key (0xFF...):
301        let self_xor: XorName = [0u8; 32];
302        let dist = xor_distance(&self_xor, &key);
303
304        // A very far key would have high distance -- this proves the concept.
305        assert_eq!(dist[0], 0xFF, "distance first byte should be 0xFF");
306
307        // Meanwhile a close key would have a small distance.
308        let close_key = xor_name_from_byte(0x01);
309        let close_dist = xor_distance(&self_xor, &close_key);
310        assert_eq!(
311            close_dist[0], 0x01,
312            "close distance first byte should be 0x01"
313        );
314
315        assert!(
316            dist > close_dist,
317            "far key should have greater distance than close key"
318        );
319    }
320
321    #[test]
322    fn config_close_group_sizes_are_valid() {
323        let config = ReplicationConfig::default();
324        assert!(
325            config.close_group_size > 0,
326            "close_group_size must be positive"
327        );
328        assert!(
329            config.paid_list_close_group_size > 0,
330            "paid_list_close_group_size must be positive"
331        );
332        assert!(
333            config.paid_list_close_group_size >= config.close_group_size,
334            "paid_list_close_group_size should be >= close_group_size"
335        );
336    }
337
338    // -----------------------------------------------------------------------
339    // Section 18 scenarios
340    // -----------------------------------------------------------------------
341
342    /// Scenario 5: Unauthorized sync peer — hints from peers not in
343    /// `LocalRT(self)` are dropped and do not enter verification.
344    ///
345    /// Two layers enforce this:
346    /// (a) `handle_sync_request` in `neighbor_sync.rs` returns
347    ///     `sender_in_rt = false` when the sender is not in `LocalRT`.
348    ///     The caller (`handle_neighbor_sync_request` in `mod.rs`) returns
349    ///     early without processing ANY inbound hints. This is the primary
350    ///     gate tested at the e2e level (scenario 17 tests the positive
351    ///     case).
352    /// (b) Even if a sender IS in `LocalRT`, the per-key relevance check
353    ///     (`is_relevant`, i.e. `is_in_paid_close_group`) in `admit_hints`
354    ///     still applies. Sender identity does not grant key admission.
355    ///
356    /// This test exercises layer (b): the admission pipeline's dedup,
357    /// cross-set precedence, and relevance filtering using the same logic
358    /// that `admit_hints` performs — without the `P2PNode` dependency
359    /// needed for the actual `is_in_paid_close_group` DHT lookup.
360    #[test]
361    fn scenario_5_sender_does_not_grant_key_relevance() {
362        let key_pending = xor_name_from_byte(0xB0);
363        let key_not_pending = xor_name_from_byte(0xB1);
364        let key_paid_existing = xor_name_from_byte(0xB2);
365        let _sender = peer_id_from_byte(0x01);
366
367        // Simulate local state: only key_pending is in the pending set,
368        // key_paid_existing is in the paid list.
369        let pending: HashSet<XorName> = std::iter::once(key_pending).collect();
370        let paid_set: HashSet<XorName> = std::iter::once(key_paid_existing).collect();
371
372        // Trace through admit_hints logic for replica hints:
373        let replica_hints = [key_pending, key_not_pending];
374        let replica_set: HashSet<XorName> = replica_hints.iter().copied().collect();
375        let mut seen = HashSet::new();
376        let mut admitted_replica = Vec::new();
377        let mut rejected = Vec::new();
378
379        for &key in &replica_hints {
380            if !seen.insert(key) {
381                continue; // dedup
382            }
383            // Fast path: already pending -> admitted.
384            if pending.contains(&key) {
385                admitted_replica.push(key);
386                continue;
387            }
388            // key_not_pending: not pending, not local, not paid -> needs the
389            // paid-close-group relevance check. Simulate it returning false.
390            let is_relevant = false;
391            if is_relevant {
392                admitted_replica.push(key);
393            } else {
394                rejected.push(key);
395            }
396        }
397
398        // Trace through paid hints:
399        let paid_hints = [key_paid_existing, key_pending]; // key_pending overlaps with replica
400        let mut admitted_paid = Vec::new();
401
402        for &key in &paid_hints {
403            if !seen.insert(key) {
404                continue; // dedup: key_pending already seen
405            }
406            if replica_set.contains(&key) {
407                continue; // cross-set precedence
408            }
409            // Fast path: already in paid list -> admitted.
410            if paid_set.contains(&key) {
411                admitted_paid.push(key);
412                continue;
413            }
414            rejected.push(key);
415        }
416
417        // Verify outcomes:
418        assert_eq!(
419            admitted_replica,
420            vec![key_pending],
421            "only the pending key should be admitted as replica"
422        );
423        assert_eq!(
424            rejected,
425            vec![key_not_pending],
426            "non-pending, non-responsible key must be rejected"
427        );
428        assert_eq!(
429            admitted_paid,
430            vec![key_paid_existing],
431            "existing paid-list key should be admitted via fast path"
432        );
433
434        // Cross-set precedence: key_pending appeared in both replica and
435        // paid hints — it was processed as replica only, paid duplicate
436        // was deduped.
437        assert!(
438            !admitted_paid.contains(&key_pending),
439            "key in both hint sets must be processed as replica only"
440        );
441    }
442
443    /// Scenario 7: Out-of-range key hint rejected regardless of quorum.
444    ///
445    /// A key whose XOR distance from self is much larger than the distance of
446    /// the paid-close-group members fails the `is_relevant` check in
447    /// `admit_hints`. The key never enters the verification pipeline, so quorum
448    /// is irrelevant.
449    ///
450    /// This test exercises the distance-based reasoning that `admit_hints`
451    /// uses, tracing through the same logic path. Full `is_in_paid_close_group`
452    /// requires a `P2PNode` for DHT lookups; here we verify the distance
453    /// comparison and admission outcome for both close and far keys.
454    #[test]
455    fn scenario_7_out_of_range_key_rejected() {
456        let self_xor: XorName = [0u8; 32];
457
458        // -- Distance proof: far key vs close key --
459
460        let far_key = xor_name_from_byte(0xFF);
461        let close_key = xor_name_from_byte(0x01);
462        let far_dist = xor_distance(&self_xor, &far_key);
463        let close_dist = xor_distance(&self_xor, &close_key);
464
465        assert_eq!(far_dist[0], 0xFF, "far_key distance should be maximal");
466        assert_eq!(close_dist[0], 0x01, "close_key distance should be small");
467        assert!(far_dist > close_dist, "far key is further than close key");
468
469        // -- Simulate admit_hints for these keys --
470        //
471        // When the paid-close-group peers are all closer to far_key than self,
472        // `is_in_paid_close_group(self, far_key)` returns false. The key is
473        // rejected without entering verification or quorum.
474
475        let pending: HashSet<XorName> = HashSet::new();
476        let replica_hints = [far_key, close_key];
477        let mut seen = HashSet::new();
478        let mut admitted = Vec::new();
479        let mut rejected = Vec::new();
480
481        for &key in &replica_hints {
482            if !seen.insert(key) {
483                continue;
484            }
485            // Not pending, not local.
486            if pending.contains(&key) {
487                admitted.push(key);
488                continue;
489            }
490            // Simulate is_in_paid_close_group: self (0x00) has the full
491            // paid close group closer to far_key (0xFF) than itself. For
492            // close_key (0x01), self is very close -> relevant.
493            let distance = xor_distance(&self_xor, &key);
494            let simulated_relevant = distance[0] < 0x80;
495            if simulated_relevant {
496                admitted.push(key);
497            } else {
498                rejected.push(key);
499            }
500        }
501
502        assert_eq!(
503            admitted,
504            vec![close_key],
505            "only close key should be admitted"
506        );
507        assert_eq!(
508            rejected,
509            vec![far_key],
510            "far key should be rejected regardless of quorum — it never enters verification"
511        );
512
513        // Verify the key doesn't sneak in via paid hints either.
514        // far_key was already seen (deduped), so paid processing skips it.
515        let paid_hints = [far_key];
516        let replica_set: HashSet<XorName> = replica_hints.iter().copied().collect();
517        let mut paid_admitted = Vec::new();
518
519        for &key in &paid_hints {
520            if !seen.insert(key) {
521                continue; // already seen from replica processing
522            }
523            if replica_set.contains(&key) {
524                continue; // cross-set precedence
525            }
526            paid_admitted.push(key);
527        }
528
529        assert!(
530            paid_admitted.is_empty(),
531            "far key already processed as replica (and rejected) should not re-enter via paid hints"
532        );
533    }
534}