runtime: own finite announce discovery

This commit is contained in:
DeFiDude committed 2026-08-16 20:13:02 -06:00
1 parent bd8c2d8264
commit da84fb0ac5
6 files changed
+490 -188

No files matched your search

+3
View File
@@ -2,6 +2,9 @@
## Unreleased
- Isolate exact announce subscriptions from legacy aspect-wide deregistration,
and resolve finite destination identities through validated recall plus
deadline-bounded path discovery instead of temporary announce handlers.
- Distinguished the Reticulum 1.3.8 compatibility-floor corpus from the
current 1.4.2 behavior reference instead of presenting the old oracle as the
newest upstream target.
@@ -0,0 +1,372 @@
//! Deadline-aware, handler-free destination identity resolution.
//!
//! Python applications resolve finite destinations through validated identity
//! recall and path requests. They do not install temporary announce handlers.
use std::time::Duration;
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportMessage, TransportQuery, TransportQueryResponse,
};
use tokio::sync::{mpsc, oneshot};
use tokio::time::{Instant, sleep_until, timeout_at};
const RECALL_POLL_INTERVAL: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DestinationResolveOptions {
/// Complete command admission, path request and recall before this budget.
pub timeout: Duration,
/// Remove an existing route before requesting a fresh path response when
/// the validated identity is not already cached.
pub drop_existing_path: bool,
/// Request a path refresh even when validated identity data is cached.
/// The cached identity remains immediately usable, matching upstream
/// applications that refresh routing separately from identity recall.
pub refresh_cached_path: bool,
}
impl DestinationResolveOptions {
pub fn new(timeout: Duration) -> Self {
Self {
timeout,
drop_existing_path: false,
refresh_cached_path: false,
}
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DestinationResolveError {
#[error("destination resolution timed out")]
Timeout,
#[error("Reticulum transport is unavailable")]
TransportUnavailable,
#[error("Reticulum transport returned an unexpected response during {0}")]
UnexpectedResponse(&'static str),
}
/// Resolve one validated destination without installing an announce handler.
///
/// A missing identity always emits an explicit path request. This deliberately
/// covers the state where a route exists but its validated announce metadata
/// is absent: `AwaitPath` alone would return immediately and never repair the
/// identity cache.
pub async fn resolve_destination_on_transport(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
options: DestinationResolveOptions,
) -> Result<RecalledDestinationRpcEntry, DestinationResolveError> {
let deadline = Instant::now()
.checked_add(options.timeout)
.ok_or(DestinationResolveError::Timeout)?;
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await? {
if options.refresh_cached_path {
send_before_deadline(
transport_tx,
TransportMessage::RequestPath { destination_hash },
deadline,
)
.await?;
}
return Ok(recalled);
}
if options.drop_existing_path {
match query_before_deadline(
transport_tx,
TransportQuery::DropPath {
dest: destination_hash,
},
deadline,
)
.await?
{
TransportQueryResponse::Ok => {}
_ => return Err(DestinationResolveError::UnexpectedResponse("path drop")),
}
}
send_before_deadline(
transport_tx,
TransportMessage::RequestPath { destination_hash },
deadline,
)
.await?;
loop {
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await?
{
return Ok(recalled);
}
let now = Instant::now();
if now >= deadline {
return Err(DestinationResolveError::Timeout);
}
sleep_until(std::cmp::min(deadline, now + RECALL_POLL_INTERVAL)).await;
}
}
async fn recall_destination(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
deadline: Instant,
) -> Result<Option<RecalledDestinationRpcEntry>, DestinationResolveError> {
match query_before_deadline(
transport_tx,
TransportQuery::RecallDestination {
dest: destination_hash,
},
deadline,
)
.await?
{
TransportQueryResponse::RecalledDestination(Some(recalled))
if recalled.dest_hash != destination_hash =>
{
Err(DestinationResolveError::UnexpectedResponse(
"destination recall",
))
}
TransportQueryResponse::RecalledDestination(recalled) => Ok(recalled),
_ => Err(DestinationResolveError::UnexpectedResponse(
"destination recall",
)),
}
}
async fn query_before_deadline(
transport_tx: &mpsc::Sender<TransportMessage>,
query: TransportQuery,
deadline: Instant,
) -> Result<TransportQueryResponse, DestinationResolveError> {
let (response_tx, response_rx) = oneshot::channel();
send_before_deadline(
transport_tx,
TransportMessage::Rpc { query, response_tx },
deadline,
)
.await?;
timeout_at(deadline, response_rx)
.await
.map_err(|_| DestinationResolveError::Timeout)?
.map_err(|_| DestinationResolveError::TransportUnavailable)
}
async fn send_before_deadline(
transport_tx: &mpsc::Sender<TransportMessage>,
message: TransportMessage,
deadline: Instant,
) -> Result<(), DestinationResolveError> {
timeout_at(deadline, transport_tx.send(message))
.await
.map_err(|_| DestinationResolveError::Timeout)?
.map_err(|_| DestinationResolveError::TransportUnavailable)
}
#[cfg(test)]
mod tests {
use super::*;
fn recalled(destination_hash: [u8; 16], public_key: [u8; 64]) -> RecalledDestinationRpcEntry {
RecalledDestinationRpcEntry {
dest_hash: destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
}
}
#[tokio::test]
async fn cache_hit_returns_without_network_discovery() {
let destination_hash = [0x11; 16];
let public_key = [0x22; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected destination recall");
};
assert!(
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
);
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_secs(1)),
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn missing_identity_requests_path_without_announce_registration() {
let destination_hash = [0x33; 16];
let public_key = [0x44; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let mut recalls = 0;
while let Some(message) = transport_rx.recv().await {
match message {
TransportMessage::Rpc { query, response_tx } => {
assert!(
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
);
recalls += 1;
let result = if recalls >= 2 {
Some(recalled(destination_hash, public_key))
} else {
None
};
response_tx
.send(TransportQueryResponse::RecalledDestination(result))
.unwrap();
if recalls >= 2 {
break;
}
}
TransportMessage::RequestPath {
destination_hash: dest,
} => {
assert_eq!(dest, destination_hash);
}
other => panic!("unexpected finite discovery message: {other:?}"),
}
}
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_secs(1)),
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn cached_identity_can_refresh_path_without_waiting_for_announce() {
let destination_hash = [0x45; 16];
let public_key = [0x46; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected destination recall");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
assert!(matches!(
transport_rx.recv().await.unwrap(),
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
));
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions {
timeout: Duration::from_secs(1),
drop_existing_path: false,
refresh_cached_path: true,
},
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn telephony_policy_drops_stale_path_before_request() {
let destination_hash = [0x55; 16];
let public_key = [0x66; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected initial recall");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.unwrap();
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected path drop");
};
assert!(matches!(query, TransportQuery::DropPath { dest } if dest == destination_hash));
response_tx.send(TransportQueryResponse::Ok).unwrap();
assert!(matches!(
transport_rx.recv().await.unwrap(),
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
));
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected recall after path request");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions {
timeout: Duration::from_secs(1),
drop_existing_path: true,
refresh_cached_path: true,
},
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn one_deadline_bounds_blocked_command_admission() {
let destination_hash = [0x77; 16];
let (transport_tx, _transport_rx) = mpsc::channel(1);
transport_tx
.send(TransportMessage::RequestPath { destination_hash })
.await
.unwrap();
let error = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_millis(5)),
)
.await
.unwrap_err();
assert_eq!(error, DestinationResolveError::Timeout);
}
}
+4
View File
@@ -4,6 +4,7 @@
pub mod buffer_stream;
pub mod config;
pub mod constants;
pub mod destination_resolver;
pub mod destination_runtime;
pub mod interface_factory;
mod interface_registry;
@@ -28,6 +29,9 @@ pub mod rpc_server;
///
/// This is additive convenience; module-qualified paths remain supported.
pub mod prelude {
pub use crate::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
pub use crate::destination_runtime::{
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
DestinationRuntimeError, DestinationRuntimeOptions, IdentityGatePolicy,
+21 -158
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use tokio::sync::{mpsc, oneshot};
use tokio::sync::mpsc;
use tokio::time::timeout;
use rns_crypto::ed25519::Ed25519PublicKey;
@@ -18,8 +18,11 @@ use rns_protocol::resource::{InboundTransfer, TransferAction};
use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{
AnnounceHandlerEvent, InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole,
OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole, OutboundRequest, TransportMessage,
};
use crate::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
#[derive(Debug, thiserror::Error)]
@@ -79,36 +82,14 @@ impl LinkClient {
let dest_hash =
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
let pubkey =
if let Some(public_key) = self.recall_routable_pubkey(dest_hash, deadline).await? {
public_key
} else {
// Register the handler before the path request so the answering
// announce (carrying the pubkey) is observed.
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
self.send_msg(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await?;
self.send_msg(TransportMessage::RequestPath {
destination_hash: dest_hash,
})
.await?;
let public_key = match time_remaining(deadline) {
Ok(remaining) => wait_for_pubkey(&mut ann_rx, dest_hash, remaining).await,
Err(error) => Err(error),
};
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
});
public_key?
};
let pubkey = resolve_destination_on_transport(
&self.transport_tx,
dest_hash,
DestinationResolveOptions::new(time_remaining(deadline)?),
)
.await
.map_err(map_destination_resolve_error)?
.public_key;
let (mut link, request_data) = Link::new_initiator(dest_hash, hops);
let link_id = link.link_id;
@@ -251,58 +232,6 @@ impl LinkClient {
.map_err(|_| LinkClientError::TransportUnavailable)
}
async fn recall_routable_pubkey(
&self,
destination_hash: [u8; 16],
deadline: Instant,
) -> Result<Option<[u8; 64]>, LinkClientError> {
let has_path = self
.transport_query(
TransportQuery::HasPath {
dest: destination_hash,
},
deadline,
)
.await?;
if !matches!(has_path, TransportQueryResponse::BoolResult(true)) {
return Ok(None);
}
match self
.transport_query(
TransportQuery::RecallDestination {
dest: destination_hash,
},
deadline,
)
.await?
{
TransportQueryResponse::RecalledDestination(Some(destination))
if destination.dest_hash == destination_hash =>
{
Ok(Some(destination.public_key))
}
TransportQueryResponse::RecalledDestination(None) => Ok(None),
response => Err(LinkClientError::UnexpectedResponse(format!(
"destination recall returned {response:?}"
))),
}
}
async fn transport_query(
&self,
query: TransportQuery,
deadline: Instant,
) -> Result<TransportQueryResponse, LinkClientError> {
let (response_tx, response_rx) = oneshot::channel();
self.send_msg(TransportMessage::Rpc { query, response_tx })
.await?;
timeout(time_remaining(deadline)?, response_rx)
.await
.map_err(|_| LinkClientError::Timeout("transport query"))?
.map_err(|_| LinkClientError::TransportUnavailable)
}
async fn send_close(&self, link: &mut Link) -> Result<bool, LinkClientError> {
let link_id = link.link_id;
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
@@ -334,24 +263,14 @@ fn time_remaining(deadline: Instant) -> Result<Duration, LinkClientError> {
}
}
async fn wait_for_pubkey(
rx: &mut mpsc::Receiver<AnnounceHandlerEvent>,
target_dest_hash: [u8; 16],
deadline: Duration,
) -> Result<[u8; 64], LinkClientError> {
let fut = async {
while let Some(ev) = rx.recv().await {
if ev.destination_hash == target_dest_hash {
if let Some(pk) = ev.public_key {
return Ok(pk);
}
}
fn map_destination_resolve_error(error: DestinationResolveError) -> LinkClientError {
match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("destination resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("path/announce discovery"))?
}
}
async fn wait_for_response(
@@ -759,62 +678,6 @@ mod tests {
));
}
#[tokio::test]
async fn validated_cached_identity_and_live_path_skip_network_discovery() {
let destination_hash = [0xD4; 16];
let remote_identity = Identity::new();
let public_key = remote_identity.get_public_key();
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let responder = tokio::spawn(async move {
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
else {
panic!("expected path query");
};
assert!(matches!(
query,
TransportQuery::HasPath { dest } if dest == destination_hash
));
response_tx
.send(TransportQueryResponse::BoolResult(true))
.unwrap();
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
else {
panic!("expected destination recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(
rns_transport::messages::RecalledDestinationRpcEntry {
dest_hash: destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 1,
timestamp: 1.0,
},
)))
.unwrap();
assert!(
transport_rx.try_recv().is_err(),
"cache hit must not emit a path request"
);
});
let client = LinkClient::new(transport_tx, Identity::new());
assert_eq!(
client
.recall_routable_pubkey(destination_hash, Instant::now() + Duration::from_secs(1),)
.await
.unwrap(),
Some(public_key)
);
responder.await.unwrap();
}
#[tokio::test]
async fn send_close_uses_authenticated_teardown_payload() {
let dest_hash = [0xCC; 16];
+18 -8
View File
@@ -1089,15 +1089,25 @@ pub async fn discover_destination(
destination_hash: [u8; 16],
timeout: Duration,
) -> Result<AnnounceRpcEntry, LinkSessionError> {
if let Some(entry) = lookup_destination(transport_tx, destination_hash).await? {
if entry.public_key.is_some() {
return Ok(entry);
crate::destination_resolver::resolve_destination_on_transport(
transport_tx,
destination_hash,
crate::destination_resolver::DestinationResolveOptions::new(timeout),
)
.await
.map_err(|error| match error {
crate::destination_resolver::DestinationResolveError::Timeout => {
LinkSessionError::Timeout("destination identity")
}
}
rns_transport::await_path::await_path(transport_tx, destination_hash, timeout)
.await
.map_err(|_| LinkSessionError::Timeout("destination path"))?;
crate::destination_resolver::DestinationResolveError::TransportUnavailable => {
LinkSessionError::TransportUnavailable
}
crate::destination_resolver::DestinationResolveError::UnexpectedResponse(operation) => {
LinkSessionError::HandshakeFailed(format!(
"unexpected transport response during {operation}"
))
}
})?;
let entry = lookup_destination(transport_tx, destination_hash)
.await?
.ok_or(LinkSessionError::PublicKeyUnavailable)?;
+72 -22
View File
@@ -957,6 +957,8 @@ pub enum LinkConnectError {
Control(#[from] ControlError),
#[error("path discovery failed: {0}")]
Path(#[from] AwaitPathError),
#[error("destination resolution failed: {0}")]
Resolve(#[from] crate::destination_resolver::DestinationResolveError),
#[error("no validated identity is known for destination {0}")]
IdentityUnavailable(String),
#[error("Link session failed: {0}")]
@@ -1204,14 +1206,13 @@ impl ReticulumHandle {
destination_hash: [u8; 16],
options: &LinkConnectOptions,
) -> Result<LinkSessionConfig, LinkConnectError> {
let mut recalled = self.recall(destination_hash).await?;
if recalled.is_none() {
self.await_path(destination_hash, options.path_timeout)
.await?;
recalled = self.recall(destination_hash).await?;
}
let recalled = recalled
.ok_or_else(|| LinkConnectError::IdentityUnavailable(hex::encode(destination_hash)))?;
let recalled = crate::destination_resolver::resolve_destination_on_transport(
&self.transport_tx,
destination_hash,
crate::destination_resolver::DestinationResolveOptions::new(options.path_timeout),
)
.await?;
let recalled = recalled_destination_from_rpc(recalled)?;
let (establishment_timeout, hops) = match options.establishment_timeout {
Some(timeout) => (timeout, recalled.hops),
None => {
@@ -5563,17 +5564,33 @@ async fn start_on_network_discovery(handle: ReticulumHandle) {
decryptor,
observer: observer_tx,
};
let (_join, callback_tx) = rns_transport::discovery::receiver::spawn(receiver_config);
let _ = handle
.transport_tx
.send(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(
rns_transport::discovery::DISCOVERY_ASPECT_FILTER.to_string(),
),
receive_path_responses: false,
callback_tx,
})
let subscription = handle
.subscribe_announces_with_capacity(
Some(rns_transport::discovery::DISCOVERY_ASPECT_FILTER.to_string()),
false,
128,
)
.await;
match subscription {
Ok(subscription) => {
let (receiver_join, callback_tx) =
rns_transport::discovery::receiver::spawn(receiver_config);
let shutdown = handle.shutdown.clone();
tokio::spawn(run_discovery_subscription(
subscription,
callback_tx,
receiver_join,
shutdown,
));
}
Err(error) => {
tracing::warn!(
error = %error,
"failed to install exact interface-discovery announce subscription"
);
*handle.discovery.receiver_started.lock().await = false;
}
}
if let Some(rx) = observer_rx {
let observer_handle = handle.clone();
@@ -5597,6 +5614,39 @@ async fn start_on_network_discovery(handle: ReticulumHandle) {
}
}
async fn run_discovery_subscription(
mut subscription: AnnounceSubscription,
callback_tx: mpsc::Sender<AnnounceHandlerEvent>,
receiver_join: tokio::task::JoinHandle<()>,
shutdown: ShutdownSignal,
) {
loop {
tokio::select! {
_ = shutdown.wait() => break,
event = subscription.recv() => match event {
Some(event) => {
if callback_tx.send(event).await.is_err() {
break;
}
}
None => break,
},
}
}
let dropped_events = subscription.dropped_events();
if let Err(error) = subscription.close().await {
tracing::debug!(error = %error, "interface-discovery subscription close failed");
}
drop(callback_tx);
let _ = receiver_join.await;
if dropped_events > 0 {
tracing::warn!(
dropped_events,
"interface-discovery announces dropped by bounded subscription"
);
}
}
async fn run_discovery_announcer(
handle: ReticulumHandle,
stamper: Arc<dyn DiscoveryStamper + Send + Sync>,
@@ -9813,13 +9863,13 @@ loglevel = 7
.send(TransportQueryResponse::RecalledDestination(None))
.expect("first recall response");
let TransportMessage::AwaitPath { dest, reply } =
transport_rx.recv().await.expect("path discovery")
let TransportMessage::RequestPath {
destination_hash: dest,
} = transport_rx.recv().await.expect("path discovery")
else {
panic!("expected path discovery");
panic!("expected explicit path request");
};
assert_eq!(dest, destination_hash);
reply.send(true).expect("path waiter");
let TransportMessage::Rpc { response_tx, .. } =
transport_rx.recv().await.expect("second recall")