telephony: stamp the link requests that open calls

This commit is contained in:
DeFiDude committed 2026-11-10 13:37:20 -07:00
1 parent 56da627f6b
commit 57171563b0
5 files changed
+339 -25

No files matched your search

+57 -1
View File
@@ -236,6 +236,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fiat-crypto"
version = "0.2.9"
@@ -263,6 +269,17 @@ dependencies = [
"wasi",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "half"
version = "2.7.1"
@@ -384,6 +401,12 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -639,6 +662,12 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.8.7"
@@ -666,7 +695,7 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
"getrandom 0.2.17",
]
[[package]]
@@ -829,6 +858,7 @@ dependencies = [
"serde",
"sha2",
"subtle",
"tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -872,6 +902,19 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "same-file"
version = "1.0.6"
@@ -1040,6 +1083,19 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "1.0.69"
+66 -10
View File
@@ -113,6 +113,8 @@ pub enum Error {
RemoteTelephonyPeerNotDiscovered,
#[error("remote LXST telephony Reticulum path was not discovered before timeout")]
RemotePathNotDiscovered,
#[error("Reticulum link request stamp failed: {0}")]
LinkStamp(#[from] rns_link::stamp::LinkStampError),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -123,6 +125,38 @@ pub struct RemoteTelephonyPeer {
pub hops: u8,
}
/// A call link request ready to send; its stamp, if any, is already generated.
pub struct OutgoingLinkRequest {
remote_identity: IdentityHash,
link: Link,
request_data: Vec<u8>,
}
impl std::fmt::Debug for OutgoingLinkRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OutgoingLinkRequest")
.field("link_id", &self.link.link_id)
.finish_non_exhaustive()
}
}
/// Build the call link request to `remote_identity`, stamped at the cost its
/// telephony destination announced, as Python's `RNS.Link` does.
pub async fn prepare_outgoing_link_request(
transport_tx: &mpsc::Sender<TransportMessage>,
remote_identity: IdentityHash,
hops: u8,
) -> Result<OutgoingLinkRequest, Error> {
let destination_hash = telephony_destination_hash(&remote_identity);
let (link, request_data) =
rns_runtime::link_stamp::new_initiator(transport_tx, destination_hash, hops.max(1)).await?;
Ok(OutgoingLinkRequest {
remote_identity,
link,
request_data,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CallerAllowPolicy {
All,
@@ -1005,7 +1039,7 @@ enum TelephonyInternalEvent {
remote_identity: IdentityHash,
profile: Option<Profile>,
mode: Option<CallMode>,
result: Result<RemoteTelephonyPeer, Error>,
result: Result<(RemoteTelephonyPeer, OutgoingLinkRequest), Error>,
},
}
@@ -1718,8 +1752,11 @@ impl TelephonyService {
stage_timeout(),
)
.await?;
let peer = refresh_peer_hops_from_transport(transport_tx, peer).await?;
Ok(peer)
let peer = refresh_peer_hops_from_transport(transport_tx.clone(), peer).await?;
let request =
prepare_outgoing_link_request(&transport_tx, remote_identity, peer.hops)
.await?;
Ok((peer, request))
}
.await;
@@ -1755,14 +1792,13 @@ impl TelephonyService {
self.outgoing_discovery = None;
self.core.set_dialling(false);
match result.and_then(|peer| {
self.endpoint.begin_outgoing_link_with_mode(
match result.and_then(|(peer, request)| {
self.endpoint.begin_prepared_outgoing_link(
&mut self.core,
remote_identity,
peer.public_key,
profile,
mode,
peer.hops,
request,
)
}) {
Ok(link_id) => {
@@ -2793,9 +2829,10 @@ impl TelephonyRnsEndpoint {
profile,
peer.hops,
)
.await
}
pub fn begin_outgoing_link_with_remote_pubkey(
pub async fn begin_outgoing_link_with_remote_pubkey(
&mut self,
core: &mut TelephonyRuntimeCore,
remote_identity: IdentityHash,
@@ -2811,11 +2848,12 @@ impl TelephonyRnsEndpoint {
None,
hops,
)
.await
}
/// Open the call link without a path request; Python `call()` requests a path only
/// when none is known, which discovery has already done.
pub fn begin_outgoing_link_with_mode(
pub async fn begin_outgoing_link_with_mode(
&mut self,
core: &mut TelephonyRuntimeCore,
remote_identity: IdentityHash,
@@ -2824,8 +2862,26 @@ impl TelephonyRnsEndpoint {
mode: Option<CallMode>,
hops: u8,
) -> Result<LinkId, Error> {
let request =
prepare_outgoing_link_request(&self.transport_tx, remote_identity, hops).await?;
self.begin_prepared_outgoing_link(core, remote_public_key, profile, mode, request)
}
/// Open a call link from a request built by [`prepare_outgoing_link_request`].
pub fn begin_prepared_outgoing_link(
&mut self,
core: &mut TelephonyRuntimeCore,
remote_public_key: [u8; 64],
profile: Option<Profile>,
mode: Option<CallMode>,
request: OutgoingLinkRequest,
) -> Result<LinkId, Error> {
let OutgoingLinkRequest {
remote_identity,
link,
request_data,
} = request;
let destination_hash = telephony_destination_hash(&remote_identity);
let (link, request_data) = Link::new_initiator(destination_hash, hops.max(1));
let link_id = link.link_id;
core.start_outgoing_call_with_mode(link_id, remote_identity, profile, mode)?;
+32 -11
View File
@@ -1565,6 +1565,8 @@ async fn begin_outgoing_link_discovers_announce_and_sends_link_request() {
)]))
.unwrap();
answer_no_link_cost(&mut transport_rx, destination_hash).await;
let register_link = transport_rx.recv().await.unwrap();
let TransportMessage::RegisterDestination {
hash: registered_link_id,
@@ -2047,6 +2049,8 @@ async fn telephony_service_call_control_discovers_peer_and_emits_started() {
)]))
.unwrap();
answer_no_link_cost(&mut transport_rx, destination_hash).await;
let register_link = transport_rx.recv().await.unwrap();
let TransportMessage::RegisterDestination {
hash: registered_link_id,
@@ -3088,8 +3092,8 @@ fn outgoing_authenticated_proof_retires_attempt_when_transport_closes() {
assert_eq!(endpoint.try_recv_link_event().unwrap(), None);
}
#[test]
fn outgoing_link_attempt_promotes_after_proof_and_drives_available_signal() {
#[tokio::test]
async fn outgoing_link_attempt_promotes_after_proof_and_drives_available_signal() {
let local_identity = Identity::new();
let remote_identity = Identity::new();
let remote_signing_key = remote_identity.get_signing_key().unwrap();
@@ -3102,15 +3106,18 @@ fn outgoing_link_attempt_promotes_after_proof_and_drives_available_signal() {
let _listener_registration = transport_rx.try_recv().unwrap();
let mut core = TelephonyRuntimeCore::new();
let link_id = endpoint
.begin_outgoing_link_with_remote_pubkey(
&mut core,
remote_hash,
remote_public_key,
Some(Profile::LatencyLow),
1,
)
.unwrap();
let call = endpoint.begin_outgoing_link_with_remote_pubkey(
&mut core,
remote_hash,
remote_public_key,
Some(Profile::LatencyLow),
1,
);
let (link_id, ()) = tokio::join!(
call,
answer_no_link_cost(&mut transport_rx, destination_hash)
);
let link_id = link_id.unwrap();
let register_link = transport_rx.try_recv().unwrap();
let TransportMessage::RegisterDestination {
@@ -4773,3 +4780,17 @@ async fn known_peer_call_sends_no_path_request_or_drop() {
control_tx.send(TelephonyControl::Shutdown).await.unwrap();
task.abort();
}
async fn answer_no_link_cost(
transport_rx: &mut mpsc::Receiver<TransportMessage>,
destination_hash: [u8; 16],
) {
let rpc = transport_rx.recv().await.unwrap();
let TransportMessage::Rpc { query, response_tx } = rpc else {
panic!("expected link cost recall, got {rpc:?}");
};
assert!(matches!(query, TransportQuery::RecallLinkCost { dest } if dest == destination_hash));
response_tx
.send(TransportQueryResponse::FloatResult(None))
.unwrap();
}
@@ -1,7 +1,7 @@
//! Opt-in live interoperability against Python LXST over real TCP interfaces.
//!
//! Every test in this binary is ignored by default. Run it explicitly with the
//! command documented in the repository README.
//! Tests are ignored by default, except the link request stamp tests at the
//! end. Run the rest explicitly with the command documented in the repository README.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
@@ -3365,3 +3365,183 @@ async fn python_caller_gets_busy_while_rust_service_discovers_a_path() {
assert!(!rang);
pair.shutdown().await;
}
// Link request stamps under enforcement (Link.py:187-200, :300-395@RNS 1.6.0).
// LXST 0.6.0 has no stamp code of its own; its Telephone destination keeps the
// default link cost LR_COST = 12.5.
const PY_ENFORCING_STAMPS: &str =
"stamp_destinations = yes;enforce_stamps = yes;destination_cost = 6;destination_value = 8";
fn low_cost_policy() -> rns_transport::stamps::StampPolicy {
rns_transport::stamps::StampPolicy {
destination_cost: 6.0,
..Default::default()
}
}
/// A Rust caller reaches an enforcing Python Telephone: it recalls the
/// announced link cost and stamps its link request at it.
#[serial_test::serial(python_lxst_live)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rust_outgoing_call_reaches_an_enforcing_python_telephone() {
let port = free_tcp_port();
let (actor_tx, server, mut handle_rx) = spawn_rust_actor_and_tcp(port).await;
actor_tx
.send(TransportMessage::SetStampPolicy {
policy: low_cost_policy(),
})
.await
.unwrap();
let mut announce_rx = register_telephony_announce_handler(&actor_tx).await;
let mut helper = PythonTelephoneHost::spawn_with_env(
port,
"client",
false,
&[("LXST_HELPER_STAMPS", PY_ENFORCING_STAMPS)],
);
let ready = helper.wait_event("READY", Duration::from_secs(10));
let remote_identity_hash = hash_from_ready(&ready, "identity_hash");
let remote_destination_hash = hash_from_ready(&ready, "destination_hash");
let accepted = tokio::time::timeout(Duration::from_secs(15), handle_rx.recv())
.await
.unwrap()
.unwrap();
let (accepted_id, accepted_entry, accepted_read_task) = register_interface_entry(accepted);
actor_tx
.send(TransportMessage::RegisterInterface {
id: accepted_id,
entry: accepted_entry,
})
.await
.unwrap();
helper.send(json!({"cmd": "announce", "id": "announce-1"}));
helper.wait_event("ANNOUNCED", Duration::from_secs(20));
tokio::time::timeout(Duration::from_secs(20), announce_rx.recv())
.await
.expect("Python announce")
.unwrap();
let recalled =
rns_runtime::link_stamp::recall_link_cost(&actor_tx, remote_destination_hash).await;
assert_eq!(recalled, Some(12.5), "announced link cost");
let local_identity = Identity::new();
let mut endpoint = TelephonyRnsEndpoint::register(actor_tx.clone(), &local_identity).unwrap();
let mut core = TelephonyRuntimeCore::new();
endpoint
.begin_outgoing_link(
&mut core,
remote_identity_hash,
None,
Duration::from_secs(5),
)
.await
.expect("start stamped outgoing call");
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
loop {
endpoint.try_drive_ready(&mut core).unwrap();
if core
.snapshot()
.active_call
.is_some_and(|call| call.status == SignallingStatus::Ringing)
{
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"Rust call did not reach the enforcing Python Telephone:\n{}",
helper.stderr_log()
);
tokio::time::sleep(Duration::from_millis(50)).await;
}
helper.wait_event("RINGING", Duration::from_secs(5));
endpoint.deregister_destination().unwrap();
accepted_read_task.abort();
server.read_task.abort();
}
/// An enforcing Rust telephone answers a Python caller that stamps at its
/// cost (`lr_cost`, via `always_stamp_lrs` since the Rust announce here
/// carries no cost) and drops one that does not stamp.
#[serial_test::serial(python_lxst_live)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn python_outgoing_call_reaches_an_enforcing_rust_telephone_only_when_stamped() {
// Below 10 upstream grinds in-process; its worker pool deadlocks in this helper.
for (rust_lr_cost, python_stamps, expect_ringing) in [
(8.0, "always_stamp_lrs = yes;lr_cost = 8", true),
(12.5, "", false),
] {
let mut policy = rns_transport::stamps::StampPolicy {
lr_cost: rust_lr_cost,
..Default::default()
};
policy.enforce();
rns_runtime::destination_stamper::configure(policy, None);
let port = free_tcp_port();
let (actor_tx, server, mut handle_rx) = spawn_rust_actor_and_tcp(port).await;
let mut helper = PythonTelephoneHost::spawn_with_env(
port,
"client",
false,
&[("LXST_HELPER_STAMPS", python_stamps)],
);
let ready = helper.wait_event("READY", Duration::from_secs(10));
let python_identity_hash = hash_from_ready(&ready, "identity_hash");
let accepted = tokio::time::timeout(Duration::from_secs(15), handle_rx.recv())
.await
.unwrap()
.unwrap();
let (accepted_id, accepted_entry, accepted_read_task) = register_interface_entry(accepted);
actor_tx
.send(TransportMessage::RegisterInterface {
id: accepted_id,
entry: accepted_entry,
})
.await
.unwrap();
let local_identity = Identity::new();
let mut endpoint =
TelephonyRnsEndpoint::register(actor_tx.clone(), &local_identity).unwrap();
let mut core = TelephonyRuntimeCore::new();
let rust_destination_hash = send_rust_telephony_announce(&actor_tx, &local_identity).await;
tokio::time::sleep(Duration::from_millis(500)).await;
helper.send(json!({
"cmd": "call",
"id": "call-rust-1",
"target_destination_hash": hex::encode(rust_destination_hash),
}));
helper.wait_event("CALL_REQUESTED", Duration::from_secs(10));
let wait = if expect_ringing { 40 } else { 15 };
let deadline = tokio::time::Instant::now() + Duration::from_secs(wait);
let rang = loop {
endpoint.try_drive_ready(&mut core).unwrap();
if core
.snapshot()
.active_call
.is_some_and(|call| call.status == SignallingStatus::Ringing)
{
break true;
}
if tokio::time::Instant::now() >= deadline {
break false;
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
rns_runtime::destination_stamper::configure(Default::default(), None);
assert_eq!(
rang,
expect_ringing,
"Python stamps {python_stamps:?} against Rust cost {rust_lr_cost}:\n{}",
helper.stderr_log()
);
if rang {
assert_eq!(
core.snapshot().active_call.unwrap().remote_identity,
python_identity_hash
);
}
endpoint.deregister_destination().unwrap();
accepted_read_task.abort();
server.read_task.abort();
}
}
+2 -1
View File
@@ -417,7 +417,8 @@ def setup_reticulum(storage: Path, tcp_role: str, tcp_host: str, tcp_port: int,
config_dir = storage / "rns"
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / "config").write_text(
build_rns_config(tcp_role, tcp_host, tcp_port, enable_transport),
build_rns_config(tcp_role, tcp_host, tcp_port, enable_transport)
+ ("\n[stamps]\n" + os.environ["LXST_HELPER_STAMPS"].replace(";", "\n") + "\n" if os.environ.get("LXST_HELPER_STAMPS") else ""),
encoding="utf-8",
)