From 4518647728b08e8bd5ef3a2e4bdf0c045497704e Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:17:46 -0700 Subject: [PATCH] runtime: answer the 1.6.0 shared-instance RPC requests --- crates/rns-runtime/src/rpc.rs | 473 +++++++++++++++++++++++++- crates/rns-runtime/src/rpc_server.rs | 296 ++++++++++++++++ crates/rns-transport/src/actor/rpc.rs | 50 +++ crates/rns-transport/src/messages.rs | 2 + 4 files changed, 816 insertions(+), 5 deletions(-) diff --git a/crates/rns-runtime/src/rpc.rs b/crates/rns-runtime/src/rpc.rs index 1d51bca..61a436a 100644 --- a/crates/rns-runtime/src/rpc.rs +++ b/crates/rns-runtime/src/rpc.rs @@ -112,6 +112,61 @@ pub enum RpcRequest { UnretainDestination { destination_hash: Vec, }, + /// Reply: the slowest online interface bitrate, or nil before one exists. + GetLowestInterfaceBitrate, + /// Reply: seconds as a float, or integer 0 without a known bitrate. + GetMediumPathTimeout, + GetActiveLinkCount, + /// Reply: a dictionary; upstream's implementation is a stub answering `{}`. + GetLinkDistribution, + /// Reply: profiler results, or nil when no profiler ran. + GetProfilingResults, + /// Reply: true, false, or nil when the interface does not exist. + ManageInterface { + operation: ManageOperation, + name: String, + }, + WantsDestinationType { + full_name: String, + requester: Vec, + signature: Option>, + }, + UnwantsDestinationType { + full_name: String, + requester: Vec, + signature: Option>, + }, + UnwantsAllDestinationTypes { + requester: Vec, + signature: Option>, + }, +} + +/// Interface management operations of the `manage` request. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ManageOperation { + Attach, + Detach, + Reload, +} + +impl ManageOperation { + pub fn as_str(self) -> &'static str { + match self { + Self::Attach => "attach_interface", + Self::Detach => "detach_interface", + Self::Reload => "reload_interface", + } + } + + fn parse(operation: &str) -> Option { + match operation { + "attach_interface" => Some(Self::Attach), + "detach_interface" => Some(Self::Detach), + "reload_interface" => Some(Self::Reload), + _ => None, + } + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -417,9 +472,51 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue { ("destination_data", PyValue::String("unretain".to_string())), ("destination_hash", PyValue::Bytes(destination_hash.clone())), ]), + RpcRequest::GetLowestInterfaceBitrate => py_get("lowest_interface_bitrate"), + RpcRequest::GetMediumPathTimeout => py_get("medium_path_timeout"), + RpcRequest::GetActiveLinkCount => py_get("active_link_count"), + RpcRequest::GetLinkDistribution => py_get("link_distribution"), + RpcRequest::GetProfilingResults => py_get("profiling_results"), + RpcRequest::ManageInterface { operation, name } => py_dict(vec![ + ("manage", PyValue::String(operation.as_str().to_string())), + ("name", PyValue::String(name.clone())), + ]), + RpcRequest::WantsDestinationType { + full_name, + requester, + signature, + } => py_dict(vec![ + ("wants_destination_type", PyValue::String(full_name.clone())), + ("requester", PyValue::Bytes(requester.clone())), + ("signature", optional_bytes_value(signature)), + ]), + RpcRequest::UnwantsDestinationType { + full_name, + requester, + signature, + } => py_dict(vec![ + ( + "unwants_destination_type", + PyValue::String(full_name.clone()), + ), + ("requester", PyValue::Bytes(requester.clone())), + ("signature", optional_bytes_value(signature)), + ]), + RpcRequest::UnwantsAllDestinationTypes { + requester, + signature, + } => py_dict(vec![ + ("unwants_all_destination_types", PyValue::Bool(true)), + ("requester", PyValue::Bytes(requester.clone())), + ("signature", optional_bytes_value(signature)), + ]), } } +fn optional_bytes_value(value: &Option>) -> PyValue { + value.clone().map(PyValue::Bytes).unwrap_or(PyValue::None) +} + fn py_get(path: &str) -> PyValue { py_dict(vec![("get", PyValue::String(path.to_string()))]) } @@ -465,12 +562,27 @@ fn py_value_to_request(value: &PyValue) -> Result { "is_blackholed" => Ok(RpcRequest::IsBlackholed { identity_hash: dict_bytes(entries, "identity_hash")?, }), + "lowest_interface_bitrate" => Ok(RpcRequest::GetLowestInterfaceBitrate), + "medium_path_timeout" => Ok(RpcRequest::GetMediumPathTimeout), + "active_link_count" => Ok(RpcRequest::GetActiveLinkCount), + "link_distribution" => Ok(RpcRequest::GetLinkDistribution), + "profiling_results" => Ok(RpcRequest::GetProfilingResults), other => Err(RpcError::Deserialize(format!( "unknown Python RPC get path: {other}" ))), }; } + if let Some(PyValue::String(operation)) = dict_get(entries, "manage") { + let operation = ManageOperation::parse(operation).ok_or_else(|| { + RpcError::Deserialize(format!("unknown Python RPC manage operation: {operation}")) + })?; + let name = dict_get(entries, "name") + .and_then(py_string) + .ok_or_else(|| RpcError::Deserialize("manage request has no name".to_string()))?; + return Ok(RpcRequest::ManageInterface { operation, name }); + } + if let Some(PyValue::String(path)) = dict_get(entries, "drop") { return match path.as_str() { "path" => Ok(RpcRequest::DropPath { @@ -514,6 +626,29 @@ fn py_value_to_request(value: &PyValue) -> Result { }); } + if let Some(full_name) = dict_get(entries, "wants_destination_type") { + return Ok(RpcRequest::WantsDestinationType { + full_name: destination_type_name(full_name)?, + requester: dict_requester(entries)?, + signature: dict_signature(entries)?, + }); + } + + if let Some(full_name) = dict_get(entries, "unwants_destination_type") { + return Ok(RpcRequest::UnwantsDestinationType { + full_name: destination_type_name(full_name)?, + requester: dict_requester(entries)?, + signature: dict_signature(entries)?, + }); + } + + if dict_get(entries, "unwants_all_destination_types").is_some() { + return Ok(RpcRequest::UnwantsAllDestinationTypes { + requester: dict_requester(entries)?, + signature: dict_signature(entries)?, + }); + } + if let Some(PyValue::String(operation)) = dict_get(entries, "destination_data") { let destination_hash = dict_bytes(entries, "destination_hash")?; return match operation.as_str() { @@ -541,6 +676,64 @@ fn py_value_to_request(value: &PyValue) -> Result { )) } +fn destination_type_name(value: &PyValue) -> Result { + py_string(value) + .ok_or_else(|| RpcError::Deserialize("destination type name is not a string".to_string())) +} + +/// Python requires the `requester` key and keys requirements by it as sent; +/// a nil requester is kept as an empty one. +fn dict_requester(entries: &[(PyDictKey, PyValue)]) -> Result, RpcError> { + match dict_get(entries, "requester") { + Some(PyValue::Bytes(requester)) => Ok(requester.clone()), + Some(PyValue::None) => Ok(Vec::new()), + _ => Err(RpcError::Deserialize( + "destination type request has no requester".to_string(), + )), + } +} + +/// Python requires the `signature` key but never validates its value, so a +/// value other than bytes is kept as `None`. +fn dict_signature(entries: &[(PyDictKey, PyValue)]) -> Result>, RpcError> { + match dict_get(entries, "signature") { + Some(PyValue::Bytes(signature)) => Ok(Some(signature.clone())), + Some(_) => Ok(None), + None => Err(RpcError::Deserialize( + "destination type request has no signature".to_string(), + )), + } +} + +/// Python `None`, as `profiling_results` answers when no profiler ran. +pub(crate) fn encode_none() -> Result, RpcError> { + encode_umsgpack(&PyValue::None) +} + +/// An integer or `None`, as `lowest_interface_bitrate` answers. +pub(crate) fn encode_optional_int(value: Option) -> Result, RpcError> { + encode_umsgpack( + &value + .map(|v| PyValue::Int(i128::from(v))) + .unwrap_or(PyValue::None), + ) +} + +/// `True`, `False` or `None`, as the `manage` request answers. +pub(crate) fn encode_optional_bool(value: Option) -> Result, RpcError> { + encode_umsgpack(&value.map(PyValue::Bool).unwrap_or(PyValue::None)) +} + +/// A float, or integer 0 when the timeout is unknown (Transport.py:3552). +pub(crate) fn encode_medium_path_timeout(seconds: Option) -> Result, RpcError> { + encode_umsgpack(&seconds.map(PyValue::Float).unwrap_or(PyValue::Int(0))) +} + +/// An empty dictionary, as upstream's stub `link_distribution` answers. +pub(crate) fn encode_empty_dict() -> Result, RpcError> { + encode_umsgpack(&PyValue::Dict(Vec::new())) +} + fn response_to_py_value(resp: &RpcResponse) -> PyValue { match resp { RpcResponse::PathTable(entries) => PyValue::List( @@ -895,15 +1088,48 @@ fn py_value_to_response_for_request( | RpcRequest::DropAnnounceQueues | RpcRequest::BlackholeIdentity { .. } | RpcRequest::UnblackholeIdentity { .. } => Ok(RpcResponse::Ok), + RpcRequest::GetLowestInterfaceBitrate => match value { + PyValue::None => Ok(RpcResponse::StringResult(None)), + _ => Ok(RpcResponse::IntResult(py_required_int(value)?)), + }, + RpcRequest::GetMediumPathTimeout => Ok(RpcResponse::FloatResult(Some( + py_optional_float(value)?.unwrap_or(0.0), + ))), + RpcRequest::GetActiveLinkCount => Ok(RpcResponse::IntResult(py_required_int(value)?)), + // Upstream's link distribution is a stub that answers `{}`. + RpcRequest::GetLinkDistribution => match value { + PyValue::Dict(_) => Ok(RpcResponse::Ok), + _ => Err(RpcError::Deserialize( + "expected link distribution dictionary".to_string(), + )), + }, + // `None` means no profiler ran; results themselves are not decoded. + RpcRequest::GetProfilingResults => Ok(match value { + PyValue::None => RpcResponse::StringResult(None), + _ => RpcResponse::Ok, + }), + // `None` (no such interface) decodes as `StringResult(None)`. + RpcRequest::ManageInterface { .. } => match value { + PyValue::Bool(v) => Ok(RpcResponse::BoolResult(*v)), + PyValue::None => Ok(RpcResponse::StringResult(None)), + _ => Err(RpcError::Deserialize( + "expected True, False or None".to_string(), + )), + }, RpcRequest::IsBlackholed { .. } | RpcRequest::UseDestination { .. } | RpcRequest::RetainDestination { .. } | RpcRequest::RetainIdentity { .. } - | RpcRequest::UnretainDestination { .. } => Ok(RpcResponse::BoolResult(match value { - PyValue::Bool(v) => *v, - PyValue::None => false, - _ => py_required_int(value)? != 0, - })), + | RpcRequest::UnretainDestination { .. } + | RpcRequest::WantsDestinationType { .. } + | RpcRequest::UnwantsDestinationType { .. } + | RpcRequest::UnwantsAllDestinationTypes { .. } => { + Ok(RpcResponse::BoolResult(match value { + PyValue::Bool(v) => *v, + PyValue::None => false, + _ => py_required_int(value)? != 0, + })) + } } } @@ -2859,4 +3085,241 @@ mod tests { data.push(0xc0); assert!(decode_umsgpack(&data).is_err()); } + + /// Requests upstream RNS 1.6.0 clients send, from the harness generator + /// `reticulum/support/rpc_parity/gen_rpc_1_6_wire.py`. + const UPSTREAM_1_6_REQUESTS: &[(&str, &str)] = &[ + ( + "lowest_interface_bitrate", + "81a3676574b86c6f776573745f696e746572666163655f62697472617465", + ), + ( + "medium_path_timeout", + "81a3676574b36d656469756d5f706174685f74696d656f7574", + ), + ( + "active_link_count", + "81a3676574b16163746976655f6c696e6b5f636f756e74", + ), + ( + "link_distribution", + "81a3676574b16c696e6b5f646973747269627574696f6e", + ), + ( + "profiling_results", + "81a3676574b170726f66696c696e675f726573756c7473", + ), + ( + "attach_interface", + "82a66d616e616765b06174746163685f696e74657266616365a46e616d65ac44697361626c656420544350", + ), + ( + "detach_interface", + "82a66d616e616765b06465746163685f696e74657266616365a46e616d65ac44697361626c656420544350", + ), + ( + "reload_interface", + "82a66d616e616765b072656c6f61645f696e74657266616365a46e616d65ac44697361626c656420544350", + ), + ( + "wants_destination_type", + "83b677616e74735f64657374696e6174696f6e5f74797065ad6c786d662e64656c6976657279a9726571756573746572c41000112233445566778899aabbccddeeffa97369676e6174757265c0", + ), + ( + "unwants_destination_type", + "83b8756e77616e74735f64657374696e6174696f6e5f74797065ad6c786d662e64656c6976657279a9726571756573746572c41000112233445566778899aabbccddeeffa97369676e6174757265c0", + ), + ( + "unwants_all_destination_types", + "83bd756e77616e74735f616c6c5f64657374696e6174696f6e5f7479706573c3a9726571756573746572c41000112233445566778899aabbccddeeffa97369676e6174757265c0", + ), + ]; + + fn upstream_request(name: &str) -> Vec { + let (_, hex) = UPSTREAM_1_6_REQUESTS + .iter() + .find(|(n, _)| *n == name) + .unwrap(); + hex::decode(hex).unwrap() + } + + #[test] + fn upstream_1_6_requests_decode_and_reencode_byte_identically() { + for (name, hex) in UPSTREAM_1_6_REQUESTS { + let bytes = hex::decode(hex).unwrap(); + let request = + decode_request(&bytes).unwrap_or_else(|e| panic!("{name}: decode failed: {e:?}")); + assert_eq!( + hex::encode(encode_request(&request).unwrap()), + *hex, + "{name}: re-encoded bytes differ from upstream" + ); + } + } + + #[test] + fn upstream_1_6_requests_decode_to_their_operations() { + assert!(matches!( + decode_request(&upstream_request("lowest_interface_bitrate")).unwrap(), + RpcRequest::GetLowestInterfaceBitrate + )); + assert!(matches!( + decode_request(&upstream_request("medium_path_timeout")).unwrap(), + RpcRequest::GetMediumPathTimeout + )); + assert!(matches!( + decode_request(&upstream_request("active_link_count")).unwrap(), + RpcRequest::GetActiveLinkCount + )); + assert!(matches!( + decode_request(&upstream_request("link_distribution")).unwrap(), + RpcRequest::GetLinkDistribution + )); + assert!(matches!( + decode_request(&upstream_request("profiling_results")).unwrap(), + RpcRequest::GetProfilingResults + )); + for (name, op) in [ + ("attach_interface", ManageOperation::Attach), + ("detach_interface", ManageOperation::Detach), + ("reload_interface", ManageOperation::Reload), + ] { + match decode_request(&upstream_request(name)).unwrap() { + RpcRequest::ManageInterface { operation, name } => { + assert_eq!(operation, op); + assert_eq!(name, "Disabled TCP"); + } + other => panic!("{name}: decoded as {other:?}"), + } + } + let requester = hex::decode("00112233445566778899aabbccddeeff").unwrap(); + match decode_request(&upstream_request("wants_destination_type")).unwrap() { + RpcRequest::WantsDestinationType { + full_name, + requester: r, + signature, + } => { + assert_eq!(full_name, "lxmf.delivery"); + assert_eq!(r, requester); + assert_eq!(signature, None); + } + other => panic!("decoded as {other:?}"), + } + assert!(matches!( + decode_request(&upstream_request("unwants_destination_type")).unwrap(), + RpcRequest::UnwantsDestinationType { full_name, .. } if full_name == "lxmf.delivery" + )); + assert!(matches!( + decode_request(&upstream_request("unwants_all_destination_types")).unwrap(), + RpcRequest::UnwantsAllDestinationTypes { requester: r, .. } if r == requester + )); + } + + #[test] + fn destination_type_request_without_requester_or_signature_is_rejected() { + // Python's rpc_loop indexes both keys and drops the call without them. + let no_signature = py_dict(vec![ + ("wants_destination_type", PyValue::String("a.b".to_string())), + ("requester", PyValue::Bytes(vec![1; 16])), + ]); + assert!(decode_request(&encode_umsgpack(&no_signature).unwrap()).is_err()); + let no_requester = py_dict(vec![ + ("unwants_all_destination_types", PyValue::Bool(true)), + ("signature", PyValue::None), + ]); + assert!(decode_request(&encode_umsgpack(&no_requester).unwrap()).is_err()); + } + + #[test] + fn unknown_manage_operation_is_rejected() { + let request = py_dict(vec![ + ("manage", PyValue::String("restart_interface".to_string())), + ("name", PyValue::String("x".to_string())), + ]); + assert!(decode_request(&encode_umsgpack(&request).unwrap()).is_err()); + } + + /// Replies upstream 1.6.0 packs, from the same generator. + #[test] + fn new_replies_encode_as_upstream_packs_them() { + assert_eq!(hex::encode(encode_optional_int(None).unwrap()), "c0"); + assert_eq!( + hex::encode(encode_optional_int(Some(500)).unwrap()), + "cd01f4" + ); + assert_eq!( + hex::encode(encode_optional_int(Some(1200)).unwrap()), + "cd04b0" + ); + assert_eq!(hex::encode(encode_optional_int(Some(3)).unwrap()), "03"); + assert_eq!(hex::encode(encode_medium_path_timeout(None).unwrap()), "00"); + assert_eq!( + hex::encode(encode_medium_path_timeout(Some(22.0)).unwrap()), + "cb4036000000000000" + ); + assert_eq!(hex::encode(encode_empty_dict().unwrap()), "80"); + assert_eq!(hex::encode(encode_none().unwrap()), "c0"); + assert_eq!(hex::encode(encode_optional_bool(Some(true)).unwrap()), "c3"); + assert_eq!( + hex::encode(encode_optional_bool(Some(false)).unwrap()), + "c2" + ); + assert_eq!(hex::encode(encode_optional_bool(None).unwrap()), "c0"); + } + + #[test] + fn new_replies_decode_for_their_requests() { + let decode = |hex: &str, request: RpcRequest| { + decode_response_for_request(&hex::decode(hex).unwrap(), &request).unwrap() + }; + assert!(matches!( + decode("cd01f4", RpcRequest::GetLowestInterfaceBitrate), + RpcResponse::IntResult(500) + )); + assert!(matches!( + decode("c0", RpcRequest::GetLowestInterfaceBitrate), + RpcResponse::StringResult(None) + )); + assert!(matches!( + decode("cb4036000000000000", RpcRequest::GetMediumPathTimeout), + RpcResponse::FloatResult(Some(v)) if v == 22.0 + )); + assert!(matches!( + decode("00", RpcRequest::GetMediumPathTimeout), + RpcResponse::FloatResult(Some(v)) if v == 0.0 + )); + assert!(matches!( + decode("01", RpcRequest::GetActiveLinkCount), + RpcResponse::IntResult(1) + )); + assert!(matches!( + decode("80", RpcRequest::GetLinkDistribution), + RpcResponse::Ok + )); + assert!(matches!( + decode("c0", RpcRequest::GetProfilingResults), + RpcResponse::StringResult(None) + )); + let manage = || RpcRequest::ManageInterface { + operation: ManageOperation::Attach, + name: "x".to_string(), + }; + assert!(matches!( + decode("c3", manage()), + RpcResponse::BoolResult(true) + )); + assert!(matches!( + decode("c2", manage()), + RpcResponse::BoolResult(false) + )); + assert!(matches!( + decode("c0", manage()), + RpcResponse::StringResult(None) + )); + let wants = RpcRequest::UnwantsAllDestinationTypes { + requester: vec![0; 16], + signature: None, + }; + assert!(matches!(decode("c3", wants), RpcResponse::BoolResult(true))); + } } diff --git a/crates/rns-runtime/src/rpc_server.rs b/crates/rns-runtime/src/rpc_server.rs index cf37d35..639e00b 100644 --- a/crates/rns-runtime/src/rpc_server.rs +++ b/crates/rns-runtime/src/rpc_server.rs @@ -3,6 +3,9 @@ //! use mutual RPC-key authentication and framed MessagePack, with a 30-second //! session budget and up to 64 concurrent clients. RPC frames are not encrypted. +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; + use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpListener; use tokio::sync::mpsc; @@ -24,6 +27,8 @@ pub(crate) struct RpcBackend { transport_tx: mpsc::Sender, ifac: Option, transport: Option, + lowest_interface_bitrate: Arc>>, + destination_types: DestinationTypeRequests, } impl RpcBackend { @@ -35,6 +40,8 @@ impl RpcBackend { transport_tx, ifac, transport: None, + lowest_interface_bitrate: Arc::default(), + destination_types: DestinationTypeRequests::default(), } } @@ -44,6 +51,54 @@ impl RpcBackend { } } +/// Shared-instance clients' destination type requirements, keyed by name +/// hash, as Python's `Transport.client_destination_types` (Transport.py:4648-4692). +type DestinationTypeRequirements = HashMap<[u8; 10], HashSet>>; + +#[derive(Clone, Default)] +struct DestinationTypeRequests { + requirements: Arc>, +} + +impl DestinationTypeRequests { + fn wants(&self, full_name: &str, requester: Vec) -> bool { + self.requirements + .lock() + .expect("destination type requirements mutex poisoned") + .entry(rns_identity::name_hash::name_hash(full_name)) + .or_default() + .insert(requester); + true + } + + fn unwants(&self, full_name: &str, requester: Vec) -> bool { + let name_hash = rns_identity::name_hash::name_hash(full_name); + let mut requirements = self + .requirements + .lock() + .expect("destination type requirements mutex poisoned"); + let Some(requesters) = requirements.get_mut(&name_hash) else { + return false; + }; + let was_registered = requesters.remove(&requester); + if requesters.is_empty() { + requirements.remove(&name_hash); + } + was_registered + } + + fn unwants_all(&self, requester: Vec) -> bool { + self.requirements + .lock() + .expect("destination type requirements mutex poisoned") + .retain(|_, requesters| { + requesters.remove(&requester); + !requesters.is_empty() + }); + true + } +} + /// A transport instance's identity, network identity, start and probe /// responder for its interface stats; the responder registers after the /// control port starts. @@ -405,6 +460,47 @@ async fn handle_rpc_client( } async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result, RpcError> { + match request { + RpcRequest::GetLowestInterfaceBitrate => { + return match lowest_interface_bitrate(backend).await { + Ok(bitrate) => rpc::encode_optional_int(bitrate), + Err(response) => rpc::encode_response(&response), + }; + } + RpcRequest::GetMediumPathTimeout => { + return match lowest_interface_bitrate(backend).await { + Ok(bitrate) => rpc::encode_medium_path_timeout(bitrate.map(medium_path_timeout)), + Err(response) => rpc::encode_response(&response), + }; + } + RpcRequest::GetLinkDistribution => return rpc::encode_empty_dict(), + RpcRequest::GetProfilingResults => return rpc::encode_none(), + // The runtime cannot attach or detach configured interfaces yet, so it + // answers as Python does with `enable_interface_management = no` + // (Reticulum.py:851, 878, 907). + RpcRequest::ManageInterface { .. } => return rpc::encode_optional_bool(Some(false)), + RpcRequest::WantsDestinationType { + full_name, + requester, + .. + } => { + let wanted = backend.destination_types.wants(&full_name, requester); + return rpc::encode_response(&RpcResponse::BoolResult(wanted)); + } + RpcRequest::UnwantsDestinationType { + full_name, + requester, + .. + } => { + let unwanted = backend.destination_types.unwants(&full_name, requester); + return rpc::encode_response(&RpcResponse::BoolResult(unwanted)); + } + RpcRequest::UnwantsAllDestinationTypes { requester, .. } => { + let unwanted = backend.destination_types.unwants_all(requester); + return rpc::encode_response(&RpcResponse::BoolResult(unwanted)); + } + _ => {} + } match process_rpc_request(request, &backend.transport_tx, backend.ifac.as_ref()).await { RpcResponse::InterfaceStats(entries) => rpc::encode_interface_stats( &entries, @@ -418,6 +514,41 @@ async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result, R } } +/// Python's `Transport.lowest_interface_bitrate`: the minimum over online +/// interfaces with a bitrate, keeping the last value when none qualifies +/// (Transport.py:708). +async fn lowest_interface_bitrate(backend: &RpcBackend) -> Result, RpcResponse> { + use rns_transport::messages::{TransportQuery, TransportQueryResponse}; + let interfaces = + match query_transport(&backend.transport_tx, TransportQuery::GetInterfaceStats).await { + Ok(TransportQueryResponse::InterfaceStats(interfaces)) => interfaces, + Ok(_) => return Err(unexpected_transport_response("interface stats query")), + Err(failure) => { + return Err(transport_failure_response("interface stats query", failure)); + } + }; + let mut cached = backend + .lowest_interface_bitrate + .lock() + .expect("lowest interface bitrate mutex poisoned"); + if let Some(lowest) = interfaces + .iter() + .filter(|interface| interface.online && interface.bitrate > 0) + .map(|interface| interface.bitrate) + .min() + { + *cached = Some(lowest); + } + Ok(*cached) +} + +/// Python's `Transport.medium_path_timeout()` for a known bitrate (Transport.py:3550-3553). +fn medium_path_timeout(lowest_bitrate: u64) -> f64 { + let bits = (rns_wire::constants::MTU * 8) as f64; + 2.0 * (bits / lowest_bitrate.max(crate::constants::MINIMUM_BITRATE) as f64) + + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT +} + const TRANSPORT_QUERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5); #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -613,6 +744,25 @@ async fn process_rpc_request( _ => unexpected_transport_response("link count query"), } } + RpcRequest::GetActiveLinkCount => { + match authoritative_query!( + TransportQuery::GetActiveLinkCount, + "active link count query" + ) { + TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n), + _ => unexpected_transport_response("active link count query"), + } + } + RpcRequest::GetLowestInterfaceBitrate + | RpcRequest::GetMediumPathTimeout + | RpcRequest::GetLinkDistribution + | RpcRequest::GetProfilingResults + | RpcRequest::ManageInterface { .. } + | RpcRequest::WantsDestinationType { .. } + | RpcRequest::UnwantsDestinationType { .. } + | RpcRequest::UnwantsAllDestinationTypes { .. } => { + RpcResponse::Error("request needs the control server's state".to_string()) + } RpcRequest::GetNextHopIfName { destination_hash } => { let Some(dest) = hash_to_array(&destination_hash) else { return invalid_request_hash("destination"); @@ -1515,4 +1665,150 @@ listener.close() } panic!("failed to connect to RPC server on {addr}: {last_err:?}"); } + + /// A transport that answers interface stats with `(online, bitrate)` pairs. + fn stats_transport(interfaces: Vec<(bool, u64)>) -> mpsc::Sender { + use rns_transport::messages::{ + InterfaceStatRpcEntry, TransportQuery, TransportQueryResponse, + }; + let (tx, mut rx) = mpsc::channel::(8); + tokio::spawn(async move { + while let Some(TransportMessage::Rpc { query, response_tx }) = rx.recv().await { + let response = match query { + TransportQuery::GetInterfaceStats => TransportQueryResponse::InterfaceStats( + interfaces + .iter() + .enumerate() + .map(|(id, &(online, bitrate))| InterfaceStatRpcEntry { + id: id as u64, + online, + bitrate, + ..Default::default() + }) + .collect(), + ), + _ => TransportQueryResponse::Error("unexpected".into()), + }; + let _ = response_tx.send(response); + } + }); + tx + } + + /// Expected bytes are upstream 1.6.0 replies + /// (reticulum/support/rpc_parity/gen_rpc_1_6_wire.py). + #[tokio::test] + async fn lowest_bitrate_and_medium_path_timeout_answer_as_upstream() { + let backend = RpcBackend::new( + stats_transport(vec![(true, 1200), (true, 115_200), (false, 300), (true, 0)]), + None, + ); + let bitrate = respond(RpcRequest::GetLowestInterfaceBitrate, &backend) + .await + .unwrap(); + assert_eq!(hex::encode(bitrate), "cd04b0"); + let timeout = respond(RpcRequest::GetMediumPathTimeout, &backend) + .await + .unwrap(); + assert_eq!(hex::encode(timeout), "cb4029555555555556"); + + let slow = RpcBackend::new(stats_transport(vec![(true, 3)]), None); + let timeout = respond(RpcRequest::GetMediumPathTimeout, &slow) + .await + .unwrap(); + assert_eq!(hex::encode(timeout), "cb4099180000000000"); + } + + #[tokio::test] + async fn lowest_bitrate_is_none_until_an_interface_qualifies_then_kept() { + let backend = RpcBackend::new(stats_transport(vec![(true, 0), (false, 500)]), None); + let bitrate = respond(RpcRequest::GetLowestInterfaceBitrate, &backend) + .await + .unwrap(); + assert_eq!(hex::encode(bitrate), "c0"); + let timeout = respond(RpcRequest::GetMediumPathTimeout, &backend) + .await + .unwrap(); + assert_eq!(hex::encode(timeout), "00"); + + // Python keeps the last qualifying value when none qualifies any more. + let kept = RpcBackend { + transport_tx: stats_transport(vec![(false, 500)]), + ..backend.clone() + }; + *backend.lowest_interface_bitrate.lock().unwrap() = Some(500); + let bitrate = respond(RpcRequest::GetLowestInterfaceBitrate, &kept) + .await + .unwrap(); + assert_eq!(hex::encode(bitrate), "cd01f4"); + } + + #[tokio::test] + async fn stub_replies_match_upstream() { + let backend = RpcBackend::new(stats_transport(Vec::new()), None); + let reply = |request| respond(request, &backend); + assert_eq!( + hex::encode(reply(RpcRequest::GetLinkDistribution).await.unwrap()), + "80" + ); + assert_eq!( + hex::encode(reply(RpcRequest::GetProfilingResults).await.unwrap()), + "c0" + ); + } + + #[tokio::test] + async fn manage_answers_as_upstream_with_management_disabled() { + let backend = RpcBackend::new(stats_transport(Vec::new()), None); + for operation in [ + rpc::ManageOperation::Attach, + rpc::ManageOperation::Detach, + rpc::ManageOperation::Reload, + ] { + for name in ["Managed TCP", "Nope"] { + let request = RpcRequest::ManageInterface { + operation, + name: name.to_string(), + }; + let got = respond(request, &backend).await.unwrap(); + assert_eq!(hex::encode(got), "c2", "{operation:?} {name}"); + } + } + } + + /// The sequence and results of upstream's live run + /// (reticulum/vectors/rpc_manage/destination_types.json), without filters. + #[tokio::test] + async fn destination_type_requests_follow_upstream_bookkeeping() { + let backend = RpcBackend::new(stats_transport(Vec::new()), None); + let requester = vec![0x11; 16]; + let wants = |name: &str| RpcRequest::WantsDestinationType { + full_name: name.to_string(), + requester: requester.clone(), + signature: None, + }; + let unwants = |name: &str| RpcRequest::UnwantsDestinationType { + full_name: name.to_string(), + requester: requester.clone(), + signature: None, + }; + let all = RpcRequest::UnwantsAllDestinationTypes { + requester: requester.clone(), + signature: None, + }; + let t = "c3"; + let f = "c2"; + for (request, want) in [ + (wants("lxmf.delivery"), t), + (unwants("lxmf.delivery"), t), + (unwants("lxmf.delivery"), f), + (unwants("never.registered"), f), + (wants("lxmf.delivery"), t), + (all, t), + (unwants("lxmf.delivery"), f), + ] { + let got = respond(request.clone(), &backend).await.unwrap(); + assert_eq!(hex::encode(got), want, "{request:?}"); + } + } } diff --git a/crates/rns-transport/src/actor/rpc.rs b/crates/rns-transport/src/actor/rpc.rs index 688bbbf..e60eccf 100644 --- a/crates/rns-transport/src/actor/rpc.rs +++ b/crates/rns-transport/src/actor/rpc.rs @@ -152,6 +152,14 @@ impl TransportActor { TransportQuery::GetLinkCount => { TransportQueryResponse::IntResult(self.link_table.len() as i64) } + // Counts validated links. Python 1.6.0 means to, but indexes the + // link id instead of the entry (Transport.py:3577). + TransportQuery::GetActiveLinkCount => TransportQueryResponse::IntResult( + self.link_table + .iter() + .filter(|(_, entry)| entry.validated) + .count() as i64, + ), TransportQuery::GetRecentAnnounces => { let mut entries: Vec = self .recent_announces @@ -712,3 +720,45 @@ fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f6 0.0 } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::messages::{TransportQuery, TransportQueryResponse}; + + fn link_entry() -> crate::link_table::LinkEntry { + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xCC; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + interface_owner: None, + receiving_owner: None, + requested_mode: 1, + accepted_mtu_ceiling: 500, + } + } + + #[test] + fn active_link_count_counts_validated_links() { + let (mut actor, _tx) = TransportActor::new(); + let mut unvalidated = link_entry(); + unvalidated.validated = false; + actor.link_table.insert([0u8; 16], link_entry()); + actor.link_table.insert([1u8; 16], unvalidated); + assert!(matches!( + actor.handle_query(TransportQuery::GetActiveLinkCount), + TransportQueryResponse::IntResult(1) + )); + assert!(matches!( + actor.handle_query(TransportQuery::GetLinkCount), + TransportQueryResponse::IntResult(2) + )); + } +} diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs index d1899f8..077e567 100644 --- a/crates/rns-transport/src/messages.rs +++ b/crates/rns-transport/src/messages.rs @@ -856,6 +856,8 @@ pub enum TransportQuery { GetInterfaceStats, GetRateTable, GetLinkCount, + /// Python's `Transport.active_link_count()`, answered as `IntResult`. + GetActiveLinkCount, GetRecentAnnounces, /// Return cached identity metadata without updating `last_used`. Locally /// restored cache metadata is trusted; this query performs no fresh signature