rns-net 0.5.5

Network interfaces and node driver 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
//! Remote management destinations for the Reticulum transport node.
//!
//! Implements the server-side handlers for:
//! - `/status` on `rnstransport.remote.management` destination
//! - `/path` on `rnstransport.remote.management` destination
//! - `/list` on `rnstransport.info.blackhole` destination
//!
//! Python reference: Transport.py:220-241, 2591-2643, 3243-3249

use rns_core::constants;
use rns_core::destination::destination_hash;
use rns_core::hash::truncated_hash;
use rns_core::msgpack::{self, Value};
use rns_core::transport::types::{InterfaceId, InterfaceInfo};
use rns_core::transport::TransportEngine;

use super::interface_stats::InterfaceStats;
use super::time;

/// View trait for interface status, decoupling management from InterfaceEntry.
pub trait InterfaceStatusView {
    fn id(&self) -> InterfaceId;
    fn info(&self) -> &InterfaceInfo;
    fn online(&self) -> bool;
    fn stats(&self) -> &InterfaceStats;
}

/// Get the path hash for "/status".
pub fn status_path_hash() -> [u8; 16] {
    truncated_hash(b"/status")
}

/// Get the path hash for "/path".
pub fn path_path_hash() -> [u8; 16] {
    truncated_hash(b"/path")
}

/// Get the path hash for "/list".
pub fn list_path_hash() -> [u8; 16] {
    truncated_hash(b"/list")
}

/// Check if a path hash matches a known management path.
pub fn is_management_path(path_hash: &[u8; 16]) -> bool {
    *path_hash == status_path_hash()
        || *path_hash == path_path_hash()
        || *path_hash == list_path_hash()
}

/// Compute the remote management destination hash.
///
/// Destination: `rnstransport.remote.management` with transport identity.
pub fn management_dest_hash(transport_identity_hash: &[u8; 16]) -> [u8; 16] {
    destination_hash(
        "rnstransport",
        &["remote", "management"],
        Some(transport_identity_hash),
    )
}

/// Compute the blackhole info destination hash.
///
/// Destination: `rnstransport.info.blackhole` with transport identity.
pub fn blackhole_dest_hash(transport_identity_hash: &[u8; 16]) -> [u8; 16] {
    destination_hash(
        "rnstransport",
        &["info", "blackhole"],
        Some(transport_identity_hash),
    )
}

/// Compute the probe responder destination hash.
///
/// Destination: `rnstransport.probe` with transport identity.
pub fn probe_dest_hash(transport_identity_hash: &[u8; 16]) -> [u8; 16] {
    destination_hash("rnstransport", &["probe"], Some(transport_identity_hash))
}

/// Build an announce packet for the probe responder destination.
///
/// Returns raw packet bytes ready for `engine.handle_outbound()`.
pub fn build_probe_announce(
    identity: &rns_crypto::identity::Identity,
    rng: &mut dyn rns_crypto::Rng,
) -> Option<Vec<u8>> {
    let identity_hash = *identity.hash();
    let dest_hash = probe_dest_hash(&identity_hash);
    let name_hash = rns_core::destination::name_hash("rnstransport", &["probe"]);
    let mut random_hash = [0u8; 10];
    rng.fill_bytes(&mut random_hash);

    let (announce_data, _has_ratchet) = rns_core::announce::AnnounceData::pack(
        identity,
        &dest_hash,
        &name_hash,
        &random_hash,
        None,
        None,
    )
    .ok()?;

    let flags = rns_core::packet::PacketFlags {
        header_type: constants::HEADER_1,
        context_flag: constants::FLAG_UNSET,
        transport_type: constants::TRANSPORT_BROADCAST,
        destination_type: constants::DESTINATION_SINGLE,
        packet_type: constants::PACKET_TYPE_ANNOUNCE,
    };

    let packet = rns_core::packet::RawPacket::pack(
        flags,
        0,
        &dest_hash,
        None,
        constants::CONTEXT_NONE,
        &announce_data,
    )
    .ok()?;

    Some(packet.raw)
}

/// Management configuration.
#[derive(Debug, Clone)]
pub struct ManagementConfig {
    /// Enable remote management destination.
    pub enable_remote_management: bool,
    /// Identity hashes allowed to query management.
    pub remote_management_allowed: Vec<[u8; 16]>,
    /// Enable blackhole list publication.
    pub publish_blackhole: bool,
}

impl Default for ManagementConfig {
    fn default() -> Self {
        ManagementConfig {
            enable_remote_management: false,
            remote_management_allowed: Vec::new(),
            publish_blackhole: false,
        }
    }
}

/// Handle a `/status` request.
///
/// Request data: msgpack([include_lstats]) where include_lstats is bool.
/// Response: msgpack([interface_stats_dict, link_count?]) matching Python format.
pub fn handle_status_request(
    data: &[u8],
    engine: &TransportEngine,
    interfaces: &[&dyn InterfaceStatusView],
    started: f64,
    probe_responder_hash: Option<[u8; 16]>,
) -> Option<Vec<u8>> {
    // Decode request data
    let include_lstats = match msgpack::unpack_exact(data) {
        Ok(Value::Array(arr)) if !arr.is_empty() => arr[0].as_bool().unwrap_or(false),
        _ => false,
    };

    // Build interface stats
    let mut iface_list = Vec::new();
    let mut total_rxb: u64 = 0;
    let mut total_txb: u64 = 0;

    for entry in interfaces {
        let id = entry.id();
        let info = entry.info();
        let stats = entry.stats();

        total_rxb += stats.rxb;
        total_txb += stats.txb;

        let mut ifstats: Vec<(&str, Value)> = Vec::new();
        ifstats.push(("name", Value::Str(info.name.clone())));
        ifstats.push(("short_name", Value::Str(info.name.clone())));
        ifstats.push(("status", Value::Bool(entry.online())));
        ifstats.push(("mode", Value::UInt(info.mode as u64)));
        ifstats.push(("rxb", Value::UInt(stats.rxb)));
        ifstats.push(("txb", Value::UInt(stats.txb)));
        if let Some(br) = info.bitrate {
            ifstats.push(("bitrate", Value::UInt(br)));
        } else {
            ifstats.push(("bitrate", Value::Nil));
        }
        ifstats.push((
            "incoming_announce_freq",
            Value::Float(stats.incoming_announce_freq()),
        ));
        ifstats.push((
            "outgoing_announce_freq",
            Value::Float(stats.outgoing_announce_freq()),
        ));
        ifstats.push((
            "held_announces",
            Value::UInt(engine.held_announce_count(&id) as u64),
        ));

        // IFAC info
        ifstats.push(("ifac_signature", Value::Nil));
        ifstats.push((
            "ifac_size",
            if info.bitrate.is_some() {
                Value::UInt(0)
            } else {
                Value::Nil
            },
        ));
        ifstats.push(("ifac_netname", Value::Nil));

        // Unused by Rust but expected by Python clients
        ifstats.push(("clients", Value::Nil));
        ifstats.push(("announce_queue", Value::Nil));
        ifstats.push(("rxs", Value::UInt(0)));
        ifstats.push(("txs", Value::UInt(0)));

        // Build as map
        let map = ifstats
            .into_iter()
            .map(|(k, v)| (Value::Str(k.into()), v))
            .collect();
        iface_list.push(Value::Map(map));
    }

    // Build top-level stats dict
    let mut stats: Vec<(&str, Value)> = Vec::new();
    stats.push(("interfaces", Value::Array(iface_list)));
    stats.push(("rxb", Value::UInt(total_rxb)));
    stats.push(("txb", Value::UInt(total_txb)));
    stats.push(("rxs", Value::UInt(0)));
    stats.push(("txs", Value::UInt(0)));

    if let Some(identity_hash) = engine.config().identity_hash {
        stats.push(("transport_id", Value::Bin(identity_hash.to_vec())));
        stats.push(("transport_uptime", Value::Float(time::now() - started)));
    }
    stats.push((
        "probe_responder",
        match probe_responder_hash {
            Some(hash) => Value::Bin(hash.to_vec()),
            None => Value::Nil,
        },
    ));
    stats.push(("rss", Value::Nil));

    let stats_map = stats
        .into_iter()
        .map(|(k, v)| (Value::Str(k.into()), v))
        .collect();

    // Build response: [stats_dict] or [stats_dict, link_count]
    let mut response = vec![Value::Map(stats_map)];
    if include_lstats {
        let link_count = engine.link_table_count();
        response.push(Value::UInt(link_count as u64));
    }

    Some(msgpack::pack(&Value::Array(response)))
}

/// Handle a `/path` request.
///
/// Request data: msgpack([command, destination_hash?, max_hops?])
/// - command = "table" → returns path table entries
/// - command = "rates" → returns rate table entries
pub fn handle_path_request(data: &[u8], engine: &TransportEngine) -> Option<Vec<u8>> {
    let arr = match msgpack::unpack_exact(data) {
        Ok(Value::Array(arr)) if !arr.is_empty() => arr,
        _ => return None,
    };

    let command = match &arr[0] {
        Value::Str(s) => s.as_str(),
        _ => return None,
    };

    let dest_filter: Option<[u8; 16]> = if arr.len() > 1 {
        match &arr[1] {
            Value::Bin(b) if b.len() == 16 => {
                let mut h = [0u8; 16];
                h.copy_from_slice(b);
                Some(h)
            }
            _ => None,
        }
    } else {
        None
    };

    let max_hops: Option<u8> = if arr.len() > 2 {
        arr[2].as_uint().map(|v| v as u8)
    } else {
        None
    };

    match command {
        "table" => {
            let paths = engine.get_path_table(max_hops);
            let mut entries = Vec::new();
            for p in &paths {
                if let Some(ref filter) = dest_filter {
                    if p.0 != *filter {
                        continue;
                    }
                }
                // p = (dest_hash, timestamp, next_hop, hops, expires, interface)
                let entry = vec![
                    (Value::Str("hash".into()), Value::Bin(p.0.to_vec())),
                    (Value::Str("timestamp".into()), Value::Float(p.1)),
                    (Value::Str("via".into()), Value::Bin(p.2.to_vec())),
                    (Value::Str("hops".into()), Value::UInt(p.3 as u64)),
                    (Value::Str("expires".into()), Value::Float(p.4)),
                    (Value::Str("interface".into()), Value::Str(p.5.clone())),
                ];
                entries.push(Value::Map(entry));
            }
            Some(msgpack::pack(&Value::Array(entries)))
        }
        "rates" => {
            let rates = engine.get_rate_table();
            let mut entries = Vec::new();
            for r in &rates {
                if let Some(ref filter) = dest_filter {
                    if r.0 != *filter {
                        continue;
                    }
                }
                // r = (dest_hash, last, rate_violations, blocked_until, timestamps)
                let timestamps: Vec<Value> = r.4.iter().map(|t| Value::Float(*t)).collect();
                let entry = vec![
                    (Value::Str("hash".into()), Value::Bin(r.0.to_vec())),
                    (Value::Str("last".into()), Value::Float(r.1)),
                    (
                        Value::Str("rate_violations".into()),
                        Value::UInt(r.2 as u64),
                    ),
                    (Value::Str("blocked_until".into()), Value::Float(r.3)),
                    (Value::Str("timestamps".into()), Value::Array(timestamps)),
                ];
                entries.push(Value::Map(entry));
            }
            Some(msgpack::pack(&Value::Array(entries)))
        }
        _ => None,
    }
}

/// Handle a `/list` (blackhole list) request.
///
/// Returns the blackholed_identities dict as msgpack.
pub fn handle_blackhole_list_request(engine: &TransportEngine) -> Option<Vec<u8>> {
    let blackholed = engine.get_blackholed();
    let mut map_entries = Vec::new();
    for (hash, created, expires, reason) in &blackholed {
        let mut entry = vec![
            (Value::Str("created".into()), Value::Float(*created)),
            (Value::Str("expires".into()), Value::Float(*expires)),
        ];
        if let Some(r) = reason {
            entry.push((Value::Str("reason".into()), Value::Str(r.clone())));
        }
        map_entries.push((Value::Bin(hash.to_vec()), Value::Map(entry)));
    }
    Some(msgpack::pack(&Value::Map(map_entries)))
}

/// Build an announce packet for the management destination.
///
/// Returns raw packet bytes ready for `engine.handle_outbound()`.
pub fn build_management_announce(
    identity: &rns_crypto::identity::Identity,
    rng: &mut dyn rns_crypto::Rng,
) -> Option<Vec<u8>> {
    let identity_hash = *identity.hash();
    let dest_hash = management_dest_hash(&identity_hash);
    let name_hash = rns_core::destination::name_hash("rnstransport", &["remote", "management"]);
    let mut random_hash = [0u8; 10];
    rng.fill_bytes(&mut random_hash);

    let (announce_data, _has_ratchet) = rns_core::announce::AnnounceData::pack(
        identity,
        &dest_hash,
        &name_hash,
        &random_hash,
        None, // no ratchet
        None, // no app_data
    )
    .ok()?;

    let flags = rns_core::packet::PacketFlags {
        header_type: constants::HEADER_1,
        context_flag: constants::FLAG_UNSET,
        transport_type: constants::TRANSPORT_BROADCAST,
        destination_type: constants::DESTINATION_SINGLE,
        packet_type: constants::PACKET_TYPE_ANNOUNCE,
    };

    let packet = rns_core::packet::RawPacket::pack(
        flags,
        0,
        &dest_hash,
        None,
        constants::CONTEXT_NONE,
        &announce_data,
    )
    .ok()?;

    Some(packet.raw)
}

/// Build an announce packet for the blackhole info destination.
///
/// Returns raw packet bytes ready for `engine.handle_outbound()`.
pub fn build_blackhole_announce(
    identity: &rns_crypto::identity::Identity,
    rng: &mut dyn rns_crypto::Rng,
) -> Option<Vec<u8>> {
    let identity_hash = *identity.hash();
    let dest_hash = blackhole_dest_hash(&identity_hash);
    let name_hash = rns_core::destination::name_hash("rnstransport", &["info", "blackhole"]);
    let mut random_hash = [0u8; 10];
    rng.fill_bytes(&mut random_hash);

    let (announce_data, _has_ratchet) = rns_core::announce::AnnounceData::pack(
        identity,
        &dest_hash,
        &name_hash,
        &random_hash,
        None,
        None,
    )
    .ok()?;

    let flags = rns_core::packet::PacketFlags {
        header_type: constants::HEADER_1,
        context_flag: constants::FLAG_UNSET,
        transport_type: constants::TRANSPORT_BROADCAST,
        destination_type: constants::DESTINATION_SINGLE,
        packet_type: constants::PACKET_TYPE_ANNOUNCE,
    };

    let packet = rns_core::packet::RawPacket::pack(
        flags,
        0,
        &dest_hash,
        None,
        constants::CONTEXT_NONE,
        &announce_data,
    )
    .ok()?;

    Some(packet.raw)
}