rns-core 0.1.17

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
use super::*;

impl TransportEngine {
    /// Return the slowest positive bitrate among registered interfaces.
    ///
    /// Returns `None` when no registered interface advertises a usable
    /// bitrate.
    pub fn lowest_interface_bitrate(&self) -> Option<u64> {
        super::path_requests::lowest_interface_bitrate(&self.interfaces)
    }

    /// Estimate a path-request round-trip timeout for the slowest medium.
    ///
    /// The estimate covers two MTU transmissions at the slowest registered
    /// positive bitrate plus the per-hop link-establishment allowance. It is
    /// zero when no usable interface bitrate is known.
    pub fn medium_path_timeout(&self) -> f64 {
        super::path_requests::medium_path_timeout(&self.interfaces)
    }

    pub fn path_table_entries(&self) -> impl Iterator<Item = (&[u8; 16], &PathEntry)> {
        self.path_table
            .iter()
            .filter_map(|(k, ps)| ps.primary().map(|e| (k, e)))
    }

    pub fn path_table_sets(&self) -> impl Iterator<Item = (&[u8; 16], &PathSet)> {
        self.path_table.iter()
    }

    pub fn interface_count(&self) -> usize {
        self.interfaces.len()
    }

    pub fn link_table_count(&self) -> usize {
        self.link_table.len()
    }

    pub fn active_link_count(&self) -> usize {
        self.link_table
            .values()
            .filter(|entry| entry.validated)
            .count()
    }

    pub fn is_unvalidated_link_packet(&self, packet: &crate::packet::RawPacket) -> bool {
        packet.flags.packet_type != crate::constants::PACKET_TYPE_ANNOUNCE
            && packet.flags.packet_type != crate::constants::PACKET_TYPE_LINKREQUEST
            && packet.context != crate::constants::CONTEXT_LRPROOF
            && self
                .link_table
                .get(&packet.destination_hash)
                .is_some_and(|entry| !entry.validated)
    }

    /// Classify packet-filter rejections that are peer protocol violations.
    pub fn is_packet_filter_protocol_violation(
        &self,
        packet: &crate::packet::RawPacket,
        interface: InterfaceId,
    ) -> bool {
        let mut hops = packet.hops.saturating_add(1);
        if self.interface_is_local_client(interface) {
            hops = hops.saturating_sub(1);
        }
        if packet.flags.packet_type == crate::constants::PACKET_TYPE_ANNOUNCE {
            return packet.flags.destination_type != crate::constants::DESTINATION_SINGLE;
        }
        (packet.flags.destination_type == crate::constants::DESTINATION_PLAIN
            || packet.flags.destination_type == crate::constants::DESTINATION_GROUP)
            && hops > 1
    }

    pub fn path_table_count(&self) -> usize {
        self.path_table.len()
    }

    pub fn announce_table_count(&self) -> usize {
        self.announce_table.len()
    }

    pub fn reverse_table_count(&self) -> usize {
        self.reverse_table.len()
    }

    pub fn held_announces_count(&self) -> usize {
        self.held_announces.len()
    }

    pub fn packet_hashlist_len(&self) -> usize {
        self.packet_hashlist.len()
    }

    /// Remove a packet hash from deduplication after an interface failover race.
    ///
    /// Network drivers should call this when an active-link packet arrives on
    /// the link's former interface, allowing the same packet to be accepted
    /// later on its current route.
    #[doc(hidden)]
    pub fn forget_packet_hash(&mut self, packet_hash: &[u8; 32]) -> bool {
        self.packet_hashlist.remove(packet_hash)
    }

    pub fn announce_sig_cache_len(&self) -> usize {
        self.announce_sig_cache.len()
    }

    pub fn rate_limiter_count(&self) -> usize {
        self.rate_limiter.len()
    }

    pub fn blackholed_count(&self) -> usize {
        self.blackholed_identities.len()
    }

    pub fn tunnel_count(&self) -> usize {
        self.tunnel_table.len()
    }

    pub fn discovery_pr_tags_count(&self) -> usize {
        self.discovery_pr_tags.len()
    }

    #[cfg(test)]
    pub(crate) fn has_discovery_pr_tag(&self, unique_tag: &[u8; 32]) -> bool {
        self.discovery_pr_tag_set.contains(unique_tag)
    }

    pub fn discovery_path_requests_count(&self) -> usize {
        self.discovery_path_requests.len()
    }

    pub fn announce_queue_count(&self) -> usize {
        self.announce_queues.queue_count()
    }

    pub fn nonempty_announce_queue_count(&self) -> usize {
        self.announce_queues.nonempty_queue_count()
    }

    pub fn queued_announce_count(&self) -> usize {
        self.announce_queues.total_queued_announces()
    }

    pub fn queued_announce_bytes(&self) -> usize {
        self.announce_queues.total_queued_bytes()
    }

    pub fn announce_queue_interface_cap_drop_count(&self) -> u64 {
        self.announce_queues.interface_cap_drop_count()
    }

    pub fn local_destinations_count(&self) -> usize {
        self.local_destinations.len()
    }

    pub fn rate_limiter(&self) -> &AnnounceRateLimiter {
        &self.rate_limiter
    }

    pub fn interface_info(&self, id: &InterfaceId) -> Option<&InterfaceInfo> {
        self.interfaces.get(id)
    }

    pub fn redirect_path(&mut self, dest_hash: &[u8; 16], interface: InterfaceId, now: f64) {
        if let Some(entry) = self
            .path_table
            .get_mut(dest_hash)
            .and_then(|ps| ps.primary_mut())
        {
            entry.receiving_interface = interface;
            // A redirected path is a true one-hop path to the destination.
            // Retaining the previous transport as next_hop makes outbound
            // routing inject a HEADER_2 transport header for that stale peer.
            entry.next_hop = *dest_hash;
            entry.hops = 1;
            entry.timestamp = now;
            entry.expires = now + 3600.0;
        } else {
            self.upsert_path_destination(
                *dest_hash,
                PathEntry {
                    timestamp: now,
                    next_hop: *dest_hash,
                    hops: 1,
                    expires: now + 3600.0,
                    random_blobs: Vec::new(),
                    receiving_interface: interface,
                    packet_hash: [0u8; 32],
                    announce_raw: None,
                },
                now,
            );
        }
    }

    pub fn inject_path(&mut self, dest_hash: [u8; 16], entry: PathEntry) {
        self.upsert_path_destination(dest_hash, entry.clone(), entry.timestamp);
    }

    pub fn drop_path(&mut self, dest_hash: &[u8; 16]) -> bool {
        self.path_table.remove(dest_hash).is_some()
    }

    pub fn drop_all_via(&mut self, transport_hash: &[u8; 16]) -> usize {
        let mut removed = 0usize;
        for ps in self.path_table.values_mut() {
            let before = ps.len();
            ps.retain(|entry| &entry.next_hop != transport_hash);
            removed += before - ps.len();
        }
        self.path_table.retain(|_, ps| !ps.is_empty());
        removed
    }

    pub fn drop_paths_for_interface(&mut self, interface: InterfaceId) -> usize {
        let mut removed = 0usize;
        let mut cleared_destinations = Vec::new();
        for (dest_hash, ps) in self.path_table.iter_mut() {
            let before = ps.len();
            ps.retain(|entry| entry.receiving_interface != interface);
            if ps.is_empty() {
                cleared_destinations.push(*dest_hash);
            }
            removed += before - ps.len();
        }
        self.path_table.retain(|_, ps| !ps.is_empty());
        for dest_hash in cleared_destinations {
            self.path_states.remove(&dest_hash);
        }
        removed
    }

    pub fn drop_reverse_for_interface(&mut self, interface: InterfaceId) -> usize {
        let before = self.reverse_table.len();
        self.reverse_table.retain(|_, entry| {
            entry.receiving_interface != interface && entry.outbound_interface != interface
        });
        before - self.reverse_table.len()
    }

    pub fn drop_links_for_interface(&mut self, interface: InterfaceId) -> usize {
        let before = self.link_table.len();
        self.link_table.retain(|_, entry| {
            entry.next_hop_interface != interface && entry.received_interface != interface
        });
        before - self.link_table.len()
    }

    pub fn drop_announce_queues(&mut self) {
        self.announce_table.clear();
        self.held_announces.clear();
        self.announce_queues = AnnounceQueues::new(self.config.announce_queue_max_interfaces);
        self.ingress_control.clear();
    }

    pub fn void_queues(&mut self) {
        self.drop_announce_queues();
        self.reverse_table.clear();
    }

    pub fn identity_hash(&self) -> Option<&[u8; 16]> {
        self.config.identity_hash.as_ref()
    }

    pub fn transport_enabled(&self) -> bool {
        self.config.transport_enabled
    }

    pub fn config(&self) -> &TransportConfig {
        &self.config
    }

    pub fn set_packet_hashlist_max_entries(&mut self, max_entries: usize) {
        self.config.packet_hashlist_max_entries = max_entries;
        self.packet_hashlist =
            PacketHashlist::with_allocation(max_entries, self.config.packet_hashlist_allocation);
    }

    pub fn get_path_table(&self, max_hops: Option<u8>) -> Vec<PathTableRow> {
        let mut result = Vec::new();
        for (dest_hash, ps) in self.path_table.iter() {
            if let Some(entry) = ps.primary() {
                if let Some(max) = max_hops {
                    if entry.hops > max {
                        continue;
                    }
                }
                let iface_name = self
                    .interfaces
                    .get(&entry.receiving_interface)
                    .map(|i| i.name.clone())
                    .unwrap_or_else(|| {
                        alloc::format!("Interface({})", entry.receiving_interface.0)
                    });
                result.push((
                    *dest_hash,
                    entry.timestamp,
                    entry.next_hop,
                    entry.hops,
                    entry.expires,
                    iface_name,
                ));
            }
        }
        result
    }

    pub fn get_rate_table(&self) -> Vec<RateTableRow> {
        self.rate_limiter
            .entries()
            .map(|(hash, entry)| {
                (
                    *hash,
                    entry.last,
                    entry.rate_violations,
                    entry.blocked_until,
                    entry.timestamps.clone(),
                )
            })
            .collect()
    }

    pub fn get_blackholed(&self) -> Vec<([u8; 16], f64, f64, Option<alloc::string::String>)> {
        self.blackholed_entries()
            .map(|(hash, entry)| (*hash, entry.created, entry.expires, entry.reason.clone()))
            .collect()
    }

    pub fn active_destination_hashes(&self) -> alloc::collections::BTreeSet<[u8; 16]> {
        self.path_table.keys().copied().collect()
    }

    pub fn path_destination_cap_evict_count(&self) -> usize {
        self.path_destination_cap_evict_count
    }

    pub fn active_packet_hashes(&self) -> Vec<[u8; 32]> {
        let mut hashes: Vec<[u8; 32]> = self
            .path_table
            .values()
            .flat_map(|ps| ps.iter().map(|p| p.packet_hash))
            .collect();

        hashes.extend(
            self.tunnel_table
                .iter()
                .flat_map(|(_, tunnel)| tunnel.paths.values().map(|p| p.packet_hash)),
        );
        hashes.sort_unstable();
        hashes.dedup();
        hashes
    }

    pub fn cull_rate_limiter(
        &mut self,
        active: &alloc::collections::BTreeSet<[u8; 16]>,
        now: f64,
        ttl_secs: f64,
    ) -> usize {
        self.rate_limiter.cull_stale(active, now, ttl_secs)
    }

    pub fn update_interface_freq(&mut self, id: InterfaceId, ia_freq: f64) {
        if let Some(info) = self.interfaces.get_mut(&id) {
            info.ia_freq = ia_freq;
        }
    }

    pub fn update_interface_freqs(
        &mut self,
        id: InterfaceId,
        ia_freq: f64,
        ip_freq: f64,
        op_freq: f64,
        op_samples: usize,
    ) {
        if let Some(info) = self.interfaces.get_mut(&id) {
            info.ia_freq = ia_freq;
            info.ip_freq = ip_freq;
            info.op_freq = op_freq;
            info.op_samples = op_samples;
        }
    }

    pub fn held_announce_count(&self, interface: &InterfaceId) -> usize {
        self.ingress_control.held_count(interface)
    }

    pub fn burst_active(&self, interface: &InterfaceId) -> bool {
        self.ingress_control.burst_active(interface)
    }

    pub fn burst_activated(&self, interface: &InterfaceId) -> f64 {
        self.ingress_control.burst_activated(interface)
    }

    pub fn pr_burst_active(&self, interface: &InterfaceId) -> bool {
        self.ingress_control.pr_burst_active(interface)
    }

    pub fn pr_burst_activated(&self, interface: &InterfaceId) -> f64 {
        self.ingress_control.pr_burst_activated(interface)
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn path_table(&self) -> &BTreeMap<[u8; 16], PathSet> {
        &self.path_table
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn announce_table(&self) -> &BTreeMap<[u8; 16], AnnounceEntry> {
        &self.announce_table
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn held_announces(&self) -> &BTreeMap<[u8; 16], AnnounceEntry> {
        &self.held_announces
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn announce_retained_bytes(&self) -> usize {
        self.announce_retained_bytes_total()
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn reverse_table(&self) -> &BTreeMap<[u8; 16], tables::ReverseEntry> {
        &self.reverse_table
    }
}