mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
lxmf: support fractional stamp costs and announce them as upstream does
This commit is contained in:
1 parent
c8a793b0d5
commit
c65f9ef960
28 files changed
+1569
-1299
No files matched your search
Generated
+1
@@ -690,6 +690,7 @@ dependencies = [
|
||||
"rns-wire",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
|
||||
@@ -163,7 +163,7 @@ pub const TICKET_GRACE: u64 = 5 * 24 * 60 * 60;
|
||||
pub const TICKET_RENEW: u64 = 14 * 24 * 60 * 60;
|
||||
pub const TICKET_INTERVAL: u64 = 24 * 60 * 60;
|
||||
/// Sentinel cost value that always exceeds the maximum PoW cost.
|
||||
pub const COST_TICKET: u16 = 0x100;
|
||||
pub const COST_TICKET: f64 = 256.0;
|
||||
|
||||
pub const MAX_DELIVERY_ATTEMPTS: u32 = 5;
|
||||
/// Interval between router job ticks (seconds).
|
||||
@@ -186,11 +186,11 @@ pub const PROPAGATION_LIMIT: usize = 256;
|
||||
pub const DELIVERY_LIMIT: usize = 1000;
|
||||
/// PROPAGATION_LIMIT * 40, in KB.
|
||||
pub const SYNC_LIMIT: usize = 10240;
|
||||
pub const PROPAGATION_COST_MIN: u8 = 13;
|
||||
pub const PROPAGATION_COST: u8 = 16;
|
||||
pub const PROPAGATION_COST_FLEX: u8 = 3;
|
||||
pub const PEERING_COST: u8 = 18;
|
||||
pub const MAX_PEERING_COST: u8 = 26;
|
||||
pub const PROPAGATION_COST_MIN: f64 = 13.0;
|
||||
pub const PROPAGATION_COST: f64 = 16.0;
|
||||
pub const PROPAGATION_COST_FLEX: f64 = 3.0;
|
||||
pub const PEERING_COST: f64 = 18.0;
|
||||
pub const MAX_PEERING_COST: f64 = 26.0;
|
||||
pub const MAX_PEERS: usize = 20;
|
||||
pub const PN_STAMP_THROTTLE: u64 = 180;
|
||||
|
||||
@@ -335,7 +335,7 @@ mod tests {
|
||||
assert_eq!(TICKET_GRACE, 432_000);
|
||||
assert_eq!(TICKET_RENEW, 1_209_600);
|
||||
assert_eq!(TICKET_INTERVAL, 86_400);
|
||||
assert_eq!(COST_TICKET, 256);
|
||||
assert_eq!(COST_TICKET, 256.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -374,8 +374,8 @@ mod tests {
|
||||
assert_eq!(P_LINK_MAX_INACTIVITY, 180);
|
||||
assert_eq!(NODE_ANNOUNCE_DELAY, 20);
|
||||
assert_eq!(SYNC_LIMIT, 10240);
|
||||
assert_eq!(PROPAGATION_COST_MIN, 13);
|
||||
assert_eq!(MAX_PEERING_COST, 26);
|
||||
assert_eq!(PROPAGATION_COST_MIN, 13.0);
|
||||
assert_eq!(MAX_PEERING_COST, 26.0);
|
||||
assert_eq!(AUTOPEER_MAXDEPTH, 4);
|
||||
assert_eq!(FASTEST_N_RANDOM_POOL, 2);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,16 @@
|
||||
//! `rns_transport::discovery::RnsDiscoveryStamper` for callers that install it.
|
||||
use rns_transport::discovery::DiscoveryStamper;
|
||||
|
||||
use rand::RngCore;
|
||||
|
||||
use crate::stamper::{stamp_valid, stamp_workblock};
|
||||
|
||||
fn random_stamp() -> [u8; 32] {
|
||||
let mut stamp = [0u8; 32];
|
||||
rand::thread_rng().fill_bytes(&mut stamp);
|
||||
stamp
|
||||
}
|
||||
|
||||
/// Python `RNS.Discovery.InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`,
|
||||
/// the expand-round count discovery uses when building its workblock.
|
||||
///
|
||||
@@ -54,7 +62,7 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
|
||||
|
||||
/// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
|
||||
/// explicit attempt limit. Uses the same construction as
|
||||
/// [`crate::stamper::generate_stamp_limited`], without a transport runtime.
|
||||
/// [`crate::stamper::generate_stamp`], without a transport runtime.
|
||||
/// For nonzero cost, a zero iteration limit returns `None`.
|
||||
pub fn generate_discovery_stamp(
|
||||
infohash: &[u8; 32],
|
||||
@@ -62,12 +70,12 @@ pub fn generate_discovery_stamp(
|
||||
max_iterations: u64,
|
||||
) -> Option<[u8; 32]> {
|
||||
if target_value == 0 {
|
||||
return Some([0u8; 32]);
|
||||
return Some(random_stamp());
|
||||
}
|
||||
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
|
||||
for _ in 0..max_iterations {
|
||||
let candidate = crate::stamper::rand_bytes();
|
||||
if stamp_valid(&candidate, target_value, &workblock) {
|
||||
let candidate = random_stamp();
|
||||
if stamp_valid(&candidate, f64::from(target_value), &workblock) {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
@@ -149,6 +157,6 @@ mod tests {
|
||||
fn generate_discovery_stamp_cost_zero_is_instant() {
|
||||
let infohash = mk_infohash(b"helper-zero");
|
||||
let stamp = generate_discovery_stamp(&infohash, 0, 1);
|
||||
assert_eq!(stamp, Some([0u8; 32]));
|
||||
assert!(stamp.is_some());
|
||||
}
|
||||
}
|
||||
@@ -51,9 +51,10 @@ pub enum CompressionSupport {
|
||||
|
||||
/// Parsed propagation-node announce data.
|
||||
///
|
||||
/// Wire layout is a 7-element msgpack array:
|
||||
/// Wire layout is an 8-element msgpack array:
|
||||
/// `[false, timebase, node_state, transfer_limit_kb, sync_limit_kb,
|
||||
/// [stamp_cost, stamp_flex, peering_cost], metadata]`.
|
||||
/// [ceil(stamp_cost), ceil(stamp_flex), ceil(peering_cost)], metadata,
|
||||
/// [stamp_cost, stamp_flex, peering_cost]]`.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_propagation_node_app_data`.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -69,9 +70,10 @@ pub struct PropagationNodeAnnounceData {
|
||||
pub transfer_limit: u64,
|
||||
/// Per-sync limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub sync_limit: u64,
|
||||
pub stamp_cost: u8,
|
||||
pub stamp_flex: u8,
|
||||
pub peering_cost: u8,
|
||||
/// Propagation stamp cost, flexibility and peering cost as announced.
|
||||
pub stamp_cost: f64,
|
||||
pub stamp_flex: f64,
|
||||
pub peering_cost: f64,
|
||||
pub metadata: HashMap<u8, Vec<u8>>,
|
||||
}
|
||||
|
||||
@@ -80,9 +82,9 @@ impl PropagationNodeAnnounceData {
|
||||
node_state: bool,
|
||||
transfer_limit: u64,
|
||||
sync_limit: u64,
|
||||
stamp_cost: u8,
|
||||
stamp_flex: u8,
|
||||
peering_cost: u8,
|
||||
stamp_cost: f64,
|
||||
stamp_flex: f64,
|
||||
peering_cost: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
legacy: false,
|
||||
@@ -116,11 +118,9 @@ impl PropagationNodeAnnounceData {
|
||||
pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<u8> {
|
||||
use rmpv::Value;
|
||||
|
||||
let stamp_costs = Value::Array(vec![
|
||||
Value::from(data.stamp_cost as u64),
|
||||
Value::from(data.stamp_flex as u64),
|
||||
Value::from(data.peering_cost as u64),
|
||||
]);
|
||||
let costs = [data.stamp_cost, data.stamp_flex, data.peering_cost];
|
||||
let ceil_costs = Value::Array(costs.iter().map(|c| Value::from(c.ceil() as i64)).collect());
|
||||
let stamp_costs = Value::Array(costs.iter().map(|c| Value::F64(*c)).collect());
|
||||
|
||||
let metadata = {
|
||||
let mut map = Vec::new();
|
||||
@@ -136,8 +136,9 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
|
||||
Value::Boolean(data.node_state),
|
||||
Value::from(data.transfer_limit),
|
||||
Value::from(data.sync_limit),
|
||||
stamp_costs,
|
||||
ceil_costs,
|
||||
metadata,
|
||||
stamp_costs,
|
||||
]);
|
||||
|
||||
crate::encode_value(&announce_data)
|
||||
@@ -389,10 +390,11 @@ pub fn pn_announce_data_is_valid(data: &[u8]) -> bool {
|
||||
|
||||
/// Parse propagation-node announce data that [`pn_announce_data_is_valid`] accepts.
|
||||
///
|
||||
/// Values are extracted with `int()` as the Python announce handler does; it
|
||||
/// returns `None` where that handler's conversion raises. Limits below zero
|
||||
/// become zero and costs saturate to the `u8` range. Fractional costs in slot
|
||||
/// 7 are not read. Only metadata with `u8` keys and binary values is retained.
|
||||
/// Limits are extracted with `int()` as the Python announce handler does.
|
||||
/// Costs come from the fractional slot 7 when present, else from `int()` of
|
||||
/// slot 5, as the handler takes them. Limits below zero become zero; announces with a
|
||||
/// non-finite cost are refused. Only metadata with `u8` keys and binary values
|
||||
/// is retained.
|
||||
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
|
||||
let value = valid_pn_announce(data)?;
|
||||
let int_at = |index: usize| python_int(&python_index(&value, index)?);
|
||||
@@ -401,9 +403,21 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
|
||||
let limit = |raw: i128| raw.clamp(0, i128::from(u64::MAX)) as u64;
|
||||
let transfer_limit = limit(int_at(3)?);
|
||||
let sync_limit = limit(int_at(4)?);
|
||||
let costs = python_index(&value, 5)?;
|
||||
let cost =
|
||||
|index: usize| python_int(&python_index(&costs, index)?).map(|raw| raw.clamp(0, 255) as u8);
|
||||
let ceil_costs = python_index(&value, 5)?;
|
||||
for index in 0..3 {
|
||||
python_int(&python_index(&ceil_costs, index)?)?;
|
||||
}
|
||||
let fractional = python_len(&value)? > 7;
|
||||
let costs = python_index(&value, if fractional { 7 } else { 5 })?;
|
||||
// Without slot 7 the handler takes int() of slot 5.
|
||||
let cost = |index: usize| {
|
||||
let item = python_index(&costs, index)?;
|
||||
if fractional {
|
||||
python_float(&item).filter(|c| c.is_finite())
|
||||
} else {
|
||||
python_int(&item).map(|c| c as f64)
|
||||
}
|
||||
};
|
||||
let (stamp_cost, stamp_flex, peering_cost) = (cost(0)?, cost(1)?, cost(2)?);
|
||||
|
||||
let mut metadata = HashMap::new();
|
||||
@@ -429,35 +443,38 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract the integer stamp cost from propagation-node announce data.
|
||||
///
|
||||
/// Uses [`parse_pn_announce_data`]; the fractional slot 7 is not read.
|
||||
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
parse_pn_announce_data(data).map(|p| p.stamp_cost)
|
||||
/// Python `pn_stamp_cost_from_app_data`: slot 7's cost when present, else slot 5's.
|
||||
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<f64> {
|
||||
let value = valid_pn_announce(data)?;
|
||||
let slot = if python_len(&value)? > 7 { 7 } else { 5 };
|
||||
python_float(&python_index(&python_index(&value, slot)?, 0)?)
|
||||
}
|
||||
|
||||
/// Encode delivery-announce `app_data` as msgpack
|
||||
/// `[display_name, stamp_cost, supported_functionality]` where the feature
|
||||
/// list advertises [`SF_COMPRESSION`].
|
||||
///
|
||||
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
|
||||
/// The name is encoded unchanged, as Python `LXMRouter.get_announce_app_data` does.
|
||||
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
|
||||
/// Encode delivery-announce `app_data` as Python `LXMRouter.get_announce_app_data`:
|
||||
/// `[display_name, ceil(cost), [SF_COMPRESSION], cost]`, where `cost` is the
|
||||
/// quantized stamp cost when it lies in `(0, STAMP_COST_CAP)` and nil otherwise.
|
||||
/// The name is encoded unchanged.
|
||||
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<f64>) -> Vec<u8> {
|
||||
use rmpv::Value;
|
||||
|
||||
let name_val = display_name.map_or(Value::Nil, |name| Value::Binary(name.as_bytes().to_vec()));
|
||||
|
||||
let cost_val = match stamp_cost {
|
||||
Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64),
|
||||
let quantized = stamp_cost
|
||||
.filter(|cost| *cost > 0.0 && *cost < crate::stamper::STAMP_COST_CAP)
|
||||
.and_then(|cost| crate::stamper::quantize_cost(cost).ok());
|
||||
let ceil_val = match quantized {
|
||||
Some(cost) if cost != 0.0 => Value::from(cost.ceil() as i64),
|
||||
_ => Value::Nil,
|
||||
};
|
||||
|
||||
let cost_val = quantized.map_or(Value::Nil, Value::F64);
|
||||
let supported_functionality =
|
||||
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]);
|
||||
|
||||
let peer_data = Value::Array(vec![name_val, cost_val, supported_functionality]);
|
||||
|
||||
crate::encode_value(&peer_data)
|
||||
crate::encode_value(&Value::Array(vec![
|
||||
name_val,
|
||||
ceil_val,
|
||||
supported_functionality,
|
||||
cost_val,
|
||||
]))
|
||||
}
|
||||
|
||||
/// First byte of the MessagePack delivery-announce format (fixarray or array16);
|
||||
@@ -477,7 +494,7 @@ fn announce_list(data: &[u8]) -> Option<Vec<rmpv::Value>> {
|
||||
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`
|
||||
/// as [`display_name_from_app_data`] and [`stamp_cost_from_app_data`] return them.
|
||||
/// Returns `None` for empty data.
|
||||
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
|
||||
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<f64>)> {
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -487,6 +504,12 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
|
||||
))
|
||||
}
|
||||
|
||||
/// Delivery-announce `app_data` whose stamp cost cannot be read: Python's
|
||||
/// announce handler raises on it and leaves the cached cost unchanged.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("delivery announce stamp cost could not be decoded")]
|
||||
pub struct UndecodableStampCost;
|
||||
|
||||
/// Python `display_name_from_app_data`: the raw name with NUL characters and
|
||||
/// surrounding whitespace removed. Original-format data is decoded as UTF-8.
|
||||
/// The name is not filtered for display; see [`crate::presentation::sanitize_name`].
|
||||
@@ -504,27 +527,53 @@ pub fn display_name_from_app_data(data: &[u8]) -> Option<String> {
|
||||
Some(crate::presentation::python_strip(&name.replace('\0', "")).to_string())
|
||||
}
|
||||
|
||||
/// Python `stamp_cost_from_app_data`: element 3 when it is an integer, else
|
||||
/// element 1, as a `u8` when representable. A fractional element 3 is not
|
||||
/// read; element 1 carries its ceiling.
|
||||
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
if !is_announce_array_marker(*data.first()?) {
|
||||
return None;
|
||||
}
|
||||
let items = announce_list(data)?;
|
||||
if items.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let cost = match items.get(3) {
|
||||
Some(rmpv::Value::Integer(n)) if items.len() > 3 => n.as_i64(),
|
||||
_ => match &items[1] {
|
||||
rmpv::Value::Integer(n) => n.as_i64(),
|
||||
rmpv::Value::F64(f) if f.fract() == 0.0 => Some(*f as i64),
|
||||
rmpv::Value::F32(f) if f.fract() == 0.0 => Some(*f as i64),
|
||||
_ => None,
|
||||
},
|
||||
/// The stamp cost a delivery announce carries, as Python's announce handler
|
||||
/// passes it to `update_stamp_cost`. `Ok(None)` means no cost was announced
|
||||
/// (no app data, the original format, a short list or nil): the cached cost
|
||||
/// must be replaced by none. `Err` means the data could not be decoded or the
|
||||
/// cost is not a number, and the cached cost must be kept.
|
||||
///
|
||||
/// Element 3 is used when it is an integer or float, else element 1. Values
|
||||
/// are returned as given, including negative values and costs above
|
||||
/// `STAMP_COST_CAP`; generation refuses those. A boolean counts as 0 or 1.
|
||||
pub fn announced_stamp_cost(data: Option<&[u8]>) -> Result<Option<f64>, UndecodableStampCost> {
|
||||
let Some(first) = data.and_then(|d| d.first()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
cost.and_then(|c| u8::try_from(c).ok())
|
||||
if !is_announce_array_marker(*first) {
|
||||
return Ok(None);
|
||||
}
|
||||
let value = decode_python(data.unwrap_or_default()).ok_or(UndecodableStampCost)?;
|
||||
let rmpv::Value::Array(items) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
if items.len() < 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number = |value: &rmpv::Value| match value {
|
||||
rmpv::Value::Integer(n) => n
|
||||
.as_i64()
|
||||
.map(|i| i as f64)
|
||||
.or(n.as_u64().map(|u| u as f64)),
|
||||
rmpv::Value::F32(f) => Some(f64::from(*f)),
|
||||
rmpv::Value::F64(f) => Some(*f),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(cost) = items.get(3).and_then(number) {
|
||||
return Ok(Some(cost));
|
||||
}
|
||||
match &items[1] {
|
||||
rmpv::Value::Nil => Ok(None),
|
||||
rmpv::Value::Boolean(b) => Ok(Some(f64::from(u8::from(*b)))),
|
||||
other => number(other).map(Some).ok_or(UndecodableStampCost),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `stamp_cost_from_app_data`: the announced stamp cost, or `None`
|
||||
/// when none is announced or it cannot be read. Use [`announced_stamp_cost`]
|
||||
/// to tell those apart.
|
||||
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<f64> {
|
||||
announced_stamp_cost(Some(data)).ok().flatten()
|
||||
}
|
||||
|
||||
/// Parse advertised `SF_COMPRESSION` support in delivery-announce `app_data`.
|
||||
@@ -960,7 +1009,7 @@ mod tests {
|
||||
assert!(parsed.node_state);
|
||||
assert_eq!(parsed.transfer_limit, 10240);
|
||||
assert_eq!(parsed.sync_limit, 10240);
|
||||
assert_eq!(parsed.stamp_cost, 16);
|
||||
assert_eq!(parsed.stamp_cost, 16.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1013,7 +1062,10 @@ mod tests {
|
||||
let negative = parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).unwrap();
|
||||
assert_eq!(negative.transfer_limit, 0);
|
||||
let large = parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).unwrap();
|
||||
assert_eq!(large.stamp_cost, 255);
|
||||
assert_eq!(large.stamp_cost, 256.0);
|
||||
let fractional =
|
||||
parse_pn_announce_data(&encode(Value::from(10240), Value::F64(16.75))).unwrap();
|
||||
assert_eq!(fractional.stamp_cost, 16.0);
|
||||
// int(nan) raises in the Python announce handler although validity passes.
|
||||
let nan = encode(Value::from(10240), Value::F64(f64::NAN));
|
||||
assert!(pn_announce_data_is_valid(&nan));
|
||||
@@ -1026,38 +1078,58 @@ mod tests {
|
||||
true,
|
||||
PROPAGATION_LIMIT as u64,
|
||||
SYNC_LIMIT as u64,
|
||||
20,
|
||||
3,
|
||||
18,
|
||||
20.0,
|
||||
3.0,
|
||||
18.0,
|
||||
);
|
||||
let packed = get_propagation_node_app_data(&data);
|
||||
assert_eq!(pn_stamp_cost_from_app_data(&packed), Some(20));
|
||||
assert_eq!(pn_stamp_cost_from_app_data(&packed), Some(20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_roundtrip() {
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12));
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12.0));
|
||||
let (name, cost) = parse_announce_app_data(&packed).unwrap();
|
||||
assert_eq!(name, Some("Alice".to_string()));
|
||||
assert_eq!(cost, Some(12));
|
||||
assert_eq!(cost, Some(12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_matches_python_101_bytes() {
|
||||
// Python 1.0.1 oracle: msgpack([b"Test", 16, [SF_COMPRESSION]]) — LXMRouter.py:999-1001.
|
||||
assert_eq!(
|
||||
hex::encode(get_announce_app_data(Some("Test"), Some(16))),
|
||||
"93c40454657374109100"
|
||||
);
|
||||
assert_eq!(hex::encode(get_announce_app_data(None, None)), "93c0c09100");
|
||||
fn delivery_announce_data_matches_python_bytes() {
|
||||
// LXMF 1.3.0 LXMRouter.get_announce_app_data output.
|
||||
for (name, cost, want) in [
|
||||
(
|
||||
Some("Test"),
|
||||
Some(16.0),
|
||||
"94c40454657374109100cb4030000000000000",
|
||||
),
|
||||
(None, None, "94c0c09100c0"),
|
||||
(
|
||||
Some("Alice"),
|
||||
Some(12.0),
|
||||
"94c405416c6963650c9100cb4028000000000000",
|
||||
),
|
||||
(None, Some(8.0), "94c0089100cb4020000000000000"),
|
||||
(Some("x"), Some(8.5), "94c40178099100cb4021000000000000"),
|
||||
] {
|
||||
assert_eq!(hex::encode(get_announce_app_data(name, cost)), want);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_announce_omits_costs_outside_zero_to_cap() {
|
||||
for cost in [0.0, -1.0, 100.0, 150.0, f64::NAN] {
|
||||
let packed = get_announce_app_data(Some("x"), Some(cost));
|
||||
assert_eq!(hex::encode(&packed), "94c40178c09100c0", "{cost}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_no_name() {
|
||||
let packed = get_announce_app_data(None, Some(8));
|
||||
let packed = get_announce_app_data(None, Some(8.0));
|
||||
let (name, cost) = parse_announce_app_data(&packed).unwrap();
|
||||
assert!(name.is_none());
|
||||
assert_eq!(cost, Some(8));
|
||||
assert_eq!(cost, Some(8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1078,7 +1150,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_cost_zero_treated_as_none() {
|
||||
let packed = get_announce_app_data(Some("Test"), Some(0));
|
||||
let packed = get_announce_app_data(Some("Test"), Some(0.0));
|
||||
let (name, cost) = parse_announce_app_data(&packed).unwrap();
|
||||
assert_eq!(name, Some("Test".to_string()));
|
||||
assert!(cost.is_none());
|
||||
@@ -1086,19 +1158,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_display_name_from_app_data() {
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12));
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12.0));
|
||||
assert_eq!(
|
||||
display_name_from_app_data(&packed),
|
||||
Some("Alice".to_string())
|
||||
);
|
||||
|
||||
let packed = get_announce_app_data(None, Some(12));
|
||||
let packed = get_announce_app_data(None, Some(12.0));
|
||||
assert_eq!(display_name_from_app_data(&packed), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_name_from_app_data_strips_null_bytes_and_whitespace() {
|
||||
let packed = get_announce_app_data(Some(" \0Alice\0 "), Some(12));
|
||||
let packed = get_announce_app_data(Some(" \0Alice\0 "), Some(12.0));
|
||||
assert_eq!(
|
||||
display_name_from_app_data(&packed),
|
||||
Some("Alice".to_string())
|
||||
@@ -1109,7 +1181,7 @@ mod tests {
|
||||
fn test_display_name_from_app_data_returns_raw_unicode() {
|
||||
let packed = get_announce_app_data(
|
||||
Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "),
|
||||
Some(12),
|
||||
Some(12.0),
|
||||
);
|
||||
assert_eq!(
|
||||
display_name_from_app_data(&packed),
|
||||
@@ -1119,13 +1191,90 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_stamp_cost_from_app_data() {
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12));
|
||||
assert_eq!(stamp_cost_from_app_data(&packed), Some(12));
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12.0));
|
||||
assert_eq!(stamp_cost_from_app_data(&packed), Some(12.0));
|
||||
|
||||
let packed = get_announce_app_data(Some("Alice"), None);
|
||||
assert_eq!(stamp_cost_from_app_data(&packed), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announced_stamp_cost_matches_python_handler() {
|
||||
// LXMF 1.3.0 stamp_cost_from_app_data; "raise" leaves the cache unchanged.
|
||||
let ok = |cost: Option<f64>| Ok::<_, UndecodableStampCost>(cost);
|
||||
let cases: [(&str, Result<Option<f64>, UndecodableStampCost>); 16] = [
|
||||
("", ok(None)),
|
||||
("726177206e616d65", ok(None)),
|
||||
("91c40141", ok(None)),
|
||||
("92c40141c0", ok(None)),
|
||||
("92c4014108", ok(Some(8.0))),
|
||||
("94c40141099100cb4021000000000000", ok(Some(8.5))),
|
||||
("94c40141c09100c0", ok(None)),
|
||||
("93c40141cd012c9100", ok(Some(300.0))),
|
||||
("93c40141cb401e6666666666669100", ok(Some(7.6))),
|
||||
("94c40141089100cb401d000000000000", ok(Some(7.25))),
|
||||
("93c40141fb9100", ok(Some(-5.0))),
|
||||
("93c40141c39100", ok(Some(1.0))),
|
||||
("94c40141089100c40178", ok(Some(8.0))),
|
||||
("93c40141c401789100", Err(UndecodableStampCost)),
|
||||
("93c1", Err(UndecodableStampCost)),
|
||||
("92c4", Err(UndecodableStampCost)),
|
||||
];
|
||||
assert_eq!(announced_stamp_cost(None), Ok(None));
|
||||
for (data, want) in cases {
|
||||
let data = hex::decode(data).unwrap();
|
||||
assert_eq!(
|
||||
announced_stamp_cost(Some(&data)),
|
||||
want,
|
||||
"{}",
|
||||
hex::encode(&data)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pn_announce_costs_follow_python_slot_rules() {
|
||||
// LXMF 1.3.0 pn_announce_data_is_valid / pn_stamp_cost_from_app_data, and the
|
||||
// announce handler's int() of slot 5 when slot 7 is absent.
|
||||
for (data, valid, cost, handled) in [
|
||||
(
|
||||
"97c201c30a0a93cb4030666666666666031280",
|
||||
true,
|
||||
Some(16.4),
|
||||
Some(16.0),
|
||||
),
|
||||
(
|
||||
"98c201c30a0a931103138093cb4030400000000000cb4008000000000000cb4032800000000000",
|
||||
true,
|
||||
Some(16.25),
|
||||
Some(16.25),
|
||||
),
|
||||
(
|
||||
"98c201c30a0a931103138093cb4030400000000000a178cb4032800000000000",
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"98c201c30a0a931103138092cb4030400000000000cb4008000000000000",
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let data = hex::decode(data).unwrap();
|
||||
assert_eq!(pn_announce_data_is_valid(&data), valid);
|
||||
assert_eq!(pn_stamp_cost_from_app_data(&data), cost);
|
||||
assert_eq!(parse_pn_announce_data(&data).map(|p| p.stamp_cost), handled);
|
||||
}
|
||||
let exact = hex::decode(
|
||||
"98c201c30a0a931103138093cb4030400000000000cb4008000000000000cb4032800000000000",
|
||||
)
|
||||
.unwrap();
|
||||
let parsed = parse_pn_announce_data(&exact).unwrap();
|
||||
assert_eq!((parsed.stamp_flex, parsed.peering_cost), (3.0, 18.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compression_support_from_app_data() {
|
||||
// Legacy <=0.9.8 2-element app_data: unknown state, fail-open true
|
||||
@@ -1199,7 +1348,7 @@ mod tests {
|
||||
assert!(compression_support_from_app_data(&[0xc1]));
|
||||
|
||||
// Our own 1.0.1 emission round-trips as explicitly supported.
|
||||
let own = get_announce_app_data(Some("Alice"), Some(12));
|
||||
let own = get_announce_app_data(Some("Alice"), Some(12.0));
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&own),
|
||||
CompressionSupport::Supported
|
||||
@@ -1212,9 +1361,9 @@ mod tests {
|
||||
true,
|
||||
PROPAGATION_LIMIT as u64,
|
||||
SYNC_LIMIT as u64,
|
||||
20,
|
||||
3,
|
||||
18,
|
||||
20.0,
|
||||
3.0,
|
||||
18.0,
|
||||
);
|
||||
data.metadata
|
||||
.insert(crate::constants::PN_META_NAME, b"HubNode".to_vec());
|
||||
@@ -1224,7 +1373,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_pn_node_state_false() {
|
||||
let data = PropagationNodeAnnounceData::new(false, 256, 10240, 16, 3, 18);
|
||||
let data = PropagationNodeAnnounceData::new(false, 256, 10240, 16.0, 3.0, 18.0);
|
||||
let packed = get_propagation_node_app_data(&data);
|
||||
let parsed = parse_pn_announce_data(&packed).unwrap();
|
||||
assert!(!parsed.node_state);
|
||||
@@ -1232,7 +1381,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_pn_empty_metadata() {
|
||||
let data = PropagationNodeAnnounceData::new(true, 256, 10240, 16, 3, 18);
|
||||
let data = PropagationNodeAnnounceData::new(true, 256, 10240, 16.0, 3.0, 18.0);
|
||||
let packed = get_propagation_node_app_data(&data);
|
||||
let parsed = parse_pn_announce_data(&packed).unwrap();
|
||||
assert!(parsed.metadata.is_empty());
|
||||
@@ -1333,7 +1482,7 @@ mod tests {
|
||||
fn test_offer_request_handler_success() {
|
||||
let local_identity = [0xAA; 16];
|
||||
let peer_hash = [0xCC; 16];
|
||||
let cost = 8;
|
||||
let cost = 8.0;
|
||||
let handler = PropagationRequestHandler::new(local_identity);
|
||||
let mut node = crate::propagation_node::PropagationNode::new(
|
||||
crate::propagation_node::PropagationNodeConfig {
|
||||
@@ -1351,8 +1500,10 @@ mod tests {
|
||||
&peering_id,
|
||||
cost,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
&crate::stamper::StampControl::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.0
|
||||
};
|
||||
|
||||
|
||||
@@ -2421,7 +2421,7 @@ impl LinkDeliveryManager {
|
||||
let mut input = plaintext.as_slice();
|
||||
let rejection = rmpv::decode::read_value(&mut input).ok();
|
||||
if input.is_empty()
|
||||
&& matches!(rejection, Some(rmpv::Value::Array(ref a)) if a.len() == 1 && a[0].as_u64() == Some(245))
|
||||
&& matches!(rejection, Some(rmpv::Value::Array(ref a)) if a.first().and_then(rmpv::Value::as_u64) == Some(245))
|
||||
{
|
||||
delivery.message.mark_rejected();
|
||||
delivery.state = DeliveryState::Rejected;
|
||||
@@ -3893,7 +3893,11 @@ impl LinkDeliveryManager {
|
||||
resource_id,
|
||||
);
|
||||
}
|
||||
if delivery.state == DeliveryState::Complete {
|
||||
// A node that rejects a stamp tears the link down; the rejection stands.
|
||||
if matches!(
|
||||
delivery.state,
|
||||
DeliveryState::Complete | DeliveryState::Rejected
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if delivery.state == DeliveryState::Idle {
|
||||
@@ -9084,6 +9088,29 @@ mod tests {
|
||||
assert_eq!(mgr.session_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propagation_stamp_rejection_survives_link_close() {
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
let mut mgr = LinkDeliveryManager::new(tx, None, None);
|
||||
let msg = crate::message::test_message(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"Propagation",
|
||||
"deposit",
|
||||
crate::constants::DeliveryMethod::Propagated,
|
||||
);
|
||||
let link_id = mgr
|
||||
.start_packed_delivery(msg, [0xC2; 16], 1, b"packed propagation".to_vec(), false)
|
||||
.unwrap();
|
||||
let delivery = mgr.pending.get_mut(&link_id).unwrap();
|
||||
delivery.message.mark_rejected();
|
||||
delivery.state = DeliveryState::Rejected;
|
||||
assert!(mgr.handle_link_closed(&link_id, None));
|
||||
let delivery = mgr.pending.get(&link_id).unwrap();
|
||||
assert_eq!(delivery.state, DeliveryState::Rejected);
|
||||
assert_ne!(delivery.failure_reason.as_deref(), Some("link closed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_packed_delivery_is_one_shot_not_direct_session() {
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
|
||||
@@ -419,16 +419,16 @@ impl LxMessage {
|
||||
/// Stamp checking is pure; the returned value is valid only for this request's policy.
|
||||
pub fn validate_stamp_with_tickets(
|
||||
&self,
|
||||
target_cost: u8,
|
||||
target_cost: f64,
|
||||
tickets: Option<&[Vec<u8>]>,
|
||||
) -> bool {
|
||||
self.validated_stamp_value(target_cost, tickets).is_some()
|
||||
}
|
||||
pub fn validated_stamp_value(
|
||||
&self,
|
||||
target_cost: u8,
|
||||
target_cost: f64,
|
||||
tickets: Option<&[Vec<u8>]>,
|
||||
) -> Option<u16> {
|
||||
) -> Option<f64> {
|
||||
let stamp = self.stamp.as_ref()?.as_bytes();
|
||||
if let Some(tickets) = tickets {
|
||||
for ticket in tickets {
|
||||
@@ -446,7 +446,7 @@ impl LxMessage {
|
||||
let stamp = <&[u8; 32]>::try_from(stamp).ok()?;
|
||||
let work = crate::stamper::stamp_workblock(&self.message_id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
|
||||
crate::stamper::stamp_valid(stamp, target_cost, &work)
|
||||
.then(|| crate::stamper::stamp_value(&work, stamp) as u16)
|
||||
.then(|| crate::stamper::stamp_value(&work, stamp))
|
||||
}
|
||||
/// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data.
|
||||
///
|
||||
|
||||
@@ -18,7 +18,7 @@ pub struct LxMessageDraft {
|
||||
pub metadata: MessageMetadata,
|
||||
pub include_ticket: bool,
|
||||
pub outbound_ticket: Option<[u8; 16]>,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
ticket_barrier: Option<Arc<()>>,
|
||||
}
|
||||
impl Deref for LxMessageDraft {
|
||||
@@ -37,7 +37,7 @@ impl DerefMut for LxMessageDraft {
|
||||
pub struct SignedLxMessage {
|
||||
message: LxMessage,
|
||||
outbound_ticket: Option<[u8; 16]>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
}
|
||||
impl Deref for SignedLxMessage {
|
||||
type Target = MessageMetadata;
|
||||
@@ -324,7 +324,7 @@ impl SignedLxMessage {
|
||||
pub(crate) fn restored(
|
||||
message: LxMessage,
|
||||
outbound_ticket: Option<[u8; 16]>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
message,
|
||||
@@ -373,16 +373,27 @@ impl SignedLxMessage {
|
||||
pub fn fields(&self) -> Fields<'_> {
|
||||
self.message.fields()
|
||||
}
|
||||
pub fn stamp_cost(&self) -> Option<u8> {
|
||||
/// The signed, unstamped message, for failing it without a stamp.
|
||||
pub fn into_unstamped(self) -> LxMessage {
|
||||
self.message
|
||||
}
|
||||
pub fn stamp_cost(&self) -> Option<f64> {
|
||||
self.stamp_cost
|
||||
}
|
||||
pub fn outbound_ticket(&self) -> Option<[u8; 16]> {
|
||||
self.outbound_ticket
|
||||
}
|
||||
/// Compute the optional recipient stamp without changing the signed body.
|
||||
/// Runs synchronously; proof of work uses [`crate::stamper::generate_stamp`]
|
||||
/// and its attempt budget.
|
||||
/// Runs synchronously until the proof of work is found; a cost Python
|
||||
/// cannot generate is an error.
|
||||
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
|
||||
self.generate_recipient_stamp_with(&crate::stamper::StampControl::default())
|
||||
}
|
||||
/// [`Self::generate_recipient_stamp`], stopped by `ctl`'s cancel flag or deadline.
|
||||
pub fn generate_recipient_stamp_with(
|
||||
&self,
|
||||
ctl: &crate::stamper::StampControl,
|
||||
) -> Result<Option<RecipientStamp>, MessageError> {
|
||||
if let Some(ticket) = self.outbound_ticket {
|
||||
let mut material = [0u8; 48];
|
||||
material[..16].copy_from_slice(&ticket);
|
||||
@@ -392,29 +403,43 @@ impl SignedLxMessage {
|
||||
let Some(cost) = self.stamp_cost else {
|
||||
return Ok(None);
|
||||
};
|
||||
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS)
|
||||
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS, ctl)
|
||||
.map_err(packed)?
|
||||
.map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp)))
|
||||
.ok_or_else(|| packed("recipient stamp generation failed"))
|
||||
.ok_or_else(|| packed("recipient stamp generation stopped"))
|
||||
}
|
||||
pub fn finalize(self, stamp: Option<RecipientStamp>) -> Result<LxMessage, MessageError> {
|
||||
self.try_finalize(stamp).map_err(|failed| failed.0)
|
||||
}
|
||||
/// [`Self::finalize`], returning the unstamped message with the error so
|
||||
/// the caller can still fail it.
|
||||
pub fn try_finalize(
|
||||
self,
|
||||
stamp: Option<RecipientStamp>,
|
||||
) -> Result<LxMessage, Box<(MessageError, LxMessage)>> {
|
||||
let Some(stamp) = stamp else {
|
||||
return Ok(self.message);
|
||||
};
|
||||
let size = self
|
||||
.message
|
||||
match Self::stamped(&self.message, &stamp) {
|
||||
Ok(message) => Ok(message),
|
||||
Err(error) => Err(Box::new((error, self.message))),
|
||||
}
|
||||
}
|
||||
fn stamped(message: &LxMessage, stamp: &RecipientStamp) -> Result<LxMessage, MessageError> {
|
||||
let size = message
|
||||
.wire
|
||||
.len()
|
||||
.checked_add(2 + stamp.as_bytes().len())
|
||||
.ok_or_else(|| packed("length overflow"))?;
|
||||
self.message.limits.check_wire(size)?;
|
||||
message.limits.check_wire(size)?;
|
||||
let mut wire = Vec::with_capacity(size);
|
||||
wire.extend_from_slice(&self.message.wire);
|
||||
wire.extend_from_slice(&message.wire);
|
||||
wire[96] = 0x95;
|
||||
write_bin(&mut wire, stamp.as_bytes())?;
|
||||
let mut message = LxMessage::unpack_owned(wire.into(), self.message.limits)?;
|
||||
debug_assert_eq!(message.message_id, self.message.message_id);
|
||||
message.metadata = self.message.metadata;
|
||||
Ok(message)
|
||||
let mut stamped = LxMessage::unpack_owned(wire.into(), message.limits)?;
|
||||
debug_assert_eq!(stamped.message_id, message.message_id);
|
||||
stamped.metadata = message.metadata.clone();
|
||||
Ok(stamped)
|
||||
}
|
||||
}
|
||||
fn packed(error: impl std::fmt::Display) -> MessageError {
|
||||
|
||||
@@ -7,20 +7,24 @@ const HEADER_LEN: usize = 96;
|
||||
/// `0xC1` is never valid MessagePack, so no LXMF parser reads a stored form as
|
||||
/// a message.
|
||||
const MAGIC: [u8; 4] = [0xc1, b'L', b'X', b'R'];
|
||||
const VERSION: u8 = 1;
|
||||
const VERSION: u8 = 2;
|
||||
/// Version 1 stored an integer floor; it is still read.
|
||||
const VERSION_INTEGER_FLOOR: u8 = 1;
|
||||
const DIGEST_LEN: usize = 16;
|
||||
const FLOOR_AT: usize = HEADER_LEN + MAGIC.len() + 1;
|
||||
const STAMP_AT: usize = FLOOR_AT + 2;
|
||||
|
||||
/// A signed, unstamped message stored so delivery can resume after a restart.
|
||||
///
|
||||
/// Version 1 holds, in order:
|
||||
/// Version 2 holds, in order:
|
||||
/// - the signed header: destination, source and signature (96 bytes);
|
||||
/// - the bytes `0xC1`, `L`, `X`, `R`, then the version byte;
|
||||
/// - the stamp cost the message was signed under: a presence byte and a value;
|
||||
/// - the stamp cost the message was signed under, as a big-endian fixed-point
|
||||
/// cost on the 1/256 grid, 0 meaning none (version 1 held a presence byte
|
||||
/// and an integer cost);
|
||||
/// - reserved slots for a finished recipient stamp (a length byte of 0, 16
|
||||
/// or 32, then the stamp) and a propagation envelope (a big-endian `u32`
|
||||
/// length, then the envelope). Version 1 writes both empty, and a reader of
|
||||
/// length, then the envelope). Both are written empty, and a reader of
|
||||
/// this version ignores filled slots and redoes that work;
|
||||
/// - the signed payload;
|
||||
/// - the first 16 bytes of the SHA-256 of everything before them.
|
||||
@@ -31,7 +35,7 @@ const STAMP_AT: usize = FLOOR_AT + 2;
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ResumableLxMessage {
|
||||
bytes: Bytes,
|
||||
stamp_cost_floor: Option<u8>,
|
||||
stamp_cost_floor: Option<u16>,
|
||||
payload_at: usize,
|
||||
}
|
||||
|
||||
@@ -44,12 +48,16 @@ impl std::fmt::Debug for ResumableLxMessage {
|
||||
}
|
||||
|
||||
impl ResumableLxMessage {
|
||||
pub(super) fn new(wire: &[u8], stamp_cost: Option<u8>) -> Self {
|
||||
pub(super) fn new(wire: &[u8], stamp_cost: Option<f64>) -> Self {
|
||||
let floor_fp = stamp_cost
|
||||
.and_then(|cost| crate::stamper::cost_to_fp(cost).ok())
|
||||
.unwrap_or(0);
|
||||
let stamp_cost = (floor_fp > 0).then_some(floor_fp);
|
||||
let mut bytes = Vec::with_capacity(wire.len() + STAMP_AT + 5 + DIGEST_LEN);
|
||||
bytes.extend_from_slice(&wire[..HEADER_LEN]);
|
||||
bytes.extend_from_slice(&MAGIC);
|
||||
bytes.push(VERSION);
|
||||
bytes.extend_from_slice(&[u8::from(stamp_cost.is_some()), stamp_cost.unwrap_or(0)]);
|
||||
bytes.extend_from_slice(&floor_fp.to_be_bytes());
|
||||
bytes.push(0);
|
||||
bytes.extend_from_slice(&0u32.to_be_bytes());
|
||||
let payload_at = bytes.len();
|
||||
@@ -75,16 +83,21 @@ impl ResumableLxMessage {
|
||||
if bytes[HEADER_LEN..HEADER_LEN + MAGIC.len()] != MAGIC {
|
||||
return Err(invalid("not a stored message"));
|
||||
}
|
||||
if bytes[HEADER_LEN + MAGIC.len()] != VERSION {
|
||||
let version = bytes[HEADER_LEN + MAGIC.len()];
|
||||
if version != VERSION && version != VERSION_INTEGER_FLOOR {
|
||||
return Err(invalid("unsupported version"));
|
||||
}
|
||||
let digest_at = bytes.len() - DIGEST_LEN;
|
||||
if sha256(&bytes[..digest_at])[..DIGEST_LEN] != bytes[digest_at..] {
|
||||
return Err(invalid("damaged"));
|
||||
}
|
||||
let stamp_cost_floor = match bytes[FLOOR_AT..STAMP_AT] {
|
||||
[0, 0] => None,
|
||||
[1, cost] => Some(cost),
|
||||
let floor = [bytes[FLOOR_AT], bytes[FLOOR_AT + 1]];
|
||||
let stamp_cost_floor = match (version, floor) {
|
||||
(_, [0, 0]) => None,
|
||||
(VERSION_INTEGER_FLOOR, [1, cost]) => Some(u16::from(cost.min(100)) * 256),
|
||||
(VERSION, _) if u16::from_be_bytes(floor) <= crate::stamper::STAMP_COST_CAP_FP => {
|
||||
Some(u16::from_be_bytes(floor))
|
||||
}
|
||||
_ => return Err(invalid("invalid stamp cost")),
|
||||
};
|
||||
let stamp_len = usize::from(bytes[STAMP_AT]);
|
||||
@@ -114,8 +127,9 @@ impl ResumableLxMessage {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
pub(crate) fn stamp_cost_floor(&self) -> Option<u8> {
|
||||
pub(crate) fn stamp_cost_floor(&self) -> Option<f64> {
|
||||
self.stamp_cost_floor
|
||||
.map(|fp| crate::stamper::cost_from_fp(u32::from(fp)))
|
||||
}
|
||||
|
||||
/// The signed, unstamped message. Its signature is not yet checked.
|
||||
|
||||
@@ -359,7 +359,7 @@ fn recipient_stamp_array_range_and_malformed_dispositions() {
|
||||
assert_eq!(m.wire_bytes(), bytes);
|
||||
assert!(m.verify_signature(&key().public_key()));
|
||||
if !valid {
|
||||
assert!(!m.validate_stamp_with_tickets(0, None));
|
||||
assert!(!m.validate_stamp_with_tickets(0.0, None));
|
||||
}
|
||||
}
|
||||
for stamp in [vec![0xc0], vec![0x91, 0], vec![0xc4, 1, 0], vec![0xa0]] {
|
||||
@@ -381,13 +381,13 @@ fn recipient_ticket_stamp_and_missing_stamp_policy() {
|
||||
let signed = d.sign(&key()).unwrap();
|
||||
let stamp = signed.generate_recipient_stamp().unwrap();
|
||||
let m = signed.finalize(stamp).unwrap();
|
||||
assert!(m.validate_stamp_with_tickets(255, Some(&[vec![3; 16]])));
|
||||
assert!(m.validate_stamp_with_tickets(255.0, Some(&[vec![3; 16]])));
|
||||
assert_eq!(
|
||||
m.validated_stamp_value(255, Some(&[vec![3; 16]])),
|
||||
m.validated_stamp_value(255.0, Some(&[vec![3; 16]])),
|
||||
Some(COST_TICKET)
|
||||
);
|
||||
assert!(!m.validate_stamp_with_tickets(1, Some(&[vec![4; 16]])));
|
||||
assert!(!freeze(draft()).validate_stamp_with_tickets(0, None));
|
||||
assert!(!m.validate_stamp_with_tickets(1.0, Some(&[vec![4; 16]])));
|
||||
assert!(!freeze(draft()).validate_stamp_with_tickets(0.0, None));
|
||||
let signed = draft().sign(&key()).unwrap();
|
||||
assert_eq!(signed.generate_recipient_stamp().unwrap(), None);
|
||||
}
|
||||
@@ -744,7 +744,7 @@ fn resumable_identity() -> rns_identity::identity::Identity {
|
||||
|
||||
fn resumable_signed(
|
||||
identity: &rns_identity::identity::Identity,
|
||||
cost: Option<u8>,
|
||||
cost: Option<f64>,
|
||||
) -> SignedLxMessage {
|
||||
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"lxmf.delivery",
|
||||
@@ -765,14 +765,18 @@ fn resumable_signed(
|
||||
|
||||
#[test]
|
||||
fn resumable_form_bytes_are_pinned() {
|
||||
let signed = resumable_signed(&resumable_identity(), Some(8));
|
||||
let signed = resumable_signed(&resumable_identity(), Some(8.5));
|
||||
let stored = signed.to_resumable();
|
||||
let bytes = stored.as_bytes().to_vec();
|
||||
let wire = signed.finalize(None).unwrap().wire_bytes().to_vec();
|
||||
assert_eq!(bytes[..96], wire[..96], "the signed header leads");
|
||||
assert_eq!(bytes[96..100], [0xc1, b'L', b'X', b'R']);
|
||||
assert_eq!(bytes[100], 1, "version");
|
||||
assert_eq!(bytes[101..103], [1, 8], "stamp-cost floor");
|
||||
assert_eq!(bytes[100], 2, "version");
|
||||
assert_eq!(
|
||||
bytes[101..103],
|
||||
[8, 0x80],
|
||||
"stamp-cost floor 8.5 in fixed point"
|
||||
);
|
||||
assert_eq!(bytes[103], 0, "no recipient stamp yet");
|
||||
assert_eq!(bytes[104..108], [0; 4], "no propagation envelope yet");
|
||||
let digest_at = bytes.len() - 16;
|
||||
@@ -786,6 +790,25 @@ fn resumable_form_bytes_are_pinned() {
|
||||
assert_eq!(
|
||||
hex::encode(&bytes),
|
||||
concat!(
|
||||
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
|
||||
"58ead48e0227a546df7a9712ea53572c",
|
||||
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
|
||||
"8a900be403ca81baac788cf29bd9d64cab486ff0c3923571f11e4a21b4c34005",
|
||||
"c14c5852",
|
||||
"02",
|
||||
"0880",
|
||||
"00",
|
||||
"00000000",
|
||||
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
|
||||
"cc26bb944896b6a1d957f3b3ac4510ea",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resumable_form_with_integer_floor_still_loads() {
|
||||
let stored = ResumableLxMessage::from_bytes(
|
||||
hex::decode(concat!(
|
||||
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
|
||||
"58ead48e0227a546df7a9712ea53572c",
|
||||
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
|
||||
@@ -797,8 +820,11 @@ fn resumable_form_bytes_are_pinned() {
|
||||
"00000000",
|
||||
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
|
||||
"370fdcdb14f43dd52931349474302403",
|
||||
)
|
||||
);
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stored.stamp_cost_floor(), Some(8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -819,7 +845,7 @@ fn resumable_form_is_not_a_wire_message() {
|
||||
|
||||
#[test]
|
||||
fn resumable_form_round_trips_and_rejects_damage() {
|
||||
let stored = resumable_signed(&resumable_identity(), Some(8)).to_resumable();
|
||||
let stored = resumable_signed(&resumable_identity(), Some(8.0)).to_resumable();
|
||||
let bytes = stored.as_bytes().to_vec();
|
||||
assert_eq!(
|
||||
ResumableLxMessage::from_bytes(bytes.clone()).unwrap(),
|
||||
@@ -840,7 +866,7 @@ fn resumable_form_round_trips_and_rejects_damage() {
|
||||
bytes[at..].copy_from_slice(&digest[..16]);
|
||||
bytes
|
||||
};
|
||||
for (at, value) in [(100, 2), (101, 2), (103, 7), (108, 0x95)] {
|
||||
for (at, value) in [(100, 3), (101, 0x65), (103, 7), (108, 0x95)] {
|
||||
let mut unknown = bytes.clone();
|
||||
unknown[at] = value;
|
||||
assert!(
|
||||
|
||||
+103
-94
@@ -14,9 +14,9 @@ type LegacyStoredPeer = (
|
||||
Vec<u8>,
|
||||
f64,
|
||||
u32,
|
||||
u8,
|
||||
Option<u8>,
|
||||
Option<u8>,
|
||||
f64,
|
||||
Option<f64>,
|
||||
Option<f64>,
|
||||
bool,
|
||||
bool,
|
||||
Vec<Vec<u8>>,
|
||||
@@ -60,16 +60,16 @@ struct StoredPeerV2 {
|
||||
destination_hash: Vec<u8>,
|
||||
last_sync: f64,
|
||||
unreachable_count: u32,
|
||||
peering_cost: u8,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_cost_flexibility: Option<u8>,
|
||||
peering_cost: f64,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_cost_flexibility: Option<f64>,
|
||||
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)>,
|
||||
peering_key: Option<(Vec<u8>, f64)>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
last_heard: f64,
|
||||
alive: bool,
|
||||
@@ -84,14 +84,14 @@ struct StoredPeerV2 {
|
||||
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 stamp_cost: Option<f64>,
|
||||
pub stamp_cost_flexibility: Option<f64>,
|
||||
pub minimum_stamp_cost: f64,
|
||||
pub peering_cost: f64,
|
||||
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_key_value: Option<f64>,
|
||||
pub peering_timebase: f64,
|
||||
pub autopeered: bool,
|
||||
pub is_static: bool,
|
||||
@@ -109,7 +109,7 @@ impl OutboundOfferPolicy {
|
||||
handled_messages: HashSet::new(),
|
||||
stamp_cost: None,
|
||||
stamp_cost_flexibility: None,
|
||||
minimum_stamp_cost: 0,
|
||||
minimum_stamp_cost: 0.0,
|
||||
peering_cost: PEERING_COST,
|
||||
propagation_transfer_limit: None,
|
||||
propagation_sync_limit: None,
|
||||
@@ -160,13 +160,13 @@ pub struct LxmPeer {
|
||||
unhandled_count_cached: bool,
|
||||
pub unreachable_count: u32,
|
||||
pub autopeered: bool,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_cost_flexibility: Option<u8>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
pub stamp_cost_flexibility: Option<f64>,
|
||||
/// Peering cost used for outbound peering-key generation.
|
||||
pub peering_cost: u8,
|
||||
pub peering_cost: f64,
|
||||
/// Cached peering stamp and work value, generated or restored from storage.
|
||||
/// Use [`Self::peering_key_ready`] to check it against the current cost.
|
||||
pub peering_key: Option<([u8; 32], u32)>,
|
||||
pub peering_key: Option<([u8; 32], f64)>,
|
||||
/// Per-transfer propagation limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub propagation_transfer_limit: Option<f64>,
|
||||
/// Per-sync propagation limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
@@ -251,9 +251,9 @@ impl LxmPeer {
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_flexibility: Option<f64>,
|
||||
peering_cost: Option<f64>,
|
||||
) -> Self {
|
||||
Self::from_announce_with_metadata(
|
||||
destination_hash,
|
||||
@@ -274,9 +274,9 @@ impl LxmPeer {
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_flexibility: Option<f64>,
|
||||
peering_cost: Option<f64>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
) -> Self {
|
||||
let mut peer = Self::new(destination_hash);
|
||||
@@ -304,9 +304,9 @@ impl LxmPeer {
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_flexibility: Option<f64>,
|
||||
peering_cost: Option<f64>,
|
||||
) -> bool {
|
||||
let metadata = self.metadata.clone();
|
||||
self.refresh_from_announce_with_metadata(
|
||||
@@ -329,9 +329,9 @@ impl LxmPeer {
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_flexibility: Option<f64>,
|
||||
peering_cost: Option<f64>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
) -> bool {
|
||||
if timebase <= self.peering_timebase {
|
||||
@@ -358,7 +358,7 @@ impl LxmPeer {
|
||||
// the daemon must generate a replacement before taking a snapshot.
|
||||
if self
|
||||
.peering_key
|
||||
.is_some_and(|(_, value)| value < self.peering_cost as u32)
|
||||
.is_some_and(|(_, value)| value < self.peering_cost)
|
||||
{
|
||||
self.peering_key = None;
|
||||
}
|
||||
@@ -370,12 +370,12 @@ impl LxmPeer {
|
||||
|
||||
/// 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 {
|
||||
pub fn minimum_accepted_stamp_cost(&self) -> f64 {
|
||||
match self.stamp_cost {
|
||||
Some(cost) => {
|
||||
cost.saturating_sub(self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX))
|
||||
(cost - self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX)).max(0.0)
|
||||
}
|
||||
None => 0,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -565,7 +565,7 @@ impl LxmPeer {
|
||||
/// This trusts the stored/public value; it does not revalidate the key.
|
||||
pub fn peering_key_ready(&self) -> bool {
|
||||
if let Some((_, value)) = self.peering_key {
|
||||
value >= self.peering_cost as u32
|
||||
value >= self.peering_cost
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -573,7 +573,7 @@ impl LxmPeer {
|
||||
|
||||
/// Cached peering-key work value (leading zero bits), if present.
|
||||
/// Restored or caller-supplied values are returned without recomputation.
|
||||
pub fn peering_key_value(&self) -> Option<u32> {
|
||||
pub fn peering_key_value(&self) -> Option<f64> {
|
||||
self.peering_key.map(|(_, value)| value)
|
||||
}
|
||||
|
||||
@@ -584,14 +584,15 @@ impl LxmPeer {
|
||||
///
|
||||
/// Returns immediately when a key is already cached; it does not revalidate
|
||||
/// that key against a changed cost. Use [`Self::peering_key_ready`] for that
|
||||
/// check. Otherwise runs synchronous proof of work with
|
||||
/// [`crate::stamper::generate_stamp`]'s attempt budget.
|
||||
/// check. Otherwise runs synchronous proof of work until found or `ctl`
|
||||
/// stops it; a peering cost above `STAMP_COST_CAP` fails at once.
|
||||
///
|
||||
/// Python reference: `LXMPeer.generate_peering_key`.
|
||||
pub fn generate_peering_key(
|
||||
&mut self,
|
||||
peer_identity_hash: &[u8; 16],
|
||||
our_identity_hash: &[u8; 16],
|
||||
ctl: &crate::stamper::StampControl,
|
||||
) -> bool {
|
||||
if self.peering_key.is_some() {
|
||||
return true;
|
||||
@@ -601,18 +602,17 @@ impl LxmPeer {
|
||||
key_material.extend_from_slice(peer_identity_hash);
|
||||
key_material.extend_from_slice(our_identity_hash);
|
||||
|
||||
// Bounded search (stamper::stamp_iteration_cap): an announce-supplied
|
||||
// hostile peering_cost can no longer pin this thread forever.
|
||||
match crate::stamper::generate_stamp(
|
||||
&key_material,
|
||||
self.peering_cost,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
ctl,
|
||||
) {
|
||||
Some((stamp, value)) => {
|
||||
Ok(Some((stamp, value))) if value >= self.peering_cost => {
|
||||
self.peering_key = Some((stamp, value));
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,7 +684,7 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
|
||||
fn from(peer: &LxmPeer) -> Self {
|
||||
let peering_key = peer
|
||||
.peering_key
|
||||
.filter(|(_, value)| *value >= peer.peering_cost as u32)
|
||||
.filter(|(_, value)| *value >= peer.peering_cost)
|
||||
.map(|(stamp, _)| stamp.to_vec())
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
@@ -793,38 +793,38 @@ mod tests {
|
||||
#[test]
|
||||
fn test_minimum_stamp_cost() {
|
||||
let mut peer = LxmPeer::new([0; 16]);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 0.0);
|
||||
|
||||
peer.stamp_cost = Some(16);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 13);
|
||||
peer.stamp_cost = Some(16.0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 13.0);
|
||||
|
||||
// cost < flex must saturate at 0.
|
||||
peer.stamp_cost = Some(2);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
|
||||
peer.stamp_cost = Some(2.0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 0.0);
|
||||
|
||||
// Announced flexibility overrides the default.
|
||||
peer.stamp_cost = Some(16);
|
||||
peer.stamp_cost_flexibility = Some(5);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 11);
|
||||
peer.stamp_cost_flexibility = Some(0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
|
||||
peer.stamp_cost = Some(16.0);
|
||||
peer.stamp_cost_flexibility = Some(5.0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 11.0);
|
||||
peer.stamp_cost_flexibility = Some(0.0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 16.0);
|
||||
}
|
||||
|
||||
#[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.stamp_cost = Some(16.0);
|
||||
peer.stamp_cost_flexibility = Some(3.0);
|
||||
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.peering_cost = 18.0;
|
||||
peer.peering_key = Some(([0x77; 32], 18.0));
|
||||
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.minimum_stamp_cost, 13.0);
|
||||
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]);
|
||||
@@ -838,27 +838,34 @@ mod tests {
|
||||
200.0,
|
||||
Some(2.0),
|
||||
Some(8.0),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(16.0),
|
||||
Some(3.0),
|
||||
Some(18.0),
|
||||
);
|
||||
|
||||
assert!(!peer.refresh_from_announce(
|
||||
199.0,
|
||||
Some(1.0),
|
||||
Some(4.0),
|
||||
Some(8),
|
||||
Some(1),
|
||||
Some(4),
|
||||
Some(8.0),
|
||||
Some(1.0),
|
||||
Some(4.0),
|
||||
));
|
||||
assert_eq!(peer.peering_timebase, 200.0);
|
||||
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
|
||||
assert_eq!(peer.stamp_cost, Some(16));
|
||||
assert_eq!(peer.stamp_cost, Some(16.0));
|
||||
|
||||
peer.peering_key = Some(([0x55; 32], 18));
|
||||
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
|
||||
peer.peering_key = Some(([0x55; 32], 18.0));
|
||||
assert!(peer.refresh_from_announce(
|
||||
201.0,
|
||||
Some(3.0),
|
||||
None,
|
||||
Some(20.0),
|
||||
Some(4.0),
|
||||
Some(19.0),
|
||||
));
|
||||
assert_eq!(peer.propagation_sync_limit, Some(3.0));
|
||||
assert_eq!(peer.stamp_cost, Some(20));
|
||||
assert_eq!(peer.stamp_cost, Some(20.0));
|
||||
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
|
||||
}
|
||||
|
||||
@@ -869,11 +876,11 @@ mod tests {
|
||||
1234.0,
|
||||
Some(1.25),
|
||||
Some(9.5),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(16.0),
|
||||
Some(3.0),
|
||||
Some(18.0),
|
||||
);
|
||||
peer.peering_key = Some(([0x66; 32], 19));
|
||||
peer.peering_key = Some(([0x66; 32], 19.0));
|
||||
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
|
||||
peer.add_handled_message(&tid(0x22));
|
||||
|
||||
@@ -881,7 +888,7 @@ mod tests {
|
||||
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.peering_key, Some(([0x66; 32], 19.0)));
|
||||
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
|
||||
assert!(restored.has_handled(&tid(0x22)));
|
||||
|
||||
@@ -889,9 +896,9 @@ mod tests {
|
||||
vec![0xBB; 16],
|
||||
42.0,
|
||||
2,
|
||||
18,
|
||||
Some(12),
|
||||
Some(2),
|
||||
18.0,
|
||||
Some(12.0),
|
||||
Some(2.0),
|
||||
true,
|
||||
false,
|
||||
vec![tid(0x33).to_vec()],
|
||||
@@ -899,7 +906,7 @@ mod tests {
|
||||
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_eq!(restored_legacy.stamp_cost, Some(12.0));
|
||||
assert!(restored_legacy.has_handled(&tid(0x33)));
|
||||
}
|
||||
|
||||
@@ -917,9 +924,9 @@ mod tests {
|
||||
10.0,
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
Some(12),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(12.0),
|
||||
Some(3.0),
|
||||
Some(18.0),
|
||||
Some(metadata),
|
||||
);
|
||||
let retained = peer.metadata.as_ref().unwrap();
|
||||
@@ -946,15 +953,15 @@ mod tests {
|
||||
#[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);
|
||||
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16.0), Some(3.0), 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.refresh_from_announce(11.0, None, None, Some(12.0), Some(3.0), 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.refresh_from_announce(12.0, None, None, Some(12.0), Some(3.0), None));
|
||||
assert!(
|
||||
!peer.needs_offer_generation(7),
|
||||
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
|
||||
@@ -966,12 +973,14 @@ mod tests {
|
||||
#[test]
|
||||
fn test_generate_peering_key_capped() {
|
||||
let mut peer = LxmPeer::new([0xAA; 16]);
|
||||
peer.peering_cost = 255;
|
||||
assert!(!peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
|
||||
let ctl = crate::stamper::StampControl::default();
|
||||
peer.peering_cost = 255.0;
|
||||
assert!(!peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16], &ctl));
|
||||
assert!(peer.peering_key.is_none());
|
||||
|
||||
peer.peering_cost = 4;
|
||||
assert!(peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
|
||||
peer.peering_cost = 4.5;
|
||||
assert!(peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16], &ctl));
|
||||
assert!(peer.peering_key.is_some_and(|(_, value)| value >= 4.5));
|
||||
assert!(peer.peering_key.is_some());
|
||||
}
|
||||
|
||||
@@ -1049,16 +1058,16 @@ mod tests {
|
||||
1000.0,
|
||||
Some(256.0),
|
||||
Some(10240.0),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(16.0),
|
||||
Some(3.0),
|
||||
Some(18.0),
|
||||
);
|
||||
assert_eq!(peer.peering_timebase, 1000.0);
|
||||
assert_eq!(peer.propagation_transfer_limit, Some(256.0));
|
||||
assert_eq!(peer.propagation_sync_limit, Some(10240.0));
|
||||
assert_eq!(peer.stamp_cost, Some(16));
|
||||
assert_eq!(peer.stamp_cost_flexibility, Some(3));
|
||||
assert_eq!(peer.peering_cost, 18);
|
||||
assert_eq!(peer.stamp_cost, Some(16.0));
|
||||
assert_eq!(peer.stamp_cost_flexibility, Some(3.0));
|
||||
assert_eq!(peer.peering_cost, 18.0);
|
||||
assert!(peer.autopeered);
|
||||
}
|
||||
|
||||
@@ -1077,10 +1086,10 @@ mod tests {
|
||||
let mut peer = LxmPeer::new([0; 16]);
|
||||
assert!(!peer.stamp_costs_known());
|
||||
|
||||
peer.stamp_cost = Some(16);
|
||||
peer.stamp_cost = Some(16.0);
|
||||
assert!(!peer.stamp_costs_known());
|
||||
|
||||
peer.stamp_cost_flexibility = Some(3);
|
||||
peer.stamp_cost_flexibility = Some(3.0);
|
||||
assert!(peer.stamp_costs_known());
|
||||
}
|
||||
|
||||
|
||||
@@ -295,14 +295,14 @@ mod tests {
|
||||
costs.insert(
|
||||
[0xAA; 16],
|
||||
StampCostEntry {
|
||||
cost: 12,
|
||||
cost: Some(12.5),
|
||||
recorded_at: 1_700_000_000.0,
|
||||
},
|
||||
);
|
||||
save_stamp_costs(tmp.path(), &costs).unwrap();
|
||||
let loaded = load_stamp_costs(tmp.path()).unwrap();
|
||||
assert_eq!(loaded.len(), 1);
|
||||
assert_eq!(loaded[&[0xAA; 16]].cost, 12);
|
||||
assert_eq!(loaded[&[0xAA; 16]].cost, Some(12.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -15,7 +15,8 @@ pub struct PropagationEntry {
|
||||
pub message_hash: [u8; 32],
|
||||
pub destination_hash: [u8; 16],
|
||||
pub stored_at: f64,
|
||||
pub stamp_value: u8,
|
||||
/// Quantized stamp value, as Python stores it.
|
||||
pub stamp_value: f64,
|
||||
pub size: usize,
|
||||
pub collected: bool,
|
||||
/// When true, the stored file contains `lxmf_data || propagation_stamp`.
|
||||
@@ -30,7 +31,7 @@ impl PropagationEntry {
|
||||
message_hash: [u8; 32],
|
||||
destination_hash: [u8; 16],
|
||||
size: usize,
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
transient_id,
|
||||
@@ -49,7 +50,7 @@ impl PropagationEntry {
|
||||
message_hash: [u8; 32],
|
||||
destination_hash: [u8; 16],
|
||||
size: usize,
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
) -> Self {
|
||||
let mut entry = Self::new(
|
||||
transient_id,
|
||||
@@ -62,13 +63,18 @@ impl PropagationEntry {
|
||||
entry
|
||||
}
|
||||
|
||||
/// Format: `{hex_transient_id}_{timestamp}_{stamp_value}`.
|
||||
/// Python's message-store name `{hex_transient_id}_{received}_{stamp_value}`,
|
||||
/// with both numbers in Python float form and no value part for value 0.
|
||||
pub fn filename(&self) -> String {
|
||||
let value = if self.stamp_value > 0.0 {
|
||||
format!("_{:?}", self.stamp_value)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
format!(
|
||||
"{}_{:.0}_{}",
|
||||
"{}_{:?}{value}",
|
||||
hex_encode(&self.transient_id),
|
||||
self.stored_at,
|
||||
self.stamp_value
|
||||
self.stored_at
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,19 +85,19 @@ impl PropagationEntry {
|
||||
/// # Panics
|
||||
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
|
||||
/// Validate that untrusted filenames are ASCII before calling.
|
||||
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
|
||||
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, f64)> {
|
||||
let parts: Vec<&str> = filename.split('_').collect();
|
||||
match parts.len() {
|
||||
3 => {
|
||||
let tid = hex_decode_32(parts[0])?;
|
||||
let ts: f64 = parts[1].parse().ok()?;
|
||||
let sv: u8 = parts[2].parse().ok()?;
|
||||
Some((tid, ts, sv))
|
||||
let sv: f64 = parts[2].parse().ok()?;
|
||||
Some((tid, ts, crate::stamper::quantize_cost(sv).ok()?))
|
||||
}
|
||||
2 => {
|
||||
let tid = hex_decode_32(parts[0])?;
|
||||
let ts: f64 = parts[1].parse().ok()?;
|
||||
Some((tid, ts, 0))
|
||||
Some((tid, ts, 0.0))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -252,7 +258,7 @@ impl PropagationStore {
|
||||
priority_weight * age_weight * entry.size as f64
|
||||
}
|
||||
|
||||
pub fn get_stamp_value(&self, transient_id: &PropagationTransientId) -> Option<u8> {
|
||||
pub fn get_stamp_value(&self, transient_id: &PropagationTransientId) -> Option<f64> {
|
||||
self.entries.get(transient_id).map(|e| e.stamp_value)
|
||||
}
|
||||
|
||||
@@ -396,7 +402,7 @@ mod tests {
|
||||
message_hash: [0xBB; 32],
|
||||
destination_hash: [0xCC; 16],
|
||||
stored_at: 1234567890.0,
|
||||
stamp_value: 8,
|
||||
stamp_value: 8.0,
|
||||
size: 500,
|
||||
collected: false,
|
||||
stamped: false,
|
||||
@@ -407,7 +413,8 @@ mod tests {
|
||||
);
|
||||
let parts: Vec<&str> = fname.split('_').collect();
|
||||
assert_eq!(parts.len(), 3);
|
||||
assert_eq!(parts[2], "8");
|
||||
assert_eq!(parts[1], "1234567890.0");
|
||||
assert_eq!(parts[2], "8.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -417,7 +424,30 @@ mod tests {
|
||||
let (tid, ts, sv) = PropagationEntry::parse_filename(fname).unwrap();
|
||||
assert_eq!(tid[0], 0xaa);
|
||||
assert_eq!(ts, 1234567890.0);
|
||||
assert_eq!(sv, 16);
|
||||
assert_eq!(sv, 16.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_filename_reads_python_float_names() {
|
||||
let tid = "ab".repeat(32);
|
||||
for (name, value) in [
|
||||
(format!("{tid}_1794274814.6018312_8.0"), 8.0),
|
||||
(format!("{tid}_1794274814.6018312_16.25"), 16.25),
|
||||
(format!("{tid}_1794274814.6018312_0.7421875"), 0.7421875),
|
||||
] {
|
||||
let (_, ts, sv) = PropagationEntry::parse_filename(&name).unwrap();
|
||||
assert_eq!(ts, 1794274814.6018312);
|
||||
assert_eq!(sv, value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filename_omits_zero_value_and_writes_fractional_value() {
|
||||
let mut entry = PropagationEntry::new(tid(0xAA), [0; 32], [0; 16], 10, 16.25);
|
||||
entry.stored_at = 1794274814.6018312;
|
||||
assert!(entry.filename().ends_with("_1794274814.6018312_16.25"));
|
||||
entry.stamp_value = 0.0;
|
||||
assert!(entry.filename().ends_with("_1794274814.6018312"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -426,7 +456,7 @@ mod tests {
|
||||
let (tid, ts, sv) = PropagationEntry::parse_filename(&fname).unwrap();
|
||||
assert_eq!(tid[0], 0xaa);
|
||||
assert_eq!(ts, 1234567890.0);
|
||||
assert_eq!(sv, 0);
|
||||
assert_eq!(sv, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -440,7 +470,7 @@ mod tests {
|
||||
let mut store = PropagationStore::new();
|
||||
assert!(store.is_empty());
|
||||
|
||||
let entry = PropagationEntry::new(tid(0xAA), [0xBB; 32], [0xCC; 16], 500, 8);
|
||||
let entry = PropagationEntry::new(tid(0xAA), [0xBB; 32], [0xCC; 16], 500, 8.0);
|
||||
store.insert(entry);
|
||||
|
||||
assert_eq!(store.len(), 1);
|
||||
@@ -457,14 +487,14 @@ mod tests {
|
||||
[0xBB; 32],
|
||||
[0xCC; 16],
|
||||
500,
|
||||
8,
|
||||
8.0,
|
||||
));
|
||||
store.insert(PropagationEntry::new(
|
||||
tid(0xDD),
|
||||
[0xEE; 32],
|
||||
[0xCC; 16],
|
||||
300,
|
||||
4,
|
||||
4.0,
|
||||
));
|
||||
|
||||
assert_eq!(store.total_size(), 800);
|
||||
@@ -480,9 +510,9 @@ mod tests {
|
||||
let dest1 = [0xAA; 16];
|
||||
let dest2 = [0xBB; 16];
|
||||
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], dest1, 100, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x02), [0; 32], dest1, 200, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x03), [0; 32], dest2, 300, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], dest1, 100, 0.0));
|
||||
store.insert(PropagationEntry::new(tid(0x02), [0; 32], dest1, 200, 0.0));
|
||||
store.insert(PropagationEntry::new(tid(0x03), [0; 32], dest2, 300, 0.0));
|
||||
|
||||
assert_eq!(store.entries_for_destination(&dest1).len(), 2);
|
||||
assert_eq!(store.entries_for_destination(&dest2).len(), 1);
|
||||
@@ -491,8 +521,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_transient_ids() {
|
||||
let mut store = PropagationStore::new();
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x02), [0; 32], [0; 16], 200, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0.0));
|
||||
store.insert(PropagationEntry::new(tid(0x02), [0; 32], [0; 16], 200, 0.0));
|
||||
|
||||
let ids = store.transient_ids();
|
||||
assert_eq!(ids.len(), 2);
|
||||
@@ -506,16 +536,16 @@ mod tests {
|
||||
|
||||
store.ignore_destination(ignored_dest);
|
||||
|
||||
let entry1 = PropagationEntry::new(tid(0x01), [0; 32], ignored_dest, 100, 0);
|
||||
let entry1 = PropagationEntry::new(tid(0x01), [0; 32], ignored_dest, 100, 0.0);
|
||||
assert!(!store.insert(entry1));
|
||||
assert_eq!(store.len(), 0);
|
||||
|
||||
let entry2 = PropagationEntry::new(tid(0x02), [0; 32], allowed_dest, 200, 0);
|
||||
let entry2 = PropagationEntry::new(tid(0x02), [0; 32], allowed_dest, 200, 0.0);
|
||||
assert!(store.insert(entry2));
|
||||
assert_eq!(store.len(), 1);
|
||||
|
||||
store.unignore_destination(&ignored_dest);
|
||||
let entry3 = PropagationEntry::new(tid(0x03), [0; 32], ignored_dest, 100, 0);
|
||||
let entry3 = PropagationEntry::new(tid(0x03), [0; 32], ignored_dest, 100, 0.0);
|
||||
assert!(store.insert(entry3));
|
||||
assert_eq!(store.len(), 2);
|
||||
}
|
||||
@@ -573,12 +603,12 @@ mod tests {
|
||||
fn test_cull_by_weight() {
|
||||
let mut store = PropagationStore::new();
|
||||
|
||||
let mut entry1 = PropagationEntry::new(tid(0x01), [0; 32], [0xAA; 16], 500, 0);
|
||||
let mut entry1 = PropagationEntry::new(tid(0x01), [0; 32], [0xAA; 16], 500, 0.0);
|
||||
entry1.stored_at = 1000.0;
|
||||
store.entries.insert(entry1.transient_id, entry1.clone());
|
||||
store.total_size += 500;
|
||||
|
||||
let mut entry2 = PropagationEntry::new(tid(0x02), [0; 32], [0xBB; 16], 300, 0);
|
||||
let mut entry2 = PropagationEntry::new(tid(0x02), [0; 32], [0xBB; 16], 300, 0.0);
|
||||
entry2.stored_at = now_f64();
|
||||
store.entries.insert(entry2.transient_id, entry2.clone());
|
||||
store.total_size += 300;
|
||||
@@ -622,7 +652,7 @@ mod tests {
|
||||
message_hash: [0; 32],
|
||||
destination_hash: [0xAA; 16],
|
||||
stored_at: now,
|
||||
stamp_value: 0,
|
||||
stamp_value: 0.0,
|
||||
size: 1000,
|
||||
collected: false,
|
||||
stamped: false,
|
||||
@@ -645,9 +675,15 @@ mod tests {
|
||||
#[test]
|
||||
fn test_get_stamp_value() {
|
||||
let mut store = PropagationStore::new();
|
||||
store.insert(PropagationEntry::new(tid(0xAA), [0; 32], [0; 16], 100, 12));
|
||||
store.insert(PropagationEntry::new(
|
||||
tid(0xAA),
|
||||
[0; 32],
|
||||
[0; 16],
|
||||
100,
|
||||
12.0,
|
||||
));
|
||||
|
||||
assert_eq!(store.get_stamp_value(&tid(0xAA)), Some(12));
|
||||
assert_eq!(store.get_stamp_value(&tid(0xAA)), Some(12.0));
|
||||
assert_eq!(store.get_stamp_value(&tid(0xBB)), None);
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,8 @@ pub struct PropagationNodeConfig {
|
||||
pub max_message_age: u64,
|
||||
/// Messages below this effective stamp value are rejected. Python derives
|
||||
/// this from `propagation_stamp_cost - propagation_stamp_cost_flexibility`.
|
||||
pub min_stamp_cost: u8,
|
||||
pub peering_cost: u8,
|
||||
pub min_stamp_cost: f64,
|
||||
pub peering_cost: f64,
|
||||
/// Maximum newly admitted image size in bytes, including the 32-byte PN stamp.
|
||||
pub max_message_size: usize,
|
||||
/// Maximum encoded inbound `/offer` request size in bytes. The default
|
||||
@@ -42,7 +42,7 @@ impl Default for PropagationNodeConfig {
|
||||
max_storage: PROPAGATION_LIMIT * 1024 * 1024,
|
||||
max_message_age: MESSAGE_EXPIRY,
|
||||
// Disabled by default; set to PROPAGATION_COST for production.
|
||||
min_stamp_cost: 0,
|
||||
min_stamp_cost: 0.0,
|
||||
peering_cost: PEERING_COST,
|
||||
max_message_size: DELIVERY_LIMIT * BYTES_PER_KILOBYTE,
|
||||
max_offer_size: SYNC_LIMIT * BYTES_PER_KILOBYTE,
|
||||
@@ -390,10 +390,10 @@ pub fn read_planned_messages(
|
||||
pub struct ValidatedOpaquePropagationBlob {
|
||||
bytes: bytes::Bytes,
|
||||
transient_id: PropagationTransientId,
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
}
|
||||
impl ValidatedOpaquePropagationBlob {
|
||||
pub fn validate(bytes: bytes::Bytes, minimum_stamp_cost: u8) -> Option<Self> {
|
||||
pub fn validate(bytes: bytes::Bytes, minimum_stamp_cost: f64) -> Option<Self> {
|
||||
if bytes.len() < DESTINATION_LENGTH + 1 + 32
|
||||
|| bytes.len() > rns_protocol::resource::MAX_RESOURCE_SIZE
|
||||
{
|
||||
@@ -404,8 +404,8 @@ impl ValidatedOpaquePropagationBlob {
|
||||
let transient_id = rns_crypto::sha::full_hash(body);
|
||||
let workblock =
|
||||
crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
|
||||
let stamp_value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8;
|
||||
(stamp_value >= minimum_stamp_cost).then_some(Self {
|
||||
let stamp_value = crate::stamper::stamp_value(&workblock, stamp);
|
||||
crate::stamper::stamp_valid(stamp, minimum_stamp_cost, &workblock).then_some(Self {
|
||||
bytes,
|
||||
transient_id,
|
||||
stamp_value,
|
||||
@@ -414,7 +414,7 @@ impl ValidatedOpaquePropagationBlob {
|
||||
pub fn transient_id(&self) -> PropagationTransientId {
|
||||
self.transient_id
|
||||
}
|
||||
pub fn stamp_value(&self) -> u8 {
|
||||
pub fn stamp_value(&self) -> f64 {
|
||||
self.stamp_value
|
||||
}
|
||||
}
|
||||
@@ -531,7 +531,7 @@ pub(crate) struct SyncOfferCandidateSnapshot {
|
||||
transient_id: PropagationTransientId,
|
||||
weight: f64,
|
||||
size: usize,
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
}
|
||||
|
||||
/// Cheap, owned view captured while the shared node lock is held. Expensive
|
||||
@@ -698,11 +698,11 @@ impl PropagationNode {
|
||||
self.storage_path.is_some()
|
||||
}
|
||||
|
||||
pub fn min_stamp_cost(&self) -> u8 {
|
||||
pub fn min_stamp_cost(&self) -> f64 {
|
||||
self.config.min_stamp_cost
|
||||
}
|
||||
|
||||
pub fn set_min_stamp_cost(&mut self, cost: u8) {
|
||||
pub fn set_min_stamp_cost(&mut self, cost: f64) {
|
||||
self.config.min_stamp_cost = cost;
|
||||
}
|
||||
|
||||
@@ -903,7 +903,7 @@ impl PropagationNode {
|
||||
&mut self,
|
||||
lxmf_data: &[u8],
|
||||
stamp_data: &[u8; 32],
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
) -> Option<PropagationStoreWritePlan> {
|
||||
let mut bytes = Vec::with_capacity(lxmf_data.len().checked_add(32)?);
|
||||
if lxmf_data.len().checked_add(32)? > self.config.max_message_size {
|
||||
@@ -948,7 +948,7 @@ impl PropagationNode {
|
||||
.filter_map(|w| w.upgrade())
|
||||
.fold(0usize, |n, r| n.saturating_add(r.size));
|
||||
if !self.is_durable()
|
||||
|| blob.stamp_value < self.config.min_stamp_cost
|
||||
|| !crate::stamper::value_meets(blob.stamp_value, self.config.min_stamp_cost)
|
||||
|| blob.bytes.len() > self.config.max_message_size
|
||||
{
|
||||
return PropagationAdmission::Rejected;
|
||||
@@ -994,7 +994,7 @@ impl PropagationNode {
|
||||
&mut self,
|
||||
lxmf_data: &[u8],
|
||||
stamp_data: &[u8; 32],
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
) -> bool {
|
||||
let Some(plan) =
|
||||
self.plan_accept_stamped_propagated_blob(lxmf_data, stamp_data, stamp_value)
|
||||
@@ -1111,10 +1111,10 @@ impl PropagationNode {
|
||||
pub fn create_offer(
|
||||
&self,
|
||||
_peer_hash: [u8; 16],
|
||||
peer_min_stamp_cost: Option<u8>,
|
||||
peer_min_stamp_cost: Option<f64>,
|
||||
) -> Vec<PropagationTransientId> {
|
||||
match peer_min_stamp_cost {
|
||||
Some(min_cost) if min_cost > 0 => self
|
||||
Some(min_cost) if min_cost > 0.0 => self
|
||||
.store
|
||||
.entries()
|
||||
.filter(|e| self.eligible(&e.transient_id) && e.stamp_value >= min_cost)
|
||||
@@ -1765,7 +1765,7 @@ pub(crate) mod tests {
|
||||
pub(crate) struct OpaqueFixture {
|
||||
pub(crate) data: Vec<u8>,
|
||||
pub(crate) stamp: [u8; 32],
|
||||
pub(crate) value: u8,
|
||||
pub(crate) value: f64,
|
||||
pub(crate) transient_id: Option<[u8; 32]>,
|
||||
pub(crate) hash: Option<[u8; 32]>,
|
||||
pub(crate) timestamp: f64,
|
||||
@@ -1775,7 +1775,7 @@ pub(crate) mod tests {
|
||||
self.transient_id.unwrap()
|
||||
}
|
||||
}
|
||||
pub(crate) fn fixture_stamp(data: &[u8], cost: u8) -> ([u8; 32], u32) {
|
||||
pub(crate) fn fixture_stamp(data: &[u8], cost: u8) -> ([u8; 32], f64) {
|
||||
let id = rns_crypto::sha::full_hash(data);
|
||||
let block = crate::stamper::stamp_workblock(
|
||||
&id,
|
||||
@@ -1787,7 +1787,7 @@ pub(crate) mod tests {
|
||||
let mut stamp = [0; 32];
|
||||
stamp[..8].copy_from_slice(&counter.to_be_bytes());
|
||||
let value = crate::stamper::stamp_value(&block, &stamp);
|
||||
if value == u32::from(cost) {
|
||||
if value.floor() == f64::from(cost) {
|
||||
return (stamp, value);
|
||||
}
|
||||
}
|
||||
@@ -1809,7 +1809,7 @@ pub(crate) mod tests {
|
||||
OpaqueFixture {
|
||||
data,
|
||||
stamp,
|
||||
value: value.min(255) as u8,
|
||||
value,
|
||||
transient_id: Some(transient_id),
|
||||
hash: Some(transient_id),
|
||||
timestamp: crate::now_f64(),
|
||||
@@ -1859,7 +1859,7 @@ pub(crate) mod tests {
|
||||
}
|
||||
pub(crate) fn accept_blob_fixture(&mut self, data: &[u8], cost: u8) -> bool {
|
||||
let (stamp, value) = fixture_stamp(data, cost);
|
||||
self.accept_stamped_propagated_blob(data, &stamp, value.min(255) as u8)
|
||||
self.accept_stamped_propagated_blob(data, &stamp, value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1871,7 +1871,7 @@ pub(crate) mod tests {
|
||||
node: &mut PropagationNode,
|
||||
transient_id: PropagationTransientId,
|
||||
size: usize,
|
||||
stamp_value: u8,
|
||||
stamp_value: f64,
|
||||
) {
|
||||
let entry =
|
||||
PropagationEntry::new(transient_id, transient_id, [0xDD; 16], size, stamp_value);
|
||||
@@ -1882,7 +1882,7 @@ pub(crate) mod tests {
|
||||
vec![byte; 32]
|
||||
}
|
||||
|
||||
fn peering_key(local_identity: &[u8; 16], remote_identity: &[u8; 16], cost: u8) -> [u8; 32] {
|
||||
fn peering_key(local_identity: &[u8; 16], remote_identity: &[u8; 16], cost: f64) -> [u8; 32] {
|
||||
let mut peering_id = Vec::with_capacity(32);
|
||||
peering_id.extend_from_slice(local_identity);
|
||||
peering_id.extend_from_slice(remote_identity);
|
||||
@@ -1890,8 +1890,10 @@ pub(crate) mod tests {
|
||||
&peering_id,
|
||||
cost,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
&crate::stamper::StampControl::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
|
||||
@@ -2029,7 +2031,7 @@ pub(crate) mod tests {
|
||||
|
||||
let mut duplicate = message.data.clone();
|
||||
duplicate.extend_from_slice(&message.stamp);
|
||||
let blob = ValidatedOpaquePropagationBlob::validate(duplicate.into(), 0).unwrap();
|
||||
let blob = ValidatedOpaquePropagationBlob::validate(duplicate.into(), 0.0).unwrap();
|
||||
let PropagationAdmission::CommittedDuplicate(check) = node.plan_opaque_admission(blob)
|
||||
else {
|
||||
panic!("previous admission retains duplicate acknowledgement authority");
|
||||
@@ -2073,7 +2075,7 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn test_reject_no_hash() {
|
||||
let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
assert!(!node.accept_stamped_propagated_blob(&[0; 16], &[0; 32], 0));
|
||||
assert!(!node.accept_stamped_propagated_blob(&[0; 16], &[0; 32], 0.0));
|
||||
assert_eq!(node.message_count(), 0);
|
||||
}
|
||||
|
||||
@@ -2128,15 +2130,15 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn authoritative_offer_policy_combines_all_filters_and_real_key() {
|
||||
let mut node = durable_test_node(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
|
||||
insert_offer_entry(&mut node, tid(0x01), 100, 20.0); // handled
|
||||
insert_offer_entry(&mut node, tid(0x02), 100, 12.0); // low stamp
|
||||
insert_offer_entry(&mut node, tid(0x03), 100, 13.0); // accepted
|
||||
insert_offer_entry(&mut node, tid(0x04), 985, 20.0); // 1001 B with overhead
|
||||
insert_offer_entry(&mut node, tid(0x05), 984, 13.0); // exact 1000 B
|
||||
|
||||
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
|
||||
policy.handled_messages.insert(tid(0x01));
|
||||
policy.minimum_stamp_cost = 13;
|
||||
policy.minimum_stamp_cost = 13.0;
|
||||
policy.propagation_transfer_limit = Some(1.0);
|
||||
policy.propagation_sync_limit = Some(10.0);
|
||||
policy.peering_key = vec![0x77; 32];
|
||||
@@ -2157,8 +2159,8 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn offer_cumulative_limit_is_decimal_and_excludes_exact_boundary() {
|
||||
let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
insert_offer_entry(&mut node, tid(0x01), 50, 0);
|
||||
insert_offer_entry(&mut node, tid(0x02), 50, 0);
|
||||
insert_offer_entry(&mut node, tid(0x01), 50, 0.0);
|
||||
insert_offer_entry(&mut node, tid(0x02), 50, 0.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.
|
||||
@@ -2172,12 +2174,12 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn prepared_offer_distinguishes_terminal_filters_from_cumulative_deferral() {
|
||||
let mut node = durable_test_node(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
|
||||
insert_offer_entry(&mut node, tid(0x01), 10, 9.0); // terminal low stamp
|
||||
insert_offer_entry(&mut node, tid(0x02), 100, 20.0); // selected
|
||||
insert_offer_entry(&mut node, tid(0x03), 100, 20.0); // cumulative deferred
|
||||
insert_offer_entry(&mut node, tid(0x04), 1000, 20.0); // terminal oversize
|
||||
let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
|
||||
policy.minimum_stamp_cost = 10;
|
||||
policy.minimum_stamp_cost = 10.0;
|
||||
policy.propagation_transfer_limit = Some(0.5);
|
||||
policy.propagation_sync_limit = Some(0.2);
|
||||
|
||||
@@ -2194,8 +2196,8 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn all_cumulatively_deferred_candidates_exhaust_unchanged_generation() {
|
||||
let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
insert_offer_entry(&mut node, tid(0x01), 50, 20);
|
||||
insert_offer_entry(&mut node, tid(0x02), 50, 20);
|
||||
insert_offer_entry(&mut node, tid(0x01), 50, 20.0);
|
||||
insert_offer_entry(&mut node, tid(0x02), 50, 20.0);
|
||||
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.
|
||||
@@ -2242,9 +2244,9 @@ pub(crate) mod tests {
|
||||
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);
|
||||
insert_offer_entry(&mut node, tid(0x01), 50, 0.0);
|
||||
insert_offer_entry(&mut node, tid(0x02), 50, 0.0);
|
||||
insert_offer_entry(&mut node, tid(0x03), 50, 0.0);
|
||||
|
||||
let mut persisted = LxmPeer::new([0xBB; 16]);
|
||||
persisted.add_handled_message(&tid(0x01));
|
||||
@@ -2632,11 +2634,11 @@ pub(crate) mod tests {
|
||||
let id = message.message_id();
|
||||
let object = node.object_paths[&id].clone();
|
||||
assert!(object.exists());
|
||||
assert!(object.with_extension("entry").exists());
|
||||
assert!(crate::propagation_store_v2::manifest_path(&object).exists());
|
||||
node.tick();
|
||||
assert_eq!(node.message_count(), 0);
|
||||
assert!(!object.exists());
|
||||
assert!(!object.with_extension("entry").exists());
|
||||
assert!(!crate::propagation_store_v2::manifest_path(&object).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2872,7 +2874,7 @@ pub(crate) mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_handle_offer_request_valid() {
|
||||
let cost = 8;
|
||||
let cost = 8.0;
|
||||
let local_identity = [0xAA; 16];
|
||||
let remote_identity = [0xBB; 16];
|
||||
let config = PropagationNodeConfig {
|
||||
@@ -2907,7 +2909,7 @@ pub(crate) mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_offer_evaluation_uses_preflight_candidate_identity() {
|
||||
let cost = 8;
|
||||
let cost = 8.0;
|
||||
let local_identity = [0xAA; 16];
|
||||
let remote_identity = [0xBB; 16];
|
||||
let config = PropagationNodeConfig {
|
||||
@@ -2962,7 +2964,7 @@ pub(crate) mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_handle_offer_request_rejects_wrong_peering_identity_order() {
|
||||
let cost = 8;
|
||||
let cost = 8.0;
|
||||
let local_identity = [0xAA; 16];
|
||||
let remote_identity = [0xBB; 16];
|
||||
let config = PropagationNodeConfig {
|
||||
@@ -3036,7 +3038,7 @@ pub(crate) mod tests {
|
||||
fn test_handle_offer_request_invalid_data() {
|
||||
let mut node = durable_test_node(
|
||||
PropagationNodeConfig {
|
||||
peering_cost: 0,
|
||||
peering_cost: 0.0,
|
||||
..Default::default()
|
||||
},
|
||||
[0xAA; 16],
|
||||
@@ -3185,20 +3187,17 @@ pub(crate) mod tests {
|
||||
let stamp = [0x5A; 32];
|
||||
let full_id = rns_crypto::sha::full_hash(&lxmf_data);
|
||||
|
||||
assert!(
|
||||
node.accept_stamped_propagated_blob(
|
||||
&lxmf_data,
|
||||
&stamp,
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(
|
||||
&rns_crypto::sha::full_hash(&lxmf_data),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN
|
||||
),
|
||||
&stamp
|
||||
)
|
||||
.min(255) as u8
|
||||
assert!(node.accept_stamped_propagated_blob(
|
||||
&lxmf_data,
|
||||
&stamp,
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(
|
||||
&rns_crypto::sha::full_hash(&lxmf_data),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN
|
||||
),
|
||||
&stamp
|
||||
)
|
||||
);
|
||||
));
|
||||
|
||||
let peer_results = node.message_get_request(&[full_id]);
|
||||
assert_eq!(peer_results.len(), 1);
|
||||
@@ -3242,20 +3241,17 @@ pub(crate) mod tests {
|
||||
dir.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
node.accept_stamped_propagated_blob(
|
||||
&lxmf_data,
|
||||
&stamp,
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(
|
||||
&rns_crypto::sha::full_hash(&lxmf_data),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN
|
||||
),
|
||||
&stamp
|
||||
)
|
||||
.min(255) as u8
|
||||
assert!(node.accept_stamped_propagated_blob(
|
||||
&lxmf_data,
|
||||
&stamp,
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(
|
||||
&rns_crypto::sha::full_hash(&lxmf_data),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN
|
||||
),
|
||||
&stamp
|
||||
)
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let mut reloaded = PropagationNode::with_storage(
|
||||
@@ -3286,7 +3282,7 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn test_accept_propagated_blob_enforces_min_stamp_cost() {
|
||||
let config = PropagationNodeConfig {
|
||||
min_stamp_cost: 8,
|
||||
min_stamp_cost: 8.0,
|
||||
..Default::default()
|
||||
};
|
||||
let mut node = durable_test_node(config, [0xAA; 16]);
|
||||
@@ -3375,7 +3371,7 @@ pub(crate) mod tests {
|
||||
let id = rns_crypto::sha::full_hash(&blob);
|
||||
let mut stored = blob.clone();
|
||||
stored.extend_from_slice(&stamp);
|
||||
assert!(node.accept_stamped_propagated_blob(&blob, &stamp, value as u8));
|
||||
assert!(node.accept_stamped_propagated_blob(&blob, &stamp, value));
|
||||
let object = node.object_paths[&id].clone();
|
||||
assert_eq!(std::fs::read(&object).unwrap(), stored);
|
||||
drop(node);
|
||||
@@ -3385,7 +3381,7 @@ pub(crate) mod tests {
|
||||
assert_eq!(node.message_count(), 1);
|
||||
assert_eq!(node.total_size(), stored.len());
|
||||
assert!(node.store.get(&id).unwrap().stamped);
|
||||
assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, value as u8));
|
||||
assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, value));
|
||||
assert!(node.pending_write_ids.is_empty());
|
||||
assert_eq!(node.pending_write_bytes, 0);
|
||||
let request = crate::encode_value(&Value::Array(vec![
|
||||
@@ -3686,7 +3682,7 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn test_stamp_cost_validation_rejects_unstamped() {
|
||||
let config = PropagationNodeConfig {
|
||||
min_stamp_cost: 8,
|
||||
min_stamp_cost: 8.0,
|
||||
..Default::default()
|
||||
};
|
||||
let mut node = durable_test_node(config, [0xAA; 16]);
|
||||
@@ -3699,7 +3695,7 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn test_stamp_cost_zero_accepts_all() {
|
||||
let config = PropagationNodeConfig {
|
||||
min_stamp_cost: 0,
|
||||
min_stamp_cost: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
let mut node = durable_test_node(config, [0xAA; 16]);
|
||||
@@ -3718,7 +3714,7 @@ pub(crate) mod tests {
|
||||
message_hash: [0x11; 32],
|
||||
destination_hash: [0xCC; 16],
|
||||
stored_at: 1000.0,
|
||||
stamp_value: 20,
|
||||
stamp_value: 20.0,
|
||||
size: 100,
|
||||
collected: false,
|
||||
stamped: false,
|
||||
@@ -3728,7 +3724,7 @@ pub(crate) mod tests {
|
||||
message_hash: [0x22; 32],
|
||||
destination_hash: [0xCC; 16],
|
||||
stored_at: 1000.0,
|
||||
stamp_value: 5,
|
||||
stamp_value: 5.0,
|
||||
size: 100,
|
||||
collected: false,
|
||||
stamped: false,
|
||||
@@ -3739,11 +3735,11 @@ pub(crate) mod tests {
|
||||
let all = node.create_offer([0xFF; 16], None);
|
||||
assert_eq!(all.len(), 2);
|
||||
|
||||
let filtered = node.create_offer([0xFF; 16], Some(10));
|
||||
let filtered = node.create_offer([0xFF; 16], Some(10.0));
|
||||
assert_eq!(filtered.len(), 1);
|
||||
assert_eq!(filtered[0], tid(0x01));
|
||||
|
||||
let all2 = node.create_offer([0xFF; 16], Some(0));
|
||||
let all2 = node.create_offer([0xFF; 16], Some(0.0));
|
||||
assert_eq!(all2.len(), 2);
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -79,7 +79,7 @@ pub(crate) fn evaluate<F>(
|
||||
request_data: &[u8],
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
peering_cost: f64,
|
||||
max_offer_size: usize,
|
||||
contains: F,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
|
||||
@@ -100,14 +100,14 @@ pub(crate) fn evaluate_decoded<F>(
|
||||
offer: DecodedOffer,
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
peering_cost: f64,
|
||||
mut contains: F,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
|
||||
where
|
||||
F: FnMut(&PropagationTransientId) -> bool,
|
||||
{
|
||||
let peering_key_valid = match offer.peering_key {
|
||||
DecodedPeeringKey::Empty => peering_cost == 0,
|
||||
DecodedPeeringKey::Empty => peering_cost == 0.0,
|
||||
DecodedPeeringKey::Key(key) => {
|
||||
let mut peering_id = [0u8; 32];
|
||||
peering_id[..16].copy_from_slice(local_identity_hash);
|
||||
@@ -241,7 +241,7 @@ mod tests {
|
||||
|
||||
for request in malformed {
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
@@ -249,7 +249,7 @@ mod tests {
|
||||
let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![]));
|
||||
trailing.push(0xc0);
|
||||
assert_eq!(
|
||||
evaluate(&trailing, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
evaluate(&trailing, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
@@ -258,7 +258,7 @@ mod tests {
|
||||
fn decode_rejects_requests_over_the_bounded_sync_budget() {
|
||||
let request = vec![0xc0; 65];
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 64, |_| false),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0.0, 64, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
@@ -271,7 +271,7 @@ mod tests {
|
||||
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0.0, usize::MAX, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
@@ -283,11 +283,11 @@ mod tests {
|
||||
Value::Array(vec![Value::Binary(id(3).to_vec())]),
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 1.0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidKey)
|
||||
);
|
||||
}
|
||||
@@ -305,7 +305,7 @@ mod tests {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]),
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |id| *id == [1; 32]),
|
||||
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! Shared propagation preparation for daemon and embedding applications.
|
||||
use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN;
|
||||
use crate::message::{LxMessage, MessageError};
|
||||
use crate::stamper::StampControl;
|
||||
use bytes::Bytes;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AdvertisedNodePolicy {
|
||||
pub stamp_cost: u8,
|
||||
/// Announced propagation stamp cost; generation clamps it to `0..=100`.
|
||||
pub stamp_cost: f64,
|
||||
pub transfer_limit_kb: f64,
|
||||
pub recorded_at: f64,
|
||||
}
|
||||
@@ -70,15 +71,35 @@ pub struct PropagationEnvelope {
|
||||
transient_id: [u8; 32],
|
||||
encryption_binding: [u8; 32],
|
||||
stamp: [u8; 32],
|
||||
stamp_value: u32,
|
||||
required_cost: u8,
|
||||
stamp_value: f64,
|
||||
required_cost: f64,
|
||||
}
|
||||
|
||||
/// Python `get_outbound_propagation_cost` clamps the node's cost into `0..=100`.
|
||||
fn outbound_pn_cost(cost: f64) -> f64 {
|
||||
cost.clamp(0.0, crate::stamper::STAMP_COST_CAP)
|
||||
}
|
||||
|
||||
fn generate_pn_stamp(
|
||||
transient_id: &[u8; 32],
|
||||
cost: f64,
|
||||
ctl: &StampControl,
|
||||
) -> Result<([u8; 32], f64), MessageError> {
|
||||
crate::stamper::generate_stamp(
|
||||
transient_id,
|
||||
outbound_pn_cost(cost),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
ctl,
|
||||
)
|
||||
.map_err(|e| MessageError::PackFailed(format!("PN stamp generation failed: {e}")))?
|
||||
.ok_or_else(|| MessageError::PackFailed("PN stamp generation cancelled".into()))
|
||||
}
|
||||
|
||||
impl PropagationEnvelope {
|
||||
pub fn new<F>(
|
||||
message: LxMessage,
|
||||
encryption_binding: [u8; 32],
|
||||
required_cost: u8,
|
||||
required_cost: f64,
|
||||
encrypt: F,
|
||||
) -> Result<Self, MessageError>
|
||||
where
|
||||
@@ -89,15 +110,15 @@ impl PropagationEnvelope {
|
||||
encryption_binding,
|
||||
required_cost,
|
||||
encrypt,
|
||||
&AtomicBool::new(false),
|
||||
&StampControl::default(),
|
||||
)
|
||||
}
|
||||
pub fn new_cancellable<F>(
|
||||
message: LxMessage,
|
||||
encryption_binding: [u8; 32],
|
||||
required_cost: u8,
|
||||
required_cost: f64,
|
||||
encrypt: F,
|
||||
cancel: &AtomicBool,
|
||||
ctl: &StampControl,
|
||||
) -> Result<Self, MessageError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -107,28 +128,7 @@ impl PropagationEnvelope {
|
||||
ciphertext.extend_from_slice(&message.destination_hash());
|
||||
ciphertext.extend_from_slice(&encrypted);
|
||||
let transient_id = rns_crypto::sha::full_hash(&ciphertext);
|
||||
let (stamp, generated_value) = crate::stamper::generate_stamp_cancellable(
|
||||
&transient_id,
|
||||
required_cost,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
cancel,
|
||||
)
|
||||
.ok_or_else(|| MessageError::PackFailed("PN stamp generation failed".into()))?;
|
||||
// The general stamper's cost-zero shortcut reports the required lower
|
||||
// bound. Envelopes carry the measured value used by strict relay ingress.
|
||||
let stamp_value = if required_cost == 0 {
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
|
||||
&stamp,
|
||||
)
|
||||
} else {
|
||||
generated_value
|
||||
};
|
||||
if cancel.load(std::sync::atomic::Ordering::Acquire) {
|
||||
return Err(MessageError::PackFailed(
|
||||
"PN stamp generation cancelled".into(),
|
||||
));
|
||||
}
|
||||
let (stamp, stamp_value) = generate_pn_stamp(&transient_id, required_cost, ctl)?;
|
||||
Ok(Self {
|
||||
message,
|
||||
ciphertext: ciphertext.into(),
|
||||
@@ -151,9 +151,13 @@ impl PropagationEnvelope {
|
||||
pub fn stamp(&self) -> &[u8; 32] {
|
||||
&self.stamp
|
||||
}
|
||||
pub fn stamp_value(&self) -> u32 {
|
||||
pub fn stamp_value(&self) -> f64 {
|
||||
self.stamp_value
|
||||
}
|
||||
/// Whether the saved stamp already meets a node's announced cost.
|
||||
pub fn meets(&self, cost: f64) -> bool {
|
||||
crate::stamper::value_meets(self.stamp_value, outbound_pn_cost(cost))
|
||||
}
|
||||
pub fn matches(&self, message: &LxMessage, encryption_binding: &[u8; 32]) -> bool {
|
||||
self.message.wire_bytes() == message.wire_bytes()
|
||||
&& &self.encryption_binding == encryption_binding
|
||||
@@ -166,27 +170,22 @@ impl PropagationEnvelope {
|
||||
node: PreparedNode,
|
||||
timestamp: f64,
|
||||
) -> Result<Vec<u8>, MessageError> {
|
||||
self.pack_for_cancellable(node, timestamp, &AtomicBool::new(false))
|
||||
self.pack_for_cancellable(node, timestamp, &StampControl::default())
|
||||
}
|
||||
pub fn pack_for_cancellable(
|
||||
&mut self,
|
||||
node: PreparedNode,
|
||||
timestamp: f64,
|
||||
cancel: &AtomicBool,
|
||||
ctl: &StampControl,
|
||||
) -> Result<Vec<u8>, MessageError> {
|
||||
if !timestamp.is_finite() {
|
||||
return Err(MessageError::PackFailed(
|
||||
"propagation timestamp must be finite".into(),
|
||||
));
|
||||
}
|
||||
if self.stamp_value < u32::from(node.policy.stamp_cost) {
|
||||
(self.stamp, self.stamp_value) = crate::stamper::generate_stamp_cancellable(
|
||||
&self.transient_id,
|
||||
node.policy.stamp_cost,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
cancel,
|
||||
)
|
||||
.ok_or_else(|| MessageError::PackFailed("PN stamp regeneration failed".into()))?;
|
||||
if !self.meets(node.policy.stamp_cost) {
|
||||
(self.stamp, self.stamp_value) =
|
||||
generate_pn_stamp(&self.transient_id, node.policy.stamp_cost, ctl)?;
|
||||
}
|
||||
self.required_cost = node.policy.stamp_cost;
|
||||
let blob_len = self
|
||||
@@ -239,7 +238,7 @@ mod tests {
|
||||
#[test]
|
||||
fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() {
|
||||
let policy = AdvertisedNodePolicy {
|
||||
stamp_cost: 0,
|
||||
stamp_cost: 0.0,
|
||||
transfer_limit_kb: 256.,
|
||||
recorded_at: 100.,
|
||||
};
|
||||
@@ -262,7 +261,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.finalize(None)
|
||||
.unwrap();
|
||||
let mut envelope = PropagationEnvelope::new(msg, [4; 32], 0, |p| Ok(p.to_vec())).unwrap();
|
||||
let mut envelope = PropagationEnvelope::new(msg, [4; 32], 0.0, |p| Ok(p.to_vec())).unwrap();
|
||||
let before = envelope.ciphertext.clone();
|
||||
let tid = envelope.transient_id();
|
||||
assert_eq!(
|
||||
@@ -275,23 +274,23 @@ mod tests {
|
||||
let mut prepared = PreparedNode {
|
||||
node: [5; 16],
|
||||
policy: AdvertisedNodePolicy {
|
||||
stamp_cost: 0,
|
||||
stamp_cost: 0.0,
|
||||
transfer_limit_kb: 256.,
|
||||
recorded_at: 100.,
|
||||
},
|
||||
};
|
||||
let first = envelope.pack_for(prepared, 101.).unwrap();
|
||||
prepared.policy.stamp_cost = 4;
|
||||
prepared.policy.stamp_cost = 4.5;
|
||||
let next = envelope.pack_for(prepared, 102.).unwrap();
|
||||
assert_eq!(envelope.ciphertext(), &before);
|
||||
assert_eq!(envelope.transient_id(), tid);
|
||||
assert!(envelope.stamp_value() >= 4);
|
||||
assert!(envelope.stamp_value() >= 4.5);
|
||||
assert_ne!(first, next);
|
||||
assert!(
|
||||
crate::stamper::stamp_value(
|
||||
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
|
||||
envelope.stamp()
|
||||
) >= 4
|
||||
) >= 4.5
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ pub(crate) struct EntryManifest {
|
||||
pub content_hash: [u8; 32],
|
||||
pub destination: [u8; 16],
|
||||
pub size: usize,
|
||||
pub stamp_value: u8,
|
||||
pub stamp_value: f64,
|
||||
pub stored_at: f64,
|
||||
pub stamped: bool,
|
||||
pub origin: OpaqueIngress,
|
||||
@@ -168,10 +168,13 @@ impl EntryManifest {
|
||||
)
|
||||
&& (self.origin == OpaqueIngress::TrustedRecovery || self.stamped)
|
||||
}
|
||||
/// Relay object name. Integer values keep the form older stores wrote.
|
||||
pub(crate) fn filename(&self) -> String {
|
||||
format!(
|
||||
"{}_{}",
|
||||
self.entry().filename(),
|
||||
"{}_{:.0}_{}_{}",
|
||||
hex::encode(self.transient_id),
|
||||
self.stored_at,
|
||||
self.stamp_value,
|
||||
hex::encode(self.admission_id)
|
||||
)
|
||||
}
|
||||
@@ -456,7 +459,8 @@ mod tests {
|
||||
);
|
||||
let tid = rns_crypto::sha::full_hash(&data);
|
||||
data.extend_from_slice(&[0; 32]);
|
||||
let mut entry = crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0);
|
||||
let mut entry =
|
||||
crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0.0);
|
||||
entry.stamped = true;
|
||||
let meta = EntryManifest::from_entry(&entry, &data);
|
||||
let object = root.join("objects").join(meta.filename());
|
||||
|
||||
@@ -22,7 +22,7 @@ pub struct RecoveryEntry {
|
||||
pub struct RecoveryPolicy {
|
||||
pub maximum_store_bytes: usize,
|
||||
pub maximum_message_bytes: usize,
|
||||
pub minimum_stamp_cost: u8,
|
||||
pub minimum_stamp_cost: f64,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RecoveryReport {
|
||||
@@ -33,7 +33,7 @@ pub struct RecoveryReport {
|
||||
fn validate(
|
||||
record: &RecoveryEntry,
|
||||
bytes: &[u8],
|
||||
minimum_stamp_cost: u8,
|
||||
minimum_stamp_cost: f64,
|
||||
) -> io::Result<EntryManifest> {
|
||||
let tail = if record.stamped { 32 } else { 0 };
|
||||
if bytes.len() < 112 + tail
|
||||
@@ -62,16 +62,15 @@ fn validate(
|
||||
&record.transient_id,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
);
|
||||
let value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8;
|
||||
if value < minimum_stamp_cost {
|
||||
if !crate::stamper::stamp_valid(stamp, minimum_stamp_cost, &workblock) {
|
||||
return Err(invalid("recovered stamp does not meet node policy"));
|
||||
}
|
||||
value
|
||||
crate::stamper::stamp_value(&workblock, stamp)
|
||||
} else {
|
||||
if minimum_stamp_cost > 0 {
|
||||
if minimum_stamp_cost > 0.0 {
|
||||
return Err(invalid("unstamped recovery does not meet node policy"));
|
||||
}
|
||||
0
|
||||
0.0
|
||||
};
|
||||
let mut destination = [0; 16];
|
||||
destination.copy_from_slice(&bytes[..16]);
|
||||
@@ -216,7 +215,7 @@ mod tests {
|
||||
RecoveryPolicy {
|
||||
maximum_store_bytes: 8192,
|
||||
maximum_message_bytes: 4096,
|
||||
minimum_stamp_cost: 0,
|
||||
minimum_stamp_cost: 0.0,
|
||||
}
|
||||
}
|
||||
fn record(bytes: &[u8], name: &str) -> RecoveryEntry {
|
||||
|
||||
@@ -2934,7 +2934,7 @@ mod tests {
|
||||
.accept_blob_fixture(&oversized, 2)
|
||||
);
|
||||
let mut policy = OutboundOfferPolicy::unrestricted(node_hash);
|
||||
policy.minimum_stamp_cost = 1;
|
||||
policy.minimum_stamp_cost = 1.0;
|
||||
policy.propagation_transfer_limit = Some(0.5);
|
||||
let mut task = PropagationSyncTask::with_shared_node(tx, shared_node);
|
||||
task.set_node(node_hash);
|
||||
|
||||
+266
-137
@@ -77,9 +77,9 @@ pub struct RouterConfig {
|
||||
pub propagation_limit_kb: usize,
|
||||
pub delivery_limit_kb: f64,
|
||||
pub sync_limit_kb: usize,
|
||||
pub propagation_stamp_cost: u8,
|
||||
pub propagation_stamp_flex: u8,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub propagation_stamp_cost: f64,
|
||||
pub propagation_stamp_flex: f64,
|
||||
pub stamp_cost: Option<f64>,
|
||||
pub ext: RouterConfigExt,
|
||||
}
|
||||
|
||||
@@ -89,9 +89,9 @@ pub struct RouterConfig {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RouterConfigExt {
|
||||
pub autopeer_maxdepth: usize,
|
||||
pub propagation_cost_min: u8,
|
||||
pub peering_cost: u8,
|
||||
pub max_peering_cost: u8,
|
||||
pub propagation_cost_min: f64,
|
||||
pub peering_cost: f64,
|
||||
pub max_peering_cost: f64,
|
||||
pub processing_outbound: bool,
|
||||
/// Maximum messages advanced per outbound-processing call (`None` = no count limit).
|
||||
pub processing_limit: Option<usize>,
|
||||
@@ -390,19 +390,20 @@ pub struct AutopeerCandidate {
|
||||
pub timebase: f64,
|
||||
pub transfer_limit: Option<f64>,
|
||||
pub sync_limit: Option<f64>,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_flexibility: Option<u8>,
|
||||
pub peering_cost: Option<u8>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
pub stamp_flexibility: Option<f64>,
|
||||
pub peering_cost: Option<f64>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// Cached stamp cost for a destination.
|
||||
/// Cached stamp cost for a destination; `None` records an announce without
|
||||
/// a cost. Integer costs stored by older versions still load.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct StampCostEntry {
|
||||
pub cost: u8,
|
||||
pub cost: Option<f64>,
|
||||
pub recorded_at: f64,
|
||||
}
|
||||
|
||||
@@ -622,7 +623,7 @@ impl LxmRouter {
|
||||
.map(|t| t.token);
|
||||
}
|
||||
if message.stamp_cost.is_none() {
|
||||
message.stamp_cost = self.get_stamp_cost(&destination).filter(|v| *v > 0);
|
||||
message.stamp_cost = self.get_stamp_cost(&destination);
|
||||
}
|
||||
if message.include_ticket
|
||||
&& message.get_field(FIELD_TICKET).is_none()
|
||||
@@ -677,7 +678,7 @@ impl LxmRouter {
|
||||
}
|
||||
if self.config.ext.defer_stamp_generation
|
||||
&& message.outbound_ticket().is_none()
|
||||
&& message.stamp_cost().unwrap_or(0) > 0
|
||||
&& message.stamp_cost().is_some()
|
||||
{
|
||||
self.defer_stamp(message);
|
||||
return Ok(());
|
||||
@@ -708,8 +709,11 @@ impl LxmRouter {
|
||||
};
|
||||
let destination = message.destination_hash();
|
||||
let outbound_ticket = self.get_outbound_ticket(&destination);
|
||||
let current_cost = self.get_stamp_cost(&destination).filter(|cost| *cost > 0);
|
||||
let stamp_cost = stored.stamp_cost_floor().max(current_cost);
|
||||
let current_cost = self.get_stamp_cost(&destination);
|
||||
let stamp_cost = match (stored.stamp_cost_floor(), current_cost) {
|
||||
(Some(floor), Some(current)) => Some(floor.max(current)),
|
||||
(floor, current) => floor.or(current),
|
||||
};
|
||||
Ok(SignedLxMessage::restored(
|
||||
message,
|
||||
outbound_ticket,
|
||||
@@ -750,41 +754,34 @@ impl LxmRouter {
|
||||
return;
|
||||
};
|
||||
let message = &self.pending_deferred_stamps[&message_hash];
|
||||
let cost = message.stamp_cost().unwrap_or(0);
|
||||
if cost == 0 || message.outbound_ticket().is_some() {
|
||||
if let Some(message) = self.pending_deferred_stamps.remove(&message_hash) {
|
||||
let stamp = message.generate_recipient_stamp();
|
||||
match stamp.and_then(|stamp| message.finalize(stamp)) {
|
||||
Ok(message) => {
|
||||
let _ = self.try_send(message);
|
||||
}
|
||||
Err(error) => tracing::warn!(%error,"recipient stamp finalization failed"),
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let cost = message.stamp_cost();
|
||||
let runtime = tokio::runtime::Handle::try_current()
|
||||
.ok()
|
||||
.or_else(|| self.runtime_handle.clone());
|
||||
if let Some(runtime) = runtime {
|
||||
let (handle, rx) = stamper::spawn_deferred_stamp_on(
|
||||
&runtime,
|
||||
message_hash,
|
||||
cost,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS,
|
||||
);
|
||||
self.active_deferred_stamp = Some(DeferredStampJob {
|
||||
message_hash,
|
||||
handle,
|
||||
rx,
|
||||
});
|
||||
} else if let Some(message) = self.pending_deferred_stamps.remove(&message_hash) {
|
||||
let stamp = message.generate_recipient_stamp();
|
||||
match stamp.and_then(|stamp| message.finalize(stamp)) {
|
||||
Ok(message) => {
|
||||
let _ = self.try_send(message);
|
||||
match (cost, runtime) {
|
||||
(Some(cost), Some(runtime)) if message.outbound_ticket().is_none() => {
|
||||
let (handle, rx) = stamper::spawn_deferred_stamp_on(
|
||||
&runtime,
|
||||
message_hash,
|
||||
cost,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS,
|
||||
);
|
||||
self.active_deferred_stamp = Some(DeferredStampJob {
|
||||
message_hash,
|
||||
handle,
|
||||
rx,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
if let Some(message) = self.pending_deferred_stamps.remove(&message_hash) {
|
||||
match message.generate_recipient_stamp() {
|
||||
Ok(stamp) => self.send_stamped(message, stamp),
|
||||
Err(error) => {
|
||||
tracing::error!(%error, "deferred stamp generation did not succeed");
|
||||
Self::fail_unsent(message.into_unstamped());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => tracing::warn!(%error,"recipient stamp generation failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -793,21 +790,56 @@ impl LxmRouter {
|
||||
let Some(mut job) = self.active_deferred_stamp.take() else {
|
||||
return;
|
||||
};
|
||||
match job.rx.try_recv() {
|
||||
let result = match job.rx.try_recv() {
|
||||
Err(oneshot::error::TryRecvError::Empty) => {
|
||||
self.active_deferred_stamp = Some(job);
|
||||
return;
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
let Some(message) = self.pending_deferred_stamps.remove(&job.message_hash) else {
|
||||
return;
|
||||
};
|
||||
match result {
|
||||
Ok(stamper::DeferredStampResult::Success { stamp, .. }) => {
|
||||
if let Some(message) = self.pending_deferred_stamps.remove(&job.message_hash) {
|
||||
match message.finalize(Some(RecipientStamp::ProofOfWork(stamp))) {
|
||||
Ok(message) => {
|
||||
let _ = self.try_send(message);
|
||||
}
|
||||
Err(error) => tracing::warn!(%error,"recipient stamp finalization failed"),
|
||||
}
|
||||
}
|
||||
self.send_stamped(message, Some(RecipientStamp::ProofOfWork(stamp)));
|
||||
}
|
||||
Err(oneshot::error::TryRecvError::Empty) => self.active_deferred_stamp = Some(job),
|
||||
_ => {
|
||||
self.pending_deferred_stamps.remove(&job.message_hash);
|
||||
Ok(stamper::DeferredStampResult::Cancelled) => {
|
||||
let mut message = message.into_unstamped();
|
||||
message.state = MessageState::Cancelled;
|
||||
message.notify_failed();
|
||||
}
|
||||
Ok(stamper::DeferredStampResult::Failed(error)) => {
|
||||
tracing::error!(%error, "deferred stamp generation did not succeed");
|
||||
Self::fail_unsent(message.into_unstamped());
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::error!("deferred stamp worker ended without a result");
|
||||
Self::fail_unsent(message.into_unstamped());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_stamped(&mut self, message: SignedLxMessage, stamp: Option<RecipientStamp>) {
|
||||
match message.try_finalize(stamp) {
|
||||
Ok(message) => {
|
||||
let _ = self.try_send(message);
|
||||
}
|
||||
Err(failed) => {
|
||||
let (error, message) = *failed;
|
||||
tracing::error!(%error, "recipient stamp finalization failed");
|
||||
Self::fail_unsent(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `fail_message` for a message outside the outbound queue.
|
||||
fn fail_unsent(mut message: LxMessage) {
|
||||
message.progress = 0.0;
|
||||
if message.state != MessageState::Rejected {
|
||||
message.mark_failed();
|
||||
} else {
|
||||
message.notify_failed();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1090,6 +1122,7 @@ impl LxmRouter {
|
||||
|
||||
let mut msg = self.pending_outbound.remove(pos);
|
||||
msg.mark_rejected();
|
||||
msg.notify_failed();
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1132,16 +1165,16 @@ impl LxmRouter {
|
||||
/// Returns the cached entry unchanged, without an expiry check. Use
|
||||
/// [`Self::get_stamp_cost`] to exclude expired entries. Unlike Python's
|
||||
/// same-named message-ID lookup, this API takes a destination hash.
|
||||
pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<u8> {
|
||||
pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<f64> {
|
||||
self.outbound_stamp_costs
|
||||
.get(destination_hash)
|
||||
.map(|e| e.cost)
|
||||
.and_then(|e| e.cost)
|
||||
}
|
||||
|
||||
/// Return the recipient stamp cost recorded on a deferred message.
|
||||
/// Despite this method's name, it reads only `pending_deferred_stamps` and
|
||||
/// does not return the separate propagation-node admission stamp target.
|
||||
pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option<u8> {
|
||||
pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option<f64> {
|
||||
self.pending_deferred_stamps
|
||||
.get(message_hash)
|
||||
.and_then(|m| m.stamp_cost())
|
||||
@@ -1423,7 +1456,7 @@ impl LxmRouter {
|
||||
// Python LXMRouter.peer() (LXMRouter.py:1896-1901): a peering cost
|
||||
// above our accepted maximum refuses the peering — and breaks an
|
||||
// existing one only when that policy announce is not stale.
|
||||
if peering_cost.unwrap_or(0) > self.config.ext.max_peering_cost {
|
||||
if peering_cost.unwrap_or(0.0) > self.config.ext.max_peering_cost {
|
||||
if self
|
||||
.peers
|
||||
.get(&destination_hash)
|
||||
@@ -1503,18 +1536,26 @@ impl LxmRouter {
|
||||
self.static_peers.retain(|h| h != destination_hash);
|
||||
}
|
||||
|
||||
/// Get a cached outbound stamp cost, or `None` if missing or expired.
|
||||
pub fn get_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<u8> {
|
||||
/// Get a cached outbound stamp cost, or `None` if missing, expired or
|
||||
/// announced without a cost.
|
||||
pub fn get_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<f64> {
|
||||
let entry = self.outbound_stamp_costs.get(destination_hash)?;
|
||||
let now = now_f64();
|
||||
if now - entry.recorded_at < STAMP_COST_EXPIRY as f64 {
|
||||
Some(entry.cost)
|
||||
entry.cost
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_stamp_cost(&mut self, destination_hash: [u8; 16], cost: u8) {
|
||||
pub fn set_stamp_cost(&mut self, destination_hash: [u8; 16], cost: f64) {
|
||||
self.update_stamp_cost(destination_hash, Some(cost));
|
||||
}
|
||||
|
||||
/// Python `update_stamp_cost`: record the cost a destination's latest
|
||||
/// announce carried. `None` keeps an entry that makes later messages
|
||||
/// unstamped until the next announce.
|
||||
pub fn update_stamp_cost(&mut self, destination_hash: [u8; 16], cost: Option<f64>) {
|
||||
let now = now_f64();
|
||||
self.outbound_stamp_costs.insert(
|
||||
destination_hash,
|
||||
@@ -1599,7 +1640,7 @@ impl LxmRouter {
|
||||
self.config.propagation_limit_kb = limit_kb;
|
||||
}
|
||||
|
||||
pub fn set_stamp_requirements(&mut self, cost: u8, flex: u8) {
|
||||
pub fn set_stamp_requirements(&mut self, cost: f64, flex: f64) {
|
||||
self.config.propagation_stamp_cost = cost;
|
||||
self.config.propagation_stamp_flex = flex;
|
||||
}
|
||||
@@ -1640,7 +1681,7 @@ impl LxmRouter {
|
||||
&self,
|
||||
message_hash: &[u8; 32],
|
||||
stamp: &[u8; 32],
|
||||
required_cost: u8,
|
||||
required_cost: f64,
|
||||
) -> bool {
|
||||
stamper::validate_stamp(
|
||||
message_hash,
|
||||
@@ -1659,7 +1700,7 @@ impl LxmRouter {
|
||||
&self,
|
||||
message_id: &[u8; 32],
|
||||
stamp: &[u8],
|
||||
required_cost: u8,
|
||||
required_cost: f64,
|
||||
destination_hash: &[u8; 16],
|
||||
) -> bool {
|
||||
let now = now_f64();
|
||||
@@ -2359,7 +2400,7 @@ pub struct PeerStats {
|
||||
pub last_heard: f64,
|
||||
pub sync_transfer_rate: f64,
|
||||
pub transfer_limit: Option<f64>,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
pub offered: u64,
|
||||
pub outgoing: u64,
|
||||
pub incoming: u64,
|
||||
@@ -2373,9 +2414,9 @@ pub struct NodeStats {
|
||||
pub delivery_limit: f64,
|
||||
pub propagation_limit: usize,
|
||||
pub sync_limit: usize,
|
||||
pub stamp_cost: u8,
|
||||
pub stamp_flex: u8,
|
||||
pub peering_cost: u8,
|
||||
pub stamp_cost: f64,
|
||||
pub stamp_flex: f64,
|
||||
pub peering_cost: f64,
|
||||
pub message_count: usize,
|
||||
pub message_size: usize,
|
||||
pub storage_limit: Option<usize>,
|
||||
@@ -2452,8 +2493,8 @@ mod tests {
|
||||
let config = RouterConfig::default();
|
||||
assert!(config.autopeer);
|
||||
assert_eq!(config.ext.autopeer_maxdepth, 4);
|
||||
assert_eq!(config.ext.propagation_cost_min, 13);
|
||||
assert_eq!(config.ext.max_peering_cost, 26);
|
||||
assert_eq!(config.ext.propagation_cost_min, 13.0);
|
||||
assert_eq!(config.ext.max_peering_cost, 26.0);
|
||||
assert!(config.ext.processing_outbound);
|
||||
assert!(config.ext.defer_stamp_generation);
|
||||
assert!(config.ext.processing_limit.is_none());
|
||||
@@ -2768,8 +2809,91 @@ mod tests {
|
||||
|
||||
assert!(router.get_stamp_cost(&dest).is_none());
|
||||
|
||||
router.set_stamp_cost(dest, 12);
|
||||
assert_eq!(router.get_stamp_cost(&dest), Some(12));
|
||||
router.set_stamp_cost(dest, 12.0);
|
||||
assert_eq!(router.get_stamp_cost(&dest), Some(12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_without_cost_keeps_an_entry_and_stops_stamping() {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let dest = [0xAA; 16];
|
||||
router.set_stamp_cost(dest, 8.5);
|
||||
router.update_stamp_cost(dest, None);
|
||||
assert!(router.outbound_stamp_costs.contains_key(&dest));
|
||||
assert_eq!(router.get_stamp_cost(&dest), None);
|
||||
let mut draft =
|
||||
crate::message::LxMessageDraft::new(dest, [0xBB; 16], "", "x", DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
router.prepare_outbound(&mut draft).unwrap();
|
||||
assert_eq!(draft.stamp_cost, None);
|
||||
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
router.save_state(tmp.path()).unwrap();
|
||||
let mut restored = LxmRouter::new(RouterConfig::default());
|
||||
restored.load_state(tmp.path()).unwrap();
|
||||
assert!(restored.outbound_stamp_costs[&dest].cost.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_stamp_costs_stored_by_older_versions_still_load() {
|
||||
#[derive(serde::Serialize)]
|
||||
struct OldEntry {
|
||||
cost: u8,
|
||||
recorded_at: f64,
|
||||
}
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let old = HashMap::from([(
|
||||
[0xAA; 16],
|
||||
OldEntry {
|
||||
cost: 12,
|
||||
recorded_at: now_f64(),
|
||||
},
|
||||
)]);
|
||||
std::fs::write(
|
||||
tmp.path().join(crate::persist::STAMP_COSTS_FILE),
|
||||
rmp_serde::to_vec(&old).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
router.load_state(tmp.path()).unwrap();
|
||||
assert_eq!(router.get_stamp_cost(&[0xAA; 16]), Some(12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_stamp_at_an_impossible_cost_fails_the_message() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _guard = rt.enter();
|
||||
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let mut draft = crate::message::LxMessageDraft::new(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"",
|
||||
"x",
|
||||
DeliveryMethod::Direct,
|
||||
)
|
||||
.unwrap();
|
||||
draft.stamp_cost = Some(150.0);
|
||||
let failed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let seen = failed.clone();
|
||||
draft.callbacks.on_failed = Some(std::sync::Arc::new(move |m: &LxMessage| {
|
||||
seen.lock().unwrap().push(m.state);
|
||||
}));
|
||||
router.submit_signed(draft.sign(&key).unwrap()).unwrap();
|
||||
for _ in 0..300 {
|
||||
router.process_deferred_stamps();
|
||||
if router.pending_deferred_stamps.is_empty() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(router.pending_deferred_stamps.is_empty());
|
||||
assert!(router.pending_outbound.is_empty());
|
||||
assert_eq!(*failed.lock().unwrap(), [MessageState::Failed]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2778,7 +2902,7 @@ mod tests {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let dest = [0xAA; 16];
|
||||
router.remember_ticket(dest, [0x42; 16], now_f64() + 60.0);
|
||||
router.set_stamp_cost(dest, 16);
|
||||
router.set_stamp_cost(dest, 16.0);
|
||||
|
||||
let mut msg = crate::message::LxMessageDraft::new(
|
||||
dest,
|
||||
@@ -2938,7 +3062,7 @@ mod tests {
|
||||
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let dest = [0xAA; 16];
|
||||
router.set_stamp_cost(dest, 1);
|
||||
router.set_stamp_cost(dest, 1.0);
|
||||
|
||||
let mut msg = crate::message::LxMessageDraft::new(
|
||||
dest,
|
||||
@@ -2977,7 +3101,7 @@ mod tests {
|
||||
assert!(stamper::validate_stamp(
|
||||
&queued.message_id(),
|
||||
stamp,
|
||||
1,
|
||||
1.0,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS
|
||||
));
|
||||
}
|
||||
@@ -2995,7 +3119,7 @@ mod tests {
|
||||
"handle captured at construction"
|
||||
);
|
||||
let dest = [0xAA; 16];
|
||||
router.set_stamp_cost(dest, 1);
|
||||
router.set_stamp_cost(dest, 1.0);
|
||||
|
||||
let mut msg = crate::message::LxMessageDraft::new(
|
||||
dest,
|
||||
@@ -3054,7 +3178,7 @@ mod tests {
|
||||
DeliveryMethod::Direct,
|
||||
)
|
||||
.unwrap();
|
||||
msg.stamp_cost = Some(1);
|
||||
msg.stamp_cost = Some(1.0);
|
||||
router.prepare_outbound(&mut msg).unwrap();
|
||||
let msg = msg.sign(&key).unwrap();
|
||||
let id = msg.message_id();
|
||||
@@ -3068,7 +3192,7 @@ mod tests {
|
||||
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let dest = [0xAA; 16];
|
||||
router.set_stamp_cost(dest, 8);
|
||||
router.set_stamp_cost(dest, 8.0);
|
||||
|
||||
let mut msg = crate::message::LxMessageDraft::new(
|
||||
dest,
|
||||
@@ -3157,7 +3281,7 @@ mod tests {
|
||||
material.extend_from_slice(&message_id);
|
||||
let stamp = rns_crypto::sha::truncated_hash(&material);
|
||||
|
||||
assert!(router.validate_stamp_with_tickets(&message_id, stamp.as_ref(), 16, &dest));
|
||||
assert!(router.validate_stamp_with_tickets(&message_id, stamp.as_ref(), 16.0, &dest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3319,7 +3443,7 @@ mod tests {
|
||||
let transient_a = [0x11; 32];
|
||||
|
||||
let mut r1 = LxmRouter::new(RouterConfig::default());
|
||||
r1.set_stamp_cost(dest_a, 8);
|
||||
r1.set_stamp_cost(dest_a, 8.0);
|
||||
// Far-future expiry so get_outbound_ticket (which uses wall-clock now) matches.
|
||||
r1.remember_ticket(dest_a, [0x01; 16], 4_102_444_800.0);
|
||||
r1.propagation_store.mark_locally_delivered(transient_a);
|
||||
@@ -3333,8 +3457,8 @@ mod tests {
|
||||
let mut r2 = LxmRouter::new(RouterConfig::default());
|
||||
r2.load_state(tmp.path()).unwrap();
|
||||
assert_eq!(
|
||||
r2.outbound_stamp_costs.get(&dest_a).map(|e| e.cost),
|
||||
Some(8)
|
||||
r2.outbound_stamp_costs.get(&dest_a).and_then(|e| e.cost),
|
||||
Some(8.0)
|
||||
);
|
||||
assert_eq!(r2.get_outbound_ticket(&dest_a), Some([0x01; 16]));
|
||||
assert!(r2.propagation_store.is_locally_delivered(&transient_a));
|
||||
@@ -3351,7 +3475,7 @@ mod tests {
|
||||
let transient = [0xB2; 32];
|
||||
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
router.set_stamp_cost(dest, 8);
|
||||
router.set_stamp_cost(dest, 8.0);
|
||||
router.remember_ticket(dest, [0xC3; 16], 4_102_444_800.0);
|
||||
router.propagation_store.mark_locally_delivered(transient);
|
||||
router.propagation_store.mark_locally_processed(transient);
|
||||
@@ -3364,7 +3488,7 @@ mod tests {
|
||||
|
||||
// Mutating every persisted router dataset after capture must not alter
|
||||
// the snapshot that a background persistence task owns.
|
||||
router.set_stamp_cost(dest, 42);
|
||||
router.set_stamp_cost(dest, 42.0);
|
||||
router.remember_ticket(dest, [0xD4; 16], 4_102_444_800.0);
|
||||
router
|
||||
.propagation_store
|
||||
@@ -3377,7 +3501,7 @@ mod tests {
|
||||
router.unpeered_propagation_incoming = 22;
|
||||
router.unpeered_propagation_rx_bytes = 23;
|
||||
|
||||
assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, 8);
|
||||
assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, Some(8.0));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
snapshot.tickets.save(dir.path(), None).unwrap();
|
||||
let (tickets, _) = crate::persist::load_tickets(dir.path()).unwrap();
|
||||
@@ -3399,7 +3523,7 @@ mod tests {
|
||||
|
||||
let snapshot = {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
router.set_stamp_cost(dest, 9);
|
||||
router.set_stamp_cost(dest, 9.0);
|
||||
router.remember_ticket(dest, [0xC7; 16], 4_102_444_800.0);
|
||||
router.propagation_store.mark_locally_delivered(transient);
|
||||
router.propagation_store.mark_locally_processed(transient);
|
||||
@@ -3414,7 +3538,7 @@ mod tests {
|
||||
|
||||
let mut restored = LxmRouter::new(RouterConfig::default());
|
||||
restored.load_state(tmp.path()).unwrap();
|
||||
assert_eq!(restored.outbound_stamp_costs[&dest].cost, 9);
|
||||
assert_eq!(restored.outbound_stamp_costs[&dest].cost, Some(9.0));
|
||||
assert_eq!(restored.get_outbound_ticket(&dest), Some([0xC7; 16]));
|
||||
assert!(restored.propagation_store.is_locally_delivered(&transient));
|
||||
assert!(restored.propagation_store.is_locally_processed(&transient));
|
||||
@@ -3508,9 +3632,9 @@ mod tests {
|
||||
10.0,
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(16.0),
|
||||
Some(3.0),
|
||||
Some(18.0),
|
||||
);
|
||||
peer.mark_offer_generation_processed(5);
|
||||
router.add_peer(peer);
|
||||
@@ -3532,9 +3656,9 @@ mod tests {
|
||||
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),
|
||||
stamp_cost: Some(12.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: Some(std::collections::HashMap::new()),
|
||||
hops: Some(1),
|
||||
}));
|
||||
@@ -3577,11 +3701,16 @@ mod tests {
|
||||
fn test_validate_stamp() {
|
||||
let router = LxmRouter::new(RouterConfig::default());
|
||||
let msg_id = rns_crypto::sha::sha256(b"test message");
|
||||
let stamp =
|
||||
stamper::generate_stamp_limited(&msg_id, 4, STAMP_WORKBLOCK_EXPAND_ROUNDS, 1_000_000);
|
||||
if let Some(stamp) = stamp {
|
||||
assert!(router.validate_stamp(&msg_id, &stamp, 4));
|
||||
}
|
||||
let (stamp, value) = stamper::generate_stamp(
|
||||
&msg_id,
|
||||
4.5,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS,
|
||||
&stamper::StampControl::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(router.validate_stamp(&msg_id, &stamp, 4.5));
|
||||
assert!(!router.validate_stamp(&msg_id, &stamp, value + 1.0 / 256.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3876,7 +4005,7 @@ mod tests {
|
||||
assert!(router.process_outbound().is_empty());
|
||||
|
||||
let pn_data = crate::handlers::get_propagation_node_app_data(
|
||||
&crate::handlers::PropagationNodeAnnounceData::new(true, 256, 10240, 16, 3, 18),
|
||||
&crate::handlers::PropagationNodeAnnounceData::new(true, 256, 10240, 16.0, 3.0, 18.0),
|
||||
);
|
||||
assert_eq!(
|
||||
router.trigger_outbound_for_propagation_node_announce(node, &pn_data),
|
||||
@@ -4258,9 +4387,9 @@ mod tests {
|
||||
timebase: 1000.0,
|
||||
transfer_limit: Some(256.0),
|
||||
sync_limit: Some(10240.0),
|
||||
stamp_cost: Some(16),
|
||||
stamp_flexibility: Some(3),
|
||||
peering_cost: Some(18),
|
||||
stamp_cost: Some(16.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: None,
|
||||
hops: Some(2),
|
||||
}));
|
||||
@@ -4300,7 +4429,7 @@ mod tests {
|
||||
let mut peer = LxmPeer::new(peer_hash);
|
||||
peer.is_static = true;
|
||||
peer.peering_timebase = 100.0;
|
||||
peer.stamp_cost = Some(8);
|
||||
peer.stamp_cost = Some(8.0);
|
||||
router.add_peer(peer);
|
||||
|
||||
let candidate = |timebase, stamp_cost| AutopeerCandidate {
|
||||
@@ -4309,29 +4438,29 @@ mod tests {
|
||||
transfer_limit: Some(2.0),
|
||||
sync_limit: Some(8.0),
|
||||
stamp_cost: Some(stamp_cost),
|
||||
stamp_flexibility: Some(3),
|
||||
peering_cost: Some(18),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: None,
|
||||
hops: Some(99),
|
||||
};
|
||||
|
||||
assert!(router.autopeer(candidate(101.0, 16)));
|
||||
assert!(router.autopeer(candidate(101.0, 16.0)));
|
||||
let refreshed = router.peers.get(&peer_hash).unwrap();
|
||||
assert_eq!(refreshed.stamp_cost, Some(16));
|
||||
assert_eq!(refreshed.stamp_cost, Some(16.0));
|
||||
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(candidate(100.0, 4.0)));
|
||||
assert_eq!(router.peers.get(&peer_hash).unwrap().stamp_cost, Some(16.0));
|
||||
|
||||
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),
|
||||
stamp_cost: Some(16.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: None,
|
||||
hops: Some(1),
|
||||
}));
|
||||
@@ -4357,9 +4486,9 @@ mod tests {
|
||||
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),
|
||||
stamp_cost: Some(16.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: Some(std::collections::HashMap::from([(
|
||||
crate::constants::PN_META_NAME,
|
||||
b"static".to_vec(),
|
||||
@@ -4393,7 +4522,7 @@ mod tests {
|
||||
sync_limit: None,
|
||||
stamp_cost: None,
|
||||
stamp_flexibility: None,
|
||||
peering_cost: Some(max + 1),
|
||||
peering_cost: Some(max + 1.0),
|
||||
metadata: None,
|
||||
hops: None,
|
||||
}));
|
||||
@@ -4408,9 +4537,9 @@ mod tests {
|
||||
timebase,
|
||||
transfer_limit: Some(2.0),
|
||||
sync_limit: Some(8.0),
|
||||
stamp_cost: Some(16),
|
||||
stamp_flexibility: Some(3),
|
||||
peering_cost: Some(18),
|
||||
stamp_cost: Some(16.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: Some(18.0),
|
||||
metadata: None,
|
||||
hops: Some(hops),
|
||||
};
|
||||
@@ -4450,20 +4579,20 @@ mod tests {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let max = router.config.ext.max_peering_cost;
|
||||
|
||||
let candidate = |cost: Option<u8>| AutopeerCandidate {
|
||||
let candidate = |cost: Option<f64>| AutopeerCandidate {
|
||||
destination_hash: [0xAA; 16],
|
||||
timebase: 1000.0,
|
||||
transfer_limit: Some(256.0),
|
||||
sync_limit: None,
|
||||
stamp_cost: Some(16),
|
||||
stamp_flexibility: Some(3),
|
||||
stamp_cost: Some(16.0),
|
||||
stamp_flexibility: Some(3.0),
|
||||
peering_cost: cost,
|
||||
metadata: None,
|
||||
hops: Some(2),
|
||||
};
|
||||
|
||||
// Over-cost announce: refused outright.
|
||||
assert!(!router.autopeer(candidate(Some(max + 1))));
|
||||
assert!(!router.autopeer(candidate(Some(max + 0.25))));
|
||||
assert!(router.peers.is_empty());
|
||||
|
||||
// At-cost announce: accepted.
|
||||
@@ -4471,7 +4600,7 @@ mod tests {
|
||||
assert_eq!(router.peers.len(), 1);
|
||||
|
||||
// Existing peer raising its cost beyond the cap: peering breaks.
|
||||
assert!(!router.autopeer(candidate(Some(max + 1))));
|
||||
assert!(!router.autopeer(candidate(Some(max + 0.25))));
|
||||
assert!(router.peers.is_empty(), "over-cost announce must unpeer");
|
||||
}
|
||||
|
||||
@@ -4795,7 +4924,7 @@ mod tests {
|
||||
let destination = [0xA7; 16];
|
||||
let mut sender = LxmRouter::new(RouterConfig::default());
|
||||
sender.remember_ticket(destination, [0x42; 16], now_f64() + 60.0);
|
||||
sender.set_stamp_cost(destination, 8);
|
||||
sender.set_stamp_cost(destination, 8.0);
|
||||
let mut draft = resumable_draft(source, "ticketed");
|
||||
sender.prepare_outbound(&mut draft).unwrap();
|
||||
assert!(draft.outbound_ticket.is_some());
|
||||
@@ -4813,21 +4942,21 @@ mod tests {
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(restored.outbound_ticket(), None);
|
||||
assert_eq!(restored.stamp_cost(), Some(8));
|
||||
assert_eq!(restored.stamp_cost(), Some(8.0));
|
||||
let id = restored.message_id();
|
||||
restarted.submit_signed(restored).unwrap();
|
||||
assert!(restarted.pending_deferred_stamps.contains_key(&id));
|
||||
|
||||
restarted.set_stamp_cost(destination, 12);
|
||||
restarted.set_stamp_cost(destination, 12.0);
|
||||
let raised = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(raised.stamp_cost(), Some(12));
|
||||
restarted.set_stamp_cost(destination, 4);
|
||||
assert_eq!(raised.stamp_cost(), Some(12.0));
|
||||
restarted.set_stamp_cost(destination, 4.0);
|
||||
let lowered = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(lowered.stamp_cost(), Some(8));
|
||||
assert_eq!(lowered.stamp_cost(), Some(8.0));
|
||||
|
||||
restarted.remember_ticket(destination, [0x43; 16], now_f64() + 60.0);
|
||||
let ticketed = restarted
|
||||
@@ -4852,7 +4981,7 @@ mod tests {
|
||||
assert_eq!(router.pending_outbound.len(), 1);
|
||||
|
||||
let mut stamped = resumable_draft(source, "stamped once");
|
||||
stamped.stamp_cost = Some(8);
|
||||
stamped.stamp_cost = Some(8.0);
|
||||
router
|
||||
.submit_signed(stamped.clone().sign(&key).unwrap())
|
||||
.unwrap();
|
||||
@@ -4892,7 +5021,7 @@ mod tests {
|
||||
let mut submitted = Vec::new();
|
||||
for n in 0..12 {
|
||||
let mut draft = resumable_draft(source, &format!("deferred {n}"));
|
||||
draft.stamp_cost = Some(1);
|
||||
draft.stamp_cost = Some(1.0);
|
||||
let signed = draft.sign(&key).unwrap();
|
||||
submitted.push(signed.message_id());
|
||||
router.submit_signed(signed).unwrap();
|
||||
|
||||
+158
-501
@@ -1,181 +1,57 @@
|
||||
//! LXMF Stamp system: Proof-of-Work generation and validation.
|
||||
//! LXMF stamps: proof of work for messages, propagation and peering.
|
||||
//!
|
||||
//! Python reference: LXMF/LXStamper.py.
|
||||
//!
|
||||
//! A single workblock construction is used for all stamp kinds (message,
|
||||
//! propagation-node, peering), matching Python `LXStamper.stamp_workblock`:
|
||||
//! per-round HKDF expansion concatenated into a `expand_rounds * 256` byte
|
||||
//! workblock. Only the expand-round count differs per kind (see
|
||||
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
|
||||
//!
|
||||
//! Rust validation requires at least `cost` leading zero bits in
|
||||
//! `SHA-256(workblock || stamp)`. Python uses an inclusive numeric threshold,
|
||||
//! `result <= 1 << (256 - cost)`; the exact equality boundary differs for
|
||||
//! nonzero cost.
|
||||
//! Python reference: `LXMF/LXStamper.py`, which takes the workblock, value,
|
||||
//! validity and generation from `RNS.Stamps`. Only the expand-round counts per
|
||||
//! stamp kind are LXMF's own (`STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}`
|
||||
//! in constants.rs). Costs and values are fractional on the 1/256 grid.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use rand::RngCore;
|
||||
use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::sha256;
|
||||
use sha2::{Digest, Sha256};
|
||||
pub use rns_identity::stamps::{
|
||||
STAMP_COST_CAP, STAMP_COST_CAP_FP, StampControl, StampError, cost_from_fp, cost_to_fp,
|
||||
quantize_cost, stamp_value, stamp_workblock,
|
||||
};
|
||||
|
||||
use crate::constants::{
|
||||
LXMF_OVERHEAD, STAMP_SIZE, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
};
|
||||
|
||||
/// Parsed propagation-node stamp parts: `(transient_id, lxm_data, value, stamp)`.
|
||||
pub type PropagationStampParts = ([u8; 32], Vec<u8>, u32, [u8; 32]);
|
||||
pub type PropagationStampParts = ([u8; 32], Vec<u8>, f64, [u8; 32]);
|
||||
|
||||
/// Matches Python `LXStamper.stamp_workblock(material, expand_rounds)`:
|
||||
///
|
||||
/// For each round n in 0..expand_rounds:
|
||||
/// salt = SHA256(material + msgpack.packb(n))
|
||||
/// workblock += HKDF(length=256, derive_from=material, salt=salt, context=None)
|
||||
///
|
||||
/// Produces `expand_rounds * 256` bytes.
|
||||
pub fn stamp_workblock(material: &[u8], expand_rounds: usize) -> Vec<u8> {
|
||||
let mut workblock = Vec::with_capacity(expand_rounds * 256);
|
||||
|
||||
for n in 0..expand_rounds {
|
||||
let n_packed = pack_msgpack_uint(n);
|
||||
|
||||
let mut salt_input = Vec::with_capacity(material.len() + n_packed.len());
|
||||
salt_input.extend_from_slice(material);
|
||||
salt_input.extend_from_slice(&n_packed);
|
||||
let salt = sha256(&salt_input);
|
||||
|
||||
let chunk = hkdf_sha256(256, material, Some(&salt), None)
|
||||
.expect("HKDF expand failed for stamp workblock");
|
||||
workblock.extend_from_slice(&chunk);
|
||||
}
|
||||
|
||||
workblock
|
||||
/// Python `stamp_valid`: the stamp hash meets the fixed-point target of
|
||||
/// `cost`. A cost of 0 always passes; a non-finite cost never does.
|
||||
pub fn stamp_valid(stamp: &[u8], cost: f64, workblock: &[u8]) -> bool {
|
||||
rns_identity::stamps::stamp_valid(stamp, cost, workblock).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn pack_msgpack_uint(n: usize) -> Vec<u8> {
|
||||
let value = rmpv::Value::Integer(rmpv::Integer::from(n as u64));
|
||||
crate::encode_value(&value)
|
||||
/// Whether a stamp of `value` passes [`stamp_valid`] at `cost`.
|
||||
pub fn value_meets(value: f64, cost: f64) -> bool {
|
||||
quantize_cost(cost).is_ok_and(|cost| value >= cost)
|
||||
}
|
||||
|
||||
fn leading_zero_bits(data: &[u8]) -> u32 {
|
||||
let mut count = 0u32;
|
||||
for &byte in data {
|
||||
if byte == 0 {
|
||||
count += 8;
|
||||
} else {
|
||||
count += byte.leading_zeros();
|
||||
break;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// Leading zero bits of `SHA-256(workblock || stamp)`. Matches Python `stamp_value()`.
|
||||
pub fn stamp_value(workblock: &[u8], stamp: &[u8; 32]) -> u32 {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(workblock);
|
||||
stamp_value_from_base(&hasher, stamp)
|
||||
}
|
||||
|
||||
pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
|
||||
if cost == 0 {
|
||||
return true;
|
||||
}
|
||||
stamp_value(workblock, stamp) >= cost as u32
|
||||
}
|
||||
|
||||
/// Attempt budget for [`generate_stamp`] and [`generate_stamp_cancellable`]:
|
||||
/// `64 * 2^cost`. Returns `None` for costs at least 58 because the budget would
|
||||
/// overflow `u64`. This limits attempts, not elapsed time. Deferred stamp
|
||||
/// workers use explicit cancellation and do not use this budget.
|
||||
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
|
||||
if cost >= 58 {
|
||||
return None;
|
||||
}
|
||||
Some(64u64 << cost)
|
||||
}
|
||||
|
||||
/// Single-threaded brute-force stamp search. Bounded by
|
||||
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
|
||||
/// requested cost has no supported iteration budget.
|
||||
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
|
||||
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
|
||||
}
|
||||
|
||||
/// Synchronous search with the [`stamp_iteration_cap`] attempt budget.
|
||||
/// Checks cancellation before workblock construction and every 1,000 attempts;
|
||||
/// workblock construction itself is not interrupted. Run on a blocking worker
|
||||
/// when called from async code.
|
||||
pub fn generate_stamp_cancellable(
|
||||
/// Python `LXStamper.generate_stamp`: a 32-byte stamp and its real value.
|
||||
/// Costs outside `0..=100` are refused as Python refuses them; a cost of 0
|
||||
/// still returns a random stamp. `None` means cancelled or past the deadline.
|
||||
pub fn generate_stamp(
|
||||
material: &[u8],
|
||||
cost: u8,
|
||||
cost: f64,
|
||||
expand_rounds: usize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<([u8; 32], u32)> {
|
||||
if cancel.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
if cost == 0 {
|
||||
return Some(([0u8; 32], 0));
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let max_iterations = stamp_iteration_cap(cost)?;
|
||||
|
||||
let workblock = stamp_workblock(material, expand_rounds);
|
||||
let mut base_hasher = Sha256::new();
|
||||
base_hasher.update(&workblock);
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
for iteration in 0..max_iterations {
|
||||
if iteration % 1000 == 0 && cancel.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
let stamp = rand_bytes_from(&mut rng);
|
||||
let value = stamp_value_from_base(&base_hasher, &stamp);
|
||||
if value >= cost as u32 {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
if elapsed_ms > 250 {
|
||||
tracing::info!(cost, value, elapsed_ms, "stamp generated");
|
||||
}
|
||||
return Some((stamp, value));
|
||||
}
|
||||
}
|
||||
tracing::warn!(
|
||||
cost,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"stamp search exhausted iteration cap"
|
||||
);
|
||||
None
|
||||
}
|
||||
|
||||
/// Stamp search with a configurable iteration limit (for tests).
|
||||
pub fn generate_stamp_limited(
|
||||
material: &[u8],
|
||||
cost: u8,
|
||||
expand_rounds: usize,
|
||||
max_iterations: u64,
|
||||
) -> Option<[u8; 32]> {
|
||||
if cost == 0 {
|
||||
return Some([0u8; 32]);
|
||||
}
|
||||
|
||||
let workblock = stamp_workblock(material, expand_rounds);
|
||||
let mut base_hasher = Sha256::new();
|
||||
base_hasher.update(&workblock);
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
for _ in 0..max_iterations {
|
||||
let stamp = rand_bytes_from(&mut rng);
|
||||
if stamp_value_from_base(&base_hasher, &stamp) >= cost as u32 {
|
||||
return Some(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
ctl: &StampControl,
|
||||
) -> Result<Option<([u8; 32], f64)>, StampError> {
|
||||
let generated =
|
||||
rns_identity::stamps::generate_stamp(material, cost, expand_rounds, STAMP_SIZE, ctl)?;
|
||||
Ok(generated.map(|(stamp, value)| {
|
||||
let stamp: [u8; 32] = stamp.try_into().expect("stamp size is 32");
|
||||
(stamp, value)
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn validate_stamp(
|
||||
message_id: &[u8; 32],
|
||||
stamp: &[u8; 32],
|
||||
cost: u8,
|
||||
stamp: &[u8],
|
||||
cost: f64,
|
||||
expand_rounds: usize,
|
||||
) -> bool {
|
||||
let workblock = stamp_workblock(message_id, expand_rounds);
|
||||
@@ -183,45 +59,27 @@ pub fn validate_stamp(
|
||||
}
|
||||
|
||||
/// Python reference: `LXStamper.validate_peering_key`.
|
||||
///
|
||||
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
|
||||
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
|
||||
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_cost: u8) -> bool {
|
||||
let workblock = stamp_workblock(
|
||||
peering_id,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
);
|
||||
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8], target_cost: f64) -> bool {
|
||||
let workblock = stamp_workblock(peering_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
|
||||
stamp_valid(peering_key, target_cost, &workblock)
|
||||
}
|
||||
|
||||
/// Python reference: `LXStamper.validate_pn_stamp`.
|
||||
///
|
||||
/// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes.
|
||||
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
|
||||
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<PropagationStampParts> {
|
||||
let stamp_size = 32;
|
||||
let lxmf_overhead = crate::constants::LXMF_OVERHEAD;
|
||||
|
||||
if transient_data.len() <= lxmf_overhead + stamp_size {
|
||||
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: f64) -> Option<PropagationStampParts> {
|
||||
if transient_data.len() <= LXMF_OVERHEAD + STAMP_SIZE {
|
||||
return None;
|
||||
}
|
||||
|
||||
let split = transient_data.len() - stamp_size;
|
||||
let split = transient_data.len() - STAMP_SIZE;
|
||||
let lxm_data = &transient_data[..split];
|
||||
let stamp_bytes = &transient_data[split..];
|
||||
let mut stamp = [0u8; 32];
|
||||
stamp.copy_from_slice(stamp_bytes);
|
||||
|
||||
let stamp: [u8; 32] = transient_data[split..].try_into().ok()?;
|
||||
let transient_id = rns_crypto::sha::full_hash(lxm_data);
|
||||
let workblock = stamp_workblock(
|
||||
&transient_id,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
|
||||
);
|
||||
|
||||
let value = stamp_value(&workblock, &stamp);
|
||||
if value < target_cost as u32 {
|
||||
let workblock = stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
|
||||
if !stamp_valid(&stamp, target_cost, &workblock) {
|
||||
return None;
|
||||
}
|
||||
let value = stamp_value(&workblock, &stamp);
|
||||
Some((transient_id, lxm_data.to_vec(), value, stamp))
|
||||
}
|
||||
|
||||
@@ -230,31 +88,32 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
|
||||
/// receiver does not stop the worker.
|
||||
#[derive(Clone)]
|
||||
pub struct DeferredStampHandle {
|
||||
cancel: Arc<AtomicBool>,
|
||||
ctl: StampControl,
|
||||
}
|
||||
|
||||
impl DeferredStampHandle {
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
self.ctl.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.cancel.load(Ordering::Relaxed)
|
||||
self.ctl.cancel.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DeferredStampResult {
|
||||
Success { stamp: [u8; 32], value: u32 },
|
||||
Success {
|
||||
stamp: [u8; 32],
|
||||
value: f64,
|
||||
},
|
||||
Cancelled,
|
||||
/// The cost cannot be generated, as Python's `generate_stamp` raises.
|
||||
Failed(StampError),
|
||||
}
|
||||
|
||||
/// Spawn a deferred stamp-generation task on a blocking worker.
|
||||
///
|
||||
/// Returns a cancellation handle and a oneshot receiver for the result.
|
||||
/// The search has no iteration cap; see [`spawn_deferred_stamp_on`] for its
|
||||
/// cancellation contract.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics when called outside a Tokio runtime.
|
||||
#[tracing::instrument(
|
||||
@@ -269,7 +128,7 @@ pub enum DeferredStampResult {
|
||||
)]
|
||||
pub fn spawn_deferred_stamp(
|
||||
message_id: [u8; 32],
|
||||
cost: u8,
|
||||
cost: f64,
|
||||
expand_rounds: usize,
|
||||
) -> (
|
||||
DeferredStampHandle,
|
||||
@@ -279,372 +138,170 @@ pub fn spawn_deferred_stamp(
|
||||
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
|
||||
}
|
||||
|
||||
/// Spawn on an explicit runtime handle, without requiring a current runtime
|
||||
/// context on the calling thread.
|
||||
///
|
||||
/// After workblock construction, a nonzero-cost search checks cancellation
|
||||
/// between batches of 1,000 attempts and runs until success or cancellation.
|
||||
/// It does not apply [`stamp_iteration_cap`]. Keep the cancellation handle and
|
||||
/// call `cancel()` when abandoning the result.
|
||||
/// Spawn on an explicit runtime handle. The search runs until it succeeds or
|
||||
/// the handle is cancelled; an invalid cost reports `Failed` at once.
|
||||
pub fn spawn_deferred_stamp_on(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
message_id: [u8; 32],
|
||||
cost: u8,
|
||||
cost: f64,
|
||||
expand_rounds: usize,
|
||||
) -> (
|
||||
DeferredStampHandle,
|
||||
tokio::sync::oneshot::Receiver<DeferredStampResult>,
|
||||
) {
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let ctl = StampControl::default();
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
|
||||
let cancel_flag = cancel.clone();
|
||||
let worker_ctl = ctl.clone();
|
||||
runtime.spawn_blocking(move || {
|
||||
if cost == 0 {
|
||||
let _ = tx.send(DeferredStampResult::Success {
|
||||
stamp: [0u8; 32],
|
||||
value: 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let workblock = stamp_workblock(&message_id, expand_rounds);
|
||||
let mut base_hasher = Sha256::new();
|
||||
base_hasher.update(&workblock);
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
loop {
|
||||
if cancel_flag.load(Ordering::Relaxed) {
|
||||
let _ = tx.send(DeferredStampResult::Cancelled);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check cancellation every 1000 iterations.
|
||||
for _ in 0..1000 {
|
||||
let stamp = rand_bytes_from(&mut rng);
|
||||
let value = stamp_value_from_base(&base_hasher, &stamp);
|
||||
if value >= cost as u32 {
|
||||
let _ = tx.send(DeferredStampResult::Success { stamp, value });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = match generate_stamp(&message_id, cost, expand_rounds, &worker_ctl) {
|
||||
Ok(Some((stamp, value))) => DeferredStampResult::Success { stamp, value },
|
||||
Ok(None) => DeferredStampResult::Cancelled,
|
||||
Err(error) => DeferredStampResult::Failed(error),
|
||||
};
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
|
||||
(DeferredStampHandle { cancel }, rx)
|
||||
}
|
||||
|
||||
pub(crate) fn rand_bytes() -> [u8; 32] {
|
||||
let mut rng = rand::thread_rng();
|
||||
rand_bytes_from(&mut rng)
|
||||
}
|
||||
|
||||
fn rand_bytes_from(rng: &mut impl RngCore) -> [u8; 32] {
|
||||
let mut bytes = [0u8; 32];
|
||||
rng.fill_bytes(&mut bytes);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn stamp_value_from_base(base_hasher: &Sha256, stamp: &[u8; 32]) -> u32 {
|
||||
let mut hasher = base_hasher.clone();
|
||||
hasher.update(stamp);
|
||||
let hash = hasher.finalize();
|
||||
leading_zero_bits(&hash)
|
||||
(DeferredStampHandle { ctl }, rx)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::constants::{STAMP_WORKBLOCK_EXPAND_ROUNDS, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN};
|
||||
use rns_crypto::sha::sha256;
|
||||
|
||||
#[test]
|
||||
fn test_workblock_deterministic() {
|
||||
let id = sha256(b"test message id");
|
||||
let wb1 = stamp_workblock(&id, 10);
|
||||
let wb2 = stamp_workblock(&id, 10);
|
||||
assert_eq!(wb1, wb2);
|
||||
assert_eq!(wb1.len(), 10 * 256);
|
||||
fn found(material: &[u8], cost: f64, rounds: usize) -> ([u8; 32], f64) {
|
||||
generate_stamp(material, cost, rounds, &StampControl::default())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_workblock_different_rounds() {
|
||||
let id = sha256(b"test");
|
||||
let wb1 = stamp_workblock(&id, 10);
|
||||
let wb2 = stamp_workblock(&id, 20);
|
||||
assert_ne!(wb1, wb2);
|
||||
}
|
||||
|
||||
/// Workblock for the default message expand rounds matches the Python
|
||||
/// construction's size: 3000 rounds * 256 bytes.
|
||||
#[test]
|
||||
fn test_workblock_message_rounds_size() {
|
||||
fn workblock_uses_lxmf_expand_rounds() {
|
||||
let id = sha256(b"size check");
|
||||
let wb = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
|
||||
assert_eq!(wb.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS * 256);
|
||||
assert_eq!(
|
||||
stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS).len(),
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS * 256
|
||||
);
|
||||
assert_eq!(stamp_workblock(&id, 0), id.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_leading_zero_bits() {
|
||||
assert_eq!(leading_zero_bits(&[0xFF]), 0);
|
||||
assert_eq!(leading_zero_bits(&[0x00, 0xFF]), 8);
|
||||
assert_eq!(leading_zero_bits(&[0x00, 0x00, 0xFF]), 16);
|
||||
assert_eq!(leading_zero_bits(&[0x0F]), 4);
|
||||
assert_eq!(leading_zero_bits(&[0x01]), 7);
|
||||
assert_eq!(leading_zero_bits(&[0x00, 0x01]), 15);
|
||||
fn zero_cost_generates_a_random_stamp_with_its_real_value() {
|
||||
let id = sha256(b"zero cost");
|
||||
let (stamp, value) = found(&id, 0.0, 20);
|
||||
assert_ne!(stamp, [0u8; 32]);
|
||||
assert_eq!(value, stamp_value(&stamp_workblock(&id, 20), &stamp));
|
||||
assert!(stamp_valid(&stamp, 0.0, &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_valid_cost_zero() {
|
||||
let stamp = [0u8; 32];
|
||||
let workblock = [0u8; 32];
|
||||
assert!(stamp_valid(&stamp, 0, &workblock));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_stamp_cost_zero() {
|
||||
let id = sha256(b"test");
|
||||
let (stamp, value) = generate_stamp(&id, 0, 20).unwrap();
|
||||
assert_eq!(stamp, [0u8; 32]);
|
||||
assert_eq!(value, 0);
|
||||
}
|
||||
|
||||
/// T0-4: the stamp search is bounded — an unsatisfiable (hostile) cost
|
||||
/// returns `None` immediately instead of pinning the thread forever.
|
||||
#[test]
|
||||
fn test_generate_stamp_capped_for_hostile_cost() {
|
||||
assert_eq!(stamp_iteration_cap(1), Some(128));
|
||||
assert_eq!(stamp_iteration_cap(26), Some(64u64 << 26));
|
||||
assert!(stamp_iteration_cap(57).is_some());
|
||||
assert_eq!(stamp_iteration_cap(58), None);
|
||||
assert_eq!(stamp_iteration_cap(255), None);
|
||||
|
||||
let id = sha256(b"hostile cost");
|
||||
// Cost 255 must fail fast (cap is None — no workblock spin at all).
|
||||
assert!(generate_stamp(&id, 255, 20).is_none());
|
||||
// Sane costs still succeed.
|
||||
assert!(generate_stamp(&id, 4, 20).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_and_validate_stamp() {
|
||||
let id = sha256(b"test message for stamping");
|
||||
let cost = 4;
|
||||
|
||||
let stamp = generate_stamp_limited(&id, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS, 1_000_000);
|
||||
assert!(stamp.is_some(), "should find a stamp with cost={cost}");
|
||||
|
||||
let stamp = stamp.unwrap();
|
||||
assert!(validate_stamp(
|
||||
&id,
|
||||
&stamp,
|
||||
cost,
|
||||
STAMP_WORKBLOCK_EXPAND_ROUNDS
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_wrong_stamp() {
|
||||
let id = sha256(b"test");
|
||||
let wrong_stamp = [0xFFu8; 32];
|
||||
assert!(!validate_stamp(&id, &wrong_stamp, 32, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_stamp_limited_fails() {
|
||||
let id = sha256(b"test");
|
||||
let result = generate_stamp_limited(&id, 128, 20, 10);
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_value_consistency() {
|
||||
let id = sha256(b"consistency test");
|
||||
let cost = 4;
|
||||
if let Some(stamp) = generate_stamp_limited(&id, cost, 20, 1_000_000) {
|
||||
let workblock = stamp_workblock(&id, 20);
|
||||
let value = stamp_value(&workblock, &stamp);
|
||||
assert!(value >= cost as u32);
|
||||
assert!(stamp_valid(&stamp, cost, &workblock));
|
||||
fn generation_refuses_costs_outside_the_cap() {
|
||||
let ctl = StampControl::default();
|
||||
for cost in [100.5, 150.0, 255.0, -1.0, f64::NAN] {
|
||||
assert!(generate_stamp(&[7; 32], cost, 1, &ctl).is_err(), "{cost}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_workblock_arbitrary_length_input() {
|
||||
let short_material = b"short";
|
||||
let wb = stamp_workblock(short_material, 5);
|
||||
assert_eq!(wb.len(), 5 * 256);
|
||||
|
||||
let wb2 = stamp_workblock(short_material, 5);
|
||||
assert_eq!(wb, wb2);
|
||||
|
||||
let wb3 = stamp_workblock(b"other", 5);
|
||||
assert_ne!(wb, wb3);
|
||||
fn fractional_cost_generates_and_validates() {
|
||||
let id = sha256(b"fractional");
|
||||
let (stamp, value) = found(&id, 4.5, 10);
|
||||
assert!(value >= 4.5);
|
||||
assert!(validate_stamp(&id, &stamp, 4.5, 10));
|
||||
assert!(!validate_stamp(&id, &stamp, value + 1.0 / 256.0, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_expand_round_constants() {
|
||||
let id = sha256(b"test expand rounds");
|
||||
let wb_pn = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
|
||||
let wb_peering =
|
||||
stamp_workblock(&id, crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
|
||||
// Workblocks are prefix-stable per construction; only length differs.
|
||||
assert_eq!(wb_pn[..wb_peering.len()], wb_peering[..]);
|
||||
assert_eq!(wb_pn.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS_PN * 256);
|
||||
assert_eq!(
|
||||
wb_peering.len(),
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING * 256
|
||||
);
|
||||
}
|
||||
|
||||
/// The first 256-byte chunk of the workblock is identical regardless of
|
||||
/// total round count — Python builds it incrementally the same way.
|
||||
#[test]
|
||||
fn test_workblock_prefix_stability() {
|
||||
let id = sha256(b"prefix stability");
|
||||
let wb_small = stamp_workblock(&id, 2);
|
||||
let wb_large = stamp_workblock(&id, 5);
|
||||
assert_eq!(wb_small[..], wb_large[..2 * 256]);
|
||||
fn non_finite_target_never_validates() {
|
||||
assert!(!stamp_valid(&[0u8; 32], f64::NAN, b"x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deferred_stamp_handle_cancel() {
|
||||
fn peering_key_validates_at_its_value() {
|
||||
let peering_id = [0xAA; 32];
|
||||
let (key, value) = found(&peering_id, 3.25, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
|
||||
assert!(validate_peering_key(&peering_id, &key, 3.25));
|
||||
assert!(validate_peering_key(&peering_id, &key, value));
|
||||
assert!(!validate_peering_key(
|
||||
&peering_id,
|
||||
&key,
|
||||
value + 1.0 / 256.0
|
||||
));
|
||||
assert!(validate_peering_key(&peering_id, &[0xFF; 32], 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pn_stamp_too_short_is_rejected() {
|
||||
let short_data = vec![0u8; LXMF_OVERHEAD + 32];
|
||||
assert!(validate_pn_stamp(&short_data, 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pn_stamp_parts_carry_the_fractional_value() {
|
||||
let lxm_data = vec![0xAB; LXMF_OVERHEAD + 64];
|
||||
let tid = rns_crypto::sha::full_hash(&lxm_data);
|
||||
let (stamp, value) = found(&tid, 2.5, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
|
||||
let mut transient_data = lxm_data.clone();
|
||||
transient_data.extend_from_slice(&stamp);
|
||||
let (transient_id, extracted, got, extracted_stamp) =
|
||||
validate_pn_stamp(&transient_data, 2.5).unwrap();
|
||||
assert_eq!(transient_id, tid);
|
||||
assert_eq!(extracted, lxm_data);
|
||||
assert_eq!(extracted_stamp, stamp);
|
||||
assert_eq!(got, value);
|
||||
assert!(validate_pn_stamp(&transient_data, value + 1.0 / 256.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_stamp_handle_cancel() {
|
||||
let handle = DeferredStampHandle {
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
ctl: StampControl::default(),
|
||||
};
|
||||
assert!(!handle.is_cancelled());
|
||||
handle.cancel();
|
||||
assert!(handle.is_cancelled());
|
||||
}
|
||||
|
||||
/// End-to-end: a stamp worker running a high-cost PoW must observe the
|
||||
/// cancellation flag and report `DeferredStampResult::Cancelled`
|
||||
/// without panicking. This exercises the worker checkpoint rather than
|
||||
/// only the handle state.
|
||||
#[tokio::test]
|
||||
async fn test_deferred_stamp_cancelled_mid_computation() {
|
||||
// Cost 32 is intentionally high enough that the worker is still
|
||||
// looping when cancellation is requested.
|
||||
async fn deferred_stamp_cancelled_mid_computation() {
|
||||
let id = sha256(b"mid-pow cancel");
|
||||
let (handle, rx) = spawn_deferred_stamp(id, 32, 10);
|
||||
|
||||
// Allow the worker to enter its inner loop.
|
||||
let (handle, rx) = spawn_deferred_stamp(id, 32.0, 10);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
handle.cancel();
|
||||
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
|
||||
.await
|
||||
.expect("worker should report back within 3s of cancel")
|
||||
.expect("worker reports back after cancel")
|
||||
.expect("oneshot sender dropped");
|
||||
|
||||
assert!(
|
||||
matches!(result, DeferredStampResult::Cancelled),
|
||||
"worker must report Cancelled after handle.cancel(), got {result:?}"
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Cost=0 is the degenerate case: no work to do, oneshot fires
|
||||
/// immediately with a zero stamp + value. Cancelling after the fact
|
||||
/// must not race or produce a spurious Cancelled result.
|
||||
#[tokio::test]
|
||||
async fn test_deferred_stamp_zero_cost_completes_before_cancel() {
|
||||
let id = sha256(b"zero cost");
|
||||
let (handle, rx) = spawn_deferred_stamp(id, 0, 10);
|
||||
|
||||
async fn deferred_stamp_refuses_cost_above_cap() {
|
||||
let (_handle, rx) = spawn_deferred_stamp([9; 32], 150.0, 1);
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
|
||||
.await
|
||||
.expect("cost=0 returns immediately")
|
||||
.expect("oneshot sender dropped");
|
||||
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(result, DeferredStampResult::Success { value: 0, .. }),
|
||||
"cost=0 returns Success with zero value, got {result:?}"
|
||||
);
|
||||
// The handle remains usable after completion; cancel is a no-op here.
|
||||
handle.cancel();
|
||||
assert!(handle.is_cancelled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_workblock_peering_id_length() {
|
||||
let mut peering_id = Vec::with_capacity(32);
|
||||
peering_id.extend_from_slice(&[0xAA; 16]);
|
||||
peering_id.extend_from_slice(&[0xBB; 16]);
|
||||
let wb = stamp_workblock(
|
||||
&peering_id,
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
|
||||
);
|
||||
assert_eq!(
|
||||
wb.len(),
|
||||
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING * 256
|
||||
matches!(result, DeferredStampResult::Failed(_)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_peering_key_cost_zero() {
|
||||
let peering_id = [0xAA; 32];
|
||||
let peering_key = [0xFF; 32];
|
||||
assert!(validate_peering_key(&peering_id, &peering_key, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_peering_key_invalid() {
|
||||
let mut peering_id = Vec::with_capacity(32);
|
||||
peering_id.extend_from_slice(&[0xAA; 16]);
|
||||
peering_id.extend_from_slice(&[0xBB; 16]);
|
||||
let peering_key = [0xFF; 32];
|
||||
assert!(!validate_peering_key(&peering_id, &peering_key, 32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_pn_stamp_too_short() {
|
||||
let short_data = vec![0u8; crate::constants::LXMF_OVERHEAD + 32];
|
||||
assert!(validate_pn_stamp(&short_data, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_pn_stamp_extracts_parts() {
|
||||
let lxm_data = vec![0xAB; crate::constants::LXMF_OVERHEAD + 64];
|
||||
let stamp = [0u8; 32];
|
||||
|
||||
let mut transient_data = lxm_data.clone();
|
||||
transient_data.extend_from_slice(&stamp);
|
||||
|
||||
let result = validate_pn_stamp(&transient_data, 0);
|
||||
assert!(result.is_some());
|
||||
|
||||
let (transient_id, extracted_lxm, value, extracted_stamp) = result.unwrap();
|
||||
assert_eq!(extracted_lxm, lxm_data);
|
||||
assert_eq!(extracted_stamp, stamp);
|
||||
assert_eq!(transient_id, rns_crypto::sha::full_hash(&lxm_data));
|
||||
let _ = value;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_value_matches_direct_sha256_of_workblock_and_stamp() {
|
||||
let material = sha256(b"propagation transient id");
|
||||
let workblock = stamp_workblock(&material, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
|
||||
let stamp = [0x5Au8; 32];
|
||||
|
||||
let mut direct = Vec::with_capacity(workblock.len() + stamp.len());
|
||||
direct.extend_from_slice(&workblock);
|
||||
direct.extend_from_slice(&stamp);
|
||||
let direct_hash = sha256(&direct);
|
||||
|
||||
assert_eq!(
|
||||
stamp_value(&workblock, &stamp),
|
||||
leading_zero_bits(&direct_hash)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_pn_stamp_high_cost_fails() {
|
||||
let lxm_data = vec![0xCD; crate::constants::LXMF_OVERHEAD + 100];
|
||||
let stamp = [0xFF; 32];
|
||||
|
||||
let mut transient_data = lxm_data.clone();
|
||||
transient_data.extend_from_slice(&stamp);
|
||||
|
||||
let result = validate_pn_stamp(&transient_data, 32);
|
||||
assert!(result.is_none());
|
||||
#[tokio::test]
|
||||
async fn deferred_stamp_zero_cost_completes_with_real_value() {
|
||||
let id = sha256(b"zero cost");
|
||||
let (_handle, rx) = spawn_deferred_stamp(id, 0.0, 10);
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let DeferredStampResult::Success { stamp, value } = result else {
|
||||
panic!("{result:?}");
|
||||
};
|
||||
assert_eq!(value, stamp_value(&stamp_workblock(&id, 10), &stamp));
|
||||
}
|
||||
}
|
||||
@@ -376,7 +376,7 @@ mod tests {
|
||||
let mut session = SyncSession::new(peer_hash);
|
||||
|
||||
let mut store = PropagationStore::new();
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0));
|
||||
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0.0));
|
||||
|
||||
let offer = SyncOffer {
|
||||
peering_key: vec![0xFF; 32],
|
||||
|
||||
@@ -241,21 +241,21 @@ fn processing_admission_fails_promptly_without_partial_credit_deadlock() {
|
||||
#[test]
|
||||
fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
|
||||
let msg = message(None);
|
||||
let mut envelope = PropagationEnvelope::new(msg, [6; 32], 0, |p| Ok(p.to_vec())).unwrap();
|
||||
let mut envelope = PropagationEnvelope::new(msg, [6; 32], 0.0, |p| Ok(p.to_vec())).unwrap();
|
||||
let initial = envelope.ciphertext().clone();
|
||||
let tid = envelope.transient_id();
|
||||
let policy = AdvertisedNodePolicy {
|
||||
stamp_cost: 0,
|
||||
stamp_cost: 0.0,
|
||||
transfer_limit_kb: 256.,
|
||||
recorded_at: 100.,
|
||||
};
|
||||
let mut ready = propagation_readiness([8; 16], true, true, Some(policy), true, 101.).unwrap();
|
||||
envelope.pack_for(ready, 101.).unwrap();
|
||||
ready.policy.stamp_cost = 4;
|
||||
ready.policy.stamp_cost = 4.0;
|
||||
envelope.pack_for(ready, 102.).unwrap();
|
||||
assert_eq!(envelope.ciphertext(), &initial);
|
||||
assert_eq!(envelope.transient_id(), tid);
|
||||
assert!(envelope.stamp_value() >= 4);
|
||||
assert!(envelope.stamp_value() >= 4.0);
|
||||
assert_eq!(
|
||||
propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(),
|
||||
MissingPropagationInput::NodePolicy
|
||||
|
||||
@@ -12,7 +12,7 @@ fn payload(destination: [u8; 16]) -> Bytes {
|
||||
bytes.into()
|
||||
}
|
||||
fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob {
|
||||
ValidatedOpaquePropagationBlob::validate(bytes, 0).unwrap()
|
||||
ValidatedOpaquePropagationBlob::validate(bytes, 0.0).unwrap()
|
||||
}
|
||||
fn request(wants: Option<Vec<[u8; 32]>>, haves: Option<Vec<[u8; 32]>>) -> Vec<u8> {
|
||||
let ids = |value: Option<Vec<[u8; 32]>>| {
|
||||
|
||||
@@ -24,6 +24,7 @@ hex = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
zeroize = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -213,7 +213,7 @@ fn round_robin_peer_order(
|
||||
#[derive(Debug)]
|
||||
struct ValidatedPnEntry {
|
||||
lxmf_data: Vec<u8>,
|
||||
stamp_value: u32,
|
||||
stamp_value: f64,
|
||||
stamp_data: [u8; 32],
|
||||
}
|
||||
|
||||
@@ -248,7 +248,7 @@ struct PnPacketValidationJob {
|
||||
receipt: Option<rns_runtime::link_manager::LinkPacketReceipt>,
|
||||
node: Arc<Mutex<PropagationNode>>,
|
||||
max_transfer_bytes: usize,
|
||||
min_cost: u8,
|
||||
min_cost: f64,
|
||||
#[cfg(test)]
|
||||
store_delay: Duration,
|
||||
#[cfg(test)]
|
||||
@@ -466,8 +466,8 @@ fn enqueue_pn_packet_validation(
|
||||
#[derive(Debug)]
|
||||
struct PeeringKeyWorkerResult {
|
||||
peer_hash: [u8; 16],
|
||||
peering_cost: u8,
|
||||
peering_key: Option<([u8; 32], u32)>,
|
||||
peering_cost: f64,
|
||||
peering_key: Option<([u8; 32], f64)>,
|
||||
}
|
||||
|
||||
fn accepts_delivery_resource(data_size: usize, limit_kb: f64) -> bool {
|
||||
@@ -547,9 +547,9 @@ async fn forward_inbound_resource_cancellations(
|
||||
struct PeerOfferConstraints {
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: u8,
|
||||
stamp_cost: Option<f64>,
|
||||
stamp_flexibility: Option<f64>,
|
||||
peering_cost: f64,
|
||||
}
|
||||
|
||||
impl From<&LxmPeer> for PeerOfferConstraints {
|
||||
@@ -566,13 +566,17 @@ impl From<&LxmPeer> for PeerOfferConstraints {
|
||||
|
||||
fn generate_peering_key_job(
|
||||
peer_hash: [u8; 16],
|
||||
peering_cost: u8,
|
||||
peering_cost: f64,
|
||||
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);
|
||||
let _ = peer.generate_peering_key(
|
||||
&peer_identity_hash,
|
||||
&local_identity_hash,
|
||||
&lxmf_core::stamper::StampControl::default(),
|
||||
);
|
||||
PeeringKeyWorkerResult {
|
||||
peer_hash,
|
||||
peering_cost,
|
||||
@@ -583,7 +587,7 @@ fn generate_peering_key_job(
|
||||
fn validate_pn_resource_job(
|
||||
job: PnValidationJob,
|
||||
max_transfer_bytes: usize,
|
||||
min_cost: u8,
|
||||
min_cost: f64,
|
||||
) -> PnValidationWorkerResult {
|
||||
let token = job.token();
|
||||
let link_id = job.link_id();
|
||||
@@ -651,7 +655,7 @@ fn validate_pn_packet_job(
|
||||
link_id: [u8; 16],
|
||||
data: Bytes,
|
||||
max_transfer_bytes: usize,
|
||||
min_cost: u8,
|
||||
min_cost: f64,
|
||||
) -> PnPacketValidationWorkerResult {
|
||||
let mut result = PnPacketValidationWorkerResult {
|
||||
link_id,
|
||||
@@ -728,7 +732,7 @@ fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution {
|
||||
return PnPacketExecution { result, pending };
|
||||
}
|
||||
};
|
||||
// Validate the complete packet before admitting even its first entry.
|
||||
// Python stores every valid entry, then rejects the packet if any failed.
|
||||
let mut validated = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
match ValidatedOpaquePropagationBlob::validate(entry, job.min_cost) {
|
||||
@@ -736,9 +740,6 @@ fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution {
|
||||
None => result.rejected += 1,
|
||||
}
|
||||
}
|
||||
if result.rejected != 0 {
|
||||
return PnPacketExecution { result, pending };
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(timing) = result.timing.as_mut() {
|
||||
timing.validation_ms = validation_started.elapsed().as_secs_f64() * 1000.;
|
||||
@@ -1434,7 +1435,7 @@ enum PropagationPreparationError {
|
||||
}
|
||||
struct PendingPropagationEnvelope {
|
||||
binding: [u8; 32],
|
||||
cost: u8,
|
||||
cost: f64,
|
||||
result: oneshot::Receiver<Result<PropagationEnvelope, MessageError>>,
|
||||
cancel: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
@@ -1486,12 +1487,12 @@ fn validate_download_policy(
|
||||
msg: &LxMessage,
|
||||
public_key: Option<[u8; 64]>,
|
||||
tickets: &[[u8; 16]],
|
||||
cost: u8,
|
||||
cost: f64,
|
||||
) -> Result<(), SuppressionReason> {
|
||||
if public_key.is_some_and(|key| msg.verify(&key).is_err()) {
|
||||
return Err(SuppressionReason::InvalidSignature);
|
||||
}
|
||||
if cost > 0 {
|
||||
if cost > 0.0 {
|
||||
let Some(stamp) = msg.recipient_stamp().map(|s| s.as_bytes()) else {
|
||||
return Err(SuppressionReason::InvalidStamp);
|
||||
};
|
||||
@@ -2149,10 +2150,8 @@ impl LxmdRunner {
|
||||
max_message_size: configured_kilobytes_to_bytes(config.propagation_limit_kb),
|
||||
max_offer_size: configured_kilobytes_to_bytes(config.sync_limit_kb),
|
||||
max_message_age: lxmf_core::constants::MESSAGE_EXPIRY,
|
||||
min_stamp_cost: config
|
||||
.propagation_stamp_cost
|
||||
.saturating_sub(config.propagation_stamp_flex),
|
||||
..Default::default()
|
||||
min_stamp_cost: config.min_accepted_stamp_cost(),
|
||||
peering_cost: config.peering_cost,
|
||||
};
|
||||
let prop_storage_path = paths.propagation_store_dir.clone();
|
||||
let pn = Arc::new(Mutex::new(PropagationNode::with_storage(
|
||||
@@ -2957,7 +2956,7 @@ impl LxmdRunner {
|
||||
// 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
|
||||
&& value >= peer.peering_cost
|
||||
{
|
||||
peer.peering_key = Some((key, value));
|
||||
applied = true;
|
||||
@@ -3052,7 +3051,7 @@ impl LxmdRunner {
|
||||
continue;
|
||||
};
|
||||
let policy = self.router.peers.get(&peer_hash).and_then(|peer| {
|
||||
(peer.stamp_costs_known() && (peer.peering_cost == 0 || peer.peering_key_ready()))
|
||||
(peer.stamp_costs_known() && (peer.peering_cost == 0.0 || peer.peering_key_ready()))
|
||||
.then(|| OutboundOfferPolicy::from(peer))
|
||||
});
|
||||
if let Some(policy) = policy {
|
||||
@@ -3899,21 +3898,27 @@ impl LxmdRunner {
|
||||
.insert(event.destination_hash, event.hops.max(1));
|
||||
|
||||
if event.name_hash == delivery_name_hash {
|
||||
if let Some(ref data) = event.app_data
|
||||
&& let Some((display_name, stamp_cost)) =
|
||||
lxmf_core::handlers::parse_announce_app_data(data)
|
||||
if let Some(name) = event
|
||||
.app_data
|
||||
.as_deref()
|
||||
.and_then(lxmf_core::handlers::display_name_from_app_data)
|
||||
{
|
||||
if let Some(name) = display_name {
|
||||
tracing::info!(dest = %dest_hex, name = %name, "announce display name");
|
||||
}
|
||||
if let Some(cost) = stamp_cost {
|
||||
self.router.set_stamp_cost(event.destination_hash, cost);
|
||||
tracing::info!(dest = %dest_hex, name = %name, "announce display name");
|
||||
}
|
||||
// Python's handler records the announced cost, including none,
|
||||
// and keeps the cached cost when the data cannot be decoded.
|
||||
match lxmf_core::handlers::announced_stamp_cost(event.app_data.as_deref()) {
|
||||
Ok(cost) => {
|
||||
self.router.update_stamp_cost(event.destination_hash, cost);
|
||||
tracing::debug!(
|
||||
dest = %dest_hex,
|
||||
stamp_cost = cost,
|
||||
"learned delivery stamp cost from announce"
|
||||
stamp_cost = ?cost,
|
||||
"updated delivery stamp cost from announce"
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(dest = %dest_hex, %error, "kept cached stamp cost");
|
||||
}
|
||||
}
|
||||
let triggered = self
|
||||
.router
|
||||
@@ -3933,12 +3938,15 @@ impl LxmdRunner {
|
||||
lxmf_core::handlers::parse_pn_announce_data(data).map(|pn| (data, pn))
|
||||
})
|
||||
{
|
||||
// Outbound costs read slot 5 as given; peering reads int() of it.
|
||||
let outbound_cost =
|
||||
lxmf_core::handlers::pn_stamp_cost_from_app_data(data).unwrap_or(pn.stamp_cost);
|
||||
self.router
|
||||
.set_stamp_cost(event.destination_hash, pn.stamp_cost);
|
||||
.set_stamp_cost(event.destination_hash, outbound_cost);
|
||||
self.node_policies.insert(
|
||||
event.destination_hash,
|
||||
AdvertisedNodePolicy {
|
||||
stamp_cost: pn.stamp_cost,
|
||||
stamp_cost: outbound_cost,
|
||||
transfer_limit_kb: pn.transfer_limit as f64,
|
||||
recorded_at: now_f64(),
|
||||
},
|
||||
@@ -4308,10 +4316,7 @@ impl LxmdRunner {
|
||||
let token = job.token();
|
||||
let link_id = job.link_id();
|
||||
let max_transfer_bytes = configured_kilobytes_to_bytes(self.config.sync_limit_kb);
|
||||
let min_cost = self
|
||||
.config
|
||||
.propagation_stamp_cost
|
||||
.saturating_sub(self.config.propagation_stamp_flex);
|
||||
let min_cost = self.config.min_accepted_stamp_cost();
|
||||
let result_tx = self.prop_validation_tx.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
@@ -4366,11 +4371,10 @@ impl LxmdRunner {
|
||||
&& let Ok(mut node) = node.lock()
|
||||
{
|
||||
for entry in &result.entries {
|
||||
let stamp_value = u8::try_from(entry.stamp_value).unwrap_or(u8::MAX);
|
||||
if let Some(plan) = node.plan_accept_stamped_propagated_blob(
|
||||
&entry.lxmf_data,
|
||||
&entry.stamp_data,
|
||||
stamp_value,
|
||||
entry.stamp_value,
|
||||
) {
|
||||
write_plans.push((plan, entry.lxmf_data.len() as u64));
|
||||
}
|
||||
@@ -4432,10 +4436,7 @@ impl LxmdRunner {
|
||||
receipt,
|
||||
node,
|
||||
max_transfer_bytes: configured_kilobytes_to_bytes(self.config.propagation_limit_kb),
|
||||
min_cost: self
|
||||
.config
|
||||
.propagation_stamp_cost
|
||||
.saturating_sub(self.config.propagation_stamp_flex),
|
||||
min_cost: self.config.min_accepted_stamp_cost(),
|
||||
#[cfg(test)]
|
||||
store_delay: self.pn_packet_store_delay,
|
||||
#[cfg(test)]
|
||||
@@ -4616,9 +4617,9 @@ impl LxmdRunner {
|
||||
.ticket_store
|
||||
.inbound_tokens(&msg.source_hash(), now_f64());
|
||||
let cost = if self.config.enforce_stamps {
|
||||
self.config.stamp_cost.unwrap_or(0)
|
||||
self.config.stamp_cost.unwrap_or(0.0)
|
||||
} else {
|
||||
0
|
||||
0.0
|
||||
};
|
||||
let disposition = if self.source_blackholed(&msg.source_hash()) {
|
||||
DurableDisposition::PolicyDiscard
|
||||
@@ -4709,7 +4710,7 @@ impl LxmdRunner {
|
||||
fn download_epochs(&self) -> AdmissionEpochs {
|
||||
let mut policy = b"lxmd admission policy v1".to_vec();
|
||||
policy.push(u8::from(self.config.enforce_stamps));
|
||||
policy.push(self.config.stamp_cost.unwrap_or(0));
|
||||
policy.extend_from_slice(&self.config.stamp_cost.unwrap_or(0.0).to_be_bytes());
|
||||
let mut blocked = self
|
||||
.blackholed_identities
|
||||
.iter()
|
||||
@@ -4962,7 +4963,7 @@ impl LxmdRunner {
|
||||
return false;
|
||||
}
|
||||
let required_cost = match self.config.stamp_cost {
|
||||
Some(c) if c > 0 => c,
|
||||
Some(c) if c > 0.0 => c,
|
||||
_ => return false,
|
||||
};
|
||||
let stamp = match msg.recipient_stamp().map(|stamp| stamp.as_bytes()) {
|
||||
@@ -5579,7 +5580,7 @@ impl LxmdRunner {
|
||||
}
|
||||
if let Some(envelope) = self.propagation_envelopes.get_mut(&id)
|
||||
&& envelope.matches(message, &binding)
|
||||
&& envelope.stamp_value() >= u32::from(prepared.policy.stamp_cost)
|
||||
&& envelope.meets(prepared.policy.stamp_cost)
|
||||
{
|
||||
return envelope
|
||||
.pack_for(prepared, now_f64())
|
||||
@@ -5594,8 +5595,8 @@ impl LxmdRunner {
|
||||
.filter(|envelope| envelope.matches(message, &binding));
|
||||
let message = message.clone();
|
||||
let cost = prepared.policy.stamp_cost;
|
||||
let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let worker_cancel = cancel.clone();
|
||||
let worker_ctl = lxmf_core::stamper::StampControl::default();
|
||||
let cancel = worker_ctl.cancel.clone();
|
||||
let (tx, result) = oneshot::channel();
|
||||
self.propagation_preparation_tasks
|
||||
.push(tokio::task::spawn_blocking(move || {
|
||||
@@ -5614,10 +5615,10 @@ impl LxmdRunner {
|
||||
.encrypt(plaintext, ratchet.as_ref())
|
||||
.map_err(|e| MessageError::PackFailed(e.to_string()))
|
||||
},
|
||||
&worker_cancel,
|
||||
&worker_ctl,
|
||||
)?,
|
||||
};
|
||||
envelope.pack_for_cancellable(prepared, now_f64(), &worker_cancel)?;
|
||||
envelope.pack_for_cancellable(prepared, now_f64(), &worker_ctl)?;
|
||||
Ok(envelope)
|
||||
})();
|
||||
let _ = tx.send(outcome);
|
||||
@@ -5825,7 +5826,7 @@ pub(crate) async fn main() {
|
||||
})?;
|
||||
let source = rns_runtime::config::Config::from_file(&config_dir.join("config"))
|
||||
.map_err(std::io::Error::other)?;
|
||||
let config = DaemonConfig::from_config(&source);
|
||||
let config = DaemonConfig::from_config(&source).map_err(std::io::Error::other)?;
|
||||
let policy = RecoveryPolicy {
|
||||
maximum_store_bytes: config
|
||||
.message_storage_limit
|
||||
@@ -5833,9 +5834,7 @@ pub(crate) async fn main() {
|
||||
maximum_message_bytes: configured_kilobytes_to_bytes(
|
||||
config.propagation_limit_kb,
|
||||
),
|
||||
minimum_stamp_cost: config
|
||||
.propagation_stamp_cost
|
||||
.saturating_sub(config.propagation_stamp_flex),
|
||||
minimum_stamp_cost: config.min_accepted_stamp_cost(),
|
||||
};
|
||||
let recovered = import_trusted_recovery_manifest(&guard, manifest, digest, policy)?;
|
||||
println!(
|
||||
@@ -5898,7 +5897,14 @@ pub(crate) async fn main() {
|
||||
}
|
||||
};
|
||||
|
||||
let mut daemon_config = DaemonConfig::from_config(&config);
|
||||
let mut daemon_config = match DaemonConfig::from_config(&config) {
|
||||
Ok(daemon_config) => daemon_config,
|
||||
Err(error) => {
|
||||
tracing::error!("Could not apply LXM Daemon configuration: {error}");
|
||||
eprintln!("Could not apply LXM Daemon configuration: {error}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
};
|
||||
if args.propagation_node {
|
||||
daemon_config.propagation_enabled = true;
|
||||
}
|
||||
@@ -7020,7 +7026,7 @@ mod tests {
|
||||
std::env::var_os("RATSPEAK_PN_TEST_CONFIG").expect("private fixture config"),
|
||||
);
|
||||
let config = rns_runtime::config::Config::from_file(&config_dir.join("config")).unwrap();
|
||||
let config = DaemonConfig::from_config(&config);
|
||||
let config = DaemonConfig::from_config(&config).unwrap();
|
||||
assert!(config.propagation_enabled);
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let rns_config = config_dir.join("rns");
|
||||
@@ -7552,7 +7558,7 @@ mod tests {
|
||||
let explicit_limit = rns_runtime::config::Config::parse(
|
||||
"[lxmf]\ndelivery_transfer_max_accepted_size = 1000\n",
|
||||
)
|
||||
.map(|config| DaemonConfig::from_config(&config))
|
||||
.map(|config| DaemonConfig::from_config(&config).unwrap())
|
||||
.unwrap()
|
||||
.delivery_transfer_max_accepted_size;
|
||||
assert_eq!(explicit_limit, 1000.0);
|
||||
@@ -7582,7 +7588,7 @@ mod tests {
|
||||
));
|
||||
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
|
||||
let config = DaemonConfig {
|
||||
stamp_cost: Some(12),
|
||||
stamp_cost: Some(12.0),
|
||||
enforce_stamps,
|
||||
..Default::default()
|
||||
};
|
||||
@@ -7594,7 +7600,7 @@ mod tests {
|
||||
announce.app_data.as_deref().expect("delivery app data"),
|
||||
)
|
||||
.expect("valid delivery app data");
|
||||
assert_eq!(stamp_cost, Some(12));
|
||||
assert_eq!(stamp_cost, Some(12.0));
|
||||
drop(runner);
|
||||
let _ = std::fs::remove_dir_all(&temp);
|
||||
}
|
||||
@@ -7865,7 +7871,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(decoded.wire_bytes(), missing.wire_bytes());
|
||||
assert_eq!(
|
||||
validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 8),
|
||||
validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 8.0),
|
||||
Err(SuppressionReason::InvalidStamp)
|
||||
);
|
||||
assert!(store.haves(recipient.hash, [9; 16], 101).is_empty());
|
||||
@@ -7876,7 +7882,7 @@ mod tests {
|
||||
.exists()
|
||||
);
|
||||
assert_eq!(
|
||||
validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 0),
|
||||
validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 0.0),
|
||||
Ok(())
|
||||
);
|
||||
assert!(matches!(
|
||||
@@ -7893,7 +7899,7 @@ mod tests {
|
||||
corrupt[32] ^= 1;
|
||||
let corrupt = LxMessage::unpack(&corrupt).unwrap();
|
||||
assert_eq!(
|
||||
validate_download_policy(&corrupt, Some(sender.get_public_key()), &[], 0),
|
||||
validate_download_policy(&corrupt, Some(sender.get_public_key()), &[], 0.0),
|
||||
Err(SuppressionReason::InvalidSignature)
|
||||
);
|
||||
let ticket = [7u8; 16];
|
||||
@@ -7914,7 +7920,7 @@ mod tests {
|
||||
MessageDecodeLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
validate_download_policy(&accepted, Some(sender.get_public_key()), &[ticket], 8).unwrap();
|
||||
validate_download_policy(&accepted, Some(sender.get_public_key()), &[ticket], 8.0).unwrap();
|
||||
let scope = AdmissionScope {
|
||||
identity: recipient.hash,
|
||||
node: [9; 16],
|
||||
@@ -8078,7 +8084,7 @@ mod tests {
|
||||
let node = Arc::new(Mutex::new(
|
||||
PropagationNode::with_storage(
|
||||
PropagationNodeConfig {
|
||||
peering_cost: 0,
|
||||
peering_cost: 0.0,
|
||||
..PropagationNodeConfig::default()
|
||||
},
|
||||
local_identity,
|
||||
@@ -8121,9 +8127,9 @@ mod tests {
|
||||
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 result = generate_peering_key_job([0x65; 16], 1.0, remote_identity, local_identity);
|
||||
let (key, value) = result.peering_key.expect("cost-one key");
|
||||
assert!(value >= 1);
|
||||
assert!(value >= 1.0);
|
||||
|
||||
let mut peering_id = [0u8; 32];
|
||||
peering_id[..16].copy_from_slice(&remote_identity);
|
||||
@@ -8131,7 +8137,7 @@ mod tests {
|
||||
assert!(lxmf_core::stamper::validate_peering_key(
|
||||
&peering_id,
|
||||
&key,
|
||||
1
|
||||
1.0
|
||||
));
|
||||
}
|
||||
|
||||
@@ -8141,7 +8147,7 @@ mod tests {
|
||||
let result = validate_pn_resource_job(
|
||||
PnValidationJob::for_test(wrapper.clone(), false),
|
||||
wrapper.len(),
|
||||
0,
|
||||
0.0,
|
||||
);
|
||||
assert_eq!(result.outcome, PnValidationOutcome::UnauthorizedMultiple);
|
||||
assert!(result.entries.is_empty());
|
||||
@@ -8150,7 +8156,7 @@ mod tests {
|
||||
let result = validate_pn_resource_job(
|
||||
PnValidationJob::for_test(wrapper.clone(), true),
|
||||
wrapper.len(),
|
||||
0,
|
||||
0.0,
|
||||
);
|
||||
assert_eq!(result.outcome, PnValidationOutcome::Valid);
|
||||
assert_eq!(result.entries.len(), 2);
|
||||
@@ -8161,12 +8167,55 @@ mod tests {
|
||||
fn packet_validation_worker_handles_hundred_plus_entries_off_loop() {
|
||||
let wrapper = pn_test_wrapper((0..128).map(pn_test_entry).collect());
|
||||
|
||||
let result = validate_pn_packet_job([0x91; 16], wrapper.clone().into(), wrapper.len(), 0);
|
||||
let result = validate_pn_packet_job([0x91; 16], wrapper.clone().into(), wrapper.len(), 0.0);
|
||||
|
||||
assert_eq!(result.entries.len(), 128);
|
||||
assert_eq!(result.rejected, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_packet_stores_valid_entries_then_rejects() {
|
||||
let mut valid = None;
|
||||
let mut invalid = None;
|
||||
for stamp_byte in 0u8..=u8::MAX {
|
||||
let entry = pn_test_entry(stamp_byte);
|
||||
if lxmf_core::stamper::validate_pn_stamp(&entry, 1.0).is_some() {
|
||||
valid.get_or_insert(entry);
|
||||
} else {
|
||||
invalid.get_or_insert(entry);
|
||||
}
|
||||
if valid.is_some() && invalid.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let valid = valid.unwrap();
|
||||
let valid_id = rns_crypto::sha::full_hash(&valid[..valid.len() - 32]);
|
||||
let wrapper = pn_test_wrapper(vec![valid, invalid.unwrap()]);
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let node = Arc::new(Mutex::new(
|
||||
PropagationNode::with_storage(
|
||||
PropagationNodeConfig::default(),
|
||||
[0x11; 16],
|
||||
temporary.path().join("store"),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let execution = execute_pn_packet_job(PnPacketValidationJob {
|
||||
link_id: [0x93; 16],
|
||||
data: wrapper.clone().into(),
|
||||
receipt: None,
|
||||
node: node.clone(),
|
||||
max_transfer_bytes: wrapper.len(),
|
||||
min_cost: 1.0,
|
||||
store_delay: Duration::ZERO,
|
||||
enqueued_at: Instant::now(),
|
||||
});
|
||||
assert_eq!(execution.result.rejected, 1);
|
||||
assert!(execution.result.stored);
|
||||
assert_eq!(execution.result.committed.len(), 1);
|
||||
assert_eq!(execution.result.committed[0].0, valid_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_validation_queue_rejects_overload_and_closed_workers() {
|
||||
let job = |link_byte| PnPacketValidationJob {
|
||||
@@ -8178,7 +8227,7 @@ mod tests {
|
||||
[0; 16],
|
||||
))),
|
||||
max_transfer_bytes: 1,
|
||||
min_cost: 0,
|
||||
min_cost: 0.0,
|
||||
store_delay: Duration::ZERO,
|
||||
enqueued_at: Instant::now(),
|
||||
};
|
||||
@@ -8198,7 +8247,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn malformed_packet_validation_requests_link_teardown() {
|
||||
let result = validate_pn_packet_job([0x92; 16], Bytes::from_static(&[0xc1]), 1, 0);
|
||||
let result = validate_pn_packet_job([0x92; 16], Bytes::from_static(&[0xc1]), 1, 0.0);
|
||||
|
||||
assert!(result.entries.is_empty());
|
||||
assert!(result.malformed);
|
||||
@@ -8211,7 +8260,7 @@ mod tests {
|
||||
let mut invalid = None;
|
||||
for stamp_byte in 0u8..=u8::MAX {
|
||||
let entry = pn_test_entry(stamp_byte);
|
||||
if lxmf_core::stamper::validate_pn_stamp(&entry, 1).is_some() {
|
||||
if lxmf_core::stamper::validate_pn_stamp(&entry, 1.0).is_some() {
|
||||
valid.get_or_insert(entry);
|
||||
} else {
|
||||
invalid.get_or_insert(entry);
|
||||
@@ -8224,7 +8273,7 @@ mod tests {
|
||||
let result = validate_pn_resource_job(
|
||||
PnValidationJob::for_test(wrapper.clone(), true),
|
||||
wrapper.len(),
|
||||
1,
|
||||
1.0,
|
||||
);
|
||||
assert_eq!(result.outcome, PnValidationOutcome::InvalidStamp);
|
||||
assert_eq!(result.entries.len(), 1);
|
||||
@@ -8234,14 +8283,14 @@ mod tests {
|
||||
#[test]
|
||||
fn pn_validation_worker_fails_malformed_or_oversized_wrapper() {
|
||||
let malformed = vec![0xc1];
|
||||
let result = validate_pn_resource_job(PnValidationJob::for_test(malformed, true), 100, 0);
|
||||
let result = validate_pn_resource_job(PnValidationJob::for_test(malformed, true), 100, 0.0);
|
||||
assert_eq!(result.outcome, PnValidationOutcome::Failed);
|
||||
|
||||
let wrapper = pn_test_wrapper(vec![pn_test_entry(0)]);
|
||||
let result = validate_pn_resource_job(
|
||||
PnValidationJob::for_test(wrapper.clone(), true),
|
||||
wrapper.len() - 1,
|
||||
0,
|
||||
0.0,
|
||||
);
|
||||
assert_eq!(result.outcome, PnValidationOutcome::Failed);
|
||||
}
|
||||
|
||||
+233
-107
@@ -18,7 +18,7 @@ pub struct PythonLxmdConfig {
|
||||
pub display_name: String,
|
||||
pub peer_announce_at_start: bool,
|
||||
pub peer_announce_interval: Option<i64>,
|
||||
pub peer_stamp_cost: i64,
|
||||
pub peer_stamp_cost: f64,
|
||||
pub delivery_transfer_max_accepted_size: f64,
|
||||
pub on_inbound: Option<String>,
|
||||
pub enable_propagation_node: bool,
|
||||
@@ -34,10 +34,10 @@ pub struct PythonLxmdConfig {
|
||||
pub message_storage_limit: f64,
|
||||
pub propagation_transfer_max_accepted_size: f64,
|
||||
pub propagation_sync_max_accepted_size: f64,
|
||||
pub propagation_stamp_cost_target: i64,
|
||||
pub propagation_stamp_cost_flexibility: i64,
|
||||
pub peering_cost: i64,
|
||||
pub remote_peering_cost_max: i64,
|
||||
pub propagation_stamp_cost_target: f64,
|
||||
pub propagation_stamp_cost_flexibility: f64,
|
||||
pub peering_cost: f64,
|
||||
pub remote_peering_cost_max: f64,
|
||||
pub prioritised_lxmf_destinations: Vec<String>,
|
||||
pub control_allowed_identities: Vec<String>,
|
||||
pub static_peers: Vec<String>,
|
||||
@@ -46,8 +46,76 @@ pub struct PythonLxmdConfig {
|
||||
pub target_loglevel: Option<i64>,
|
||||
}
|
||||
|
||||
/// A stamp-cost key lxmd cannot run with.
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
pub enum DaemonConfigError {
|
||||
/// Python `as_float` raises and lxmd exits.
|
||||
#[error("[{section}] {key} = {value:?} is not a number")]
|
||||
NotANumber {
|
||||
section: &'static str,
|
||||
key: &'static str,
|
||||
value: String,
|
||||
},
|
||||
/// Stamps at this cost cannot be generated (`STAMP_COST_CAP`).
|
||||
#[error("[{section}] {key} = {value} must be a finite cost below 100")]
|
||||
CostOutOfRange {
|
||||
section: &'static str,
|
||||
key: &'static str,
|
||||
value: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// A cost key read as Python `as_float`; `None` when absent.
|
||||
fn get_cost(
|
||||
section: Option<&ConfigSection>,
|
||||
section_name: &'static str,
|
||||
key: &'static str,
|
||||
) -> Result<Option<f64>, DaemonConfigError> {
|
||||
let Some(raw) = section.and_then(|sec| sec.get(key)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
section
|
||||
.and_then(|sec| sec.get_float(key))
|
||||
.map(Some)
|
||||
.ok_or_else(|| DaemonConfigError::NotANumber {
|
||||
section: section_name,
|
||||
key,
|
||||
value: raw.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Costs a stamp is generated at must be finite and below `STAMP_COST_CAP`.
|
||||
fn generated_cost(
|
||||
value: f64,
|
||||
section: &'static str,
|
||||
key: &'static str,
|
||||
) -> Result<f64, DaemonConfigError> {
|
||||
if value.is_finite() && value < lxmf_core::stamper::STAMP_COST_CAP {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(DaemonConfigError::CostOutOfRange {
|
||||
section,
|
||||
key,
|
||||
value,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn floored_cost(
|
||||
section: Option<&ConfigSection>,
|
||||
section_name: &'static str,
|
||||
key: &'static str,
|
||||
floor: f64,
|
||||
default: f64,
|
||||
) -> Result<f64, DaemonConfigError> {
|
||||
Ok(get_cost(section, section_name, key)?.map_or(default, |v| v.max(floor)))
|
||||
}
|
||||
|
||||
impl PythonLxmdConfig {
|
||||
pub fn from_config(config: &Config) -> Self {
|
||||
/// Python `lxmd.apply_config`. Stamp-cost keys use `as_float` with its
|
||||
/// floors and defaults; an unparsable cost, or one a stamp cannot be
|
||||
/// generated at, is an error.
|
||||
pub fn from_config(config: &Config) -> Result<Self, DaemonConfigError> {
|
||||
let lxmf = config.section("lxmf");
|
||||
let propagation = config.section("propagation");
|
||||
let logging = config.section("logging");
|
||||
@@ -57,16 +125,56 @@ impl PythonLxmdConfig {
|
||||
.map(|v| v.max(0.38))
|
||||
.unwrap_or(256.0);
|
||||
|
||||
Self {
|
||||
let peer_stamp_cost = generated_cost(
|
||||
floored_cost(lxmf, "lxmf", "stamp_cost", 1.0, 12.0)?,
|
||||
"lxmf",
|
||||
"stamp_cost",
|
||||
)?;
|
||||
let propagation_stamp_cost_target = generated_cost(
|
||||
floored_cost(
|
||||
propagation,
|
||||
"propagation",
|
||||
"propagation_stamp_cost_target",
|
||||
PROPAGATION_COST_MIN,
|
||||
PROPAGATION_COST,
|
||||
)?,
|
||||
"propagation",
|
||||
"propagation_stamp_cost_target",
|
||||
)?;
|
||||
let peering_cost = generated_cost(
|
||||
floored_cost(
|
||||
propagation,
|
||||
"propagation",
|
||||
"peering_cost",
|
||||
0.0,
|
||||
PEERING_COST,
|
||||
)?,
|
||||
"propagation",
|
||||
"peering_cost",
|
||||
)?;
|
||||
let propagation_stamp_cost_flexibility = floored_cost(
|
||||
propagation,
|
||||
"propagation",
|
||||
"propagation_stamp_cost_flexibility",
|
||||
0.0,
|
||||
PROPAGATION_COST_FLEX,
|
||||
)?;
|
||||
let remote_peering_cost_max = floored_cost(
|
||||
propagation,
|
||||
"propagation",
|
||||
"remote_peering_cost_max",
|
||||
0.0,
|
||||
MAX_PEERING_COST,
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
display_name: lxmf
|
||||
.and_then(|sec| sec.get("display_name"))
|
||||
.unwrap_or("Anonymous Peer")
|
||||
.to_string(),
|
||||
peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false),
|
||||
peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60),
|
||||
peer_stamp_cost: get_int(lxmf, "stamp_cost")
|
||||
.map(|value| value.max(1))
|
||||
.unwrap_or(12),
|
||||
peer_stamp_cost,
|
||||
delivery_transfer_max_accepted_size: get_float_or_floor(
|
||||
lxmf,
|
||||
"delivery_transfer_max_accepted_size",
|
||||
@@ -111,28 +219,17 @@ impl PythonLxmdConfig {
|
||||
256.0 * 40.0,
|
||||
0.38,
|
||||
),
|
||||
propagation_stamp_cost_target: get_int(propagation, "propagation_stamp_cost_target")
|
||||
.map(|v| v.max(PROPAGATION_COST_MIN as i64))
|
||||
.unwrap_or(PROPAGATION_COST as i64),
|
||||
propagation_stamp_cost_flexibility: get_int(
|
||||
propagation,
|
||||
"propagation_stamp_cost_flexibility",
|
||||
)
|
||||
.map(|v| v.max(0))
|
||||
.unwrap_or(PROPAGATION_COST_FLEX as i64),
|
||||
peering_cost: get_int(propagation, "peering_cost")
|
||||
.map(|v| v.max(0))
|
||||
.unwrap_or(PEERING_COST as i64),
|
||||
remote_peering_cost_max: get_int(propagation, "remote_peering_cost_max")
|
||||
.map(|v| v.max(0))
|
||||
.unwrap_or(MAX_PEERING_COST as i64),
|
||||
propagation_stamp_cost_target,
|
||||
propagation_stamp_cost_flexibility,
|
||||
peering_cost,
|
||||
remote_peering_cost_max,
|
||||
prioritised_lxmf_destinations: get_list(propagation, "prioritise_destinations"),
|
||||
control_allowed_identities: get_list(propagation, "control_allowed"),
|
||||
static_peers: get_list(propagation, "static_peers"),
|
||||
max_peers: get_int(propagation, "max_peers"),
|
||||
from_static_only: get_bool_or(propagation, "from_static_only", false),
|
||||
target_loglevel: get_int(logging, "loglevel"),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,13 +261,13 @@ pub struct DaemonConfig {
|
||||
pub node_name: Option<String>,
|
||||
pub announce_at_start: bool,
|
||||
pub announce_interval: Option<u64>,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
pub propagation_enabled: bool,
|
||||
pub outbound_propagation_node: Option<String>,
|
||||
pub propagation_stamp_cost: u8,
|
||||
pub propagation_stamp_flex: u8,
|
||||
pub peering_cost: u8,
|
||||
pub max_peering_cost: u8,
|
||||
pub propagation_stamp_cost: f64,
|
||||
pub propagation_stamp_flex: f64,
|
||||
pub peering_cost: f64,
|
||||
pub max_peering_cost: f64,
|
||||
pub max_peers: usize,
|
||||
pub autopeer: bool,
|
||||
pub autopeer_maxdepth: usize,
|
||||
@@ -201,7 +298,7 @@ impl Default for DaemonConfig {
|
||||
node_name: None,
|
||||
announce_at_start: false,
|
||||
announce_interval: None,
|
||||
stamp_cost: Some(12),
|
||||
stamp_cost: Some(12.0),
|
||||
propagation_enabled: false,
|
||||
outbound_propagation_node: None,
|
||||
propagation_stamp_cost: PROPAGATION_COST,
|
||||
@@ -259,6 +356,11 @@ impl DaemonConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `max(0, propagation_stamp_cost - propagation_stamp_cost_flexibility)`.
|
||||
pub fn min_accepted_stamp_cost(&self) -> f64 {
|
||||
(self.propagation_stamp_cost - self.propagation_stamp_flex).max(0.0)
|
||||
}
|
||||
|
||||
/// Build the long-lived inbound propagation admission policy.
|
||||
pub fn to_inbound_admission_config(&self) -> PnInboundAdmissionConfig {
|
||||
PnInboundAdmissionConfig {
|
||||
@@ -270,25 +372,19 @@ impl DaemonConfig {
|
||||
}
|
||||
|
||||
/// Parse from `[lxmf]`, `[propagation]`, and `[control]` sections.
|
||||
pub fn from_config(config: &Config) -> Self {
|
||||
let py = PythonLxmdConfig::from_config(config);
|
||||
pub fn from_config(config: &Config) -> Result<Self, DaemonConfigError> {
|
||||
let py = PythonLxmdConfig::from_config(config)?;
|
||||
let mut dc = DaemonConfig {
|
||||
display_name: Some(py.display_name),
|
||||
node_name: py.node_name,
|
||||
announce_at_start: py.peer_announce_at_start,
|
||||
announce_interval: seconds_to_u64(py.peer_announce_interval),
|
||||
stamp_cost: normalize_peer_stamp_cost(py.peer_stamp_cost),
|
||||
stamp_cost: Some(py.peer_stamp_cost),
|
||||
propagation_enabled: py.enable_propagation_node,
|
||||
propagation_stamp_cost: clamp_python_cost_to_u8(
|
||||
py.propagation_stamp_cost_target,
|
||||
PROPAGATION_COST_MIN as i64,
|
||||
),
|
||||
propagation_stamp_flex: clamp_python_cost_to_u8(
|
||||
py.propagation_stamp_cost_flexibility,
|
||||
0,
|
||||
),
|
||||
peering_cost: clamp_python_cost_to_u8(py.peering_cost, 0),
|
||||
max_peering_cost: clamp_python_cost_to_u8(py.remote_peering_cost_max, 0),
|
||||
propagation_stamp_cost: py.propagation_stamp_cost_target,
|
||||
propagation_stamp_flex: py.propagation_stamp_cost_flexibility,
|
||||
peering_cost: py.peering_cost,
|
||||
max_peering_cost: py.remote_peering_cost_max,
|
||||
max_peers: py
|
||||
.max_peers
|
||||
.and_then(|value| usize::try_from(value).ok())
|
||||
@@ -323,10 +419,14 @@ 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")
|
||||
if !sec.has("propagation_stamp_cost_target")
|
||||
&& let Some(cost) = get_cost(Some(sec), "propagation", "propagation_stamp_cost")?
|
||||
{
|
||||
dc.propagation_stamp_cost = cost as u8;
|
||||
dc.propagation_stamp_cost = generated_cost(
|
||||
cost.max(PROPAGATION_COST_MIN),
|
||||
"propagation",
|
||||
"propagation_stamp_cost",
|
||||
)?;
|
||||
}
|
||||
if get_float(Some(sec), "propagation_message_max_accepted_size").is_none()
|
||||
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
|
||||
@@ -352,21 +452,10 @@ impl DaemonConfig {
|
||||
}
|
||||
}
|
||||
|
||||
dc
|
||||
Ok(dc)
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp_python_cost_to_u8(value: i64, floor: i64) -> u8 {
|
||||
value.max(floor).min(u8::MAX as i64) as u8
|
||||
}
|
||||
|
||||
/// Apply Python lxmd's signed floor, then mirror `set_inbound_stamp_cost`:
|
||||
/// delivery stamp costs are valid only in `1..=254`.
|
||||
fn normalize_peer_stamp_cost(value: i64) -> Option<u8> {
|
||||
let cost = u8::try_from(value.max(1)).ok()?;
|
||||
(cost < u8::MAX).then_some(cost)
|
||||
}
|
||||
|
||||
fn get_float(section: Option<&ConfigSection>, key: &str) -> Option<f64> {
|
||||
section.and_then(|sec| sec.get_float(key))
|
||||
}
|
||||
@@ -590,12 +679,12 @@ mod tests {
|
||||
assert_eq!(dc.display_name.as_deref(), Some("Anonymous Peer"));
|
||||
assert!(!dc.announce_at_start);
|
||||
assert_eq!(dc.announce_interval, None);
|
||||
assert_eq!(dc.stamp_cost, Some(12));
|
||||
assert_eq!(dc.stamp_cost, Some(12.0));
|
||||
assert!(!dc.propagation_enabled);
|
||||
assert_eq!(dc.propagation_stamp_cost, 16);
|
||||
assert_eq!(dc.propagation_stamp_flex, 3);
|
||||
assert_eq!(dc.peering_cost, 18);
|
||||
assert_eq!(dc.max_peering_cost, 26);
|
||||
assert_eq!(dc.propagation_stamp_cost, 16.0);
|
||||
assert_eq!(dc.propagation_stamp_flex, 3.0);
|
||||
assert_eq!(dc.peering_cost, 18.0);
|
||||
assert_eq!(dc.max_peering_cost, 26.0);
|
||||
assert_eq!(dc.max_peers, 20);
|
||||
assert!(dc.autopeer);
|
||||
assert_eq!(dc.autopeer_maxdepth, AUTOPEER_MAXDEPTH);
|
||||
@@ -618,12 +707,12 @@ mod tests {
|
||||
#[test]
|
||||
fn python_normalized_config_matches_omitted_defaults() {
|
||||
let config = rns_runtime::config::Config::parse("").unwrap();
|
||||
let py = PythonLxmdConfig::from_config(&config);
|
||||
let py = PythonLxmdConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(py.display_name, "Anonymous Peer");
|
||||
assert!(!py.peer_announce_at_start);
|
||||
assert_eq!(py.peer_announce_interval, None);
|
||||
assert_eq!(py.peer_stamp_cost, 12);
|
||||
assert_eq!(py.peer_stamp_cost, 12.0);
|
||||
assert_eq!(py.delivery_transfer_max_accepted_size, 1.0);
|
||||
assert_eq!(py.on_inbound, None);
|
||||
assert!(!py.enable_propagation_node);
|
||||
@@ -639,10 +728,10 @@ mod tests {
|
||||
assert_eq!(py.message_storage_limit, 500.0);
|
||||
assert_eq!(py.propagation_transfer_max_accepted_size, 256.0);
|
||||
assert_eq!(py.propagation_sync_max_accepted_size, 10240.0);
|
||||
assert_eq!(py.propagation_stamp_cost_target, 16);
|
||||
assert_eq!(py.propagation_stamp_cost_flexibility, 3);
|
||||
assert_eq!(py.peering_cost, 18);
|
||||
assert_eq!(py.remote_peering_cost_max, 26);
|
||||
assert_eq!(py.propagation_stamp_cost_target, 16.0);
|
||||
assert_eq!(py.propagation_stamp_cost_flexibility, 3.0);
|
||||
assert_eq!(py.peering_cost, 18.0);
|
||||
assert_eq!(py.remote_peering_cost_max, 26.0);
|
||||
assert!(py.prioritised_lxmf_destinations.is_empty());
|
||||
assert!(py.control_allowed_identities.is_empty());
|
||||
assert!(py.static_peers.is_empty());
|
||||
@@ -681,19 +770,19 @@ delivery_transfer_max_accepted_size = 0.1
|
||||
loglevel = 6
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let py = PythonLxmdConfig::from_config(&config);
|
||||
let py = PythonLxmdConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(py.peer_announce_interval, Some(180));
|
||||
assert_eq!(py.node_announce_interval, Some(120));
|
||||
assert_eq!(py.peer_stamp_cost, 1);
|
||||
assert_eq!(py.peer_stamp_cost, 1.0);
|
||||
assert_eq!(py.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(py.message_storage_limit, 0.005);
|
||||
assert_eq!(py.propagation_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(py.propagation_sync_max_accepted_size, 0.38);
|
||||
assert_eq!(py.propagation_stamp_cost_target, 13);
|
||||
assert_eq!(py.propagation_stamp_cost_flexibility, 0);
|
||||
assert_eq!(py.peering_cost, 0);
|
||||
assert_eq!(py.remote_peering_cost_max, 0);
|
||||
assert_eq!(py.propagation_stamp_cost_target, 13.0);
|
||||
assert_eq!(py.propagation_stamp_cost_flexibility, 0.0);
|
||||
assert_eq!(py.peering_cost, 0.0);
|
||||
assert_eq!(py.remote_peering_cost_max, 0.0);
|
||||
assert_eq!(py.static_peers, ["00112233445566778899aabbccddeeff"]);
|
||||
assert_eq!(
|
||||
py.prioritised_lxmf_destinations,
|
||||
@@ -718,7 +807,7 @@ loglevel = 6
|
||||
propagation_transfer_max_accepted_size = 12
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let py = PythonLxmdConfig::from_config(&config);
|
||||
let py = PythonLxmdConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
py.propagation_transfer_max_accepted_size, 256.0,
|
||||
@@ -733,7 +822,7 @@ propagation_transfer_max_accepted_size = 12
|
||||
propagation_transfer_max_accepted_size = 12
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
dc.propagation_limit_kb, 256,
|
||||
@@ -751,11 +840,11 @@ propagation_transfer_max_accepted_size = 12
|
||||
assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0);
|
||||
assert_eq!(rc.propagation_limit_kb, 256);
|
||||
assert_eq!(rc.sync_limit_kb, 10_240);
|
||||
assert_eq!(rc.propagation_stamp_cost, 16);
|
||||
assert_eq!(rc.propagation_stamp_flex, 3);
|
||||
assert_eq!(rc.propagation_stamp_cost, 16.0);
|
||||
assert_eq!(rc.propagation_stamp_flex, 3.0);
|
||||
assert_eq!(rc.ext.autopeer_maxdepth, AUTOPEER_MAXDEPTH);
|
||||
assert_eq!(rc.ext.peering_cost, 18);
|
||||
assert_eq!(rc.ext.max_peering_cost, 26);
|
||||
assert_eq!(rc.ext.peering_cost, 18.0);
|
||||
assert_eq!(rc.ext.max_peering_cost, 26.0);
|
||||
assert!(!rc.ext.auth_required);
|
||||
assert_eq!(rc.ext.message_storage_limit, Some(500_000_000));
|
||||
assert_eq!(rc.ext.name, None);
|
||||
@@ -813,12 +902,12 @@ control_allowed = 11111111111111111111111111111111
|
||||
from_static_only = yes
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
assert_eq!(dc.display_name.as_deref(), Some("TestNode"));
|
||||
assert!(dc.announce_at_start);
|
||||
assert_eq!(dc.announce_interval, Some(180));
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(dc.stamp_cost, Some(8));
|
||||
assert_eq!(dc.stamp_cost, Some(8.0));
|
||||
assert!(dc.propagation_enabled);
|
||||
assert_eq!(dc.node_name.as_deref(), Some("PropNode"));
|
||||
assert_eq!(
|
||||
@@ -830,10 +919,10 @@ from_static_only = yes
|
||||
assert_eq!(dc.message_storage_limit, Some(5_000));
|
||||
assert_eq!(dc.propagation_limit_kb, 1);
|
||||
assert_eq!(dc.sync_limit_kb, 1);
|
||||
assert_eq!(dc.propagation_stamp_cost, 13);
|
||||
assert_eq!(dc.propagation_stamp_flex, 0);
|
||||
assert_eq!(dc.peering_cost, 0);
|
||||
assert_eq!(dc.max_peering_cost, 0);
|
||||
assert_eq!(dc.propagation_stamp_cost, 13.0);
|
||||
assert_eq!(dc.propagation_stamp_flex, 0.0);
|
||||
assert_eq!(dc.peering_cost, 0.0);
|
||||
assert_eq!(dc.max_peering_cost, 0.0);
|
||||
assert_eq!(dc.max_peers, 10);
|
||||
assert!(!dc.autopeer);
|
||||
assert_eq!(dc.autopeer_maxdepth, 2);
|
||||
@@ -859,22 +948,59 @@ from_static_only = yes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_stamp_cost_matches_python_floor_and_destination_range() {
|
||||
for (configured, normalized, expected) in [
|
||||
(-7, 1, Some(1)),
|
||||
(0, 1, Some(1)),
|
||||
(254, 254, Some(254)),
|
||||
(255, 255, None),
|
||||
(256, 256, None),
|
||||
(1000, 1000, None),
|
||||
fn delivery_stamp_cost_matches_python_floor_and_cap() {
|
||||
for (configured, expected) in [
|
||||
("-7", 1.0),
|
||||
("0", 1.0),
|
||||
("0.5", 1.0),
|
||||
("12.5", 12.5),
|
||||
("99.5", 99.5),
|
||||
] {
|
||||
let input = format!("[lxmf]\nstamp_cost = {configured}\n");
|
||||
let config = rns_runtime::config::Config::parse(&input).unwrap();
|
||||
let py = PythonLxmdConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let py = PythonLxmdConfig::from_config(&config).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(py.peer_stamp_cost, normalized, "configured {configured}");
|
||||
assert_eq!(dc.stamp_cost, expected, "configured {configured}");
|
||||
assert_eq!(py.peer_stamp_cost, expected, "configured {configured}");
|
||||
assert_eq!(dc.stamp_cost, Some(expected), "configured {configured}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamp_costs_of_100_or_more_are_refused_naming_the_key() {
|
||||
for (section, key) in [
|
||||
("lxmf", "stamp_cost"),
|
||||
("propagation", "propagation_stamp_cost_target"),
|
||||
("propagation", "peering_cost"),
|
||||
] {
|
||||
for value in ["100", "150", "254", "1000"] {
|
||||
let input = format!("[{section}]\n{key} = {value}\n");
|
||||
let config = rns_runtime::config::Config::parse(&input).unwrap();
|
||||
let error = DaemonConfig::from_config(&config).unwrap_err();
|
||||
assert!(error.to_string().contains(key), "{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparsable_stamp_cost_is_an_error() {
|
||||
for (section, key) in [
|
||||
("lxmf", "stamp_cost"),
|
||||
("propagation", "propagation_stamp_cost_target"),
|
||||
("propagation", "propagation_stamp_cost_flexibility"),
|
||||
("propagation", "peering_cost"),
|
||||
("propagation", "remote_peering_cost_max"),
|
||||
] {
|
||||
let input = format!("[{section}]\n{key} = abc\n");
|
||||
let config = rns_runtime::config::Config::parse(&input).unwrap();
|
||||
match DaemonConfig::from_config(&config).unwrap_err() {
|
||||
DaemonConfigError::NotANumber {
|
||||
section: s,
|
||||
key: k,
|
||||
value,
|
||||
} => assert_eq!((s, k, value.as_str()), (section, key, "abc")),
|
||||
other => panic!("{other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -884,7 +1010,7 @@ from_static_only = yes
|
||||
"[lxmf]\ndelivery_transfer_max_accepted_size = 0.38\n",
|
||||
)
|
||||
.unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(dc.to_router_config().delivery_limit_kb, 0.38);
|
||||
@@ -897,7 +1023,7 @@ from_static_only = yes
|
||||
propagation_stamp_cost_target = 1
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(dc.propagation_stamp_cost, PROPAGATION_COST_MIN);
|
||||
assert_eq!(
|
||||
@@ -913,10 +1039,10 @@ propagation_stamp_cost_target = 1
|
||||
propagation_stamp_cost = 19
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert_eq!(dc.propagation_stamp_cost, 19);
|
||||
assert_eq!(dc.to_router_config().propagation_stamp_cost, 19);
|
||||
assert_eq!(dc.propagation_stamp_cost, 19.0);
|
||||
assert_eq!(dc.to_router_config().propagation_stamp_cost, 19.0);
|
||||
}
|
||||
|
||||
/// Python lxmd exposes no enforce_ratchets option; the key must parse as a no-op.
|
||||
@@ -928,7 +1054,7 @@ enforce_ratchets = yes
|
||||
enforce_stamps = yes
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config).unwrap();
|
||||
|
||||
assert!(dc.enforce_stamps);
|
||||
}
|
||||
|
||||
@@ -231,15 +231,15 @@ pub fn encode_router_control_stats(
|
||||
),
|
||||
(
|
||||
Value::String("target_stamp_cost".into()),
|
||||
option_u8(peer.stamp_cost),
|
||||
option_f64(peer.stamp_cost),
|
||||
),
|
||||
(
|
||||
Value::String("stamp_cost_flexibility".into()),
|
||||
option_u8(peer.stamp_cost_flexibility),
|
||||
option_f64(peer.stamp_cost_flexibility),
|
||||
),
|
||||
(
|
||||
Value::String("peering_cost".into()),
|
||||
Value::from(peer.peering_cost as u64),
|
||||
Value::F64(peer.peering_cost),
|
||||
),
|
||||
(Value::String("peering_key".into()), peering_key_value),
|
||||
(
|
||||
@@ -303,19 +303,19 @@ pub fn encode_router_control_stats(
|
||||
),
|
||||
(
|
||||
Value::String("target_stamp_cost".into()),
|
||||
Value::from(router.config.propagation_stamp_cost as u64),
|
||||
Value::F64(router.config.propagation_stamp_cost),
|
||||
),
|
||||
(
|
||||
Value::String("stamp_cost_flexibility".into()),
|
||||
Value::from(router.config.propagation_stamp_flex as u64),
|
||||
Value::F64(router.config.propagation_stamp_flex),
|
||||
),
|
||||
(
|
||||
Value::String("peering_cost".into()),
|
||||
Value::from(router.config.ext.peering_cost as u64),
|
||||
Value::F64(router.config.ext.peering_cost),
|
||||
),
|
||||
(
|
||||
Value::String("max_peering_cost".into()),
|
||||
Value::from(router.config.ext.max_peering_cost as u64),
|
||||
Value::F64(router.config.ext.max_peering_cost),
|
||||
),
|
||||
(
|
||||
Value::String("autopeer_maxdepth".into()),
|
||||
@@ -506,13 +506,13 @@ pub fn format_remote_status(
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"Required propagation stamp cost is {}, flexibility is {}\n",
|
||||
map_u64(stats, "target_stamp_cost").unwrap_or(0),
|
||||
map_u64(stats, "stamp_cost_flexibility").unwrap_or(0),
|
||||
map_python_str(stats, "target_stamp_cost"),
|
||||
map_python_str(stats, "stamp_cost_flexibility"),
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"Peering cost is {}, max remote peering cost is {}\n",
|
||||
map_u64(stats, "peering_cost").unwrap_or(0),
|
||||
map_u64(stats, "max_peering_cost").unwrap_or(0),
|
||||
map_python_str(stats, "peering_cost"),
|
||||
map_python_str(stats, "max_peering_cost"),
|
||||
));
|
||||
out.push_str(&format!("Accepting propagated messages from {who}\n"));
|
||||
out.push_str(&format!(
|
||||
@@ -624,9 +624,9 @@ pub fn format_remote_status(
|
||||
));
|
||||
out.push_str(&format!(
|
||||
" Costs : Propagation {} (flex {}), peering {}\n",
|
||||
map_optional_display(peer, "target_stamp_cost"),
|
||||
map_optional_display(peer, "stamp_cost_flexibility"),
|
||||
map_optional_display(peer, "peering_cost"),
|
||||
map_optional_cost(peer, "target_stamp_cost"),
|
||||
map_optional_cost(peer, "stamp_cost_flexibility"),
|
||||
map_optional_cost(peer, "peering_cost"),
|
||||
));
|
||||
out.push_str(&format!(" Sync key : {peering_key}\n"));
|
||||
out.push_str(&format!(
|
||||
@@ -712,13 +712,6 @@ fn map_display(value: &Value, key: &str) -> String {
|
||||
.unwrap_or_else(|| "None".to_string())
|
||||
}
|
||||
|
||||
fn map_optional_display(value: &Value, key: &str) -> String {
|
||||
match map_value(value, key) {
|
||||
Some(v) if !v.is_nil() => value_to_display(v),
|
||||
_ => "unknown".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn value_to_display(value: &Value) -> String {
|
||||
if value.is_nil() {
|
||||
"None".to_string()
|
||||
@@ -839,8 +832,21 @@ fn format_python_float(value: f64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn option_u8(value: Option<u8>) -> Value {
|
||||
value.map(|v| Value::from(v as u64)).unwrap_or(Value::Nil)
|
||||
fn map_optional_cost(value: &Value, key: &str) -> String {
|
||||
match map_value(value, key) {
|
||||
Some(v) if !v.is_nil() => map_python_str(value, key),
|
||||
_ => "unknown".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `str()` of a number: floats keep their decimal point.
|
||||
fn map_python_str(value: &Value, key: &str) -> String {
|
||||
match map_value(value, key) {
|
||||
Some(Value::F64(f)) => format!("{f:?}"),
|
||||
Some(Value::F32(f)) => format!("{:?}", f64::from(*f)),
|
||||
Some(v) if !v.is_nil() => value_to_display(v),
|
||||
_ => "0".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn option_f64(value: Option<f64>) -> Value {
|
||||
|
||||
@@ -163,7 +163,7 @@ pub fn format_local_peers(peers: &[LocalPeerView]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
pub fn delivery_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
|
||||
pub fn delivery_announce_app_data(display_name: Option<&str>, stamp_cost: Option<f64>) -> Vec<u8> {
|
||||
lxmf_core::handlers::get_announce_app_data(display_name, stamp_cost)
|
||||
}
|
||||
|
||||
@@ -452,28 +452,35 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn delivery_announce_app_data_matches_python_msgpack() {
|
||||
// Python 1.0.1: msgpack([display_name, stamp_cost, [SF_COMPRESSION]])
|
||||
// — LXMRouter.py:999-1001.
|
||||
// LXMF 1.3.0 LXMRouter.get_announce_app_data output.
|
||||
assert_eq!(
|
||||
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
|
||||
"93c40454657374109100"
|
||||
hex::encode(delivery_announce_app_data(Some("Test"), Some(16.0))),
|
||||
"94c40454657374109100cb4030000000000000"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(delivery_announce_app_data(Some("x"), Some(8.5))),
|
||||
"94c40178099100cb4021000000000000"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(delivery_announce_app_data(None, None)),
|
||||
"93c0c09100"
|
||||
"94c0c09100c0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propagation_announce_app_data_matches_python_msgpack() {
|
||||
let mut data =
|
||||
lxmf_core::handlers::PropagationNodeAnnounceData::new(true, 256, 10_240, 16, 3, 18);
|
||||
let mut data = lxmf_core::handlers::PropagationNodeAnnounceData::new(
|
||||
true, 256, 10_240, 16.25, 3.0, 18.5,
|
||||
);
|
||||
data.timebase = 1_700_000_000;
|
||||
data.set_name("Node");
|
||||
|
||||
assert_eq!(
|
||||
hex::encode(propagation_announce_app_data(&data)),
|
||||
"97c2ce6553f100c3cd0100cd2800931003128101c4044e6f6465"
|
||||
concat!(
|
||||
"98c2ce6553f100c3cd0100cd2800931103138101c4044e6f6465",
|
||||
"93cb4030400000000000cb4008000000000000cb4032800000000000"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user