propagation: complete live peer offer sync

This commit is contained in:
DeFiDude committed 2026-07-25 23:18:26 -06:00
1 parent b47a2d29b9
commit d22fa362fa
7 files changed
+3199 -184

No files matched your search

+66 -25
View File
@@ -144,6 +144,17 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
/// dropped because it duplicated this function's checks and every
/// in-tree caller called both back-to-back.
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_i64().and_then(|number| number.try_into().ok()))
.or_else(|| {
value.as_f64().and_then(|number| {
(number.is_finite() && number >= 0.0).then_some(number as u64)
})
})
}
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
if arr.len() < 7 {
@@ -155,38 +166,27 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
.or_else(|| arr[1].as_u64().map(|u| u as i64))
.or_else(|| arr[1].as_f64().map(|f| f as i64))?;
let node_state = arr[2].as_bool()?;
let transfer_limit = arr[3]
.as_u64()
.or_else(|| arr[3].as_i64().map(|i| i as u64))
.or_else(|| arr[3].as_f64().map(|f| f as u64))?;
let sync_limit = arr[4]
.as_u64()
.or_else(|| arr[4].as_i64().map(|i| i as u64))
.or_else(|| arr[4].as_f64().map(|f| f as u64))?;
let transfer_limit = nonnegative_u64(&arr[3])?;
let sync_limit = nonnegative_u64(&arr[4])?;
let costs = arr[5].as_array()?;
if costs.len() < 3 {
return None;
}
let stamp_cost = costs[0]
.as_u64()
.or_else(|| costs[0].as_i64().map(|i| i as u64))? as u8;
let stamp_flex = costs[1]
.as_u64()
.or_else(|| costs[1].as_i64().map(|i| i as u64))? as u8;
let peering_cost = costs[2]
.as_u64()
.or_else(|| costs[2].as_i64().map(|i| i as u64))? as u8;
let stamp_cost = u8::try_from(nonnegative_u64(&costs[0])?).ok()?;
let stamp_flex = u8::try_from(nonnegative_u64(&costs[1])?).ok()?;
let peering_cost = u8::try_from(nonnegative_u64(&costs[2])?).ok()?;
// Python's `pn_announce_data_is_valid()` requires the metadata element to
// be a map. Unknown keys and non-binary values are ignored here because
// the typed Rust API can only retain metadata it can represent safely.
let mut metadata = HashMap::new();
if let Some(map) = arr[6].as_map() {
for (k, v) in map {
if let (Some(key), Some(val)) = (
k.as_u64().map(|u| u as u8),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
for (k, v) in arr[6].as_map()? {
if let (Some(key), Some(val)) = (
k.as_u64().and_then(|number| number.try_into().ok()),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
}
@@ -715,6 +715,47 @@ mod tests {
assert!(parse_pn_announce_data(&[]).is_none());
assert!(parse_pn_announce_data(&[0x91, 0xC2]).is_none());
assert!(parse_pn_announce_data(&[0x01]).is_none());
let non_map_metadata = rmpv::Value::Array(vec![
rmpv::Value::Boolean(false),
rmpv::Value::from(1_777_716_440u64),
rmpv::Value::Boolean(true),
rmpv::Value::from(10_240),
rmpv::Value::from(10_240),
rmpv::Value::Array(vec![
rmpv::Value::from(16),
rmpv::Value::from(3),
rmpv::Value::from(18),
]),
rmpv::Value::Array(Vec::new()),
]);
assert!(
parse_pn_announce_data(&crate::encode_value(&non_map_metadata)).is_none(),
"Python rejects propagation announces whose metadata is not a map"
);
}
#[test]
fn test_pn_announce_data_rejects_wrapping_policy_values() {
use rmpv::Value;
let encode = |transfer_limit: Value, stamp_cost: Value| {
let value = Value::Array(vec![
Value::Boolean(false),
Value::from(1_777_716_440u64),
Value::Boolean(true),
transfer_limit,
Value::from(10240),
Value::Array(vec![stamp_cost, Value::from(3), Value::from(18)]),
Value::Map(vec![]),
]);
let mut packed = Vec::new();
rmpv::encode::write_value(&mut packed, &value).unwrap();
packed
};
assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none());
assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none());
}
#[test]
+489 -19
View File
@@ -2,12 +2,15 @@
//!
//! Python reference: LXMF/LXMPeer.py.
use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::constants::*;
use crate::types::PropagationTransientId;
type StoredPeer = (
type LegacyStoredPeer = (
Vec<u8>,
f64,
u32,
@@ -19,6 +22,133 @@ type StoredPeer = (
Vec<Vec<u8>>,
);
const STORED_PEER_VERSION: u8 = 2;
const MAX_PEER_METADATA_ENTRIES: usize = 16;
const MAX_PEER_METADATA_VALUE_BYTES: usize = 1024;
const MAX_PEER_METADATA_BYTES: usize = 4096;
fn bounded_peer_metadata(metadata: Option<HashMap<u8, Vec<u8>>>) -> Option<HashMap<u8, Vec<u8>>> {
let metadata = metadata?;
let mut entries = metadata.into_iter().collect::<Vec<_>>();
entries.sort_by_key(|(key, _)| *key);
let mut retained = HashMap::new();
let mut retained_bytes = 0usize;
for (key, value) in entries.into_iter().take(MAX_PEER_METADATA_ENTRIES) {
if value.len() > MAX_PEER_METADATA_VALUE_BYTES {
continue;
}
let entry_bytes = 1usize.saturating_add(value.len());
if retained_bytes.saturating_add(entry_bytes) > MAX_PEER_METADATA_BYTES {
continue;
}
retained_bytes += entry_bytes;
retained.insert(key, value);
}
Some(retained)
}
/// Versioned peer persistence used by propagation sync.
///
/// The original Rust format was a nine-element tuple. Readers continue to
/// accept that tuple, while new writes retain the announce-derived policy
/// needed to prepare a correct outbound offer after restart.
#[derive(Debug, Serialize, Deserialize)]
struct StoredPeerV2 {
version: u8,
destination_hash: Vec<u8>,
last_sync: f64,
unreachable_count: u32,
peering_cost: u8,
stamp_cost: Option<u8>,
stamp_cost_flexibility: Option<u8>,
autopeered: bool,
is_static: bool,
handled_ids: Vec<Vec<u8>>,
peering_timebase: f64,
propagation_transfer_limit: Option<f64>,
propagation_sync_limit: Option<f64>,
peering_key: Option<(Vec<u8>, u32)>,
metadata: Option<HashMap<u8, Vec<u8>>>,
last_heard: f64,
alive: bool,
}
/// Immutable inputs for one outbound propagation offer.
///
/// `LxmPeer` remains the authoritative mutable owner. The network task gets a
/// clone of this snapshot so offer selection cannot silently fall back to a
/// newly-created peer that lacks announce or handled-message state.
#[derive(Debug, Clone, PartialEq)]
pub struct OutboundOfferPolicy {
pub peer_hash: [u8; 16],
pub handled_messages: HashSet<PropagationTransientId>,
pub stamp_cost: Option<u8>,
pub stamp_cost_flexibility: Option<u8>,
pub minimum_stamp_cost: u8,
pub peering_cost: u8,
pub propagation_transfer_limit: Option<f64>,
pub propagation_sync_limit: Option<f64>,
pub peering_key: Vec<u8>,
pub peering_key_value: Option<u32>,
pub peering_timebase: f64,
pub autopeered: bool,
pub is_static: bool,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
}
impl OutboundOfferPolicy {
/// Compatibility policy for callers that only know a peer hash.
///
/// This preserves the old unbounded selection behavior. Production
/// callers should construct a snapshot from the authoritative `LxmPeer`.
pub fn unrestricted(peer_hash: [u8; 16]) -> Self {
Self {
peer_hash,
handled_messages: HashSet::new(),
stamp_cost: None,
stamp_cost_flexibility: None,
minimum_stamp_cost: 0,
peering_cost: PEERING_COST,
propagation_transfer_limit: None,
propagation_sync_limit: None,
peering_key: Vec::new(),
peering_key_value: None,
peering_timebase: 0.0,
autopeered: false,
is_static: false,
metadata: None,
}
}
pub(crate) fn to_peer(&self) -> LxmPeer {
let mut peer = LxmPeer::new(self.peer_hash);
self.apply_to_peer(&mut peer);
peer
}
pub(crate) fn apply_to_peer(&self, peer: &mut LxmPeer) {
if self.peering_timebase >= peer.peering_timebase {
peer.peering_timebase = self.peering_timebase;
peer.stamp_cost = self.stamp_cost;
peer.stamp_cost_flexibility = self.stamp_cost_flexibility;
peer.peering_cost = self.peering_cost;
peer.propagation_transfer_limit = self.propagation_transfer_limit;
peer.propagation_sync_limit = self.propagation_sync_limit;
peer.peering_key = self.peering_key_value.and_then(|value| {
let stamp: [u8; 32] = self.peering_key.clone().try_into().ok()?;
Some((stamp, value))
});
peer.autopeered = self.autopeered;
peer.is_static = self.is_static;
peer.metadata = self.metadata.clone();
}
peer.handled_messages
.extend(self.handled_messages.iter().copied());
}
}
/// An LXMF peer propagation node.
#[derive(Debug)]
pub struct LxmPeer {
@@ -58,11 +188,15 @@ pub struct LxmPeer {
pub last_sync_attempt: f64,
pub next_sync_attempt: f64,
pub sync_backoff: f64,
pub metadata: Option<Vec<u8>>,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
/// Last local propagation-store revision conclusively processed by this
/// peer. This is intentionally process-local because node revisions reset
/// when the store is reconstructed at startup.
pub last_offer_generation: u64,
/// Static peers are operator-configured; autopeered peers come from announces.
pub is_static: bool,
/// Message hashes already handled by this peer, for sync filtering.
pub handled_messages: std::collections::HashSet<PropagationTransientId>,
pub handled_messages: HashSet<PropagationTransientId>,
}
impl LxmPeer {
@@ -100,8 +234,9 @@ impl LxmPeer {
next_sync_attempt: 0.0,
sync_backoff: 0.0,
metadata: None,
last_offer_generation: 0,
is_static: false,
handled_messages: std::collections::HashSet::new(),
handled_messages: HashSet::new(),
}
}
@@ -118,18 +253,115 @@ impl LxmPeer {
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> Self {
Self::from_announce_with_metadata(
destination_hash,
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
None,
)
}
/// Construct a peer from announce data, retaining bounded metadata.
#[allow(clippy::too_many_arguments)]
pub fn from_announce_with_metadata(
destination_hash: [u8; 16],
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> Self {
let mut peer = Self::new(destination_hash);
peer.peering_timebase = timebase;
peer.propagation_transfer_limit = transfer_limit;
peer.propagation_sync_limit = sync_limit;
peer.propagation_sync_limit = sync_limit.or(transfer_limit);
peer.stamp_cost = stamp_cost;
peer.stamp_cost_flexibility = stamp_flexibility;
peer.peering_cost = peering_cost.unwrap_or(PEERING_COST);
peer.metadata = bounded_peer_metadata(metadata);
peer.autopeered = true;
peer
}
/// Refresh announce-derived policy only when `timebase` is newer.
///
/// Returns `true` when the peer was updated. Runtime counters, handled
/// messages and static-peer status remain owned by the existing peer.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> bool {
let metadata = self.metadata.clone();
self.refresh_from_announce_with_metadata(
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
)
}
/// Refresh announce-derived policy and bounded metadata only when newer.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce_with_metadata(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> bool {
if timebase <= self.peering_timebase {
return false;
}
let offer_constraints_changed = self.propagation_transfer_limit != transfer_limit
|| self.propagation_sync_limit != sync_limit.or(transfer_limit)
|| self.stamp_cost != stamp_cost
|| self.stamp_cost_flexibility != stamp_flexibility
|| self.peering_cost != peering_cost.unwrap_or(PEERING_COST);
self.peering_timebase = timebase;
self.propagation_transfer_limit = transfer_limit;
self.propagation_sync_limit = sync_limit.or(transfer_limit);
self.stamp_cost = stamp_cost;
self.stamp_cost_flexibility = stamp_flexibility;
self.peering_cost = peering_cost.unwrap_or(PEERING_COST);
self.metadata = bounded_peer_metadata(metadata);
if offer_constraints_changed {
self.last_offer_generation = 0;
}
// A key remains usable when it still meets the new target. Otherwise
// the daemon must generate a replacement before taking a snapshot.
if self
.peering_key
.is_some_and(|(_, value)| value < self.peering_cost as u32)
{
self.peering_key = None;
}
self.heard();
self.next_sync_attempt = 0.0;
true
}
/// Effective minimum stamp cost this peer will accept, using the peer's
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
@@ -145,6 +377,11 @@ impl LxmPeer {
self.stamp_cost.is_some() && self.stamp_cost_flexibility.is_some()
}
/// Snapshot the complete immutable policy for one outbound sync offer.
pub fn outbound_offer_policy(&self) -> OutboundOfferPolicy {
OutboundOfferPolicy::from(self)
}
pub fn add_unhandled_message(&mut self) {
self.unhandled_count_cached = false;
self.unhandled_count += 1;
@@ -174,27 +411,50 @@ impl LxmPeer {
self.handled_messages.contains(hash)
}
pub fn needs_offer_generation(&self, generation: u64) -> bool {
generation > self.last_offer_generation
}
pub fn mark_offer_generation_processed(&mut self, generation: u64) {
self.last_offer_generation = self.last_offer_generation.max(generation);
}
/// Serialize peer state, including handled messages, for persistence.
pub fn to_bytes_with_handled(&self) -> Vec<u8> {
let handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
let data = (
self.destination_hash.to_vec(),
self.last_sync,
self.unreachable_count,
self.peering_cost,
self.stamp_cost,
self.stamp_cost_flexibility,
self.autopeered,
self.is_static,
handled,
);
rmp_serde::to_vec(&data).unwrap_or_default()
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
handled.sort();
let data = StoredPeerV2 {
version: STORED_PEER_VERSION,
destination_hash: self.destination_hash.to_vec(),
last_sync: self.last_sync,
unreachable_count: self.unreachable_count,
peering_cost: self.peering_cost,
stamp_cost: self.stamp_cost,
stamp_cost_flexibility: self.stamp_cost_flexibility,
autopeered: self.autopeered,
is_static: self.is_static,
handled_ids: handled,
peering_timebase: self.peering_timebase,
propagation_transfer_limit: self.propagation_transfer_limit,
propagation_sync_limit: self.propagation_sync_limit,
peering_key: self
.peering_key
.map(|(stamp, value)| (stamp.to_vec(), value)),
metadata: self.metadata.clone(),
last_heard: self.last_heard,
alive: self.alive,
};
rmp_serde::to_vec_named(&data).unwrap_or_default()
}
/// Deserialize peer state, including handled messages, from [`to_bytes_with_handled`] output.
///
/// [`to_bytes_with_handled`]: Self::to_bytes_with_handled
pub fn from_bytes_with_handled(data: &[u8]) -> Option<Self> {
if let Ok(stored) = rmp_serde::from_slice::<StoredPeerV2>(data) {
return Self::from_stored_v2(stored);
}
let (
dest_hash_vec,
last_sync,
@@ -205,7 +465,7 @@ impl LxmPeer {
autopeered,
is_static,
handled_vec,
): StoredPeer = rmp_serde::from_slice(data).ok()?;
): LegacyStoredPeer = rmp_serde::from_slice(data).ok()?;
if dest_hash_vec.len() != 16 {
return None;
}
@@ -234,6 +494,39 @@ impl LxmPeer {
Some(peer)
}
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
if stored.version != STORED_PEER_VERSION || stored.destination_hash.len() != 16 {
return None;
}
let mut destination_hash = [0u8; 16];
destination_hash.copy_from_slice(&stored.destination_hash);
let mut peer = Self::new(destination_hash);
peer.last_sync = stored.last_sync;
peer.unreachable_count = stored.unreachable_count;
peer.peering_cost = stored.peering_cost;
peer.stamp_cost = stored.stamp_cost;
peer.stamp_cost_flexibility = stored.stamp_cost_flexibility;
peer.autopeered = stored.autopeered;
peer.is_static = stored.is_static;
peer.peering_timebase = stored.peering_timebase;
peer.propagation_transfer_limit = stored.propagation_transfer_limit;
peer.propagation_sync_limit = stored.propagation_sync_limit;
peer.peering_key = stored.peering_key.and_then(|(stamp, value)| {
let stamp: [u8; 32] = stamp.try_into().ok()?;
Some((stamp, value))
});
peer.metadata = stored.metadata;
peer.last_heard = stored.last_heard;
peer.alive = stored.alive;
peer.handled_messages = stored
.handled_ids
.into_iter()
.filter_map(|value| value.try_into().ok())
.collect();
Some(peer)
}
pub fn mark_unreachable(&mut self) {
self.unreachable_count += 1;
let now = now_f64();
@@ -375,6 +668,32 @@ impl LxmPeer {
}
}
impl From<&LxmPeer> for OutboundOfferPolicy {
fn from(peer: &LxmPeer) -> Self {
let peering_key = peer
.peering_key
.filter(|(_, value)| *value >= peer.peering_cost as u32)
.map(|(stamp, _)| stamp.to_vec())
.unwrap_or_default();
Self {
peer_hash: peer.destination_hash,
handled_messages: peer.handled_messages.clone(),
stamp_cost: peer.stamp_cost,
stamp_cost_flexibility: peer.stamp_cost_flexibility,
minimum_stamp_cost: peer.minimum_accepted_stamp_cost(),
peering_cost: peer.peering_cost,
propagation_transfer_limit: peer.propagation_transfer_limit,
propagation_sync_limit: peer.propagation_sync_limit,
peering_key,
peering_key_value: peer.peering_key.map(|(_, value)| value),
peering_timebase: peer.peering_timebase,
autopeered: peer.autopeered,
is_static: peer.is_static,
metadata: peer.metadata.clone(),
}
}
}
/// Select the best peer to sync with from a set of candidates.
///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
@@ -477,6 +796,157 @@ mod tests {
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
}
#[test]
fn outbound_offer_policy_captures_authoritative_peer_state() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(3);
peer.propagation_transfer_limit = Some(1.5);
peer.propagation_sync_limit = Some(4.5);
peer.peering_cost = 18;
peer.peering_key = Some(([0x77; 32], 18));
peer.add_handled_message(&tid(0x11));
let policy = peer.outbound_offer_policy();
assert_eq!(policy.peer_hash, [0xAA; 16]);
assert_eq!(policy.minimum_stamp_cost, 13);
assert_eq!(policy.propagation_transfer_limit, Some(1.5));
assert_eq!(policy.propagation_sync_limit, Some(4.5));
assert_eq!(policy.peering_key, vec![0x77; 32]);
assert!(policy.handled_messages.contains(&tid(0x11)));
}
#[test]
fn stale_announce_cannot_overwrite_newer_peer_policy() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
200.0,
Some(2.0),
Some(8.0),
Some(16),
Some(3),
Some(18),
);
assert!(!peer.refresh_from_announce(
199.0,
Some(1.0),
Some(4.0),
Some(8),
Some(1),
Some(4),
));
assert_eq!(peer.peering_timebase, 200.0);
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
assert_eq!(peer.stamp_cost, Some(16));
peer.peering_key = Some(([0x55; 32], 18));
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
assert_eq!(peer.propagation_sync_limit, Some(3.0));
assert_eq!(peer.stamp_cost, Some(20));
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
}
#[test]
fn peer_persistence_retains_offer_policy_and_reads_legacy_tuple() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
1234.0,
Some(1.25),
Some(9.5),
Some(16),
Some(3),
Some(18),
);
peer.peering_key = Some(([0x66; 32], 19));
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
peer.add_handled_message(&tid(0x22));
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.peering_timebase, 1234.0);
assert_eq!(restored.propagation_transfer_limit, Some(1.25));
assert_eq!(restored.propagation_sync_limit, Some(9.5));
assert_eq!(restored.peering_key, Some(([0x66; 32], 19)));
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
assert!(restored.has_handled(&tid(0x22)));
let legacy: LegacyStoredPeer = (
vec![0xBB; 16],
42.0,
2,
18,
Some(12),
Some(2),
true,
false,
vec![tid(0x33).to_vec()],
);
let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap();
let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap();
assert_eq!(restored_legacy.destination_hash, [0xBB; 16]);
assert_eq!(restored_legacy.stamp_cost, Some(12));
assert!(restored_legacy.has_handled(&tid(0x33)));
}
#[test]
fn announce_metadata_is_typed_bounded_and_persisted() {
let mut metadata = HashMap::new();
metadata.insert(0, b"node name".to_vec());
metadata.insert(1, vec![0xAA; MAX_PEER_METADATA_VALUE_BYTES + 1]);
for key in 2..=30 {
metadata.insert(key, vec![key; 8]);
}
let peer = LxmPeer::from_announce_with_metadata(
[0xAA; 16],
10.0,
Some(1.0),
Some(2.0),
Some(12),
Some(3),
Some(18),
Some(metadata),
);
let retained = peer.metadata.as_ref().unwrap();
assert_eq!(retained.get(&0), Some(&b"node name".to_vec()));
assert!(!retained.contains_key(&1));
assert!(retained.len() <= MAX_PEER_METADATA_ENTRIES);
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.metadata, peer.metadata);
let empty = LxmPeer::from_announce_with_metadata(
[0xBB; 16],
10.0,
None,
None,
None,
None,
None,
Some(HashMap::new()),
);
assert_eq!(empty.metadata, Some(HashMap::new()));
}
#[test]
fn newer_policy_invalidates_processed_store_generation() {
let mut peer =
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None);
peer.mark_offer_generation_processed(7);
assert!(!peer.needs_offer_generation(7));
assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None));
assert!(peer.needs_offer_generation(7));
peer.mark_offer_generation_processed(7);
assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None));
assert!(
!peer.needs_offer_generation(7),
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
);
}
/// T0-4: an absurd announce-supplied peering cost must fail the bounded
/// key search instead of spinning forever; sane costs still succeed.
#[test]
+440 -21
View File
@@ -10,7 +10,7 @@ use std::path::PathBuf;
use crate::constants::*;
use crate::message::LxMessage;
use crate::peer::LxmPeer;
use crate::peer::{LxmPeer, OutboundOfferPolicy};
use crate::propagation::{PropagationEntry, PropagationStore, hex_encode};
use crate::propagation_admission::PnOfferCandidate;
use crate::propagation_offer::{PnOfferEvaluation, PnOfferEvaluationError};
@@ -147,6 +147,129 @@ pub fn read_planned_messages(
.collect()
}
#[derive(Debug, Clone)]
pub(crate) struct SyncOfferCandidateSnapshot {
transient_id: PropagationTransientId,
weight: f64,
size: usize,
stamp_value: u8,
}
/// Cheap, owned view captured while the shared node lock is held. Expensive
/// peer-file loading and full-store sorting happen from this snapshot on a
/// blocking worker.
#[derive(Debug, Clone)]
pub(crate) struct SyncOfferPreparationSnapshot {
pub policy: OutboundOfferPolicy,
pub generation: u64,
peer_path: Option<PathBuf>,
candidates: Vec<SyncOfferCandidateSnapshot>,
}
#[derive(Debug)]
pub(crate) struct PreparedSyncOffer {
pub policy: OutboundOfferPolicy,
pub generation: u64,
pub selected_ids: Vec<PropagationTransientId>,
pub terminal_handled_ids: Vec<PropagationTransientId>,
pub generation_exhausted: bool,
}
#[derive(Debug)]
pub(crate) enum InstallPreparedSyncOffer {
Installed {
offer: SyncOffer,
generation: u64,
terminal_handled_ids: Vec<PropagationTransientId>,
generation_exhausted: bool,
},
Stale,
}
/// Blocking half of outbound-offer preparation. This function owns its input
/// and never touches a live `PropagationNode` or shared lock.
pub(crate) fn prepare_sync_offer_snapshot(
snapshot: SyncOfferPreparationSnapshot,
) -> PreparedSyncOffer {
const PER_MESSAGE_OVERHEAD: usize = 16;
const INITIAL_STRUCTURE_OVERHEAD: usize = 24;
let transfer_limit = snapshot
.policy
.propagation_transfer_limit
.map(kilobytes_to_bytes_fail_closed);
let sync_limit = snapshot
.policy
.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);
}
let mut candidates = snapshot.candidates;
candidates.sort_by(|left, right| {
left.weight
.total_cmp(&right.weight)
.then_with(|| left.transient_id.cmp(&right.transient_id))
});
let mut cumulative_size = INITIAL_STRUCTURE_OVERHEAD;
let mut selected_ids = Vec::new();
let mut terminal_handled_ids = Vec::new();
let mut cumulative_deferred = false;
for candidate in candidates {
if handled_messages.contains(&candidate.transient_id) {
continue;
}
if candidate.stamp_value < snapshot.policy.minimum_stamp_cost {
terminal_handled_ids.push(candidate.transient_id);
continue;
}
let transfer_size = candidate.size.saturating_add(PER_MESSAGE_OVERHEAD);
if transfer_limit.is_some_and(|limit| transfer_size > limit) {
terminal_handled_ids.push(candidate.transient_id);
continue;
}
let next_size = cumulative_size.saturating_add(transfer_size);
if sync_limit.is_some_and(|limit| next_size >= limit) {
// The cumulative limit is session-local. Keep this candidate
// pending so a later sync can offer it.
cumulative_deferred = true;
continue;
}
cumulative_size = next_size;
selected_ids.push(candidate.transient_id);
}
// If not even one candidate fits the peer's cumulative limit, retrying
// this unchanged generation would only establish another Link and reach
// the same empty result. Treat that generation as scheduled-and-exhausted
// for the current constraints. A store revision or material announce
// policy change re-enables scheduling.
let generation_exhausted = !cumulative_deferred || selected_ids.is_empty();
PreparedSyncOffer {
policy: snapshot.policy,
generation: snapshot.generation,
selected_ids,
terminal_handled_ids,
generation_exhausted,
}
}
fn kilobytes_to_bytes_fail_closed(kilobytes: f64) -> usize {
if !kilobytes.is_finite() || kilobytes <= 0.0 {
return 0;
}
(kilobytes * 1000.0).floor() as usize
}
pub struct PropagationNode {
config: PropagationNodeConfig,
store: PropagationStore,
@@ -156,6 +279,10 @@ pub struct PropagationNode {
/// Transitional pre-1.1 behavior; removed when the daemon-lifetime
/// `PnInboundAdmission` becomes the live throttle owner.
last_offer_times: HashMap<[u8; 16], f64>,
/// Monotonic in-process revision of the propagation store. Outbound peer
/// scheduling and offer-preparation revalidation use this to avoid both
/// stale offers and repeated scans of an unchanged fully-handled store.
offer_generation: u64,
}
impl PropagationNode {
@@ -168,6 +295,7 @@ impl PropagationNode {
dest_hash,
storage_path: None,
last_offer_times: HashMap::new(),
offer_generation: 0,
}
}
@@ -179,6 +307,14 @@ impl PropagationNode {
self.config.min_stamp_cost = cost;
}
pub fn offer_generation(&self) -> u64 {
self.offer_generation
}
fn advance_offer_generation(&mut self) {
self.offer_generation = self.offer_generation.saturating_add(1);
}
/// Disk-backed node. Loads existing messages from `storage_path` on startup.
pub fn with_storage(
config: PropagationNodeConfig,
@@ -193,6 +329,7 @@ impl PropagationNode {
dest_hash,
storage_path: Some(storage_path),
last_offer_times: HashMap::new(),
offer_generation: 0,
};
node.load_from_disk()?;
Ok(node)
@@ -266,8 +403,11 @@ impl PropagationNode {
}
}
self.store.insert(entry);
true
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
}
/// Store an already propagation-packed LXMF blob (`dest_hash || encrypted_data`).
@@ -313,7 +453,11 @@ impl PropagationNode {
}
}
self.store.insert(entry)
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
}
/// Store a validated propagated LXMF blob with its propagation-node stamp.
@@ -369,7 +513,11 @@ impl PropagationNode {
}
}
self.store.insert(entry)
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
}
fn load_from_disk(&mut self) -> std::io::Result<()> {
@@ -453,14 +601,18 @@ impl PropagationNode {
pe.stamped = false;
}
self.store.insert(pe);
loaded += 1;
if self.store.insert(pe) {
loaded += 1;
}
}
}
if loaded > 0 || quarantined > 0 {
tracing::info!(loaded, quarantined, "loaded propagation messages from disk");
}
if loaded > 0 {
self.advance_offer_generation();
}
Ok(())
}
@@ -475,6 +627,10 @@ impl PropagationNode {
self.store.cull_by_weight(self.config.max_storage);
let after = self.store.len();
if before != after {
self.advance_offer_generation();
}
if before > after
&& let Some(ref dir) = self.storage_path
{
@@ -576,6 +732,20 @@ impl PropagationNode {
Ok(())
}
/// Remove persisted state for an explicitly unpeered destination.
pub fn delete_peer(&mut self, peer_hash: &[u8; 16]) -> std::io::Result<()> {
self.remove_session(peer_hash);
let Some(dir) = self.storage_path.as_ref() else {
return Ok(());
};
let path = dir.join(format!("{}.peer", hex_encode(peer_hash)));
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
/// Inverse-offer pattern: the peer lists what it has; we return the IDs
/// we hold that the peer does not. Python reference:
/// LXMRouter.offer_request_received().
@@ -806,11 +976,12 @@ impl PropagationNode {
if !owned {
return;
}
if let Some(entry) = self.store.remove(tid)
&& let Some(ref dir) = self.storage_path
{
let path = dir.join(entry.filename());
let _ = std::fs::remove_file(&path);
if let Some(entry) = self.store.remove(tid) {
self.advance_offer_generation();
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
let _ = std::fs::remove_file(&path);
}
}
}
@@ -852,18 +1023,104 @@ impl PropagationNode {
/// The caller sends it over an established link. Python reference:
/// LXMRouter.sync_request_received().
pub fn prepare_sync_offer(&mut self, peer_hash: [u8; 16]) -> SyncOffer {
// Compute IDs before borrowing sync_sessions mutably.
let our_ids = if let Some(peer) = self.load_peer(&peer_hash) {
self.create_offer_filtered(&peer.handled_messages)
} else {
self.create_offer(peer_hash, None)
};
let policy = self
.load_peer(&peer_hash)
.as_ref()
.map(OutboundOfferPolicy::from)
.unwrap_or_else(|| OutboundOfferPolicy::unrestricted(peer_hash));
self.prepare_sync_offer_with_policy(&policy)
}
/// Capture an owned offer-preparation snapshot while holding the node lock.
/// The returned value contains no references into the live store.
pub(crate) fn snapshot_sync_offer_preparation(
&self,
policy: &OutboundOfferPolicy,
) -> SyncOfferPreparationSnapshot {
let now = crate::now_f64();
let candidates = self
.store
.entries()
.map(|entry| SyncOfferCandidateSnapshot {
transient_id: entry.transient_id,
weight: self.store.compute_weight(entry, now),
size: entry.size,
stamp_value: entry.stamp_value,
})
.collect();
let peer_path = self
.storage_path
.as_ref()
.map(|dir| dir.join(format!("{}.peer", hex_encode(&policy.peer_hash))));
SyncOfferPreparationSnapshot {
policy: policy.clone(),
generation: self.offer_generation,
peer_path,
candidates,
}
}
/// Revalidate and install a prepared offer. A store mutation invalidates
/// the entire result so weight ordering and limits are recomputed from a
/// fresh snapshot instead of partially accepting stale work.
pub(crate) fn install_prepared_sync_offer(
&mut self,
prepared: PreparedSyncOffer,
) -> InstallPreparedSyncOffer {
if prepared.generation != self.offer_generation
|| prepared
.selected_ids
.iter()
.any(|transient_id| !self.store.contains(transient_id))
{
return InstallPreparedSyncOffer::Stale;
}
let session = self
.sync_sessions
.entry(peer_hash)
.or_insert_with(|| SyncSession::new(peer_hash));
session.prepare_offer(our_ids, Vec::new())
.entry(prepared.policy.peer_hash)
.or_insert_with(|| SyncSession::new(prepared.policy.peer_hash));
let offer =
session.prepare_offer(prepared.selected_ids, prepared.policy.peering_key.clone());
InstallPreparedSyncOffer::Installed {
offer,
generation: prepared.generation,
terminal_handled_ids: prepared.terminal_handled_ids,
generation_exhausted: prepared.generation_exhausted,
}
}
/// Prepare one offer from an authoritative peer-policy snapshot.
///
/// Selection mirrors `LXMPeer.sync`: only existing, unhandled messages
/// meeting the peer's stamp and transfer limits are eligible. Candidates
/// are ordered by ascending store weight before the cumulative sync cap is
/// applied. The chosen IDs are retained in the session so a subsequent
/// response cannot request data outside this offer.
pub fn prepare_sync_offer_with_policy(&mut self, policy: &OutboundOfferPolicy) -> SyncOffer {
loop {
let snapshot = self.snapshot_sync_offer_preparation(policy);
let prepared = prepare_sync_offer_snapshot(snapshot);
match self.install_prepared_sync_offer(prepared) {
InstallPreparedSyncOffer::Installed {
offer,
terminal_handled_ids,
..
} => {
// 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");
}
return offer;
}
InstallPreparedSyncOffer::Stale => continue,
}
}
}
/// Compare a peer's `SyncOffer` against our store and return a `SyncGet`
@@ -927,6 +1184,23 @@ impl PropagationNode {
}
}
/// Merge peer-handled observations into persisted state using the same
/// authoritative policy that produced the offer.
pub fn persist_peer_handled(
&self,
policy: &OutboundOfferPolicy,
transient_ids: &[PropagationTransientId],
) -> std::io::Result<()> {
let mut peer = self
.load_peer(&policy.peer_hash)
.unwrap_or_else(|| policy.to_peer());
policy.apply_to_peer(&mut peer);
for transient_id in transient_ids {
peer.add_handled_message(transient_id);
}
self.save_peer(&peer)
}
pub fn complete_sync(&mut self, peer_hash: &[u8; 16]) {
if let Some(session) = self.sync_sessions.get_mut(peer_hash) {
session.mark_complete();
@@ -1004,6 +1278,17 @@ mod tests {
[byte; 32]
}
fn insert_offer_entry(
node: &mut PropagationNode,
transient_id: PropagationTransientId,
size: usize,
stamp_value: u8,
) {
let entry =
PropagationEntry::new(transient_id, transient_id, [0xDD; 16], size, stamp_value);
assert!(node.store.insert(entry));
}
fn id(byte: u8) -> Vec<u8> {
vec![byte; 32]
}
@@ -1127,6 +1412,140 @@ mod tests {
assert_eq!(filtered.len(), 1);
}
#[test]
fn authoritative_offer_policy_combines_all_filters_and_real_key() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
insert_offer_entry(&mut node, tid(0x01), 100, 20); // handled
insert_offer_entry(&mut node, tid(0x02), 100, 12); // low stamp
insert_offer_entry(&mut node, tid(0x03), 100, 13); // accepted
insert_offer_entry(&mut node, tid(0x04), 985, 20); // 1001 B with overhead
insert_offer_entry(&mut node, tid(0x05), 984, 13); // exact 1000 B
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
policy.handled_messages.insert(tid(0x01));
policy.minimum_stamp_cost = 13;
policy.propagation_transfer_limit = Some(1.0);
policy.propagation_sync_limit = Some(10.0);
policy.peering_key = vec![0x77; 32];
let offer = node.prepare_sync_offer_with_policy(&policy);
assert_eq!(offer.peering_key, vec![0x77; 32]);
assert_eq!(
offer.transient_ids,
vec![tid(0x03).to_vec(), tid(0x05).to_vec()]
);
assert_eq!(
node.get_session(&policy.peer_hash).unwrap().offered_ids,
vec![tid(0x03), tid(0x05)]
);
}
#[test]
fn offer_cumulative_limit_is_decimal_and_excludes_exact_boundary() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
insert_offer_entry(&mut node, tid(0x01), 50, 0);
insert_offer_entry(&mut node, tid(0x02), 50, 0);
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
// 24 initial + (50 + 16) + (50 + 16) = 156 bytes. The second
// candidate is excluded because upstream uses next_size >= limit.
policy.propagation_sync_limit = Some(0.156);
let offer = node.prepare_sync_offer_with_policy(&policy);
assert_eq!(offer.transient_ids, vec![tid(0x01).to_vec()]);
}
#[test]
fn prepared_offer_distinguishes_terminal_filters_from_cumulative_deferral() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
insert_offer_entry(&mut node, tid(0x01), 10, 9); // terminal low stamp
insert_offer_entry(&mut node, tid(0x02), 100, 20); // selected
insert_offer_entry(&mut node, tid(0x03), 100, 20); // cumulative deferred
insert_offer_entry(&mut node, tid(0x04), 1000, 20); // terminal oversize
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
policy.minimum_stamp_cost = 10;
policy.propagation_transfer_limit = Some(0.5);
policy.propagation_sync_limit = Some(0.2);
let prepared = prepare_sync_offer_snapshot(node.snapshot_sync_offer_preparation(&policy));
assert_eq!(prepared.selected_ids, vec![tid(0x02)]);
assert_eq!(prepared.terminal_handled_ids, vec![tid(0x01), tid(0x04)]);
assert!(
!prepared.generation_exhausted,
"cumulative-only skips must stay pending for another batch"
);
}
#[test]
fn all_cumulatively_deferred_candidates_exhaust_unchanged_generation() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
insert_offer_entry(&mut node, tid(0x01), 50, 20);
insert_offer_entry(&mut node, tid(0x02), 50, 20);
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
// Initial overhead (24) + either transfer (50 + 16) exceeds this
// generation's peer policy, so a reconnect cannot make progress.
policy.propagation_sync_limit = Some(0.05);
let prepared = prepare_sync_offer_snapshot(node.snapshot_sync_offer_preparation(&policy));
assert!(prepared.selected_ids.is_empty());
assert!(prepared.terminal_handled_ids.is_empty());
assert!(
prepared.generation_exhausted,
"zero-progress cumulative deferral must not hot-loop the same generation"
);
}
#[test]
fn prepared_offer_revalidates_store_generation_before_install() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let mut first = vec![0x11; DESTINATION_LENGTH + 1];
first[0] = 0x01;
assert!(node.accept_propagated_blob(&first, 0));
let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
let snapshot = node.snapshot_sync_offer_preparation(&policy);
let mut second = vec![0x22; DESTINATION_LENGTH + 1];
second[0] = 0x02;
assert!(node.accept_propagated_blob(&second, 0));
let prepared = prepare_sync_offer_snapshot(snapshot);
assert!(matches!(
node.install_prepared_sync_offer(prepared),
InstallPreparedSyncOffer::Stale
));
}
#[test]
fn passed_and_persisted_handled_sets_are_unioned() {
let dir = std::env::temp_dir().join("lxmf_test_offer_handled_union");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
insert_offer_entry(&mut node, tid(0x01), 50, 0);
insert_offer_entry(&mut node, tid(0x02), 50, 0);
insert_offer_entry(&mut node, tid(0x03), 50, 0);
let mut persisted = LxmPeer::new([0xBB; 16]);
persisted.add_handled_message(&tid(0x01));
node.save_peer(&persisted).unwrap();
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
policy.handled_messages.insert(tid(0x02));
let offer = node.prepare_sync_offer_with_policy(&policy);
assert_eq!(offer.transient_ids, vec![tid(0x03).to_vec()]);
node.delete_peer(&[0xBB; 16]).unwrap();
assert!(node.load_peers().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_propagation_disk_persistence() {
let dir = std::env::temp_dir().join("lxmf_test_prop_persist");
File diff suppressed because it is too large. Load diff
+279 -10
View File
@@ -12,7 +12,7 @@ use tokio::sync::{mpsc, oneshot};
use crate::constants::*;
use crate::message::{LxMessage, MessageError};
use crate::peer::LxmPeer;
use crate::peer::{LxmPeer, OutboundOfferPolicy};
use crate::propagation::PropagationStore;
use crate::stamper;
use crate::ticket::{Ticket, TicketStore};
@@ -317,6 +317,9 @@ pub struct AutopeerCandidate {
pub stamp_cost: Option<u8>,
pub stamp_flexibility: Option<u8>,
pub peering_cost: Option<u8>,
/// Parsed propagation-node announce metadata. The peer layer applies
/// deterministic entry/value/aggregate bounds before retaining it.
pub metadata: Option<std::collections::HashMap<u8, Vec<u8>>>,
pub hops: Option<u8>,
}
@@ -940,6 +943,29 @@ impl LxmRouter {
due
}
/// Return authoritative policies for peers that have not processed the
/// current propagation-store generation. This is an O(peers) scheduler
/// query; exact message eligibility is intentionally deferred to the
/// sync task's off-loop offer preparation.
///
/// 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
.peers
.values()
.filter(|peer| {
peer.alive
&& peer.state == PeerState::Idle
&& peer.should_sync()
&& peer.needs_offer_generation(offer_generation)
})
.map(OutboundOfferPolicy::from)
.collect::<Vec<_>>();
policies.sort_by_key(|policy| policy.peer_hash);
policies
}
pub fn add_peer(&mut self, peer: LxmPeer) -> bool {
if self.peers.len() >= self.config.max_peers {
return false;
@@ -961,31 +987,69 @@ impl LxmRouter {
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
hops,
} = candidate;
let configured_static = self.static_peers.contains(&destination_hash);
if !self.config.autopeer {
return false;
}
// Python LXMRouter.peer() (LXMRouter.py:1896-1901): a peering cost
// above our accepted maximum refuses the peering — and breaks an
// existing one — before any PoW could be attempted.
// existing one only when that policy announce is not stale.
if peering_cost.unwrap_or(0) > self.config.ext.max_peering_cost {
if self.peers.contains_key(&destination_hash) {
self.unpeer(&destination_hash);
if self
.peers
.get(&destination_hash)
.is_some_and(|peer| timebase >= peer.peering_timebase)
{
self.remove_peer(&destination_hash);
}
return false;
}
if self.peers.contains_key(&destination_hash) {
// Configured static peers always consume newer policy announces.
// Automatically discovered peers remain governed by the live
// autopeer/range policy, matching the upstream announce handler.
if let Some(peer) = self.peers.get(&destination_hash) {
let static_peer = configured_static || peer.is_static;
if !static_peer && !self.config.autopeer {
return false;
}
if !static_peer && hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth)
{
if timebase >= peer.peering_timebase {
self.remove_peer(&destination_hash);
}
return false;
}
}
if let Some(peer) = self.peers.get_mut(&destination_hash) {
let refreshed = peer.refresh_from_announce_with_metadata(
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
);
if configured_static {
peer.is_static = true;
peer.autopeered = false;
}
return refreshed;
}
if !configured_static && !self.config.autopeer {
return false;
}
if let Some(h) = hops
if !configured_static
&& let Some(h) = hops
&& h as usize > self.config.ext.autopeer_maxdepth
{
return false;
}
let peer = LxmPeer::from_announce(
let mut peer = LxmPeer::from_announce_with_metadata(
destination_hash,
timebase,
transfer_limit,
@@ -993,7 +1057,12 @@ impl LxmRouter {
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
);
if configured_static {
peer.is_static = true;
peer.autopeered = false;
}
self.add_peer(peer)
}
@@ -2629,6 +2698,48 @@ mod tests {
assert!(router.sync_peers().is_empty());
}
#[test]
fn store_generation_scheduler_skips_unchanged_and_reenables_on_store_or_policy_change() {
let peer_hash = [0x11; 16];
let mut router = LxmRouter::new(RouterConfig::default());
let mut peer = LxmPeer::from_announce(
peer_hash,
10.0,
Some(1.0),
Some(2.0),
Some(16),
Some(3),
Some(18),
);
peer.mark_offer_generation_processed(5);
router.add_peer(peer);
assert!(router.sync_peer_policies_for_store(5).is_empty());
let due = router.sync_peer_policies_for_store(6);
assert_eq!(due.len(), 1);
assert_eq!(due[0].peer_hash, peer_hash);
assert_eq!(router.peers[&peer_hash].state, PeerState::Idle);
router
.peers
.get_mut(&peer_hash)
.unwrap()
.mark_offer_generation_processed(6);
assert!(router.sync_peer_policies_for_store(6).is_empty());
assert!(router.autopeer(AutopeerCandidate {
destination_hash: peer_hash,
timebase: 11.0,
transfer_limit: Some(1.0),
sync_limit: Some(2.0),
stamp_cost: Some(12),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: Some(std::collections::HashMap::new()),
hops: Some(1),
}));
assert_eq!(router.sync_peer_policies_for_store(6).len(), 1);
}
#[test]
fn test_validate_stamp() {
let router = LxmRouter::new(RouterConfig::default());
@@ -3210,6 +3321,7 @@ mod tests {
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: None,
hops: Some(2),
}));
assert_eq!(router.peers.len(), 1);
@@ -3222,6 +3334,7 @@ mod tests {
stamp_cost: None,
stamp_flexibility: None,
peering_cost: None,
metadata: None,
hops: None,
}));
assert!(!router.autopeer(AutopeerCandidate {
@@ -3232,10 +3345,163 @@ mod tests {
stamp_cost: None,
stamp_flexibility: None,
peering_cost: None,
metadata: None,
hops: Some(10),
}));
}
#[test]
fn existing_static_peer_accepts_only_newer_policy_when_autopeer_is_disabled() {
let peer_hash = [0xAA; 16];
let mut router = LxmRouter::new(RouterConfig {
autopeer: false,
..Default::default()
});
let mut peer = LxmPeer::new(peer_hash);
peer.is_static = true;
peer.peering_timebase = 100.0;
peer.stamp_cost = Some(8);
router.add_peer(peer);
let candidate = |timebase, stamp_cost| AutopeerCandidate {
destination_hash: peer_hash,
timebase,
transfer_limit: Some(2.0),
sync_limit: Some(8.0),
stamp_cost: Some(stamp_cost),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: None,
hops: Some(99),
};
assert!(router.autopeer(candidate(101.0, 16)));
let refreshed = router.peers.get(&peer_hash).unwrap();
assert_eq!(refreshed.stamp_cost, Some(16));
assert_eq!(refreshed.propagation_sync_limit, Some(8.0));
assert!(refreshed.is_static);
assert!(!router.autopeer(candidate(100.0, 4)));
assert_eq!(router.peers.get(&peer_hash).unwrap().stamp_cost, Some(16));
assert!(!router.autopeer(AutopeerCandidate {
destination_hash: [0xBB; 16],
timebase: 101.0,
transfer_limit: Some(2.0),
sync_limit: Some(8.0),
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: None,
hops: Some(1),
}));
assert!(!router.peers.contains_key(&[0xBB; 16]));
}
#[test]
fn configured_static_announce_recreates_missing_peer_with_autopeer_disabled() {
let peer_hash = [0xA5; 16];
let mut router = LxmRouter::new(RouterConfig {
autopeer: false,
ext: RouterConfigExt {
autopeer_maxdepth: 1,
..Default::default()
},
..Default::default()
});
router.static_peers.push(peer_hash);
router.remove_peer(&peer_hash);
assert!(router.autopeer(AutopeerCandidate {
destination_hash: peer_hash,
timebase: 101.0,
transfer_limit: Some(2.0),
sync_limit: Some(8.0),
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: Some(std::collections::HashMap::from([(
crate::constants::PN_META_NAME,
b"static".to_vec(),
)])),
hops: Some(99),
}));
let peer = router.peers.get(&peer_hash).unwrap();
assert!(peer.is_static);
assert!(!peer.autopeered);
assert_eq!(
peer.metadata
.as_ref()
.and_then(|metadata| metadata.get(&crate::constants::PN_META_NAME)),
Some(&b"static".to_vec())
);
}
#[test]
fn stale_over_cost_announce_does_not_remove_newer_peer() {
let peer_hash = [0xAA; 16];
let mut router = LxmRouter::new(RouterConfig::default());
let mut peer = LxmPeer::new(peer_hash);
peer.peering_timebase = 200.0;
router.add_peer(peer);
let max = router.config.ext.max_peering_cost;
assert!(!router.autopeer(AutopeerCandidate {
destination_hash: peer_hash,
timebase: 199.0,
transfer_limit: None,
sync_limit: None,
stamp_cost: None,
stamp_flexibility: None,
peering_cost: Some(max + 1),
metadata: None,
hops: None,
}));
assert!(router.peers.contains_key(&peer_hash));
}
#[test]
fn nonstatic_peer_still_obeys_autopeer_and_range_on_refresh() {
let peer_hash = [0xAA; 16];
let candidate = |timebase, hops| AutopeerCandidate {
destination_hash: peer_hash,
timebase,
transfer_limit: Some(2.0),
sync_limit: Some(8.0),
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: Some(18),
metadata: None,
hops: Some(hops),
};
let mut disabled = LxmRouter::new(RouterConfig {
autopeer: false,
..Default::default()
});
let mut peer = LxmPeer::new(peer_hash);
peer.peering_timebase = 100.0;
disabled.add_peer(peer);
assert!(!disabled.autopeer(candidate(101.0, 1)));
assert_eq!(
disabled.peers.get(&peer_hash).unwrap().peering_timebase,
100.0
);
let mut ranged = LxmRouter::new(RouterConfig {
ext: RouterConfigExt {
autopeer_maxdepth: 1,
..Default::default()
},
..Default::default()
});
let mut peer = LxmPeer::new(peer_hash);
peer.peering_timebase = 100.0;
ranged.add_peer(peer);
assert!(!ranged.autopeer(candidate(101.0, 2)));
assert!(!ranged.peers.contains_key(&peer_hash));
}
/// T0-4: peering cost above `max_peering_cost` refuses peering, and an
/// existing peering breaks when the peer raises its cost beyond the cap
/// (Python LXMRouter.py:1896-1901).
@@ -3252,6 +3518,7 @@ mod tests {
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: cost,
metadata: None,
hops: Some(2),
};
@@ -3286,6 +3553,7 @@ mod tests {
stamp_cost: None,
stamp_flexibility: None,
peering_cost: None,
metadata: None,
hops: Some(2),
}));
assert!(router.autopeer(AutopeerCandidate {
@@ -3296,6 +3564,7 @@ mod tests {
stamp_cost: None,
stamp_flexibility: None,
peering_cost: None,
metadata: None,
hops: Some(1),
}));
}
+411 -18
View File
@@ -24,10 +24,11 @@ use lxmf_core::link_delivery::{
is_retryable_link_delivery_failure,
};
use lxmf_core::message::LxMessage;
use lxmf_core::peer::{LxmPeer, OutboundOfferPolicy};
use lxmf_core::propagation_node::{PropagationNode, PropagationNodeConfig};
use lxmf_core::router::{
DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, DirectRouteSnapshot,
LxmRouter, OutboundAction, plan_direct_delivery,
AutopeerCandidate, DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState,
DirectRouteSnapshot, LxmRouter, OutboundAction, plan_direct_delivery,
};
use lxmf_tools::daemon::{DaemonConfig, create_router_with_transport, execute_on_inbound};
use lxmf_tools::lxmd_cli::{
@@ -88,6 +89,50 @@ struct PnValidationWorkerResult {
rejected: usize,
}
#[derive(Debug)]
struct PeeringKeyWorkerResult {
peer_hash: [u8; 16],
peering_cost: u8,
peering_key: Option<([u8; 32], u32)>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct PeerOfferConstraints {
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: u8,
}
impl From<&LxmPeer> for PeerOfferConstraints {
fn from(peer: &LxmPeer) -> Self {
Self {
transfer_limit: peer.propagation_transfer_limit,
sync_limit: peer.propagation_sync_limit,
stamp_cost: peer.stamp_cost,
stamp_flexibility: peer.stamp_cost_flexibility,
peering_cost: peer.peering_cost,
}
}
}
fn generate_peering_key_job(
peer_hash: [u8; 16],
peering_cost: u8,
peer_identity_hash: [u8; 16],
local_identity_hash: [u8; 16],
) -> PeeringKeyWorkerResult {
let mut peer = LxmPeer::new(peer_hash);
peer.peering_cost = peering_cost;
let _ = peer.generate_peering_key(&peer_identity_hash, &local_identity_hash);
PeeringKeyWorkerResult {
peer_hash,
peering_cost,
peering_key: peer.peering_key,
}
}
fn validate_pn_resource_job(
job: PnValidationJob,
max_transfer_bytes: usize,
@@ -637,6 +682,11 @@ struct LxmdRunner {
prop_validation_rx: mpsc::Receiver<PnValidationWorkerResult>,
/// Retained sender used to dispatch bounded validation results.
prop_validation_tx: mpsc::Sender<PnValidationWorkerResult>,
/// Peering keys are CPU-bound PoW and must never run on the daemon loop.
peering_key_result_rx: mpsc::Receiver<PeeringKeyWorkerResult>,
peering_key_result_tx: mpsc::Sender<PeeringKeyWorkerResult>,
peering_key_jobs: HashSet<[u8; 16]>,
pending_peer_syncs: HashSet<[u8; 16]>,
/// Non-link inbound packets; still encrypted, need destination-level decrypt.
inbound_raw_rx: mpsc::Receiver<Vec<u8>>,
announce_rx: mpsc::Receiver<AnnounceHandlerEvent>,
@@ -742,7 +792,7 @@ impl LxmdRunner {
"Crypto state loaded"
);
let router = create_router_with_transport(&config, transport_tx.clone());
let mut router = create_router_with_transport(&config, transport_tx.clone());
// LinkManager handles link handshakes (ECDH), keepalive, identification,
// and resource transfers; it forwards plaintext application data here.
@@ -754,6 +804,8 @@ impl LxmdRunner {
mpsc::unbounded_channel::<rns_runtime::link_manager::LinkManagerAccountingEvent>();
let (prop_validation_tx, prop_validation_rx) =
mpsc::channel::<PnValidationWorkerResult>(256);
let (peering_key_result_tx, peering_key_result_rx) =
mpsc::channel::<PeeringKeyWorkerResult>(64);
let (inbound_raw_tx, inbound_raw_rx) = mpsc::channel::<Vec<u8>>(256);
let (link_command_tx, link_command_rx) =
mpsc::channel::<rns_runtime::link_manager::LinkManagerCommand>(256);
@@ -806,6 +858,11 @@ impl LxmdRunner {
delivery_tx: Some(prop_delivery_tx),
});
let static_peer_hashes = config
.static_peers
.iter()
.filter_map(|peer| parse_destination_hash(peer).ok())
.collect::<Vec<_>>();
let pn_config = PropagationNodeConfig {
max_storage: config
.message_storage_limit
@@ -844,12 +901,13 @@ impl LxmdRunner {
)))
}
};
if let Ok(node) = pn.lock() {
for mut peer in node.load_peers() {
peer.is_static = static_peer_hashes.contains(&peer.destination_hash);
let _ = router.add_peer(peer);
}
}
let static_peer_hashes = config
.static_peers
.iter()
.filter_map(|peer| parse_destination_hash(peer).ok())
.collect::<Vec<_>>();
let pn_admission = Arc::new(Mutex::new(PnInboundRuntime::new(
config.to_inbound_admission_config(),
static_peer_hashes,
@@ -1150,6 +1208,10 @@ impl LxmdRunner {
prop_accounting_rx,
prop_validation_rx,
prop_validation_tx,
peering_key_result_rx,
peering_key_result_tx,
peering_key_jobs: HashSet::new(),
pending_peer_syncs: HashSet::new(),
inbound_raw_rx,
announce_rx,
last_peer_announce: 0.0,
@@ -1166,10 +1228,17 @@ impl LxmdRunner {
if runner.config.propagation_enabled {
if let Some(ref pn) = propagation_node {
let sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node(
let mut sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node(
transport_tx.clone(),
pn.clone(),
);
if let Some(signing_key) = runner.identity.get_signing_key() {
sync.set_identity(runner.identity.get_public_key(), signing_key);
} else {
tracing::error!(
"local identity has no signing key; outbound peer sync cannot identify"
);
}
runner.propagation_sync = Some(sync);
}
runner.propagation_node = propagation_node;
@@ -1190,11 +1259,12 @@ impl LxmdRunner {
node.copy_from_slice(&bytes);
client.set_propagation_node(node);
runner.router.outbound_propagation_node = Some(node);
runner
let peer = runner
.router
.peers
.entry(node)
.or_insert_with(|| lxmf_core::peer::LxmPeer::new(node));
peer.is_static = true;
if !runner.router.static_peers.contains(&node) {
runner.router.static_peers.push(node);
}
@@ -1257,10 +1327,12 @@ impl LxmdRunner {
if !self.router.static_peers.contains(&hash) {
self.router.static_peers.push(hash);
}
self.router
let peer = self
.router
.peers
.entry(hash)
.or_insert_with(|| lxmf_core::peer::LxmPeer::new(hash));
peer.is_static = true;
}
Err(e) => {
tracing::warn!(hash = %configured, "ignoring invalid static peer hash: {e}")
@@ -1389,9 +1461,7 @@ impl LxmdRunner {
if !self.router.peers.contains_key(&peer_hash) {
continue;
}
if let Some(ref mut sync) = self.propagation_sync {
sync.request_sync_now(peer_hash);
}
self.pending_peer_syncs.insert(peer_hash);
if let Some(peer) = self.router.peers.get_mut(&peer_hash) {
peer.next_sync_attempt = 0.0;
peer.alive = true;
@@ -1399,11 +1469,21 @@ impl LxmdRunner {
tracing::info!(peer = %hex::encode(peer_hash), "control: queued peer sync");
}
ControlCommand::Unpeer(peer_hash) => {
self.router.unpeer(&peer_hash);
if let Some(ref admission) = self.propagation_admission
&& let Ok(mut admission) = admission.lock()
self.pending_peer_syncs.remove(&peer_hash);
if let Some(sync) = self.propagation_sync.as_mut() {
sync.cancel_peer_sync(&peer_hash);
}
// Upstream control unpeer breaks the live peering without
// mutating the operator's configured static-peer set.
self.router.remove_peer(&peer_hash);
if let Some(ref node) = self.propagation_node
&& let Ok(mut node) = node.lock()
&& let Err(error) = node.delete_peer(&peer_hash)
{
admission.remove_static_peer(&peer_hash);
tracing::warn!(
peer = %hex::encode(peer_hash),
"failed to remove persisted propagation peer: {error}"
);
}
if let Err(e) = self.router.save_state(&self.data_dir) {
tracing::warn!("Failed to save router state after control unpeer: {e}");
@@ -1414,6 +1494,157 @@ impl LxmdRunner {
}
}
fn drain_peering_key_results(&mut self) {
while let Ok(result) = self.peering_key_result_rx.try_recv() {
self.peering_key_jobs.remove(&result.peer_hash);
let mut applied = false;
let mut current_cost = false;
if let Some(peer) = self.router.peers.get_mut(&result.peer_hash) {
current_cost = peer.peering_cost == result.peering_cost;
// Peering-key work binds only the two identities. A newer
// announce timebase (or a lower current target) does not make
// a completed key stale if its measured value is still high
// enough for the current policy.
if let Some((key, value)) = result.peering_key
&& value >= peer.peering_cost as u32
{
peer.peering_key = Some((key, value));
applied = true;
}
}
if applied {
if let (Some(node), Some(peer)) = (
self.propagation_node.as_ref(),
self.router.peers.get(&result.peer_hash),
) && let Ok(node) = node.lock()
&& let Err(error) = node.save_peer(peer)
{
tracing::warn!(
peer = %hex::encode(result.peer_hash),
"failed to persist generated peering key: {error}"
);
}
} else if current_cost {
// A bounded key search can fail for an excessive advertised
// cost. Put this policy generation into the normal peer
// backoff instead of spinning a fresh CPU job every tick.
self.pending_peer_syncs.remove(&result.peer_hash);
if let Some(peer) = self.router.peers.get_mut(&result.peer_hash) {
peer.next_sync_attempt =
now_f64() + lxmf_core::constants::SYNC_BACKOFF_STEP as f64;
}
tracing::warn!(
peer = %hex::encode(result.peer_hash),
peering_cost = result.peering_cost,
"could not generate a peering key; sync remains postponed"
);
}
// A result for a different cost that no longer satisfies policy
// is ignored. The pending sync remains queued and dispatches a
// new job for the current target.
}
}
fn queue_due_peer_syncs(&mut self) {
if self.propagation_sync.is_none() {
return;
}
let Some(offer_generation) = self
.propagation_node
.as_ref()
.and_then(|node| node.lock().ok().map(|node| node.offer_generation()))
else {
return;
};
for policy in self.router.sync_peer_policies_for_store(offer_generation) {
self.pending_peer_syncs.insert(policy.peer_hash);
}
}
fn drive_pending_peer_syncs(&mut self) {
if self
.propagation_sync
.as_ref()
.is_none_or(|sync| sync.state != lxmf_core::propagation_sync::SyncTaskState::Idle)
{
return;
}
let mut pending = self.pending_peer_syncs.iter().copied().collect::<Vec<_>>();
pending.sort_unstable();
for peer_hash in pending {
let Some(peer_identity_hash) = recall_identity_hash(&self.known_identities, &peer_hash)
else {
tracing::debug!(
peer = %hex::encode(peer_hash),
"peer sync postponed until its identity is known"
);
continue;
};
let policy = self.router.peers.get(&peer_hash).and_then(|peer| {
(peer.stamp_costs_known() && (peer.peering_cost == 0 || peer.peering_key_ready()))
.then(|| OutboundOfferPolicy::from(peer))
});
if let Some(policy) = policy {
if let Some(sync) = self.propagation_sync.as_mut()
&& sync.request_sync_now_with_policy(policy)
{
if let Some(peer) = self.router.peers.get_mut(&peer_hash) {
peer.begin_sync();
}
self.pending_peer_syncs.remove(&peer_hash);
}
return;
}
if self
.router
.peers
.get(&peer_hash)
.is_some_and(|peer| !peer.stamp_costs_known())
{
tracing::debug!(
peer = %hex::encode(peer_hash),
"peer sync postponed until its stamp policy is known"
);
continue;
}
if self.peering_key_jobs.contains(&peer_hash) {
continue;
}
let Some(peer) = self.router.peers.get(&peer_hash) else {
self.pending_peer_syncs.remove(&peer_hash);
continue;
};
let peering_cost = peer.peering_cost;
let local_identity_hash = self.identity.hash;
let result_tx = self.peering_key_result_tx.clone();
self.peering_key_jobs.insert(peer_hash);
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
generate_peering_key_job(
peer_hash,
peering_cost,
peer_identity_hash,
local_identity_hash,
)
})
.await
.unwrap_or(PeeringKeyWorkerResult {
peer_hash,
peering_cost,
peering_key: None,
});
let _ = result_tx.send(result).await;
});
}
}
fn drain_backchannel_events(&mut self) {
let mut identified = Vec::new();
while let Ok(item) = self.link_identified_rx.try_recv() {
@@ -1663,6 +1894,9 @@ impl LxmdRunner {
let now = now_f64();
self.drain_control_commands();
self.drain_peering_key_results();
self.queue_due_peer_syncs();
self.drive_pending_peer_syncs();
self.drain_backchannel_events();
self.router.process_deferred_stamps();
@@ -1717,9 +1951,58 @@ impl LxmdRunner {
}
}
let mut peer_handled_updates = None;
let mut peer_terminal_result = None;
if let Some(ref mut ps) = self.propagation_sync {
ps.drain_events(&self.known_identities);
ps.tick();
let updates = ps.take_handled_updates();
if !updates.is_empty()
&& let Some(peer_hash) = ps.node_dest_hash()
{
peer_handled_updates = Some((peer_hash, updates));
}
peer_terminal_result = ps.take_terminal_peer_result();
}
let mut peers_to_persist = HashSet::new();
if let Some((peer_hash, updates)) = peer_handled_updates
&& let Some(peer) = self.router.peers.get_mut(&peer_hash)
{
for transient_id in updates {
peer.add_handled_message(&transient_id);
}
peers_to_persist.insert(peer_hash);
}
if let Some(result) = peer_terminal_result
&& let Some(peer) = self.router.peers.get_mut(&result.peer_hash)
{
match result.state {
lxmf_core::propagation_sync::PeerSyncTerminalState::Complete => {
peer.sync_complete();
if result.generation_exhausted
&& let Some(generation) = result.offer_generation
{
peer.mark_offer_generation_processed(generation);
}
}
lxmf_core::propagation_sync::PeerSyncTerminalState::Failed => {
peer.sync_failed();
}
}
peers_to_persist.insert(result.peer_hash);
}
for peer_hash in peers_to_persist {
if let (Some(node), Some(peer)) = (
self.propagation_node.as_ref(),
self.router.peers.get(&peer_hash),
) && let Ok(node) = node.lock()
&& let Err(error) = node.save_peer(peer)
{
tracing::warn!(
peer = %hex::encode(peer_hash),
"failed to persist peer sync state: {error}"
);
}
}
// Drive propagation client (download from node)
@@ -1897,6 +2180,98 @@ impl LxmdRunner {
{
self.router
.set_stamp_cost(event.destination_hash, pn.stamp_cost);
let is_static = self.router.static_peers.contains(&event.destination_hash);
let previous_offer_constraints = self
.router
.peers
.get(&event.destination_hash)
.map(PeerOfferConstraints::from);
let static_observation = is_static
&& (!event.is_path_response
|| self
.router
.peers
.get(&event.destination_hash)
.is_some_and(|peer| !peer.stamp_costs_known()));
let autopeer_observation =
!is_static && self.config.autopeer && !event.is_path_response;
let mut peer_changed = false;
let mut peer_removed = false;
if static_observation || (autopeer_observation && pn.node_state) {
let had_peer = self.router.peers.contains_key(&event.destination_hash);
peer_changed = self.router.autopeer(AutopeerCandidate {
destination_hash: event.destination_hash,
timebase: pn.timebase as f64,
transfer_limit: Some(pn.transfer_limit as f64),
sync_limit: Some(pn.sync_limit as f64),
stamp_cost: Some(pn.stamp_cost),
stamp_flexibility: Some(pn.stamp_flex),
peering_cost: Some(pn.peering_cost),
hops: Some(event.hops),
metadata: Some(pn.metadata.clone()),
});
peer_removed =
had_peer && !self.router.peers.contains_key(&event.destination_hash);
} else if autopeer_observation
&& !pn.node_state
&& self
.router
.peers
.get(&event.destination_hash)
.is_some_and(|peer| {
!peer.is_static && pn.timebase as f64 >= peer.peering_timebase
})
{
self.router.remove_peer(&event.destination_hash);
peer_removed = true;
}
if peer_removed {
self.pending_peer_syncs.remove(&event.destination_hash);
if let Some(sync) = self.propagation_sync.as_mut() {
sync.cancel_peer_sync(&event.destination_hash);
}
if let Some(node) = self.propagation_node.as_ref()
&& let Ok(mut node) = node.lock()
&& let Err(error) = node.delete_peer(&event.destination_hash)
{
tracing::warn!(
peer = %dest_hex,
"failed to remove retired propagation peer: {error}"
);
}
} else if peer_changed {
let offer_constraints_changed =
previous_offer_constraints.is_some_and(|previous| {
self.router
.peers
.get(&event.destination_hash)
.map(PeerOfferConstraints::from)
!= Some(previous)
});
if offer_constraints_changed
&& self
.propagation_sync
.as_mut()
.is_some_and(|sync| sync.cancel_peer_sync(&event.destination_hash))
{
if let Some(peer) = self.router.peers.get_mut(&event.destination_hash) {
peer.link_closed();
}
self.pending_peer_syncs.insert(event.destination_hash);
}
if let (Some(node), Some(peer)) = (
self.propagation_node.as_ref(),
self.router.peers.get(&event.destination_hash),
) && let Ok(node) = node.lock()
&& let Err(error) = node.save_peer(peer)
{
tracing::warn!(
peer = %dest_hex,
"failed to persist propagation peer policy: {error}"
);
}
}
tracing::debug!(
dest = %dest_hex,
stamp_cost = pn.stamp_cost,
@@ -3928,6 +4303,24 @@ mod tests {
);
}
#[test]
fn peer_key_worker_binds_remote_identity_before_local_identity() {
let remote_identity = [0x21; 16];
let local_identity = [0x43; 16];
let result = generate_peering_key_job([0x65; 16], 1, remote_identity, local_identity);
let (key, value) = result.peering_key.expect("cost-one key");
assert!(value >= 1);
let mut peering_id = [0u8; 32];
peering_id[..16].copy_from_slice(&remote_identity);
peering_id[16..].copy_from_slice(&local_identity);
assert!(lxmf_core::stamper::validate_peering_key(
&peering_id,
&key,
1
));
}
#[test]
fn pn_validation_worker_enforces_client_batch_authorization() {
let wrapper = pn_test_wrapper(vec![pn_test_entry(0), pn_test_entry(1)]);
-10
View File
@@ -241,10 +241,6 @@ impl PnInboundRuntime {
self.admission.discard_candidate(candidate)
}
pub(super) fn remove_static_peer(&mut self, peer_destination_hash: &[u8; 16]) -> bool {
self.admission.remove_static_peer(peer_destination_hash)
}
pub(super) fn is_link_quarantined(&self, link_id: &LinkId) -> bool {
self.quarantined_links.contains(link_id)
}
@@ -1032,12 +1028,6 @@ mod tests {
assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer)));
assert!(!runtime.accept_resource(link(2), resource(4), 100, Some(identity(9))));
assert!(!runtime.accept_resource(link(3), resource(5), 100, None));
assert!(runtime.remove_static_peer(&peer_destination));
assert!(
!runtime.accept_resource(link(1), resource(3), 100, Some(peer)),
"live unpeer revokes later split advertisements"
);
}
#[test]