rns-core 0.1.9

Wire protocol, transport routing, and link/resource engine for the Reticulum Network Stack
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use alloc::collections::BTreeMap;
use alloc::vec::Vec;

use super::types::{IngressControlConfig, InterfaceId};

/// A held announce waiting for release after burst conditions subside.
#[derive(Debug, Clone)]
pub struct HeldAnnounce {
    /// Original raw bytes (pre-hop-increment).
    pub raw: Vec<u8>,
    /// Hop count (post-increment, for priority selection).
    pub hops: u8,
    /// Interface the announce was received on.
    pub receiving_interface: InterfaceId,
    /// When the announce was held.
    pub timestamp: f64,
}

/// Per-interface ingress control state.
#[derive(Debug)]
struct IngressControlState {
    burst_active: bool,
    burst_activated: f64,
    held_release: f64,
    held_announces: BTreeMap<[u8; 16], HeldAnnounce>,
}

impl IngressControlState {
    fn new() -> Self {
        IngressControlState {
            burst_active: false,
            burst_activated: 0.0,
            held_release: 0.0,
            held_announces: BTreeMap::new(),
        }
    }
}

/// Ingress control system: detects announce bursts per-interface
/// and holds announces from unknown destinations during bursts.
#[derive(Debug)]
pub struct IngressControl {
    states: BTreeMap<InterfaceId, IngressControlState>,
}

impl IngressControl {
    pub fn new() -> Self {
        IngressControl {
            states: BTreeMap::new(),
        }
    }

    /// Determine whether to ingress-limit an announce on this interface.
    ///
    /// Returns true if the announce should be held (burst is active or just activated).
    pub fn should_ingress_limit(
        &mut self,
        interface: InterfaceId,
        config: &IngressControlConfig,
        ia_freq: f64,
        interface_started: f64,
        now: f64,
    ) -> bool {
        if !config.enabled {
            return false;
        }

        let state = self
            .states
            .entry(interface)
            .or_insert_with(IngressControlState::new);
        let interface_age = now - interface_started;
        let threshold = if interface_age < config.new_time {
            config.burst_freq_new
        } else {
            config.burst_freq
        };

        if state.burst_active {
            // Check if burst can deactivate
            if ia_freq < threshold && now > state.burst_activated + config.burst_hold {
                state.burst_active = false;
                return false;
            }
            true
        } else if ia_freq > threshold {
            // Activate burst
            state.burst_active = true;
            state.burst_activated = now;
            state.held_release = now + config.burst_penalty;
            true
        } else {
            false
        }
    }

    /// Store a held announce for later release.
    ///
    /// If the destination already has a held announce, it is updated.
    /// If the max is reached, the announce is dropped.
    pub fn hold_announce(
        &mut self,
        interface: InterfaceId,
        config: &IngressControlConfig,
        dest_hash: [u8; 16],
        held: HeldAnnounce,
    ) {
        let state = self
            .states
            .entry(interface)
            .or_insert_with(IngressControlState::new);
        if state.held_announces.contains_key(&dest_hash) {
            // Update existing
            state.held_announces.insert(dest_hash, held);
        } else if state.held_announces.len() < config.max_held_announces {
            state.held_announces.insert(dest_hash, held);
        }
        // else: at max, silently drop
    }

    /// Try to release one held announce from this interface.
    ///
    /// Conditions: not currently limiting, held announces exist,
    /// now >= held_release, freq < threshold.
    /// Selects the announce with the lowest hop count (closest source).
    pub fn process_held_announces(
        &mut self,
        interface: InterfaceId,
        config: &IngressControlConfig,
        ia_freq: f64,
        interface_started: f64,
        now: f64,
    ) -> Option<HeldAnnounce> {
        if !config.enabled {
            return None;
        }

        let state = self.states.get_mut(&interface)?;

        if state.held_announces.is_empty() {
            return None;
        }

        // Wait for penalty period
        if now < state.held_release {
            return None;
        }

        // Check frequency is below threshold
        let interface_age = now - interface_started;
        let threshold = if interface_age < config.new_time {
            config.burst_freq_new
        } else {
            config.burst_freq
        };
        if ia_freq >= threshold {
            return None;
        }
        state.burst_active = false;

        // Find announce with lowest hops
        let best_key = state
            .held_announces
            .iter()
            .min_by_key(|(_, h)| h.hops)
            .map(|(k, _)| *k)?;

        let held = state.held_announces.remove(&best_key)?;
        state.held_release = now + config.held_release_interval;
        Some(held)
    }

    /// Return interface IDs that have held announces.
    pub fn interfaces_with_held(&self) -> Vec<InterfaceId> {
        self.states
            .iter()
            .filter(|(_, s)| !s.held_announces.is_empty())
            .map(|(id, _)| *id)
            .collect()
    }

    /// Remove all state for an interface.
    pub fn remove_interface(&mut self, id: &InterfaceId) {
        self.states.remove(id);
    }

    /// Clear all ingress control state.
    pub fn clear(&mut self) {
        self.states.clear();
    }

    /// Count of held announces for a specific interface.
    pub fn held_count(&self, interface: &InterfaceId) -> usize {
        self.states
            .get(interface)
            .map(|s| s.held_announces.len())
            .unwrap_or(0)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants;

    fn iface(n: u64) -> InterfaceId {
        InterfaceId(n)
    }

    #[test]
    fn test_no_limiting_below_threshold() {
        let mut ic = IngressControl::new();
        // Mature interface, freq below threshold
        let started = 0.0;
        let now = 10000.0;
        assert!(!ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            5.0,
            started,
            now
        ));
    }

    #[test]
    fn test_burst_activates_above_threshold() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;
        // Exceed mature threshold (35.0)
        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            36.0,
            started,
            now
        ));
    }

    #[test]
    fn test_disabled_config_never_limits() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        assert!(!ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::disabled(),
            100.0,
            started,
            now
        ));
    }

    #[test]
    fn test_new_interface_lower_threshold() {
        let mut ic = IngressControl::new();
        let started = 9000.0;
        let now = 9500.0; // interface_age = 500s < IC_NEW_TIME (7200s)
                          // Below mature threshold but above new threshold (6.0)
        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            7.0,
            started,
            now
        ));
    }

    #[test]
    fn test_burst_stays_active_during_hold_period() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        // Activate burst
        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            36.0,
            started,
            now
        ));

        // Freq drops but within hold period
        let now2 = now + 30.0; // < IC_BURST_HOLD (60s)
        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now2
        ));
    }

    #[test]
    fn test_burst_deactivates_after_hold_period() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        // Activate burst
        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            36.0,
            started,
            now
        ));

        // After hold period with low freq
        let now2 = now + constants::IC_BURST_HOLD + 1.0;
        assert!(!ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now2
        ));
    }

    #[test]
    fn test_penalty_period_prevents_release() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        // Activate burst
        ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            36.0,
            started,
            now,
        );

        // Hold an announce
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 3,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );

        // Deactivate burst
        let now2 = now + constants::IC_BURST_HOLD + 1.0;
        ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now2,
        );

        // During penalty period, no release
        let now3 = now + 10.0; // < IC_BURST_PENALTY (15s) from burst activation
        assert!(ic
            .process_held_announces(
                iface(1),
                &IngressControlConfig::enabled(),
                1.0,
                started,
                now3
            )
            .is_none());

        // After penalty period, release
        let now4 = now + constants::IC_BURST_PENALTY + 1.0;
        let released = ic.process_held_announces(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now4,
        );
        assert!(released.is_some());
        assert_eq!(released.unwrap().hops, 3);
    }

    #[test]
    fn test_process_held_announces_deactivates_burst_after_penalty() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        assert!(ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            36.0,
            started,
            now
        ));

        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 3,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );

        let released = ic.process_held_announces(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now + constants::IC_BURST_PENALTY + 1.0,
        );
        assert!(released.is_some());
        assert_eq!(released.unwrap().hops, 3);

        assert!(!ic.should_ingress_limit(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now + constants::IC_BURST_HOLD + 1.0
        ));
    }

    #[test]
    fn test_released_lowest_hops_first() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 5,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [2u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 2,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [3u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 8,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );

        // Release (no burst active, past penalty)
        let release_time = now + 1.0;
        let released = ic.process_held_announces(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            release_time,
        );
        assert!(released.is_some());
        assert_eq!(released.unwrap().hops, 2);

        let release_time2 = release_time + constants::IC_HELD_RELEASE_INTERVAL + 1.0;
        let released2 = ic.process_held_announces(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            release_time2,
        );
        assert!(released2.is_some());
        assert_eq!(released2.unwrap().hops, 5);
    }

    #[test]
    fn test_max_held_announces() {
        let mut ic = IngressControl::new();

        for i in 0..constants::IC_MAX_HELD_ANNOUNCES {
            let mut hash = [0u8; 16];
            hash[0] = (i >> 8) as u8;
            hash[1] = (i & 0xff) as u8;
            ic.hold_announce(
                iface(1),
                &IngressControlConfig::enabled(),
                hash,
                HeldAnnounce {
                    raw: vec![0; 10],
                    hops: 1,
                    receiving_interface: iface(1),
                    timestamp: 0.0,
                },
            );
        }

        assert_eq!(ic.held_count(&iface(1)), constants::IC_MAX_HELD_ANNOUNCES);

        // One more should be dropped
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [0xff; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 1,
                receiving_interface: iface(1),
                timestamp: 0.0,
            },
        );
        assert_eq!(ic.held_count(&iface(1)), constants::IC_MAX_HELD_ANNOUNCES);
    }

    #[test]
    fn test_custom_max_held_announces() {
        let mut ic = IngressControl::new();
        let config = IngressControlConfig {
            max_held_announces: 2,
            ..IngressControlConfig::enabled()
        };

        for i in 0..3 {
            ic.hold_announce(
                iface(1),
                &config,
                [i as u8; 16],
                HeldAnnounce {
                    raw: vec![i as u8],
                    hops: 1,
                    receiving_interface: iface(1),
                    timestamp: i as f64,
                },
            );
        }

        assert_eq!(ic.held_count(&iface(1)), 2);
    }

    #[test]
    fn test_duplicate_destination_updates() {
        let mut ic = IngressControl::new();
        let hash = [1u8; 16];

        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            hash,
            HeldAnnounce {
                raw: vec![1; 10],
                hops: 5,
                receiving_interface: iface(1),
                timestamp: 0.0,
            },
        );
        assert_eq!(ic.held_count(&iface(1)), 1);

        // Update with better hops
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            hash,
            HeldAnnounce {
                raw: vec![2; 10],
                hops: 2,
                receiving_interface: iface(1),
                timestamp: 1.0,
            },
        );
        assert_eq!(ic.held_count(&iface(1)), 1);
    }

    #[test]
    fn test_interfaces_with_held() {
        let mut ic = IngressControl::new();
        assert!(ic.interfaces_with_held().is_empty());

        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 1,
                receiving_interface: iface(1),
                timestamp: 0.0,
            },
        );

        let ifaces = ic.interfaces_with_held();
        assert_eq!(ifaces.len(), 1);
        assert_eq!(ifaces[0], iface(1));
    }

    #[test]
    fn test_remove_interface() {
        let mut ic = IngressControl::new();
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 1,
                receiving_interface: iface(1),
                timestamp: 0.0,
            },
        );
        assert_eq!(ic.held_count(&iface(1)), 1);

        ic.remove_interface(&iface(1));
        assert_eq!(ic.held_count(&iface(1)), 0);
        assert!(ic.interfaces_with_held().is_empty());
    }

    #[test]
    fn test_release_interval() {
        let mut ic = IngressControl::new();
        let started = 0.0;
        let now = 10000.0;

        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [1u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 1,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );
        ic.hold_announce(
            iface(1),
            &IngressControlConfig::enabled(),
            [2u8; 16],
            HeldAnnounce {
                raw: vec![0; 10],
                hops: 2,
                receiving_interface: iface(1),
                timestamp: now,
            },
        );

        // First release
        let released = ic.process_held_announces(
            iface(1),
            &IngressControlConfig::enabled(),
            1.0,
            started,
            now,
        );
        assert!(released.is_some());

        // Too soon for second release
        let too_soon = now + 1.0; // < IC_HELD_RELEASE_INTERVAL (2s)
        assert!(ic
            .process_held_announces(
                iface(1),
                &IngressControlConfig::enabled(),
                1.0,
                started,
                too_soon
            )
            .is_none());

        // After interval, second release works
        let ok_time = now + constants::IC_HELD_RELEASE_INTERVAL + 1.0;
        assert!(ic
            .process_held_announces(
                iface(1),
                &IngressControlConfig::enabled(),
                1.0,
                started,
                ok_time
            )
            .is_some());
    }
}