ant-node 0.14.1

Pure quantum-proof network node for the Autonomi decentralized network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! LRU cache for verified `XorName` values.
//!
//! Caches `XorName` values that have been verified to exist on the autonomi network,
//! reducing the number of network queries needed for repeated/popular data.

use lru::LruCache;
use parking_lot::Mutex;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

pub use super::quote::XorName;

/// Default cache capacity (100,000 entries = 3.2MB memory).
const DEFAULT_CACHE_CAPACITY: usize = 100_000;

/// LRU cache for verified `XorName` values.
///
/// This cache stores `XorName` values that have been verified to exist on the
/// autonomi network, avoiding repeated network queries for the same data.
///
/// Each entry records which fresh proof verification level inserted it. A
/// paid-list entry must not satisfy a later client-PUT fast-path because
/// paid-list admission does not authorize storing the actual chunk. Stronger
/// entries satisfy weaker lookups.
#[derive(Clone)]
pub struct VerifiedCache {
    inner: Arc<Mutex<LruCache<XorName, VerificationLevel>>>,
    hits: Arc<AtomicU64>,
    misses: Arc<AtomicU64>,
    additions: Arc<AtomicU64>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum VerificationLevel {
    PaidList,
    ClientPut,
}

impl VerificationLevel {
    fn satisfies(self, required: Self) -> bool {
        matches!(
            (self, required),
            (Self::PaidList, Self::PaidList) | (Self::ClientPut, Self::PaidList | Self::ClientPut)
        )
    }
}

/// Cache statistics for monitoring.
#[derive(Debug, Default, Clone, Copy)]
pub struct CacheStats {
    /// Number of cache hits.
    pub hits: u64,
    /// Number of cache misses.
    pub misses: u64,
    /// Number of entries added.
    pub additions: u64,
}

impl CacheStats {
    /// Calculate hit rate as a percentage.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            (self.hits as f64 / total as f64) * 100.0
        }
    }
}

impl VerifiedCache {
    /// Create a new cache with default capacity.
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CACHE_CAPACITY)
    }

    /// Create a new cache with the specified capacity.
    ///
    /// If capacity is 0, defaults to 1.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        // Use max(1, capacity) to ensure non-zero, avoiding unsafe or expect
        let effective_capacity = capacity.max(1);
        // This is guaranteed to succeed since effective_capacity >= 1
        // Using if-let pattern since we know it will always be Some
        let cap = NonZeroUsize::new(effective_capacity).unwrap_or(NonZeroUsize::MIN);
        Self {
            inner: Arc::new(Mutex::new(LruCache::new(cap))),
            hits: Arc::new(AtomicU64::new(0)),
            misses: Arc::new(AtomicU64::new(0)),
            additions: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Check if a `XorName` is in the cache (verified under any fresh check set).
    ///
    /// Returns `true` if the `XorName` is cached (verified to exist on autonomi).
    /// Paid-list and client-PUT lookups must use their stricter helpers.
    #[must_use]
    pub fn contains(&self, xorname: &XorName) -> bool {
        let found = self.inner.lock().get(xorname).is_some();

        if found {
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
        }

        found
    }

    /// Check if a `XorName` is cached AND its verification ran at least the
    /// paid-list admission check set.
    ///
    /// A client-PUT entry returns `true` here because it passed the stricter
    /// store-admission path at the caller.
    #[must_use]
    pub fn contains_paid_list_verified(&self, xorname: &XorName) -> bool {
        let found = self
            .inner
            .lock()
            .get(xorname)
            .copied()
            .is_some_and(|level| level.satisfies(VerificationLevel::PaidList));

        if found {
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
        }

        found
    }

    /// Check if a `XorName` is cached AND its verification ran the full
    /// client-PUT store-admission check set.
    ///
    /// Paid-list entries return `false` here because they did not pass the
    /// client-PUT store-admission path.
    #[must_use]
    pub fn contains_client_put_verified(&self, xorname: &XorName) -> bool {
        let found = self
            .inner
            .lock()
            .get(xorname)
            .copied()
            .is_some_and(|level| level.satisfies(VerificationLevel::ClientPut));

        if found {
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
        }

        found
    }

    /// Add a `XorName` verified under the full client-PUT check set.
    ///
    /// This should be called after verifying that data exists on the autonomi network.
    /// Also upgrades an existing paid-list-verified entry.
    pub fn insert(&self, xorname: XorName) {
        self.insert_with_level(xorname, VerificationLevel::ClientPut);
    }

    /// Add a `XorName` verified under paid-list admission checks.
    ///
    /// Never downgrades an existing client-PUT-verified entry.
    pub fn insert_paid_list_verified(&self, xorname: XorName) {
        self.insert_with_level(xorname, VerificationLevel::PaidList);
    }

    fn insert_with_level(&self, xorname: XorName, level: VerificationLevel) {
        let added = {
            let mut inner = self.inner.lock();
            // `get_mut` refreshes LRU recency for existing entries of either kind.
            if inner.get(&xorname).is_some() {
                if let Some(existing) = inner.get_mut(&xorname) {
                    if !existing.satisfies(level) {
                        *existing = level;
                    }
                }
                false
            } else {
                inner.put(xorname, level);
                true
            }
        };
        if added {
            self.additions.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Get current cache statistics.
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            additions: self.additions.load(Ordering::Relaxed),
        }
    }

    /// Get the current number of entries in the cache.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.lock().len()
    }

    /// Check if the cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.lock().is_empty()
    }

    /// Clear all entries from the cache.
    pub fn clear(&self) {
        self.inner.lock().clear();
    }
}

impl Default for VerifiedCache {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_basic_operations() {
        let cache = VerifiedCache::new();

        let xorname1 = [1u8; 32];
        let xorname2 = [2u8; 32];

        // Initially empty
        assert!(cache.is_empty());
        assert!(!cache.contains(&xorname1));

        // Insert and check
        cache.insert(xorname1);
        assert!(cache.contains(&xorname1));
        assert!(!cache.contains(&xorname2));
        assert_eq!(cache.len(), 1);

        // Insert another
        cache.insert(xorname2);
        assert!(cache.contains(&xorname1));
        assert!(cache.contains(&xorname2));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_cache_verification_levels_do_not_downgrade_or_over_authorize() {
        let cache = VerifiedCache::new();
        let paid_list = [2u8; 32];
        let client_put = [3u8; 32];

        cache.insert_paid_list_verified(paid_list);
        assert!(cache.contains(&paid_list));
        assert!(cache.contains_paid_list_verified(&paid_list));
        assert!(!cache.contains_client_put_verified(&paid_list));

        cache.insert(paid_list);
        assert!(cache.contains_client_put_verified(&paid_list));

        cache.insert(client_put);
        assert!(cache.contains(&client_put));
        assert!(cache.contains_paid_list_verified(&client_put));
        assert!(cache.contains_client_put_verified(&client_put));

        cache.insert_paid_list_verified(client_put);
        assert!(cache.contains_client_put_verified(&client_put));
    }

    #[test]
    fn test_cache_stats() {
        let cache = VerifiedCache::new();
        let xorname = [1u8; 32];

        // Miss
        assert!(!cache.contains(&xorname));
        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 0);

        // Add
        cache.insert(xorname);
        let stats = cache.stats();
        assert_eq!(stats.additions, 1);

        // Hit
        assert!(cache.contains(&xorname));
        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);

        // Hit rate should be 50%
        assert!((stats.hit_rate() - 50.0).abs() < 0.01);
    }

    #[test]
    fn test_cache_lru_eviction() {
        // Small cache for testing eviction
        let cache = VerifiedCache::with_capacity(2);

        let xorname1 = [1u8; 32];
        let xorname2 = [2u8; 32];
        let xorname3 = [3u8; 32];

        cache.insert(xorname1);
        cache.insert(xorname2);
        assert_eq!(cache.len(), 2);

        // Insert third, should evict xorname1 (least recently used)
        cache.insert(xorname3);
        assert_eq!(cache.len(), 2);
        assert!(!cache.contains(&xorname1)); // evicted
                                             // Note: after contains call on evicted item, stats will show a miss
    }

    #[test]
    fn test_cache_clear() {
        let cache = VerifiedCache::new();

        cache.insert([1u8; 32]);
        cache.insert([2u8; 32]);
        assert_eq!(cache.len(), 2);

        cache.clear();
        assert!(cache.is_empty());
    }

    #[test]
    fn test_with_capacity_zero_defaults_to_one() {
        let cache = VerifiedCache::with_capacity(0);
        // Should be able to store at least 1 element
        cache.insert([1u8; 32]);
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn test_default_impl() {
        let cache = VerifiedCache::default();
        assert!(cache.is_empty());
        cache.insert([1u8; 32]);
        assert!(cache.contains(&[1u8; 32]));
    }

    #[test]
    fn test_hit_rate_zero_total() {
        let stats = CacheStats::default();
        assert!(stats.hit_rate().abs() < f64::EPSILON);
    }

    #[test]
    fn test_hit_rate_all_hits() {
        let stats = CacheStats {
            hits: 10,
            misses: 0,
            additions: 0,
        };
        assert!((stats.hit_rate() - 100.0).abs() < 0.01);
    }

    #[test]
    fn test_hit_rate_all_misses() {
        let stats = CacheStats {
            hits: 0,
            misses: 10,
            additions: 0,
        };
        assert!(stats.hit_rate().abs() < f64::EPSILON);
    }

    #[test]
    fn test_clear_does_not_reset_stats() {
        let cache = VerifiedCache::new();
        cache.insert([1u8; 32]);
        let _ = cache.contains(&[1u8; 32]); // hit
        let _ = cache.contains(&[2u8; 32]); // miss

        cache.clear();

        // Stats should persist after clear
        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.additions, 1);
    }

    #[test]
    fn test_concurrent_insert_and_contains() {
        use std::sync::Arc;
        use std::thread;

        let cache = Arc::new(VerifiedCache::with_capacity(1000));
        let mut handles = Vec::new();

        // 10 threads inserting
        for i in 0..10u8 {
            let c = cache.clone();
            handles.push(thread::spawn(move || {
                let xorname = [i; 32];
                c.insert(xorname);
            }));
        }

        // 10 threads checking
        for i in 0..10u8 {
            let c = cache.clone();
            handles.push(thread::spawn(move || {
                let xorname = [i; 32];
                let _ = c.contains(&xorname);
            }));
        }

        for handle in handles {
            handle.join().expect("thread panicked");
        }

        // All 10 should have been inserted
        assert_eq!(cache.len(), 10);
    }

    #[test]
    fn test_cache_stats_copy() {
        let stats = CacheStats {
            hits: 5,
            misses: 3,
            additions: 8,
        };
        let stats2 = stats; // Copy
        assert_eq!(stats.hits, stats2.hits);
        assert_eq!(stats.misses, stats2.misses);
        assert_eq!(stats.additions, stats2.additions);
    }
}