rns-core 0.1.11

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
use super::tables::{PathEntry, PathSet};
use crate::constants;

/// Extract emission timestamp from bytes [5:10] of a random_blob (big-endian u64).
pub fn timebase_from_random_blob(blob: &[u8; 10]) -> u64 {
    let mut bytes = [0u8; 8];
    bytes[3..8].copy_from_slice(&blob[5..10]);
    u64::from_be_bytes(bytes)
}

/// Maximum emission timestamp across all random blobs.
pub fn timebase_from_random_blobs(blobs: &[[u8; 10]]) -> u64 {
    let mut timebase: u64 = 0;
    for blob in blobs {
        let emitted = timebase_from_random_blob(blob);
        if emitted > timebase {
            timebase = emitted;
        }
    }
    timebase
}

/// Extract the random_blob from announce packet data.
///
/// Located at offset `KEYSIZE/8 + NAME_HASH_LENGTH/8` = 64 + 10 = 74,
/// length 10 bytes.
pub fn extract_random_blob(packet_data: &[u8]) -> Option<[u8; 10]> {
    let offset = constants::KEYSIZE / 8 + constants::NAME_HASH_LENGTH / 8;
    if packet_data.len() < offset + 10 {
        return None;
    }
    let mut blob = [0u8; 10];
    blob.copy_from_slice(&packet_data[offset..offset + 10]);
    Some(blob)
}

#[derive(Debug, PartialEq, Eq)]
pub enum PathDecision {
    Add,
    Reject,
}

/// Full path update decision tree from Transport.py:1604-1686.
///
/// Determines whether an incoming announce should update the path table.
pub fn should_update_path(
    existing: Option<&PathEntry>,
    announce_hops: u8,
    announce_emitted_ts: u64,
    random_blob: &[u8; 10],
    path_is_unresponsive: bool,
    now: f64,
    prefer_shorter_path: bool,
) -> PathDecision {
    // Hop limit
    if announce_hops > constants::PATHFINDER_M {
        return PathDecision::Reject;
    }

    let existing = match existing {
        None => return PathDecision::Add,
        Some(e) => e,
    };

    let path_timebase = timebase_from_random_blobs(&existing.random_blobs);
    let blob_is_new = !existing.random_blobs.contains(random_blob);

    if announce_hops <= existing.hops {
        // Accept strictly shorter path even with duplicate blob
        if prefer_shorter_path && announce_hops < existing.hops {
            return PathDecision::Add;
        }
        // Equal or fewer hops: accept if new blob AND newer emission
        if blob_is_new && announce_emitted_ts > path_timebase {
            return PathDecision::Add;
        }
        // Same emission + unresponsive path: accept for path recovery
        if announce_emitted_ts == path_timebase && path_is_unresponsive {
            return PathDecision::Add;
        }
        PathDecision::Reject
    } else {
        // More hops than existing path
        let path_expired = now >= existing.expires;

        if path_expired && blob_is_new {
            return PathDecision::Add;
        }

        if announce_emitted_ts > path_timebase && blob_is_new {
            return PathDecision::Add;
        }

        if announce_emitted_ts == path_timebase && path_is_unresponsive {
            return PathDecision::Add;
        }

        PathDecision::Reject
    }
}

/// Decision for multi-path announce processing.
#[derive(Debug, PartialEq, Eq)]
pub enum MultiPathDecision {
    /// Replace/update the primary path (or the path with the same next_hop).
    ReplacePrimary,
    /// Accept as an alternative path via a new next_hop.
    AddAlternative,
    /// Reject this announce.
    Reject,
}

/// Multi-path aware announce decision.
///
/// Determines whether an incoming announce should update the primary path,
/// be stored as an alternative, or be rejected.
///
/// - No existing `PathSet` → `ReplacePrimary` (first path for this dest)
/// - Same `next_hop` exists in the set → delegate to `should_update_path`
///   against **that** specific path entry
/// - New `next_hop` → accept as `AddAlternative` if the blob is genuinely
///   new (not in any stored path's blobs) and emission timestamp is valid
#[allow(clippy::too_many_arguments)]
pub fn decide_announce_multipath(
    existing_set: Option<&PathSet>,
    announce_hops: u8,
    announce_emitted_ts: u64,
    random_blob: &[u8; 10],
    next_hop: &[u8; 16],
    path_is_unresponsive: bool,
    now: f64,
    prefer_shorter_path: bool,
) -> MultiPathDecision {
    // Hop limit
    if announce_hops > constants::PATHFINDER_M {
        return MultiPathDecision::Reject;
    }

    let path_set = match existing_set {
        None => return MultiPathDecision::ReplacePrimary,
        Some(ps) if ps.is_empty() => return MultiPathDecision::ReplacePrimary,
        Some(ps) => ps,
    };

    // Check if there's already a path with the same next_hop
    if let Some(existing_path) = path_set.find_by_next_hop(next_hop) {
        let decision = should_update_path(
            Some(existing_path),
            announce_hops,
            announce_emitted_ts,
            random_blob,
            path_is_unresponsive,
            now,
            prefer_shorter_path,
        );
        match decision {
            PathDecision::Add => MultiPathDecision::ReplacePrimary,
            PathDecision::Reject => MultiPathDecision::Reject,
        }
    } else {
        // New next_hop — check if blob is genuinely new across all paths
        let all_blobs = path_set.all_random_blobs();
        let blob_is_new = !all_blobs.contains(random_blob);

        if !blob_is_new {
            return MultiPathDecision::Reject;
        }

        let max_timebase = timebase_from_random_blobs(&all_blobs);
        if announce_emitted_ts >= max_timebase {
            MultiPathDecision::AddAlternative
        } else {
            MultiPathDecision::Reject
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::types::InterfaceId;
    use super::*;

    fn make_blob(timebase: u64) -> [u8; 10] {
        let mut blob = [0u8; 10];
        let bytes = timebase.to_be_bytes();
        // timebase is stored in blob[5..10] = last 5 bytes of u64
        blob[5..10].copy_from_slice(&bytes[3..8]);
        blob
    }

    fn make_path_entry(hops: u8, blobs: &[[u8; 10]], expires: f64) -> PathEntry {
        PathEntry {
            timestamp: 1000.0,
            next_hop: [0xAA; 16],
            hops,
            expires,
            random_blobs: blobs.to_vec(),
            receiving_interface: InterfaceId(1),
            packet_hash: [0xBB; 32],
            announce_raw: None,
        }
    }

    #[test]
    fn test_timebase_extraction() {
        let blob = make_blob(12345);
        assert_eq!(timebase_from_random_blob(&blob), 12345);
    }

    #[test]
    fn test_timebase_from_multiple_blobs() {
        let b1 = make_blob(100);
        let b2 = make_blob(200);
        let b3 = make_blob(50);
        assert_eq!(timebase_from_random_blobs(&[b1, b2, b3]), 200);
    }

    #[test]
    fn test_timebase_empty_blobs() {
        assert_eq!(timebase_from_random_blobs(&[]), 0);
    }

    #[test]
    fn test_extract_random_blob() {
        // Need at least 74 + 10 = 84 bytes
        let mut data = [0u8; 100];
        // Put a known blob at offset 74
        data[74..84].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        let blob = extract_random_blob(&data).unwrap();
        assert_eq!(blob, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    #[test]
    fn test_extract_random_blob_too_short() {
        let data = [0u8; 80]; // too short
        assert!(extract_random_blob(&data).is_none());
    }

    // --- Decision tree tests ---

    #[test]
    fn test_no_existing_path_always_add() {
        let blob = make_blob(100);
        assert_eq!(
            should_update_path(None, 3, 100, &blob, false, 1000.0, false),
            PathDecision::Add
        );
    }

    #[test]
    fn test_hop_limit_reject() {
        let blob = make_blob(100);
        assert_eq!(
            should_update_path(None, 129, 100, &blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_fewer_hops_new_blob_newer_emission_add() {
        let old_blob = make_blob(100);
        let new_blob = make_blob(200);
        let entry = make_path_entry(5, &[old_blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 200, &new_blob, false, 1000.0, false),
            PathDecision::Add
        );
    }

    #[test]
    fn test_fewer_hops_duplicate_blob_reject() {
        let blob = make_blob(100);
        let entry = make_path_entry(5, &[blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 200, &blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_fewer_hops_same_emission_unresponsive_add() {
        let old_blob = make_blob(100);
        let mut different_blob = [0u8; 10];
        different_blob[0] = 0xFF;
        different_blob[5..10].copy_from_slice(&100u64.to_be_bytes()[3..8]);

        let entry = make_path_entry(5, &[old_blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 100, &different_blob, true, 1000.0, false),
            PathDecision::Add
        );
    }

    #[test]
    fn test_fewer_hops_same_emission_responsive_reject() {
        let old_blob = make_blob(100);
        let mut different_blob = [0u8; 10];
        different_blob[0] = 0xFF;
        different_blob[5..10].copy_from_slice(&100u64.to_be_bytes()[3..8]);

        let entry = make_path_entry(5, &[old_blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 100, &different_blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_more_hops_expired_path_new_blob_add() {
        let old_blob = make_blob(100);
        let new_blob = make_blob(50); // older emission but path expired
        let entry = make_path_entry(2, &[old_blob], 500.0); // expires at 500

        assert_eq!(
            should_update_path(Some(&entry), 5, 50, &new_blob, false, 600.0, false), // now > expires
            PathDecision::Add
        );
    }

    #[test]
    fn test_more_hops_not_expired_older_emission_reject() {
        let old_blob = make_blob(200);
        let new_blob = make_blob(100);
        let entry = make_path_entry(2, &[old_blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 5, 100, &new_blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_more_hops_newer_emission_new_blob_add() {
        let old_blob = make_blob(100);
        let new_blob = make_blob(200);
        let entry = make_path_entry(2, &[old_blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 5, 200, &new_blob, false, 1000.0, false),
            PathDecision::Add
        );
    }

    #[test]
    fn test_more_hops_same_emission_unresponsive_add() {
        let old_blob = make_blob(100);
        let mut different_blob = [0u8; 10];
        different_blob[0] = 0xFF;
        different_blob[5..10].copy_from_slice(&100u64.to_be_bytes()[3..8]);

        let entry = make_path_entry(2, &[old_blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 5, 100, &different_blob, true, 1000.0, false),
            PathDecision::Add
        );
    }

    #[test]
    fn test_more_hops_same_emission_responsive_reject() {
        let old_blob = make_blob(100);
        let mut different_blob = [0u8; 10];
        different_blob[0] = 0xFF;
        different_blob[5..10].copy_from_slice(&100u64.to_be_bytes()[3..8]);

        let entry = make_path_entry(2, &[old_blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 5, 100, &different_blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_more_hops_duplicate_blob_reject() {
        let blob = make_blob(200);
        let entry = make_path_entry(2, &[blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 5, 200, &blob, false, 1000.0, false),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_equal_hops_new_blob_newer_emission_add() {
        let old_blob = make_blob(100);
        let new_blob = make_blob(200);
        let entry = make_path_entry(3, &[old_blob], 9999.0);

        assert_eq!(
            should_update_path(Some(&entry), 3, 200, &new_blob, false, 1000.0, false),
            PathDecision::Add
        );
    }

    // --- prefer_shorter_path tests ---

    #[test]
    fn test_prefer_shorter_path_strictly_fewer_hops_duplicate_blob_add() {
        let blob = make_blob(100);
        let entry = make_path_entry(5, &[blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 100, &blob, false, 1000.0, true),
            PathDecision::Add
        );
    }

    #[test]
    fn test_prefer_shorter_path_equal_hops_duplicate_blob_reject() {
        // Equal hops with same blob: no benefit, still rejected
        let blob = make_blob(100);
        let entry = make_path_entry(3, &[blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 3, 100, &blob, false, 1000.0, true),
            PathDecision::Reject
        );
    }

    #[test]
    fn test_prefer_shorter_path_more_hops_duplicate_blob_reject() {
        // More hops: prefer_shorter_path does not help
        let blob = make_blob(100);
        let entry = make_path_entry(2, &[blob], 9999.0);
        assert_eq!(
            should_update_path(Some(&entry), 5, 100, &blob, false, 1000.0, true),
            PathDecision::Reject
        );
    }

    // --- MultiPathDecision tests ---

    #[test]
    fn test_multipath_no_existing_set_replace_primary() {
        let blob = make_blob(100);
        assert_eq!(
            decide_announce_multipath(None, 3, 100, &blob, &[0xBB; 16], false, 1000.0, false),
            MultiPathDecision::ReplacePrimary
        );
    }

    #[test]
    fn test_multipath_same_nexthop_update() {
        let blob_old = make_blob(100);
        let blob_new = make_blob(200);
        let entry = make_path_entry(3, &[blob_old], 9999.0);
        let ps = PathSet::from_single(entry, 3);

        // Same next_hop, newer blob → ReplacePrimary
        assert_eq!(
            decide_announce_multipath(
                Some(&ps),
                2,
                200,
                &blob_new,
                &[0xAA; 16],
                false,
                1000.0,
                false
            ),
            MultiPathDecision::ReplacePrimary
        );
    }

    #[test]
    fn test_multipath_same_nexthop_reject() {
        let blob = make_blob(100);
        let entry = make_path_entry(3, &[blob], 9999.0);
        let ps = PathSet::from_single(entry, 3);

        // Same next_hop, same blob → Reject
        assert_eq!(
            decide_announce_multipath(Some(&ps), 3, 100, &blob, &[0xAA; 16], false, 1000.0, false),
            MultiPathDecision::Reject
        );
    }

    #[test]
    fn test_multipath_new_nexthop_novel_blob_add_alternative() {
        let blob_existing = make_blob(100);
        let blob_new = make_blob(200);
        let entry = make_path_entry(3, &[blob_existing], 9999.0);
        let ps = PathSet::from_single(entry, 3);

        // Different next_hop, novel blob, newer emission → AddAlternative
        assert_eq!(
            decide_announce_multipath(
                Some(&ps),
                4,
                200,
                &blob_new,
                &[0xCC; 16],
                false,
                1000.0,
                false
            ),
            MultiPathDecision::AddAlternative
        );
    }

    #[test]
    fn test_multipath_new_nexthop_known_blob_reject() {
        let blob = make_blob(100);
        let entry = make_path_entry(3, &[blob], 9999.0);
        let ps = PathSet::from_single(entry, 3);

        // Different next_hop but blob already known → Reject
        assert_eq!(
            decide_announce_multipath(Some(&ps), 4, 100, &blob, &[0xCC; 16], false, 1000.0, false),
            MultiPathDecision::Reject
        );
    }

    #[test]
    fn test_multipath_new_nexthop_older_emission_reject() {
        let blob_existing = make_blob(200);
        let blob_new = make_blob(100); // older emission
        let entry = make_path_entry(3, &[blob_existing], 9999.0);
        let ps = PathSet::from_single(entry, 3);

        // Novel blob but older emission timestamp → Reject
        assert_eq!(
            decide_announce_multipath(
                Some(&ps),
                4,
                100,
                &blob_new,
                &[0xCC; 16],
                false,
                1000.0,
                false
            ),
            MultiPathDecision::Reject
        );
    }

    #[test]
    fn test_multipath_hop_limit_reject() {
        let blob = make_blob(100);
        assert_eq!(
            decide_announce_multipath(None, 129, 100, &blob, &[0xBB; 16], false, 1000.0, false),
            MultiPathDecision::Reject
        );
    }
}