Compare commits

...
22 changed files with 4454 additions and 1296 deletions

No files matched your search

+29 -3
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install system deps
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace
- run: cargo test --workspace --locked
working-directory: rsLXMF
lint:
@@ -60,10 +60,36 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo fmt --all -- --check
working-directory: rsLXMF
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps
run: cargo doc --workspace --no-deps --locked
working-directory: rsLXMF
msrv:
name: Rust 1.85 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
with:
path: rsLXMF
- uses: actions/checkout@v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
path: rsReticulum
- uses: dtolnay/rust-toolchain@1.85.0
with:
components: clippy
- uses: Swatinem/rust-cache@v2
with:
workspaces: rsLXMF -> target
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
+15
View File
@@ -1,5 +1,20 @@
# Changelog
## Unreleased
- Added automatic pre-sign reply-ticket issue, signature-gated inbound
learning, directional migration-safe persistence, and proof-gated delivery
accounting, with live Python restart/reply interoperability.
- Made Opportunistic one-shot delivery wait for an authenticated Reticulum
proof, with atomic receipt-first dispatch and bounded retries.
- Moved propagation-store persistence off the daemon loop through
reserve/write/commit transactions so visibility, handled IDs and counters
advance only after durable writes.
- Added coalescing announce handoff, live allow-list rotation and split
peer-Resource convergence coverage.
- Made one-shot remote control commands wait for a real online Reticulum
interface before opening their Link, avoiding stale-path startup loss.
## 1.1.0 - 2026-07-26
- Added bounded propagation-node admission, exact inbound Resource ownership,
Generated
+1
View File
@@ -684,6 +684,7 @@ dependencies = [
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
+8 -4
View File
@@ -239,7 +239,7 @@ Minimal config:
display_name = Rat
announce_at_start = no
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1000
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
[propagation]
@@ -284,7 +284,7 @@ and, where network-backed, through `lxmd-rs --send-method`.
| Method | Behavior |
| --- | --- |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Oversized opportunistic messages are downgraded to Direct by the router. |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. Oversized opportunistic messages are downgraded to Direct by the router. |
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. |
| Propagated | Store-and-forward delivery through a propagation node, including deposit, retrieve, peer sync, stamps, and tickets. |
| Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
@@ -302,6 +302,10 @@ payload MessagePack([timestamp, title, content, fields, optional_stamp
application-defined data such as tickets, attachments, location data, or
application envelopes.
Library callers requesting a reply ticket set `include_ticket`, call
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a
requested ticket that would require changing an already-signed message.
## Feature Status
@@ -309,8 +313,8 @@ application envelopes.
| --- | --- |
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct downgrade, and compression signalling in delivery announces. |
| Propagation | Disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, propagation tickets, and restart-safe ticket persistence. |
| Propagation | Transactional disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
| Access lists | `ignored` and `allowed` hash-list files in the LXMF config directory. |
+2
View File
@@ -0,0 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.85"
+3
View File
@@ -175,6 +175,9 @@ pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
/// Delay before announcing propagation node (seconds).
pub const NODE_ANNOUNCE_DELAY: u64 = 20;
/// LXMF configuration and announce values use decimal kilobytes, matching
/// Python's `limit_kb * 1000` accounting.
pub const BYTES_PER_KILOBYTE: usize = 1000;
pub const PROPAGATION_LIMIT: usize = 256;
pub const DELIVERY_LIMIT: usize = 1000;
/// PROPAGATION_LIMIT * 40, in KB.
+21 -21
View File
@@ -159,15 +159,14 @@ impl DeliveryRatchetState {
}
}
if control_file_trusted
&& (!control_existed || control_changed)
&& let Err(error) = control.save_verified(&control_path, identity)
{
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
if control_file_trusted && (!control_existed || control_changed) {
if let Err(error) = control.save_verified(&control_path, identity) {
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
}
}
Ok(Self {
@@ -211,12 +210,13 @@ impl DeliveryRatchetState {
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
&& let Some(packet) = self
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind {
if let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
{
return Ok(packet);
}
}
if !self.control_file_trusted {
@@ -292,15 +292,15 @@ impl DeliveryRatchetState {
/// Best-effort shutdown checkpoint. Invalid files detected during load are
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted
&& let Err(error) = self.ring.save_verified(&self.ring_path, identity)
{
tracing::warn!(%error, "failed to save ratchet ring");
if self.ring_file_trusted {
if let Err(error) = self.ring.save_verified(&self.ring_path, identity) {
tracing::warn!(%error, "failed to save ratchet ring");
}
}
if self.control_file_trusted
&& let Err(error) = self.control.save_verified(&self.control_path, identity)
{
tracing::warn!(%error, "failed to save ratchet control state");
if self.control_file_trusted {
if let Err(error) = self.control.save_verified(&self.control_path, identity) {
tracing::warn!(%error, "failed to save ratchet control state");
}
}
}
File diff suppressed because it is too large. Load diff
+28 -23
View File
@@ -101,6 +101,10 @@ pub struct LxMessage {
pub stamp_cost: Option<u8>,
/// Outbound ticket for stamp bypass (16 bytes).
pub outbound_ticket: Option<[u8; 16]>,
/// Ask the router to include a reply ticket before this message is signed.
///
/// Python reference: `LXMessage.include_ticket`.
pub include_ticket: bool,
/// Computed stamp value: leading zero bits, or `COST_TICKET`.
pub stamp_value: Option<u16>,
pub unverified_reason: Option<UnverifiedReason>,
@@ -170,6 +174,7 @@ impl LxMessage {
transient_id: None,
stamp_cost: None,
outbound_ticket: None,
include_ticket: false,
stamp_value: None,
unverified_reason: None,
representation: DeliveryRepresentation::Unknown,
@@ -391,19 +396,19 @@ impl LxMessage {
self.transient_id = Some(tid);
let mut stamp_value = 0;
if let Some(target_cost) = propagation_stamp_cost
&& self.propagation_stamp.is_none()
{
let (stamp, value) = crate::stamper::generate_stamp(
&tid,
target_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| {
MessageError::PackFailed("failed to generate propagation stamp".to_string())
})?;
self.propagation_stamp = Some(stamp);
stamp_value = value;
if let Some(target_cost) = propagation_stamp_cost {
if self.propagation_stamp.is_none() {
let (stamp, value) = crate::stamper::generate_stamp(
&tid,
target_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| {
MessageError::PackFailed("failed to generate propagation stamp".to_string())
})?;
self.propagation_stamp = Some(stamp);
stamp_value = value;
}
}
if let Some(ref prop_stamp) = self.propagation_stamp {
@@ -551,6 +556,7 @@ impl LxMessage {
transient_id: None,
stamp_cost: None,
outbound_ticket: None,
include_ticket: false,
stamp_value: None,
unverified_reason: None,
representation: DeliveryRepresentation::Unknown,
@@ -791,9 +797,7 @@ impl LxMessage {
///
/// Python reference: LXMessage.py:301-332.
pub fn get_stamp(&mut self) -> Option<Vec<u8>> {
if let Some(ticket) = self.outbound_ticket
&& let Some(message_id) = self.message_id
{
if let (Some(ticket), Some(message_id)) = (self.outbound_ticket, self.message_id) {
let mut material = Vec::with_capacity(TICKET_LENGTH + 32);
material.extend_from_slice(&ticket);
material.extend_from_slice(&message_id);
@@ -816,13 +820,14 @@ impl LxMessage {
// 4. Generate PoW stamp
let cost = self.stamp_cost.unwrap();
if let Some(message_id) = self.message_id
&& let Some((stamp, value)) =
if let Some(message_id) = self.message_id {
if let Some((stamp, value)) =
crate::stamper::generate_stamp(&message_id, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS)
{
self.stamp_value = Some(value as u16);
self.stamp = Some(stamp.to_vec());
return Some(stamp.to_vec());
{
self.stamp_value = Some(value as u16);
self.stamp = Some(stamp.to_vec());
return Some(stamp.to_vec());
}
}
None
@@ -1347,7 +1352,7 @@ fn deserialize_bin_or_str<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<String, D::Error> {
struct BinOrStrVisitor;
impl<'de> serde::de::Visitor<'de> for BinOrStrVisitor {
impl serde::de::Visitor<'_> for BinOrStrVisitor {
type Value = String;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("string or binary data")
+47 -21
View File
@@ -2,7 +2,7 @@
//!
//! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
//! * `available_tickets` — `Vec<Ticket>`
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//!
@@ -16,7 +16,7 @@ use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::Ticket;
use crate::ticket::{Ticket, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
@@ -68,15 +68,14 @@ pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
fs::rename(&tmp, path)
})();
if result.is_err()
&& tmp.exists()
&& let Err(e) = fs::remove_file(&tmp)
{
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
if result.is_err() && tmp.exists() {
if let Err(e) = fs::remove_file(&tmp) {
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
}
}
result
@@ -111,12 +110,23 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &[Ticket]) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), &tickets)
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
}
pub fn load_tickets(dir: &Path) -> io::Result<Vec<Ticket>> {
Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default())
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PersistedTickets {
Directional(TicketStoreSnapshot),
Legacy(Vec<Ticket>),
}
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
None => (TicketStoreSnapshot::default(), None),
})
}
pub fn save_local_deliveries(
@@ -177,12 +187,26 @@ mod tests {
#[test]
fn tickets_roundtrip() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
let tickets = TicketStoreSnapshot {
version: 1,
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
};
save_tickets(tmp.path(), &tickets).unwrap();
let loaded = load_tickets(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].token, [0x01; 16]);
assert_eq!(loaded[0].destination_hash, [0x02; 16]);
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
assert!(legacy.is_none());
assert_eq!(loaded, tickets);
}
#[test]
fn legacy_flat_tickets_are_detected_for_migration() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(snapshot, TicketStoreSnapshot::default());
assert_eq!(legacy.unwrap(), tickets);
}
#[test]
@@ -199,7 +223,9 @@ mod tests {
fn missing_file_returns_default() {
let tmp = TempDir::new().unwrap();
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
assert!(load_tickets(tmp.path()).unwrap().is_empty());
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(tickets, TicketStoreSnapshot::default());
assert!(legacy.is_none());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
+352 -107
View File
@@ -12,12 +12,12 @@
//! 7. Client processes received messages.
//! 8. Final `/get` with `[None, received_ids]` purges them from the server.
use std::collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration, Instant};
use bytes::Bytes;
use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use rns_link::link::{CloseReason, Link};
use rns_link::link::{CloseReason, Link, LinkAction};
use rns_protocol::resource::{
InboundTransfer, MAX_SEGMENTS, MultiSegmentInbound, RANDOM_HASH_SIZE, ResourceError,
TransferAction,
@@ -97,8 +97,13 @@ pub struct PropagationClient {
inbound_resources: HashMap<[u8; 32], InboundTransfer>,
inbound_split_resources: HashMap<[u8; 32], MultiSegmentInbound>,
segment_routing: HashMap<[u8; 32], SegmentRoute>,
/// Ordered, bounded staging for transport backpressure.
pending_transport: VecDeque<TransportMessage>,
/// KB per transfer; `None` means unlimited.
delivery_limit: Option<f64>,
/// `None` means all messages; Python's `PR_ALL_MESSAGES` value is zero.
max_messages: Option<usize>,
retain_synced_on_node: bool,
started_at: Option<Instant>,
timeout: Duration,
identified: bool,
@@ -129,7 +134,10 @@ impl PropagationClient {
inbound_resources: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
pending_transport: VecDeque::new(),
delivery_limit: Some(DELIVERY_LIMIT as f64),
max_messages: None,
retain_synced_on_node: false,
started_at: None,
timeout: Duration::from_secs(120),
identified: false,
@@ -153,6 +161,17 @@ impl PropagationClient {
self.local_messages.insert(transient_id);
}
pub fn replace_local_message_ids<I>(&mut self, transient_ids: I)
where
I: IntoIterator<Item = Vec<u8>>,
{
self.local_messages = transient_ids.into_iter().collect();
}
pub fn set_retain_synced_on_node(&mut self, retain: bool) {
self.retain_synced_on_node = retain;
}
pub fn available_messages(&self) -> &[Vec<u8>] {
&self.available_messages
}
@@ -184,6 +203,12 @@ impl PropagationClient {
}
pub fn start_download(&mut self) -> bool {
self.start_download_with_limit(None)
}
/// Start a propagation download, limiting newly requested messages.
/// `None` and zero mirror Python's `PR_ALL_MESSAGES`.
pub fn start_download_with_limit(&mut self, max_messages: Option<usize>) -> bool {
let node_hash = match self.outbound_propagation_node {
Some(h) => h,
None => return false,
@@ -202,20 +227,21 @@ impl PropagationClient {
) {
self.cleanup();
}
self.flush_pending_transport();
if !self.pending_transport.is_empty() {
return false;
}
let (link, request_data) = Link::new_initiator(node_hash, 1);
let link_id = link.link_id;
if let Err(e) = self
.transport_tx
.try_send(TransportMessage::RegisterDestination {
hash: link_id,
app_name: "lxmf.propagation.client".to_string(),
delivery_tx: Some(self.event_tx.clone()),
})
{
tracing::warn!(err = %e,
"failed to register propagation client destination; download will fail");
if !self.queue_transport(TransportMessage::RegisterDestination {
hash: link_id,
app_name: "lxmf.propagation.client".to_string(),
delivery_tx: Some(self.event_tx.clone()),
}) {
tracing::warn!("failed to register propagation client destination");
return false;
}
let flags = rns_wire::flags::PacketFlags {
@@ -235,12 +261,14 @@ impl PropagationClient {
let mut raw = header.pack();
raw.extend_from_slice(&request_data);
let _ = self
.transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: node_hash,
}));
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: node_hash,
})) {
tracing::warn!("failed to stage propagation client Link request");
self.pending_transport.clear();
return false;
}
self.status = PropagationTransferStatus {
state: PropagationClientState::LinkEstablishing,
@@ -250,6 +278,7 @@ impl PropagationClient {
self.link = Some(link);
self.link_id = Some(link_id);
self.started_at = Some(Instant::now());
self.max_messages = max_messages.filter(|limit| *limit > 0);
self.identified = false;
self.available_messages.clear();
self.received_messages.clear();
@@ -260,6 +289,49 @@ impl PropagationClient {
true
}
/// Cancel an active request and return to the idle state.
pub fn cancel_download(&mut self) {
self.cleanup();
self.status = PropagationTransferStatus::default();
}
const PENDING_TRANSPORT_LIMIT: usize = 256;
fn queue_transport(&mut self, message: TransportMessage) -> bool {
if self.pending_transport.is_empty() {
match self.transport_tx.try_send(message) {
Ok(()) => return true,
Err(mpsc::error::TrySendError::Full(message)) => {
self.pending_transport.push_back(message);
return true;
}
Err(mpsc::error::TrySendError::Closed(_)) => return false,
}
}
if self.pending_transport.len() >= Self::PENDING_TRANSPORT_LIMIT {
return false;
}
self.pending_transport.push_back(message);
true
}
fn flush_pending_transport(&mut self) {
while let Some(message) = self.pending_transport.pop_front() {
match self.transport_tx.try_send(message) {
Ok(()) => {}
Err(mpsc::error::TrySendError::Full(message)) => {
self.pending_transport.push_front(message);
break;
}
Err(mpsc::error::TrySendError::Closed(_)) => {
self.pending_transport.clear();
self.status.state = PropagationClientState::Failed;
break;
}
}
}
}
pub fn drain_events(&mut self, known_identities: &std::collections::HashMap<String, [u8; 64]>) {
let mut events = Vec::new();
while let Ok(event) = self.event_rx.try_recv() {
@@ -284,6 +356,10 @@ impl PropagationClient {
} else {
&[]
};
if let Some(link) = self.link.as_mut() {
link.record_inbound();
link.record_rx(data.len());
}
match header.context {
rns_wire::context::PacketContext::Lrproof
@@ -295,23 +371,25 @@ impl PropagationClient {
continue;
}
let node_hex = self.outbound_propagation_node.map(|h| hex_encode(&h));
if let Some(node_hex) = node_hex
&& let Some(pub_key) = known_identities.get(&node_hex)
{
let ed25519_bytes: [u8; 32] = pub_key[32..64]
.try_into()
.expect("known_identities values are [u8; 64]; slice [32..64] is always 32 bytes");
if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(data, &verify_key, &ed25519_bytes);
if let Some(node_hex) = node_hex {
if let Some(pub_key) = known_identities.get(&node_hex) {
let ed25519_bytes: [u8; 32] = pub_key[32..64]
.try_into()
.expect("known_identities values are [u8; 64]; slice [32..64] is always 32 bytes");
if let Ok(verify_key) =
Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(data, &verify_key, &ed25519_bytes);
}
}
}
}
rns_wire::context::PacketContext::Response => {
if let Some(ref mut link) = self.link
&& let Ok((_request_id, response_data)) = link.handle_response(data)
{
self.handle_response_data(&response_data);
if let Some(ref mut link) = self.link {
if let Ok((_request_id, response_data)) = link.handle_response(data)
{
self.handle_response_data(&response_data);
}
}
}
rns_wire::context::PacketContext::ResourceAdv => {
@@ -395,14 +473,16 @@ impl PropagationClient {
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
let _ =
self.transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
}));
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
})) {
self.status.state = PropagationClientState::Failed;
return;
}
}
self.status.state = PropagationClientState::LinkEstablished;
self.started_at = Some(Instant::now());
}
Err(_) => {
self.status.state = PropagationClientState::Failed;
@@ -619,10 +699,13 @@ impl PropagationClient {
return;
};
let Some(transfer) = self.inbound_resources.get_mut(&resource_hash) else {
return;
let action = {
let Some(transfer) = self.inbound_resources.get_mut(&resource_hash) else {
return;
};
transfer.hashmap_update(segment, hashmap_data)
};
match transfer.hashmap_update(segment, hashmap_data) {
match action {
TransferAction::SendRequest(req) => {
self.send_encrypted_resource_control(
rns_wire::context::PacketContext::ResourceReq,
@@ -659,7 +742,7 @@ impl PropagationClient {
}
fn complete_resource(&mut self, resource_hash: [u8; 32]) {
let assembled = {
let (assembled, proof) = {
let Some(link) = self.link.as_ref() else {
return;
};
@@ -671,16 +754,14 @@ impl PropagationClient {
return;
};
match transfer.complete(Some(&decrypt_fn)) {
Ok((assembled, proof)) => {
self.send_resource_proof(&proof);
assembled
}
Ok(result) => result,
Err(_) => {
self.status.state = PropagationClientState::Failed;
return;
}
}
};
self.send_resource_proof(&proof);
let route = self.segment_routing.remove(&resource_hash);
if let Some(link) = self.link.as_mut() {
@@ -741,18 +822,20 @@ impl PropagationClient {
}
fn send_encrypted_resource_control(
&self,
&mut self,
context: rns_wire::context::PacketContext,
plaintext: &[u8],
) {
if let Some(link) = self.link.as_ref()
&& let Ok(encrypted) = link.encrypt(plaintext)
{
let encrypted = self
.link
.as_ref()
.and_then(|link| link.encrypt(plaintext).ok());
if let Some(encrypted) = encrypted {
self.send_link_packet(context, rns_wire::flags::PacketType::Data, &encrypted);
}
}
fn send_resource_proof(&self, proof: &[u8]) {
fn send_resource_proof(&mut self, proof: &[u8]) {
self.send_link_packet(
rns_wire::context::PacketContext::ResourcePrf,
rns_wire::flags::PacketType::Proof,
@@ -761,7 +844,7 @@ impl PropagationClient {
}
fn send_link_packet(
&self,
&mut self,
context: rns_wire::context::PacketContext,
packet_type: rns_wire::flags::PacketType,
payload: &[u8],
@@ -784,12 +867,14 @@ impl PropagationClient {
};
let mut raw = header.pack();
raw.extend_from_slice(payload);
let _ = self
.transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
}));
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
})) {
self.status.state = PropagationClientState::Failed;
} else if let Some(link) = self.link.as_mut() {
link.record_tx(payload.len());
}
}
/// Phase 1: parse available transient IDs from the server.
@@ -805,10 +890,10 @@ impl PropagationClient {
if let Some(arr) = value.as_array() {
self.available_messages.clear();
for item in arr {
if let Some(id_bytes) = item.as_slice()
&& id_bytes.len() == 32
{
self.available_messages.push(id_bytes.to_vec());
if let Some(id_bytes) = item.as_slice() {
if id_bytes.len() == 32 {
self.available_messages.push(id_bytes.to_vec());
}
}
}
@@ -864,22 +949,78 @@ impl PropagationClient {
}
pub fn tick(&mut self) {
if let Some(started) = self.started_at
&& started.elapsed() > self.timeout
&& self.status.state != PropagationClientState::Idle
&& self.status.state != PropagationClientState::Complete
{
self.flush_pending_transport();
if self.status.state == PropagationClientState::Failed {
self.cleanup();
self.status.state = PropagationClientState::Failed;
return;
}
if let Some(started) = self.started_at {
if started.elapsed() > self.timeout
&& matches!(
self.status.state,
PropagationClientState::LinkEstablishing
| PropagationClientState::ListRequested
| PropagationClientState::GetRequested
| PropagationClientState::PurgeRequested
)
{
self.cleanup();
self.status.state = PropagationClientState::Failed;
return;
}
}
let link_action = self.link.as_mut().map(Link::tick);
match link_action {
Some(LinkAction::SendKeepalive) | Some(LinkAction::TransitionedToStale) => {
self.send_link_packet(
rns_wire::context::PacketContext::Keepalive,
rns_wire::flags::PacketType::Data,
&[rns_link::constants::KEEPALIVE_REQUEST],
);
}
Some(LinkAction::SendTeardownAndClose(payload)) => {
self.send_link_packet(
rns_wire::context::PacketContext::LinkClose,
rns_wire::flags::PacketType::Data,
&payload,
);
self.status.state = PropagationClientState::Failed;
}
Some(LinkAction::Closed(_)) => self.status.state = PropagationClientState::Failed,
Some(LinkAction::None) | None => {}
}
if self.status.state == PropagationClientState::Receiving {
let mut retry_requests = Vec::new();
for transfer in self.inbound_resources.values_mut() {
match transfer.check_timeout() {
TransferAction::SendRequest(request) => retry_requests.push(request),
TransferAction::Failed(_) => {
self.status.state = PropagationClientState::Failed;
break;
}
_ => {}
}
}
for request in retry_requests {
self.send_encrypted_resource_control(
rns_wire::context::PacketContext::ResourceReq,
&request,
);
}
}
match self.status.state {
PropagationClientState::Idle => {}
PropagationClientState::LinkEstablishing => {}
PropagationClientState::LinkEstablished => {
if !self.identified {
self.send_identify();
if self.status.state == PropagationClientState::Failed {
return;
}
self.identified = true;
}
self.send_list_request();
@@ -895,31 +1036,41 @@ impl PropagationClient {
}
fn send_identify(&mut self) {
if let (Some(link), Some(link_id)) = (&mut self.link, self.link_id)
&& let (Some(pub_key), Some(sign_key)) = (&self.identity_pub, &self.identity_key)
&& let Ok(identify_data) = link.identify(pub_key, sign_key)
{
let id_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::LinkIdentify,
};
let mut id_raw = id_header.pack();
id_raw.extend_from_slice(&identify_data);
let _ = self
.transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(id_raw),
destination_hash: link_id,
}));
let outbound = if let (Some(link), Some(link_id)) = (&mut self.link, self.link_id) {
if let (Some(pub_key), Some(sign_key)) = (&self.identity_pub, &self.identity_key) {
if let Ok(identify_data) = link.identify(pub_key, sign_key) {
let id_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::LinkIdentify,
};
let mut id_raw = id_header.pack();
id_raw.extend_from_slice(&identify_data);
Some(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(id_raw),
destination_hash: link_id,
}))
} else {
None
}
} else {
None
}
} else {
None
};
if let Some(outbound) = outbound {
if !self.queue_transport(outbound) {
self.status.state = PropagationClientState::Failed;
}
}
}
@@ -935,6 +1086,7 @@ impl PropagationClient {
if self.send_get_path_request(&request_data) {
self.status.state = PropagationClientState::ListRequested;
self.started_at = Some(Instant::now());
} else {
self.status.state = PropagationClientState::Failed;
}
@@ -953,6 +1105,7 @@ impl PropagationClient {
.available_messages
.iter()
.filter(|id| !self.local_messages.contains(*id))
.take(self.max_messages.unwrap_or(usize::MAX))
.map(|id| Value::Binary(id.clone()))
.collect();
@@ -960,7 +1113,7 @@ impl PropagationClient {
let haves: Vec<Value> = self
.available_messages
.iter()
.filter(|id| self.local_messages.contains(*id))
.filter(|id| !self.retain_synced_on_node && self.local_messages.contains(*id))
.map(|id| Value::Binary(id.clone()))
.collect();
@@ -975,6 +1128,7 @@ impl PropagationClient {
let buf = crate::encode_value(&array);
if self.send_get_path_request(&buf) {
self.status.state = PropagationClientState::PurgeRequested;
self.started_at = Some(Instant::now());
} else {
self.status.state = PropagationClientState::Failed;
}
@@ -991,6 +1145,7 @@ impl PropagationClient {
if self.send_get_path_request(&buf) {
self.status.state = PropagationClientState::GetRequested;
self.started_at = Some(Instant::now());
} else {
self.status.state = PropagationClientState::Failed;
}
@@ -1012,6 +1167,7 @@ impl PropagationClient {
if self.send_get_path_request(&buf) {
self.status.state = PropagationClientState::PurgeRequested;
self.started_at = Some(Instant::now());
} else {
self.status.state = PropagationClientState::Failed;
}
@@ -1020,7 +1176,7 @@ impl PropagationClient {
/// Send a msgpack request to the `MESSAGE_GET_PATH` endpoint; returns `true`
/// if the request was dispatched successfully.
fn send_get_path_request(&mut self, request_data: &[u8]) -> bool {
if let Some(ref mut link) = self.link {
let outbound = if let Some(ref mut link) = self.link {
match link.request(
MESSAGE_GET_PATH,
Some(request_data),
@@ -1048,27 +1204,31 @@ impl PropagationClient {
rns_wire::flags::HeaderType::Header1,
);
link.update_pending_request_id(&_request_id, packet_request_id);
let _ = self.transport_tx.try_send(TransportMessage::Outbound(
OutboundRequest {
raw: Bytes::from(req_raw),
destination_hash: link_id,
},
));
return true;
Some(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(req_raw),
destination_hash: link_id,
}))
} else {
None
}
}
Err(_) => return false,
Err(_) => None,
}
}
false
} else {
None
};
outbound.is_some_and(|message| self.queue_transport(message))
}
fn cleanup(&mut self) {
self.send_teardown();
if let Some(link_id) = self.link_id.take() {
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: link_id });
if !self.queue_transport(TransportMessage::DeregisterDestination { hash: link_id }) {
tracing::warn!(
link_id = %hex::encode(link_id),
"failed to deregister propagation client Link"
);
}
}
self.link = None;
self.inbound_resources.clear();
@@ -1193,6 +1353,46 @@ mod tests {
assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_)));
}
#[test]
fn start_download_rejects_a_closed_transport_instead_of_false_success() {
let (tx, rx) = mpsc::channel(1);
drop(rx);
let mut client = PropagationClient::new(tx, None, None);
client.set_propagation_node([0xB0; 16]);
assert!(!client.start_download());
assert_eq!(client.state(), PropagationClientState::Idle);
assert!(client.link.is_none());
assert!(client.pending_transport.is_empty());
}
#[test]
fn start_download_preserves_register_before_request_under_backpressure() {
let (tx, mut rx) = mpsc::channel(1);
tx.try_send(TransportMessage::DeregisterDestination { hash: [1; 16] })
.unwrap();
let mut client = PropagationClient::new(tx, None, None);
client.set_propagation_node([0xB2; 16]);
assert!(client.start_download());
assert_eq!(client.pending_transport.len(), 2);
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::DeregisterDestination { .. }
));
client.tick();
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::RegisterDestination { .. }
));
client.tick();
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::Outbound(_)
));
assert!(client.pending_transport.is_empty());
}
#[test]
fn test_start_download_rejects_an_active_transfer() {
let (tx, mut rx) = mpsc::channel(64);
@@ -1228,6 +1428,34 @@ mod tests {
assert_eq!(client.delivery_limit, Some(512.0));
}
#[test]
fn get_request_honours_max_messages_and_retain_policy() {
let (tx, mut rx) = mpsc::channel(16);
let mut client = PropagationClient::new(tx, None, None);
let (initiator, responder) = active_link_pair([0xB3; 16]);
client.link_id = Some(initiator.link_id);
client.link = Some(initiator);
client.max_messages = Some(1);
client.retain_synced_on_node = true;
client.available_messages = vec![vec![1; 32], vec![2; 32], vec![3; 32]];
client.local_messages.insert(vec![1; 32]);
client.send_get_request();
let request = match rx.try_recv().unwrap() {
TransportMessage::Outbound(request) => request,
other => panic!("expected request packet, got {other:?}"),
};
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
let (_, _, _, request_data) = responder.handle_request(&request.raw[offset..]).unwrap();
let value = rmpv::decode::read_value(&mut &request_data[..]).unwrap();
let fields = value.as_array().unwrap();
assert_eq!(
fields[0].as_array().unwrap(),
&[rmpv::Value::Binary(vec![2; 32])]
);
assert!(fields[1].as_array().unwrap().is_empty());
}
#[test]
fn test_take_received_messages() {
let (tx, _rx) = mpsc::channel(16);
@@ -1448,6 +1676,23 @@ mod tests {
assert_eq!(client.status.state, PropagationClientState::Idle);
}
#[test]
fn progressive_resource_phase_is_not_killed_by_absolute_operation_timeout() {
let (tx, _rx) = mpsc::channel(16);
let mut client = PropagationClient::new(tx, None, None);
let (initiator, _responder) = active_link_pair([0xC1; 16]);
client.link_id = Some(initiator.link_id);
client.link = Some(initiator);
client.status.state = PropagationClientState::Receiving;
client.started_at = Some(Instant::now() - Duration::from_secs(600));
client.timeout = Duration::ZERO;
client.tick();
assert_eq!(client.state(), PropagationClientState::Receiving);
assert!(client.link.is_some());
}
#[test]
fn test_cleanup_deregisters() {
let (tx, mut rx) = mpsc::channel(64);
+348 -109
View File
@@ -39,8 +39,8 @@ impl Default for PropagationNodeConfig {
// Disabled by default; set to PROPAGATION_COST for production.
min_stamp_cost: 0,
peering_cost: PEERING_COST,
max_message_size: DELIVERY_LIMIT * 1024,
max_offer_size: SYNC_LIMIT * 1000,
max_message_size: DELIVERY_LIMIT * BYTES_PER_KILOBYTE,
max_offer_size: SYNC_LIMIT * BYTES_PER_KILOBYTE,
}
}
}
@@ -69,9 +69,16 @@ impl GetRequestAction {
/// Resolve to response bytes, performing any planned file reads inline.
/// Blocking; do not call while holding a shared node lock.
pub fn into_response(self) -> Vec<u8> {
self.into_response_with_served_count().0
}
/// Resolve the response and report how many messages were actually read
/// and admitted by the client's transfer limit. This lets the daemon keep
/// Python-compatible served-message accounting without repeating I/O.
pub fn into_response_with_served_count(self) -> (Vec<u8>, u64) {
match self {
GetRequestAction::Respond(bytes) => bytes,
GetRequestAction::ServeFiles(plan) => plan.serve(),
GetRequestAction::Respond(bytes) => (bytes, 0),
GetRequestAction::ServeFiles(plan) => plan.serve_with_count(),
}
}
}
@@ -98,6 +105,10 @@ impl GetServePlan {
/// over-limit entries skipped (not a transfer abort), stamps stripped
/// for client download. Unreadable files are skipped.
pub fn serve(&self) -> Vec<u8> {
self.serve_with_count().0
}
fn serve_with_count(&self) -> (Vec<u8>, u64) {
use rmpv::Value;
const PER_MESSAGE_OVERHEAD: f64 = 16.0;
@@ -121,7 +132,8 @@ impl GetServePlan {
messages.push(Value::Binary(payload));
}
crate::encode_value(&Value::Array(messages))
let served = messages.len() as u64;
(crate::encode_value(&Value::Array(messages)), served)
}
}
@@ -147,6 +159,45 @@ pub fn read_planned_messages(
.collect()
}
/// One propagation-store admission reserved under the node lock. Persist it
/// on a blocking worker, then commit the returned value under a short lock.
#[derive(Debug)]
pub struct PropagationStoreWritePlan {
entry: PropagationEntry,
data: Vec<u8>,
path: Option<PathBuf>,
}
impl PropagationStoreWritePlan {
pub fn transient_id(&self) -> PropagationTransientId {
self.entry.transient_id
}
pub fn size(&self) -> usize {
self.entry.size
}
/// Perform the potentially blocking durable write. Disk-backed nodes use
/// atomic temp-file replacement; in-memory nodes complete immediately.
pub fn persist(self) -> std::io::Result<PersistedPropagationStoreWrite> {
if let Some(ref path) = self.path {
crate::persist::write_file_atomic(path, &self.data)?;
}
Ok(PersistedPropagationStoreWrite {
entry: self.entry,
path: self.path,
})
}
}
/// Durable half of a propagation-store admission, ready for an in-memory
/// commit under the node lock.
#[derive(Debug)]
pub struct PersistedPropagationStoreWrite {
entry: PropagationEntry,
path: Option<PathBuf>,
}
#[derive(Debug, Clone)]
pub(crate) struct SyncOfferCandidateSnapshot {
transient_id: PropagationTransientId,
@@ -203,11 +254,12 @@ pub(crate) fn prepare_sync_offer_snapshot(
.propagation_sync_limit
.map(kilobytes_to_bytes_fail_closed);
let mut handled_messages = snapshot.policy.handled_messages.clone();
if let Some(path) = snapshot.peer_path.as_ref()
&& let Ok(data) = std::fs::read(path)
&& let Some(peer) = LxmPeer::from_bytes_with_handled(&data)
{
handled_messages.extend(peer.handled_messages);
if let Some(path) = snapshot.peer_path.as_ref() {
if let Ok(data) = std::fs::read(path) {
if let Some(peer) = LxmPeer::from_bytes_with_handled(&data) {
handled_messages.extend(peer.handled_messages);
}
}
}
let mut candidates = snapshot.candidates;
@@ -267,7 +319,7 @@ fn kilobytes_to_bytes_fail_closed(kilobytes: f64) -> usize {
if !kilobytes.is_finite() || kilobytes <= 0.0 {
return 0;
}
(kilobytes * 1000.0).floor() as usize
(kilobytes * BYTES_PER_KILOBYTE as f64).floor() as usize
}
pub struct PropagationNode {
@@ -283,6 +335,11 @@ pub struct PropagationNode {
/// scheduling and offer-preparation revalidation use this to avoid both
/// stale offers and repeated scans of an unchanged fully-handled store.
offer_generation: u64,
/// IDs and bytes reserved by off-lock store writes. Reservations prevent
/// duplicate acceptance and storage-cap oversubscription while I/O is in
/// flight.
pending_write_ids: HashSet<PropagationTransientId>,
pending_write_bytes: usize,
}
impl PropagationNode {
@@ -296,6 +353,8 @@ impl PropagationNode {
storage_path: None,
last_offer_times: HashMap::new(),
offer_generation: 0,
pending_write_ids: HashSet::new(),
pending_write_bytes: 0,
}
}
@@ -311,6 +370,31 @@ impl PropagationNode {
self.offer_generation
}
/// Apply the daemon's destination deny policy to the authoritative hosted
/// store. The reusable router has its own optional store, so production
/// wiring must configure this node explicitly as well.
pub fn ignore_destination(&mut self, dest_hash: [u8; 16]) {
self.store.ignore_destination(dest_hash);
}
pub fn unignore_destination(&mut self, dest_hash: &[u8; 16]) {
self.store.unignore_destination(dest_hash);
}
pub fn is_destination_ignored(&self, dest_hash: &[u8; 16]) -> bool {
self.store.is_destination_ignored(dest_hash)
}
/// Apply the daemon's culling-priority policy to the authoritative hosted
/// store.
pub fn prioritise_destination(&mut self, dest_hash: [u8; 16]) {
self.store.prioritise_destination(dest_hash);
}
pub fn unprioritise_destination(&mut self, dest_hash: &[u8; 16]) {
self.store.unprioritise_destination(dest_hash);
}
fn advance_offer_generation(&mut self) {
self.offer_generation = self.offer_generation.saturating_add(1);
}
@@ -330,11 +414,91 @@ impl PropagationNode {
storage_path: Some(storage_path),
last_offer_times: HashMap::new(),
offer_generation: 0,
pending_write_ids: HashSet::new(),
pending_write_bytes: 0,
};
node.load_from_disk()?;
Ok(node)
}
fn reserve_store_write(
&mut self,
entry: PropagationEntry,
data: Vec<u8>,
) -> Option<PropagationStoreWritePlan> {
let transient_id = entry.transient_id;
if self.store.contains(&transient_id) || self.pending_write_ids.contains(&transient_id) {
return None;
}
// Python checks the current store size before inserting and permits
// the message that crosses the cap; the next admission is rejected
// until culling makes room. Include reservations in that current-size
// view so concurrent writers cannot all pass the same preflight.
let occupied = self
.store
.total_size()
.saturating_add(self.pending_write_bytes);
if occupied > self.config.max_storage {
return None;
}
self.pending_write_ids.insert(transient_id);
self.pending_write_bytes = self.pending_write_bytes.saturating_add(data.len());
let path = self
.storage_path
.as_ref()
.map(|dir| dir.join(entry.filename()));
Some(PropagationStoreWritePlan { entry, data, path })
}
/// Release a reservation after a failed blocking write.
pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) {
if self.pending_write_ids.remove(transient_id) {
self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size);
}
}
/// Commit a successfully persisted admission. The normal path performs no
/// filesystem I/O while holding the node lock.
pub fn commit_store_write(&mut self, persisted: PersistedPropagationStoreWrite) -> bool {
let transient_id = persisted.entry.transient_id;
let size = persisted.entry.size;
if !self.pending_write_ids.remove(&transient_id) {
if let Some(path) = persisted.path {
let _ = std::fs::remove_file(path);
}
return false;
}
self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size);
let inserted = self.store.insert(persisted.entry);
if inserted {
self.advance_offer_generation();
} else if let Some(path) = persisted.path {
// Reservation loss/duplicate commit is exceptional; cleanup is a
// short best-effort operation and never occurs on normal traffic.
let _ = std::fs::remove_file(path);
}
inserted
}
fn persist_reserved(&mut self, plan: PropagationStoreWritePlan) -> bool {
let transient_id = plan.transient_id();
let size = plan.size();
match plan.persist() {
Ok(persisted) => self.commit_store_write(persisted),
Err(error) => {
self.abort_store_write(&transient_id, size);
tracing::warn!(
transient_id = %hex::encode(transient_id),
%error,
"failed to persist propagation message"
);
false
}
}
}
/// Returns `true` if the message was stored, `false` on duplicate, overflow,
/// pack failure, oversized message, or insufficient stamp.
#[tracing::instrument(
@@ -346,28 +510,22 @@ impl PropagationNode {
size = message.content.len(),
),
)]
pub fn accept_message(&mut self, message: &LxMessage) -> bool {
let hash = match message.hash {
Some(h) => h,
None => return false,
};
pub fn plan_accept_message(
&mut self,
message: &LxMessage,
) -> Option<PropagationStoreWritePlan> {
let hash = message.hash?;
let transient_id = message.transient_id.unwrap_or(hash);
if self.store.contains(&transient_id) {
return false;
}
if self.store.total_size() > self.config.max_storage {
return false;
return None;
}
let packed = match message.pack() {
Ok(p) => p,
Err(_) => return false,
};
let packed = message.pack().ok()?;
let msg_size = packed.len();
if msg_size > self.config.max_message_size {
return false;
return None;
}
// Compute stamp value via HKDF workblock over full_hash(packed) using
@@ -388,26 +546,21 @@ impl PropagationNode {
};
if self.config.min_stamp_cost > 0 && sv < self.config.min_stamp_cost {
return false;
return None;
}
let mut entry =
PropagationEntry::new(transient_id, hash, message.destination_hash, msg_size, sv);
entry.stored_at = message.timestamp;
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, &packed) {
// In-memory insert still proceeds on disk failure.
tracing::warn!(error = %e, "failed to persist propagation message");
}
}
self.reserve_store_write(entry, packed)
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_message(&mut self, message: &LxMessage) -> bool {
let Some(plan) = self.plan_accept_message(message) else {
return false;
};
self.persist_reserved(plan)
}
/// Store an already propagation-packed LXMF blob (`dest_hash || encrypted_data`).
@@ -416,23 +569,24 @@ impl PropagationNode {
/// [`Self::accept_message`], the node cannot decrypt or unpack this data;
/// it indexes by the transient ID and serves the raw blob back to the
/// destination client during `/get`.
pub fn accept_propagated_blob(&mut self, lxmf_data: &[u8], stamp_value: u8) -> bool {
pub fn plan_accept_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_value: u8,
) -> Option<PropagationStoreWritePlan> {
if lxmf_data.len() < DESTINATION_LENGTH + 1 {
return false;
return None;
}
if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost {
return false;
return None;
}
let transient_id = rns_crypto::sha::full_hash(lxmf_data);
if self.store.contains(&transient_id) {
return false;
}
if self.store.total_size() > self.config.max_storage {
return false;
return None;
}
if lxmf_data.len() > self.config.max_message_size {
return false;
return None;
}
let mut destination_hash = [0u8; 16];
@@ -446,18 +600,14 @@ impl PropagationNode {
stamp_value,
);
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, lxmf_data) {
tracing::warn!(error = %e, "failed to persist propagated message");
}
}
self.reserve_store_write(entry, lxmf_data.to_vec())
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_propagated_blob(&mut self, lxmf_data: &[u8], stamp_value: u8) -> bool {
let Some(plan) = self.plan_accept_propagated_blob(lxmf_data, stamp_value) else {
return false;
};
self.persist_reserved(plan)
}
/// Store a validated propagated LXMF blob with its propagation-node stamp.
@@ -466,33 +616,30 @@ impl PropagationNode {
/// `lxmf_data || stamp` on disk so peer sync can forward proof-carrying
/// data. Client `/get` strips the final 32-byte stamp before returning
/// messages to recipients.
pub fn accept_stamped_propagated_blob(
pub fn plan_accept_stamped_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_data: &[u8; 32],
stamp_value: u8,
) -> bool {
) -> Option<PropagationStoreWritePlan> {
if lxmf_data.len() < DESTINATION_LENGTH + 1 {
return false;
return None;
}
if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost {
return false;
return None;
}
let transient_id = rns_crypto::sha::full_hash(lxmf_data);
if self.store.contains(&transient_id) {
return false;
return None;
}
let mut stored_data = Vec::with_capacity(lxmf_data.len() + stamp_data.len());
stored_data.extend_from_slice(lxmf_data);
stored_data.extend_from_slice(stamp_data);
if self.store.total_size() > self.config.max_storage {
return false;
}
if stored_data.len() > self.config.max_message_size {
return false;
return None;
}
let mut destination_hash = [0u8; 16];
@@ -506,18 +653,21 @@ impl PropagationNode {
stamp_value,
);
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, &stored_data) {
tracing::warn!(error = %e, "failed to persist stamped propagated message");
}
}
self.reserve_store_write(entry, stored_data)
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_stamped_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_data: &[u8; 32],
stamp_value: u8,
) -> bool {
let Some(plan) =
self.plan_accept_stamped_propagated_blob(lxmf_data, stamp_data, stamp_value)
else {
return false;
};
self.persist_reserved(plan)
}
fn load_from_disk(&mut self) -> std::io::Result<()> {
@@ -631,10 +781,10 @@ impl PropagationNode {
self.advance_offer_generation();
}
if before > after
&& let Some(ref dir) = self.storage_path
{
self.cleanup_orphaned_files(dir);
if before > after {
if let Some(ref dir) = self.storage_path {
self.cleanup_orphaned_files(dir);
}
}
}
@@ -652,10 +802,10 @@ impl PropagationNode {
if filename.ends_with(".peer") || filename.ends_with(".msgpack") {
continue;
}
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename)
&& !self.store.contains(&tid)
{
let _ = std::fs::remove_file(&path);
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename) {
if !self.store.contains(&tid) {
let _ = std::fs::remove_file(&path);
}
}
}
}
@@ -696,6 +846,20 @@ impl PropagationNode {
self.store.len()
}
/// Count live store entries not yet handled by one peer. The daemon's
/// generation scheduler does not maintain `LxmPeer`'s legacy cached
/// unhandled counter, so control status must derive this from the same
/// authoritative store used to prepare offers.
pub fn unhandled_message_count(
&self,
handled_messages: &HashSet<PropagationTransientId>,
) -> usize {
self.store
.entries()
.filter(|entry| !handled_messages.contains(&entry.transient_id))
.count()
}
pub fn total_size(&self) -> usize {
self.store.total_size()
}
@@ -939,24 +1103,26 @@ impl PropagationNode {
let mut reads = Vec::new();
if let Some(wants_arr) = arr[0].as_array() {
for want_val in wants_arr {
if let Some(tid) = parse_store_id(want_val)
&& let Some(ref dir) = self.storage_path
&& let Some(entry) = self.store.get(&tid)
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
&& entry.destination_hash == *client_dest_hash
if let (Some(tid), Some(dir)) =
(parse_store_id(want_val), self.storage_path.as_ref())
{
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
if let Some(entry) = self.store.get(&tid) {
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
if entry.destination_hash == *client_dest_hash {
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
}
}
}
}
}
// Wire value is kilobytes ×1000 (Python LXMRouter.py:1471).
// Wire value is decimal kilobytes (Python LXMRouter.py:1471).
let limit_bytes = if arr.len() > 2 {
arr[2].as_f64().map(|kb| kb * 1000.0)
arr[2].as_f64().map(|kb| kb * BYTES_PER_KILOBYTE as f64)
} else {
None
};
@@ -1111,10 +1277,11 @@ impl PropagationNode {
// Compatibility wrapper: production uses the staged task
// path and exposes this delta to the daemon for off-loop
// persistence.
if !terminal_handled_ids.is_empty()
&& let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
if !terminal_handled_ids.is_empty() {
if let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
}
}
return offer;
}
@@ -1228,12 +1395,13 @@ impl PropagationNode {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "peer").unwrap_or(false)
&& let Ok(data) = std::fs::read(&path)
&& let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data)
{
self.prune_handled_against_store(&mut peer);
peers.push(peer);
if path.extension().map(|e| e == "peer").unwrap_or(false) {
if let Ok(data) = std::fs::read(&path) {
if let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data) {
self.prune_handled_against_store(&mut peer);
peers.push(peer);
}
}
}
}
}
@@ -1326,7 +1494,9 @@ mod tests {
#[test]
fn test_new_propagation_node() {
let node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let config = PropagationNodeConfig::default();
assert_eq!(config.max_message_size, 1_000_000);
let node = PropagationNode::new(config, [0xAA; 16]);
assert_eq!(node.message_count(), 0);
assert_eq!(node.total_size(), 0);
assert_eq!(node.dest_hash, [0xAA; 16]);
@@ -1341,6 +1511,73 @@ mod tests {
assert_eq!(node.message_count(), 1);
}
#[test]
fn store_write_reservation_blocks_duplicates_until_durable_commit() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "reserved");
let plan = node.plan_accept_message(&msg).expect("first reservation");
assert_eq!(node.message_count(), 0, "reservation is not served state");
assert!(node.plan_accept_message(&msg).is_none());
let persisted = plan.persist().unwrap();
assert!(node.commit_store_write(persisted));
assert_eq!(node.message_count(), 1);
}
#[test]
fn failed_store_write_is_not_inserted_and_releases_reservation() {
let root = tempfile::tempdir().unwrap();
let store_dir = root.path().join("store");
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
store_dir.clone(),
)
.unwrap();
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "durable");
let plan = node.plan_accept_message(&msg).expect("reservation");
let transient_id = plan.transient_id();
let size = plan.size();
std::fs::remove_dir(&store_dir).unwrap();
assert!(plan.persist().is_err());
node.abort_store_write(&transient_id, size);
assert_eq!(node.message_count(), 0);
std::fs::create_dir(&store_dir).unwrap();
assert!(node.accept_message(&msg));
assert_eq!(node.message_count(), 1);
}
#[test]
fn hosted_node_applies_ignored_destination_policy() {
let destination = [0x44; 16];
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
node.ignore_destination(destination);
assert!(node.is_destination_ignored(&destination));
let mut blob = destination.to_vec();
blob.extend_from_slice(b"encrypted-lxmf");
assert!(!node.accept_stamped_propagated_blob(&blob, &[0; 32], 0));
assert_eq!(node.message_count(), 0);
node.unignore_destination(&destination);
assert!(node.accept_stamped_propagated_blob(&blob, &[0; 32], 0));
}
#[test]
fn unhandled_count_is_derived_from_live_store_and_peer_handled_set() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content");
let transient_id = msg.transient_id.or(msg.hash).unwrap();
assert!(node.accept_message(&msg));
let mut handled = HashSet::new();
assert_eq!(node.unhandled_message_count(&handled), 1);
handled.insert(transient_id);
assert_eq!(node.unhandled_message_count(&handled), 0);
}
#[test]
fn test_reject_duplicate() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
@@ -2715,8 +2952,10 @@ mod tests {
};
// Reads resolve after the node borrow ends (embedder drops the lock).
drop(node);
let response: Value = rmpv::decode::read_value(&mut &plan.serve()[..]).unwrap();
let (response_bytes, served) = plan.serve_with_count();
let response: Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let messages = response.as_array().unwrap();
assert_eq!(served, 1);
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].as_slice().unwrap(), blob.as_slice());
File diff suppressed because it is too large. Load diff
+410 -109
View File
@@ -109,12 +109,17 @@ pub struct DeferredStampJob {
#[derive(Debug)]
pub enum SendError {
MissingOutboundPropagationNode(Box<LxMessage>),
TicketPreparation {
message: Box<LxMessage>,
source: TicketPreparationError,
},
}
impl SendError {
pub fn message(&self) -> &LxMessage {
match self {
Self::MissingOutboundPropagationNode(message) => message,
Self::TicketPreparation { message, .. } => message,
}
}
}
@@ -125,12 +130,21 @@ impl fmt::Display for SendError {
Self::MissingOutboundPropagationNode(_) => f.write_str(
"attempt to send propagated message with no outbound propagation node configured",
),
Self::TicketPreparation { source, .. } => source.fmt(f),
}
}
}
impl std::error::Error for SendError {}
#[derive(Debug, thiserror::Error)]
pub enum TicketPreparationError {
#[error("reply ticket must be added before the LXMF message is signed")]
AlreadySigned,
#[error("failed to encode LXMF reply ticket: {0}")]
Encode(String),
}
/// Current route metadata for an LXMF Direct delivery destination.
#[derive(Debug, Clone, PartialEq)]
pub struct DirectRouteSnapshot {
@@ -457,6 +471,7 @@ impl LxmRouter {
content_len = message.content.len(),
),
)]
#[deprecated(note = "use try_send() and handle the immediate routing result")]
pub fn send(&mut self, message: LxMessage) {
let _ = self.try_send(message);
}
@@ -479,11 +494,12 @@ impl LxmRouter {
return Err(SendError::MissingOutboundPropagationNode(Box::new(message)));
}
let now = now_f64();
if message.outbound_ticket.is_none()
&& let Some(ticket) = self.ticket_store.find(&message.destination_hash, now)
{
message.outbound_ticket = Some(ticket.token);
if let Err(source) = self.prepare_outbound(&mut message) {
message.mark_failed();
return Err(SendError::TicketPreparation {
message: Box::new(message),
source,
});
}
if message.stamp.is_none() && message.stamp_cost.is_none() {
@@ -514,16 +530,16 @@ impl LxmRouter {
}
}
if message.method == DeliveryMethod::Opportunistic
&& let Ok(packed) = message.pack_payload()
{
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
if message.method == DeliveryMethod::Opportunistic {
if let Ok(packed) = message.pack_payload() {
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
}
}
}
@@ -532,6 +548,53 @@ impl LxmRouter {
Ok(())
}
/// Apply router-owned ticket state before a caller signs `message`.
///
/// Learned outbound tickets do not change signed fields and can be
/// attached at any time. A requested reply ticket is a signed LXMF field,
/// so it must be inserted before signing. The method is deliberately
/// signer-agnostic: callers may subsequently use either `sign` or
/// `sign_with` without exposing private key material to the router.
pub fn prepare_outbound(
&mut self,
message: &mut LxMessage,
) -> Result<(), TicketPreparationError> {
let now = now_f64();
if message.outbound_ticket.is_none() {
if let Some(ticket) = self
.ticket_store
.find_outbound(&message.destination_hash, now)
{
message.outbound_ticket = Some(ticket.token);
}
}
if message.include_ticket && !message.fields.contains_key(&FIELD_TICKET) {
if message.signature.is_some() {
if self
.ticket_store
.should_issue_for(&message.destination_hash, now)
{
return Err(TicketPreparationError::AlreadySigned);
}
return Ok(());
}
if let Some(ticket) =
self.ticket_store
.issue_for(message.destination_hash, TICKET_EXPIRY, now)
{
let encoded = ticket
.encode_field()
.map_err(|error| TicketPreparationError::Encode(error.to_string()))?;
message
.set_msgpack_field(FIELD_TICKET, encoded)
.map_err(|error| TicketPreparationError::Encode(error.to_string()))?;
}
}
Ok(())
}
/// Queue `message` for off-thread stamp generation; it re-enters
/// `pending_outbound` with the stamp attached once the worker finishes.
/// Returns the message back when it carries no id to key the job on.
@@ -758,7 +821,7 @@ impl LxmRouter {
rand::thread_rng().fill_bytes(&mut token);
let expires = now_f64() + expiry_secs.unwrap_or(TICKET_EXPIRY) as f64;
self.ticket_store
.add(Ticket::new(token, destination_hash, expires));
.add_inbound(Ticket::new(token, destination_hash, expires));
token
}
@@ -767,7 +830,7 @@ impl LxmRouter {
/// Python reference: `LXMRouter.remember_ticket` — LXMRouter.py:1110-1113.
pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) {
self.ticket_store
.add(Ticket::new(token, destination_hash, expires));
.remember_outbound(Ticket::new(token, destination_hash, expires));
}
/// Returns the token of the first valid ticket for `destination_hash`.
@@ -776,7 +839,7 @@ impl LxmRouter {
pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> {
let now = now_f64();
self.ticket_store
.find(destination_hash, now)
.find_outbound(destination_hash, now)
.map(|t| t.token)
}
@@ -786,7 +849,7 @@ impl LxmRouter {
pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option<f64> {
let now = now_f64();
self.ticket_store
.find(destination_hash, now)
.find_outbound(destination_hash, now)
.map(|t| t.expires)
}
@@ -794,7 +857,7 @@ impl LxmRouter {
///
/// Python reference: `LXMRouter.get_inbound_tickets` — LXMRouter.py:1133-1136.
pub fn get_inbound_tickets(&self) -> &[Ticket] {
self.ticket_store.all()
self.ticket_store.inbound()
}
/// Cancel an outbound message before it is sent.
@@ -817,13 +880,14 @@ impl LxmRouter {
if let Some(mut msg) = self.pending_deferred_stamps.remove(message_hash) {
msg.cancel();
if self
let active_matches = self
.active_deferred_stamp
.as_ref()
.is_some_and(|job| job.message_hash == *message_hash)
&& let Some(job) = self.active_deferred_stamp.take()
{
job.handle.cancel();
.is_some_and(|job| job.message_hash == *message_hash);
if active_matches {
if let Some(job) = self.active_deferred_stamp.take() {
job.handle.cancel();
}
}
return true;
}
@@ -842,11 +906,26 @@ impl LxmRouter {
return false;
};
let mut msg = self.pending_outbound.remove(pos);
msg.mark_delivered();
let msg = self.pending_outbound.remove(pos);
self.complete_outbound_message(msg);
true
}
/// Complete an outbound message whose in-flight ownership moved from the
/// router queue into an embedding runtime.
///
/// Opportunistic packet delivery is asynchronous: the network accepts the
/// packet first and authenticates a delivery proof later. Embedders retain
/// the message between those events and return it here only after proof so
/// ticket-delivery accounting and callbacks reflect the observable result.
pub fn complete_outbound_message(&mut self, mut msg: LxMessage) {
if msg.include_ticket && msg.fields.contains_key(&FIELD_TICKET) {
self.ticket_store
.mark_ticket_delivered(msg.destination_hash, now_f64());
}
msg.mark_delivered();
}
/// Mark a pending outbound message failed and remove it from the outbound
/// queue.
pub fn mark_outbound_failed(&mut self, message_hash: &[u8; 32]) -> bool {
@@ -949,6 +1028,8 @@ impl LxmRouter {
/// distinct from its signed message hash; both identifiers are retained
/// so a later delivery through another representation is still deduped.
pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool {
self.learn_ticket_from_inbound(message);
let Some(message_id) = message.message_id.or(message.hash) else {
return false;
};
@@ -975,6 +1056,22 @@ impl LxmRouter {
true
}
/// Learn a reply ticket only from a cryptographically validated inbound
/// message. Returns whether valid outbound ticket state changed.
pub fn learn_ticket_from_inbound(&mut self, message: &LxMessage) -> bool {
if !message.signature_validated {
return false;
}
let Some(encoded) = message.fields.get(&FIELD_TICKET) else {
return false;
};
let Some(ticket) = Ticket::decode_field(message.source_hash, encoded, now_f64()) else {
return false;
};
self.ticket_store.remember_outbound(ticket);
true
}
/// Ingest an encrypted paper (`lxm://...`) URI and invoke the delivery callback as if the
/// message had arrived via the network.
///
@@ -1009,8 +1106,12 @@ impl LxmRouter {
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
self.ticket_store
.replace_all(persist::load_tickets(state_dir)?);
let (snapshot, legacy) = persist::load_tickets(state_dir)?;
if let Some(legacy) = legacy {
self.ticket_store.replace_legacy(legacy);
} else {
self.ticket_store.replace_snapshot(snapshot);
}
self.propagation_store
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
self.propagation_store
@@ -1034,7 +1135,7 @@ impl LxmRouter {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, self.ticket_store.all())?;
persist::save_tickets(state_dir, &self.ticket_store.snapshot())?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
persist::save_node_stats(
@@ -1078,15 +1179,19 @@ impl LxmRouter {
/// The method does not mutate peer state, allowing a single shared sync
/// task to accept one policy before the daemon marks that peer started.
pub fn sync_peer_policies_for_store(&self, offer_generation: u64) -> Vec<OutboundOfferPolicy> {
let mut policies = self
let eligible = self
.peers
.values()
.filter(|peer| {
peer.alive
&& peer.state == PeerState::Idle
peer.state == PeerState::Idle
&& peer.should_sync()
&& peer.needs_offer_generation(offer_generation)
})
.collect::<Vec<_>>();
let has_alive = eligible.iter().any(|peer| peer.alive);
let mut policies = eligible
.into_iter()
.filter(|peer| peer.alive == has_alive)
.map(OutboundOfferPolicy::from)
.collect::<Vec<_>>();
policies.sort_by_key(|policy| policy.peer_hash);
@@ -1170,8 +1275,7 @@ impl LxmRouter {
return false;
}
if !configured_static
&& let Some(h) = hops
&& h as usize > self.config.ext.autopeer_maxdepth
&& hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth)
{
return false;
}
@@ -1362,12 +1466,9 @@ impl LxmRouter {
destination_hash: &[u8; 16],
) -> bool {
let now = now_f64();
for ticket in self.ticket_store.all() {
if &ticket.destination_hash != destination_hash || !ticket.is_valid(now) {
continue;
}
for token in self.ticket_store.inbound_tokens(destination_hash, now) {
let mut material = Vec::with_capacity(16 + 32);
material.extend_from_slice(&ticket.token);
material.extend_from_slice(&token);
material.extend_from_slice(message_id);
let expected = rns_crypto::sha::truncated_hash(&material);
if stamp == expected.as_ref() {
@@ -1546,8 +1647,11 @@ impl LxmRouter {
let mut i = 0;
while i < self.pending_outbound.len() {
if let Some(limit) = self.config.ext.processing_limit
&& processed >= limit
if self
.config
.ext
.processing_limit
.is_some_and(|limit| processed >= limit)
{
break;
}
@@ -1592,7 +1696,8 @@ impl LxmRouter {
}
// State transitions match Python LXMessage.py:476-499:
// Opportunistic -> Sent immediately (single packet, fire-and-forget).
// Opportunistic -> Sent immediately; the embedding runtime keeps
// receipt ownership until an authenticated packet proof arrives.
// Direct / Propagated -> Sending (multi-step).
match msg.method {
DeliveryMethod::Direct => {
@@ -1665,8 +1770,11 @@ impl LxmRouter {
let mut i = 0;
while i < self.pending_outbound.len() {
if let Some(limit) = self.config.ext.processing_limit
&& processed >= limit
if self
.config
.ext
.processing_limit
.is_some_and(|limit| processed >= limit)
{
break;
}
@@ -1882,14 +1990,21 @@ impl LxmRouter {
{
message.mark_sent();
message.progress = 1.0;
} else {
tracing::warn!(
dest = %hex::encode(dest_hash),
"transport backpressure deferred opportunistic LXMF delivery"
);
self.pending_outbound.push(message);
}
}
Err(err) => {
tracing::warn!(
dest = %hex::encode(dest_hash),
error = %err,
"cannot execute opportunistic LXMF action"
"cannot execute opportunistic LXMF action; re-queueing"
);
self.pending_outbound.push(message);
}
}
}
@@ -1955,20 +2070,16 @@ impl LxmRouter {
fn run_periodic_jobs(&mut self) {
// Job cadences match the Python LXMRouter jobloop.
if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) {
if self.processing_count % JOB_TRANSIENT_INTERVAL == 0 {
self.propagation_store.clean_transient_caches(now_f64());
}
if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL)
&& self.config.propagation_enabled
{
if self.processing_count % JOB_STORE_INTERVAL == 0 && self.config.propagation_enabled {
self.cull_propagation();
}
if self.processing_count.is_multiple_of(JOB_PEERSYNC_INTERVAL) {
if self.processing_count % JOB_PEERSYNC_INTERVAL == 0 {
self.clean_throttled_peers();
}
if self.processing_count.is_multiple_of(JOB_ROTATE_INTERVAL)
&& self.config.propagation_enabled
{
if self.processing_count % JOB_ROTATE_INTERVAL == 0 && self.config.propagation_enabled {
self.rotate_peers();
}
}
@@ -2293,7 +2404,7 @@ mod tests {
let msg = direct_policy_message();
let msg_hash = msg.hash;
let dest = msg.destination_hash;
router.send(msg);
router.try_send(msg).unwrap();
let actions =
router.process_outbound_with_direct(|message, _now| DirectDeliveryPlanInput {
@@ -2330,7 +2441,7 @@ mod tests {
let mut msg = direct_policy_message();
msg.next_delivery_attempt = now_f64() + 3600.0;
let msg_hash = msg.hash;
router.send(msg);
router.try_send(msg).unwrap();
let actions =
router.process_outbound_with_direct(|_message, _now| DirectDeliveryPlanInput {
@@ -2355,7 +2466,7 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let first = direct_policy_message();
let first_hash = first.hash.expect("first hash");
router.send(first);
router.try_send(first).unwrap();
assert!(router.defer_outbound_for_path_request(&first_hash, 1000.0));
assert_eq!(
@@ -2369,7 +2480,7 @@ mod tests {
let second = direct_policy_message();
let second_hash = second.hash.expect("second hash");
router.send(second);
router.try_send(second).unwrap();
assert!(router.mark_outbound_failed(&second_hash));
assert!(router.pending_outbound.is_empty());
}
@@ -2458,7 +2569,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_deferred_stamps.is_empty());
assert_eq!(router.pending_outbound.len(), 1);
@@ -2467,6 +2578,114 @@ mod tests {
assert_eq!(queued.stamp_value, Some(COST_TICKET));
}
#[test]
fn prepare_outbound_issues_native_reply_ticket_before_signing() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAA; 16];
let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "reply", DeliveryMethod::Direct);
msg.include_ticket = true;
router.prepare_outbound(&mut msg).unwrap();
assert!(msg.msgpack_field_ids.contains(&FIELD_TICKET));
let field = msg.fields.get(&FIELD_TICKET).unwrap();
let value = rmpv::decode::read_value(&mut field.as_slice()).unwrap();
assert_eq!(value.as_array().unwrap().len(), 2);
msg.sign(&key).unwrap();
router.try_send(msg).unwrap();
let hash = router.pending_outbound[0].hash.unwrap();
assert!(router.mark_outbound_delivered(&hash));
let mut next = LxMessage::new(dest, [0xBB; 16], "ticket", "later", DeliveryMethod::Direct);
next.include_ticket = true;
router.prepare_outbound(&mut next).unwrap();
assert!(!next.fields.contains_key(&FIELD_TICKET));
}
#[test]
fn externally_retained_message_updates_ticket_only_when_completed() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAC; 16];
let mut in_flight = LxMessage::new(
dest,
[0xBD; 16],
"ticket",
"proof",
DeliveryMethod::Opportunistic,
);
in_flight.include_ticket = true;
router.prepare_outbound(&mut in_flight).unwrap();
in_flight.sign(&key).unwrap();
let mut before_proof =
LxMessage::new(dest, [0xBD; 16], "ticket", "before", DeliveryMethod::Direct);
before_proof.include_ticket = true;
router.prepare_outbound(&mut before_proof).unwrap();
assert!(before_proof.fields.contains_key(&FIELD_TICKET));
router.complete_outbound_message(in_flight);
let mut after_proof =
LxMessage::new(dest, [0xBD; 16], "ticket", "after", DeliveryMethod::Direct);
after_proof.include_ticket = true;
router.prepare_outbound(&mut after_proof).unwrap();
assert!(!after_proof.fields.contains_key(&FIELD_TICKET));
}
#[test]
fn signed_message_requesting_ticket_fails_instead_of_invalidating_signature() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let mut msg = LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"ticket",
"late",
DeliveryMethod::Direct,
);
msg.include_ticket = true;
msg.sign(&key).unwrap();
assert!(matches!(
router.try_send(msg),
Err(SendError::TicketPreparation {
source: TicketPreparationError::AlreadySigned,
..
})
));
assert!(router.pending_outbound.is_empty());
}
#[test]
fn deliver_inbound_learns_ticket_only_after_signature_validation() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let public = key.public_key();
let source = [0xBB; 16];
let mut sender = LxmRouter::new(RouterConfig::default());
let mut msg = LxMessage::new(
[0xAA; 16],
source,
"ticket",
"learn",
DeliveryMethod::Direct,
);
msg.include_ticket = true;
sender.prepare_outbound(&mut msg).unwrap();
msg.sign(&key).unwrap();
let mut unsigned_receiver = LxmRouter::new(RouterConfig::default());
assert!(unsigned_receiver.deliver_inbound(&msg, false));
assert!(unsigned_receiver.get_outbound_ticket(&source).is_none());
let mut verified = msg.clone();
assert!(verified.verify(&public));
let mut receiver = LxmRouter::new(RouterConfig::default());
assert!(receiver.deliver_inbound(&verified, false));
assert!(receiver.get_outbound_ticket(&source).is_some());
}
#[tokio::test]
async fn test_deferred_stamp_queue_completes_before_outbound_processing() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
@@ -2477,7 +2696,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "defer", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_outbound.is_empty());
assert!(router.pending_deferred_stamps.contains_key(&message_id));
@@ -2521,7 +2740,7 @@ mod tests {
);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_deferred_stamps.contains_key(&message_id));
// Drive entirely from a blocking thread (no implicit runtime).
@@ -2576,7 +2795,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "cancel", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.process_deferred_stamps();
assert!(router.active_deferred_stamp.is_some());
@@ -2621,13 +2840,16 @@ mod tests {
assert!(router.get_inbound_tickets().is_empty());
let token = router.generate_ticket(dest, None);
assert_eq!(router.get_outbound_ticket(&dest), Some(token));
assert!(router.get_outbound_ticket_expiry(&dest).unwrap() > now_f64());
assert!(router.get_outbound_ticket(&dest).is_none());
assert_eq!(router.get_inbound_tickets().len(), 1);
assert_eq!(router.get_inbound_tickets()[0].token, token);
// remember_ticket adds another entry for the same dest.
// A remembered peer ticket is outbound and does not alter the
// locally-issued inbound set.
router.remember_ticket(dest, [0x55; 16], now_f64() + 1000.0);
assert_eq!(router.get_inbound_tickets().len(), 2);
assert_eq!(router.get_inbound_tickets().len(), 1);
assert_eq!(router.get_outbound_ticket(&dest), Some([0x55; 16]));
assert!(router.get_outbound_ticket_expiry(&dest).unwrap() > now_f64());
}
#[test]
@@ -2635,8 +2857,12 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAA; 16];
let expires = now_f64() + 1000.0;
router.remember_ticket(dest, [0x01; 16], expires);
router.remember_ticket(dest, [0x02; 16], expires);
router
.ticket_store
.add_inbound(Ticket::new([0x01; 16], dest, expires));
router
.ticket_store
.add_inbound(Ticket::new([0x02; 16], dest, expires));
// Stamp derived from the SECOND ticket must still validate.
let message_id = [0x33u8; 32];
@@ -2934,6 +3160,38 @@ mod tests {
assert_eq!(router.sync_peer_policies_for_store(6).len(), 1);
}
#[test]
fn store_generation_scheduler_falls_back_to_backoff_expired_unresponsive_peers() {
let alive_hash = [0x21; 16];
let fallback_hash = [0x22; 16];
let mut router = LxmRouter::new(RouterConfig::default());
let alive = LxmPeer::new(alive_hash);
let mut fallback = LxmPeer::new(fallback_hash);
fallback.alive = false;
fallback.next_sync_attempt = 0.0;
assert!(router.add_peer(alive));
assert!(router.add_peer(fallback));
let policies = router.sync_peer_policies_for_store(1);
assert_eq!(
policies
.iter()
.map(|policy| policy.peer_hash)
.collect::<Vec<_>>(),
vec![alive_hash]
);
router.peers.get_mut(&alive_hash).unwrap().begin_sync();
let policies = router.sync_peer_policies_for_store(1);
assert_eq!(
policies
.iter()
.map(|policy| policy.peer_hash)
.collect::<Vec<_>>(),
vec![fallback_hash]
);
}
#[test]
fn test_validate_stamp() {
let router = LxmRouter::new(RouterConfig::default());
@@ -2955,7 +3213,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
assert_eq!(router.pending_outbound.len(), 1);
assert_eq!(router.pending_outbound[0].state, MessageState::Outbound);
}
@@ -2990,7 +3248,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS + 1;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3010,7 +3268,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3064,7 +3322,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_direct = actions
@@ -3088,7 +3346,7 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_propagated = actions
@@ -3107,7 +3365,7 @@ mod tests {
"Content",
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_opportunistic = actions
@@ -3126,7 +3384,10 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
assert!(matches!(
router.try_send(msg),
Err(SendError::MissingOutboundPropagationNode(_))
));
assert!(
router.pending_outbound.is_empty(),
@@ -3148,7 +3409,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1);
@@ -3174,7 +3435,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1);
@@ -3199,7 +3460,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
@@ -3221,13 +3482,15 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let node = [0xCC; 16];
router.set_outbound_propagation_node(Some(node));
router.send(LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"Propagated",
"Content",
DeliveryMethod::Propagated,
));
router
.try_send(LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"Propagated",
"Content",
DeliveryMethod::Propagated,
))
.unwrap();
assert_eq!(
router.trigger_outbound_for_propagation_node_announce([0xDD; 16], b"not-msgpack"),
@@ -3255,7 +3518,7 @@ mod tests {
);
// Anchor the timestamp comfortably past the expiry window.
msg.timestamp = now_f64() - (MESSAGE_EXPIRY as f64) - 60.0;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3287,7 +3550,7 @@ mod tests {
// Simulate one failed attempt very recently.
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64() - 1.0; // 1 s ago, inside the 10 s window.
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert!(
@@ -3317,7 +3580,7 @@ mod tests {
);
msg.last_delivery_attempt = now_f64() - 1.0;
router.set_outbound_propagation_node(Some([0xCC; 16]));
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert!(
@@ -3343,7 +3606,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3374,7 +3637,7 @@ mod tests {
DeliveryMethod::Opportunistic,
);
msg.sign(&signing_key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.tick_with_encryptor(|_dest, plaintext| Ok(plaintext.to_vec()));
@@ -3451,6 +3714,40 @@ mod tests {
);
}
#[test]
fn opportunistic_transport_backpressure_requeues_instead_of_dropping() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let dest_hash = [0xA1; 16];
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
tx.try_send(
rns_transport::messages::TransportMessage::DeregisterDestination { hash: [0xF0; 16] },
)
.unwrap();
let mut router = LxmRouter::new(RouterConfig::default());
router.set_transport(tx);
let mut message = LxMessage::new(
dest_hash,
[0xB1; 16],
"defer",
"payload",
DeliveryMethod::Opportunistic,
);
message.sign(&key).unwrap();
let message_hash = message.hash;
router.execute_actions_with_encryptor(
vec![OutboundAction::DeliverOpportunistic { message, dest_hash }],
|_dest, plaintext| Ok(plaintext.to_vec()),
);
assert!(matches!(
rx.try_recv().unwrap(),
rns_transport::messages::TransportMessage::DeregisterDestination { .. }
));
assert_eq!(router.pending_outbound.len(), 1);
assert_eq!(router.pending_outbound.first().unwrap().hash, message_hash);
}
#[test]
fn test_execute_actions_without_encryptor_does_not_send_opportunistic_plaintext() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
@@ -3802,20 +4099,24 @@ mod tests {
config.ext.processing_limit = Some(1);
let mut router = LxmRouter::new(config);
router.send(LxMessage::new(
[0x01; 16],
[0; 16],
"a",
"b",
DeliveryMethod::Direct,
));
router.send(LxMessage::new(
[0x02; 16],
[0; 16],
"c",
"d",
DeliveryMethod::Direct,
));
router
.try_send(LxMessage::new(
[0x01; 16],
[0; 16],
"a",
"b",
DeliveryMethod::Direct,
))
.unwrap();
router
.try_send(LxMessage::new(
[0x02; 16],
[0; 16],
"c",
"d",
DeliveryMethod::Direct,
))
.unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3843,7 +4144,7 @@ mod tests {
&large_content,
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
assert_eq!(router.pending_outbound[0].method, DeliveryMethod::Direct);
}
@@ -3858,7 +4159,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3885,7 +4186,7 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3907,7 +4208,7 @@ mod tests {
"Content",
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3935,7 +4236,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.sign(&signing_key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.tick();
+245 -66
View File
@@ -1,20 +1,22 @@
//! LXMF Ticket system: bypass PoW with pre-shared 16-byte tokens.
//! LXMF ticket lifecycle and persistence state.
//!
//! Trusted peers may exchange tickets that bypass stamp requirements for a
//! fixed expiry window. Tickets are reusable until expiry and renewed once
//! within `TICKET_RENEW` of expiring.
//! A ticket issued to a peer is an *inbound* ticket: it validates that peer's
//! future stamps. A ticket learned from a peer is an *outbound* ticket: it is
//! used to stamp future messages to that peer. Keeping those directions
//! separate is required for Python LXMF compatibility.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::constants::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ticket {
pub token: [u8; 16],
pub destination_hash: [u8; 16],
/// Expiry timestamp (Unix epoch seconds).
pub expires: f64,
pub used: bool,
}
impl Ticket {
@@ -23,22 +25,90 @@ impl Ticket {
token,
destination_hash,
expires,
used: false,
}
}
pub fn is_valid(&self, now: f64) -> bool {
!self.used && now < self.expires
now < self.expires
}
pub fn should_renew(&self, now: f64) -> bool {
self.is_valid(now) && (self.expires - now) < TICKET_RENEW as f64
self.is_valid(now) && (self.expires - now) <= TICKET_RENEW as f64
}
/// Encode Python's native MessagePack ticket field `[expires, token]`.
pub fn encode_field(&self) -> Result<Vec<u8>, rmpv::encode::Error> {
let value = rmpv::Value::Array(vec![
rmpv::Value::F64(self.expires),
rmpv::Value::Binary(self.token.to_vec()),
]);
let mut encoded = Vec::new();
rmpv::encode::write_value(&mut encoded, &value)?;
Ok(encoded)
}
/// Decode a signed inbound Python-compatible ticket field.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
if cursor.position() != encoded.len() as u64 {
return None;
}
let values = value.as_array()?;
if values.len() != 2 {
return None;
}
let expires = values[0].as_f64()?;
let token = values[1].as_slice()?;
if !expires.is_finite() || expires <= now || token.len() != TICKET_LENGTH {
return None;
}
let mut token_array = [0u8; TICKET_LENGTH];
token_array.copy_from_slice(token);
Some(Self::new(token_array, destination_hash, expires))
}
}
/// Versioned, serializable ticket state.
///
/// Version 1 replaces the former flat `Vec<Ticket>` representation. The flat
/// form could not distinguish tickets issued to peers from tickets learned
/// from peers and therefore could not implement Python's reply semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TicketStoreSnapshot {
#[serde(default = "ticket_store_version")]
pub version: u8,
#[serde(default)]
pub outbound: Vec<Ticket>,
#[serde(default)]
pub inbound: Vec<Ticket>,
#[serde(default)]
pub last_deliveries: HashMap<[u8; 16], f64>,
}
const fn ticket_store_version() -> u8 {
1
}
impl Default for TicketStoreSnapshot {
fn default() -> Self {
Self {
version: ticket_store_version(),
outbound: Vec::new(),
inbound: Vec::new(),
last_deliveries: HashMap::new(),
}
}
}
#[derive(Debug, Default)]
pub struct TicketStore {
tickets: Vec<Ticket>,
/// One learned ticket per destination, matching Python's outbound map.
outbound: HashMap<[u8; 16], Ticket>,
/// Multiple locally issued tickets may overlap during renewal/grace.
inbound: Vec<Ticket>,
/// Last successful delivery of a message containing a ticket.
last_deliveries: HashMap<[u8; 16], f64>,
}
impl TicketStore {
@@ -46,34 +116,130 @@ impl TicketStore {
Self::default()
}
pub fn add(&mut self, ticket: Ticket) {
self.tickets.push(ticket);
/// Store a ticket issued locally for `destination_hash`.
pub fn add_inbound(&mut self, ticket: Ticket) {
if self.inbound.iter().any(|existing| {
existing.destination_hash == ticket.destination_hash && existing.token == ticket.token
}) {
return;
}
self.inbound.push(ticket);
}
pub fn find(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.tickets
/// Store or replace the ticket learned from `destination_hash`.
pub fn remember_outbound(&mut self, ticket: Ticket) {
self.outbound.insert(ticket.destination_hash, ticket);
}
/// Return the valid ticket learned from `destination_hash`.
pub fn find_outbound(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.outbound
.get(destination_hash)
.filter(|ticket| ticket.is_valid(now))
}
/// Return every valid ticket issued locally for `destination_hash`.
pub fn inbound_tokens(&self, destination_hash: &[u8; 16], now: f64) -> Vec<[u8; 16]> {
self.inbound
.iter()
.find(|t| &t.destination_hash == destination_hash && t.is_valid(now))
.filter(|ticket| &ticket.destination_hash == destination_hash && ticket.is_valid(now))
.map(|ticket| ticket.token)
.collect()
}
/// Drop expired and used tickets (past TICKET_GRACE).
/// Generate or reuse a ticket for a peer, respecting Python's delivery
/// interval and renewal window. `None` means a ticket was delivered too
/// recently and should not be included in this message.
pub fn issue_for(
&mut self,
destination_hash: [u8; 16],
expiry_secs: u64,
now: f64,
) -> Option<Ticket> {
if !self.should_issue_for(&destination_hash, now) {
return None;
}
if let Some(ticket) = self.inbound.iter().find(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
}) {
return Some(ticket.clone());
}
let token: [u8; TICKET_LENGTH] = rand::random();
let ticket = Ticket::new(token, destination_hash, now + expiry_secs as f64);
self.inbound.push(ticket.clone());
Some(ticket)
}
pub fn should_issue_for(&self, destination_hash: &[u8; 16], now: f64) -> bool {
!self
.last_deliveries
.get(destination_hash)
.is_some_and(|last| now - *last < TICKET_INTERVAL as f64)
}
pub fn mark_ticket_delivered(&mut self, destination_hash: [u8; 16], delivered_at: f64) {
self.last_deliveries.insert(destination_hash, delivered_at);
}
/// Drop expired outbound tickets and inbound tickets after their grace
/// period. Delivery timestamps need only survive one interval.
pub fn cull(&mut self, now: f64) {
self.tickets
.retain(|t| !t.used && now < t.expires + TICKET_GRACE as f64);
self.outbound.retain(|_, ticket| ticket.is_valid(now));
self.inbound
.retain(|ticket| now < ticket.expires + TICKET_GRACE as f64);
self.last_deliveries
.retain(|_, delivered| now - *delivered < TICKET_INTERVAL as f64);
}
pub fn count_valid(&self, now: f64) -> usize {
self.tickets.iter().filter(|t| t.is_valid(now)).count()
self.outbound
.values()
.filter(|ticket| ticket.is_valid(now))
.count()
+ self
.inbound
.iter()
.filter(|ticket| ticket.is_valid(now))
.count()
}
/// Snapshot of all stored tickets (including expired / used).
pub fn all(&self) -> &[Ticket] {
&self.tickets
pub fn inbound(&self) -> &[Ticket] {
&self.inbound
}
/// Replace the entire ticket set — used when restoring from persisted state.
pub fn replace_all(&mut self, tickets: Vec<Ticket>) {
self.tickets = tickets;
pub fn snapshot(&self) -> TicketStoreSnapshot {
TicketStoreSnapshot {
version: ticket_store_version(),
outbound: self.outbound.values().cloned().collect(),
inbound: self.inbound.clone(),
last_deliveries: self.last_deliveries.clone(),
}
}
pub fn replace_snapshot(&mut self, snapshot: TicketStoreSnapshot) {
self.outbound = snapshot
.outbound
.into_iter()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = snapshot.inbound;
self.last_deliveries = snapshot.last_deliveries;
}
/// Migrate the legacy flat representation conservatively. Old Rust used
/// every entry for both directions, so retaining entries in both stores
/// preserves working stamps while all new state is direction-correct.
pub fn replace_legacy(&mut self, tickets: Vec<Ticket>) {
self.outbound = tickets
.iter()
.cloned()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = tickets;
self.last_deliveries.clear();
}
}
@@ -82,54 +248,67 @@ mod tests {
use super::*;
#[test]
fn test_ticket_validity() {
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(999.0));
assert!(!ticket.is_valid(1001.0));
}
#[test]
fn test_ticket_used() {
// `used` survives only for persisted-state compat; is_valid must
// still reject such entries.
let mut ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(500.0));
ticket.used = true;
assert!(!ticket.is_valid(500.0));
}
#[test]
fn test_ticket_renew() {
let expires = 2_000_000.0;
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], expires);
// TICKET_RENEW is ~1 week; close to expiry should trigger, far should not.
assert!(ticket.should_renew(expires - 1.0));
assert!(!ticket.should_renew(0.0));
}
#[test]
fn test_ticket_store() {
fn direction_state_is_separate() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
store.add_inbound(Ticket::new([0x01; 16], dest, 2_000.0));
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
assert!(store.find_outbound(&dest, 1_000.0).is_none());
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.add(Ticket::new([0x02; 16], dest, 2000.0));
store.add(Ticket::new([0x03; 16], [0xCC; 16], 1500.0));
assert_eq!(store.count_valid(500.0), 3);
assert_eq!(store.count_valid(1500.0), 1);
let found = store.find(&dest, 500.0);
assert!(found.is_some());
store.remember_outbound(Ticket::new([0x02; 16], dest, 2_000.0));
assert_eq!(
store.find_outbound(&dest, 1_000.0).unwrap().token,
[0x02; 16]
);
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
}
#[test]
fn test_ticket_store_cull() {
fn issuance_reuses_then_renews_and_throttles_after_delivery() {
let mut store = TicketStore::new();
store.add(Ticket::new([0x01; 16], [0xBB; 16], 100.0));
store.add(Ticket::new([0x02; 16], [0xBB; 16], 99999.0));
let dest = [0xBB; 16];
let first = store.issue_for(dest, TICKET_EXPIRY, 1_000.0).unwrap();
let reused = store.issue_for(dest, TICKET_EXPIRY, 2_000.0).unwrap();
assert_eq!(reused.token, first.token);
store.cull(100.0 + TICKET_GRACE as f64 + 1.0);
assert_eq!(store.count_valid(99999.0 - 1.0), 1);
store.mark_ticket_delivered(dest, 2_000.0);
assert!(store.issue_for(dest, TICKET_EXPIRY, 2_001.0).is_none());
let renewed = store
.issue_for(dest, TICKET_EXPIRY, 2_000.0 + TICKET_INTERVAL as f64)
.unwrap();
assert_eq!(renewed.token, first.token);
let near_expiry = first.expires - TICKET_RENEW as f64 + 1.0;
let replacement = store.issue_for(dest, TICKET_EXPIRY, near_expiry).unwrap();
assert_ne!(replacement.token, first.token);
}
#[test]
fn snapshot_roundtrip_preserves_directions_and_delivery_gate() {
let mut store = TicketStore::new();
let dest = [0xCC; 16];
store.add_inbound(Ticket::new([1; 16], dest, 9_999.0));
store.remember_outbound(Ticket::new([2; 16], dest, 9_999.0));
store.mark_ticket_delivered(dest, 100.0);
let mut restored = TicketStore::new();
restored.replace_snapshot(store.snapshot());
assert_eq!(restored.inbound_tokens(&dest, 200.0), vec![[1; 16]]);
assert_eq!(restored.find_outbound(&dest, 200.0).unwrap().token, [2; 16]);
assert!(restored.issue_for(dest, TICKET_EXPIRY, 200.0).is_none());
}
#[test]
fn ticket_field_is_native_python_shape_and_rejects_expired_values() {
let ticket = Ticket::new([0x42; 16], [0x11; 16], 2_000.0);
let encoded = ticket.encode_field().unwrap();
let value = rmpv::decode::read_value(&mut encoded.as_slice()).unwrap();
let values = value.as_array().unwrap();
assert_eq!(values[0].as_f64(), Some(2_000.0));
assert_eq!(values[1].as_slice(), Some(&[0x42; 16][..]));
let decoded = Ticket::decode_field([0x11; 16], &encoded, 1_000.0).unwrap();
assert_eq!(decoded, ticket);
assert!(Ticket::decode_field([0x11; 16], &encoded, 2_000.0).is_none());
}
}
+3
View File
@@ -23,6 +23,9 @@ base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
[[bin]]
name = "lxmd-rs"
path = "src/bin/lxmd-rs.rs"
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -106,6 +106,7 @@ pub(super) enum PnValidationOutcome {
pub(super) struct PnValidationClaim {
link_id: LinkId,
outcome: PnValidationOutcome,
peer_destination_hash: Option<[u8; 16]>,
}
impl PnValidationClaim {
@@ -117,6 +118,10 @@ impl PnValidationClaim {
self.outcome
}
pub(super) fn peer_destination_hash(self) -> Option<[u8; 16]> {
self.peer_destination_hash
}
pub(super) fn should_close_link(self) -> bool {
matches!(
self.outcome,
@@ -590,7 +595,11 @@ impl PnInboundRuntime {
self.install_untracked_invalid_throttle(pending.peer_destination_hash, now);
}
Some(PnValidationClaim { link_id, outcome })
Some(PnValidationClaim {
link_id,
outcome,
peer_destination_hash: pending.peer_destination_hash,
})
}
fn install_untracked_invalid_throttle(
+166 -21
View File
@@ -71,7 +71,7 @@ impl PythonLxmdConfig {
delivery_transfer_max_accepted_size: get_float_or_floor(
lxmf,
"delivery_transfer_max_accepted_size",
1000.0,
1.0,
0.38,
),
on_inbound: lxmf
@@ -227,7 +227,10 @@ impl Default for DaemonConfig {
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
delivery_transfer_max_accepted_size: 1000.0,
// Current Python lxmd 1.1.0 deliberately narrows the standalone
// daemon default to 1 decimal KB. The reusable RouterConfig keeps
// its 1000 KB library default, matching Python LXMRouter.
delivery_transfer_max_accepted_size: 1.0,
}
}
}
@@ -321,16 +324,17 @@ impl DaemonConfig {
dc.outbound_propagation_node = Some(trimmed.to_string());
}
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none()
&& let Some(cost) = sec.get_uint("propagation_stamp_cost")
{
dc.propagation_stamp_cost = cost as u8;
if get_int(Some(sec), "propagation_stamp_cost_target").is_none() {
if let Some(cost) = sec.get_uint("propagation_stamp_cost") {
dc.propagation_stamp_cost = cost as u8;
}
}
if get_float(Some(sec), "propagation_message_max_accepted_size").is_none()
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
&& let Some(limit) = sec.get_uint("propagation_limit")
{
dc.propagation_limit_kb = limit as usize;
if let Some(limit) = sec.get_uint("propagation_limit") {
dc.propagation_limit_kb = limit as usize;
}
}
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -339,14 +343,14 @@ impl DaemonConfig {
if !dc.auth_required {
dc.auth_required = sec.get_bool_or("auth_required", false);
}
if dc.control_allowed.is_empty()
&& let Some(allowed) = sec.get("allowed")
{
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if dc.control_allowed.is_empty() {
if let Some(allowed) = sec.get("allowed") {
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
}
@@ -403,12 +407,12 @@ pub fn create_router_with_transport(
pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> {
use std::process::Command;
let parts: Vec<&str> = command.split_whitespace().collect();
let parts = split_command_line(command)?;
if parts.is_empty() {
return Ok(());
}
let mut cmd = Command::new(parts[0]);
let mut cmd = Command::new(&parts[0]);
for arg in &parts[1..] {
cmd.arg(arg);
}
@@ -421,10 +425,151 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
Ok(())
}
/// Parse the configured hook using the shell-like quoting supported by
/// Python's `shlex.split()`, without invoking a shell.
fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
use std::io::{Error, ErrorKind};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut parts = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut escaped = false;
let mut started = false;
for ch in command.chars() {
if escaped {
current.push(ch);
escaped = false;
started = true;
continue;
}
match quote {
Quote::Single => {
if ch == '\'' {
quote = Quote::None;
} else {
current.push(ch);
}
started = true;
}
Quote::Double => {
if ch == '"' {
quote = Quote::None;
} else if ch == '\\' {
escaped = true;
} else {
current.push(ch);
}
started = true;
}
Quote::None => match ch {
'\'' => {
quote = Quote::Single;
started = true;
}
'"' => {
quote = Quote::Double;
started = true;
}
'\\' => {
escaped = true;
started = true;
}
c if c.is_whitespace() => {
if started {
parts.push(std::mem::take(&mut current));
started = false;
}
}
_ => {
current.push(ch);
started = true;
}
},
}
}
if escaped || quote != Quote::None {
return Err(Error::new(
ErrorKind::InvalidInput,
"unterminated quote or escape in on_inbound command",
));
}
if started {
parts.push(current);
}
Ok(parts)
}
/// Persist a received message before invoking the configured hook. Keeping
/// both operations in one blocking job prevents the hook from racing the
/// atomic file write and keeps process execution off the async daemon loop.
pub fn persist_inbound_and_execute(
message_path: &std::path::Path,
packed: &[u8],
command: Option<&str>,
) -> std::io::Result<()> {
lxmf_core::persist::write_file_atomic(message_path, packed)?;
if let Some(command) = command {
execute_on_inbound(command, &message_path.to_string_lossy())?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_inbound_parser_matches_shell_like_quoting_without_a_shell() {
assert_eq!(
split_command_line("/tmp/a\\ b --label 'two words' \"\" --quoted=\"x y\"").unwrap(),
["/tmp/a b", "--label", "two words", "", "--quoted=x y"]
);
assert!(split_command_line("hook 'unterminated").is_err());
assert!(split_command_line("hook trailing\\").is_err());
}
#[cfg(unix)]
#[test]
fn inbound_hook_observes_fully_persisted_message() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let hook = dir.path().join("hook with spaces.sh");
let message = dir.path().join("message.lxm");
let observed = dir.path().join("observed");
std::fs::write(
&hook,
"#!/bin/sh\nexpected=$1\nobserved=$2\nmessage=$3\ncmp \"$expected\" \"$message\" && printf ok > \"$observed\"\n",
)
.unwrap();
let mut permissions = std::fs::metadata(&hook).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&hook, permissions).unwrap();
let expected = dir.path().join("expected");
std::fs::write(&expected, b"complete payload").unwrap();
let command = format!(
"'{}' '{}' '{}'",
hook.display(),
expected.display(),
observed.display()
);
persist_inbound_and_execute(&message, b"complete payload", Some(&command)).unwrap();
assert_eq!(std::fs::read(&message).unwrap(), b"complete payload");
assert_eq!(std::fs::read(&observed).unwrap(), b"ok");
}
#[test]
fn test_default_config() {
let dc = DaemonConfig::default();
@@ -452,7 +597,7 @@ mod tests {
assert!(!dc.node_announce_at_start);
assert_eq!(dc.node_announce_interval, None);
assert_eq!(dc.message_storage_limit, Some(500_000_000));
assert_eq!(dc.delivery_transfer_max_accepted_size, 1000.0);
assert_eq!(dc.delivery_transfer_max_accepted_size, 1.0);
assert!(!dc.from_static_only);
}
@@ -465,7 +610,7 @@ mod tests {
assert!(!py.peer_announce_at_start);
assert_eq!(py.peer_announce_interval, None);
assert_eq!(py.peer_stamp_cost, 12);
assert_eq!(py.delivery_transfer_max_accepted_size, 1000.0);
assert_eq!(py.delivery_transfer_max_accepted_size, 1.0);
assert_eq!(py.on_inbound, None);
assert!(!py.enable_propagation_node);
assert_eq!(py.node_name, None);
@@ -588,7 +733,7 @@ propagation_transfer_max_accepted_size = 12
let rc = dc.to_router_config();
assert!(!rc.propagation_enabled);
assert_eq!(rc.max_peers, 20);
assert_eq!(rc.delivery_limit_kb, 1000.0);
assert_eq!(rc.delivery_limit_kb, 1.0);
assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0);
assert_eq!(rc.propagation_limit_kb, 256);
assert_eq!(rc.sync_limit_kb, 10_240);
+1 -1
View File
@@ -224,7 +224,7 @@ announce_at_start = no
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1000
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
+12 -9
View File
@@ -92,10 +92,10 @@ pub async fn resolve_remote_identity_hash(
let wait = async {
while let Some(event) = ann_rx.recv().await {
if event.destination_hash == remote_destination_hash
&& let Some(identity_hash) = event.identity_hash
{
return Ok(identity_hash);
if event.destination_hash == remote_destination_hash {
if let Some(identity_hash) = event.identity_hash {
return Ok(identity_hash);
}
}
}
Err(LinkClientError::PubkeyNotDiscovered)
@@ -123,10 +123,10 @@ pub fn decode_control_response(response: &[u8]) -> ControlResponse {
return ControlResponse::Success;
};
if let Some(code) = value.as_u64()
&& let Some(error) = peer_error_from_code(code as u8)
{
return ControlResponse::Error(error);
if let Some(code) = value.as_u64() {
if let Some(error) = peer_error_from_code(code as u8) {
return ControlResponse::Error(error);
}
}
if value.is_nil() {
@@ -193,6 +193,9 @@ pub fn encode_router_control_stats(
.as_ref()
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.handled_messages))
.unwrap_or_else(|| peer.unhandled_messages() as usize);
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -269,7 +272,7 @@ pub fn encode_router_control_stats(
(Value::String("incoming".into()), Value::from(peer.incoming)),
(
Value::String("unhandled".into()),
Value::from(peer.unhandled_messages() as u64),
Value::from(unhandled as u64),
),
]),
),
+6 -5
View File
@@ -228,7 +228,7 @@ fn example_config_exits_before_runtime_initialisation() {
assert!(text.contains("display_name = Anonymous Peer"));
assert!(text.contains("announce_at_start = no"));
assert!(text.contains("# stamp_cost = 12"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1000"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1"));
assert!(text.contains("[propagation]"));
assert!(text.contains("enable_node = no"));
assert!(text.contains("announce_interval = 360"));
@@ -289,7 +289,7 @@ fn clap_requires_send_argument() {
}
#[test]
fn status_and_peers_query_control_and_timeout_without_daemon() {
fn status_and_peers_fail_before_link_without_an_online_interface() {
let lxmf_dir = TestDir::new("lxmf");
let rns_dir = TestDir::new("rns");
write_rust_identity(&lxmf_dir.path().join("identity"));
@@ -323,12 +323,13 @@ discover_interfaces = No
assert_eq!(
output.status.code(),
Some(200),
"expected Python-compatible control timeout, got:\n{}",
"expected interface-readiness failure, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Getting lxmd statistics timed out, exiting now"),
"expected Python-compatible control timeout text, got:\n{}",
combined_output(&output)
.contains("No online Reticulum interface became available, exiting now"),
"expected specific interface-readiness error, got:\n{}",
combined_output(&output)
);
assert!(