mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-27 13:52:18 +00:00
propagation: isolate bounded offer evaluation
This commit is contained in:
1 parent
3a17ca6845
commit
356ba6a305
8 files changed
+450
-223
No files matched your search
Generated
+1
@@ -650,6 +650,7 @@ dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
"rand 0.8.5",
|
||||
"rmp",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"rns-crypto",
|
||||
|
||||
@@ -30,6 +30,7 @@ lxmf-tools = { path = "crates/lxmf-tools", version = "1.0.1" }
|
||||
base64 = "0.22"
|
||||
|
||||
# Serialization
|
||||
rmp = "0.8"
|
||||
rmp-serde = "1"
|
||||
rmpv = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
@@ -17,6 +17,7 @@ thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
rmp = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -441,12 +441,10 @@ impl PropagationRequestHandler {
|
||||
true
|
||||
};
|
||||
|
||||
let peer_hash = remote_identity_hash.copied().unwrap_or([0u8; 16]);
|
||||
|
||||
node.handle_offer_request(
|
||||
request_data,
|
||||
crate::propagation_node::OfferRequestContext {
|
||||
peer_hash,
|
||||
peer_hash: remote_identity_hash.copied().unwrap_or([0u8; 16]),
|
||||
identity_known,
|
||||
is_throttled,
|
||||
access_allowed,
|
||||
|
||||
@@ -53,6 +53,7 @@ pub mod propagation;
|
||||
pub mod propagation_admission;
|
||||
pub mod propagation_client;
|
||||
pub mod propagation_node;
|
||||
pub mod propagation_offer;
|
||||
pub mod propagation_sync;
|
||||
pub mod router;
|
||||
pub mod stamper;
|
||||
|
||||
@@ -12,6 +12,8 @@ use crate::constants::*;
|
||||
use crate::message::LxMessage;
|
||||
use crate::peer::LxmPeer;
|
||||
use crate::propagation::{PropagationEntry, PropagationStore, hex_encode};
|
||||
use crate::propagation_admission::PnOfferCandidate;
|
||||
use crate::propagation_offer::{PnOfferEvaluation, PnOfferEvaluationError};
|
||||
use crate::sync::{OfferResponse, SyncGet, SyncOffer, SyncSession};
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
@@ -24,6 +26,9 @@ pub struct PropagationNodeConfig {
|
||||
pub min_stamp_cost: u8,
|
||||
pub peering_cost: u8,
|
||||
pub max_message_size: usize,
|
||||
/// Maximum encoded inbound `/offer` request size. This follows the
|
||||
/// node's advertised propagation sync budget.
|
||||
pub max_offer_size: usize,
|
||||
}
|
||||
|
||||
impl Default for PropagationNodeConfig {
|
||||
@@ -35,6 +40,7 @@ impl Default for PropagationNodeConfig {
|
||||
min_stamp_cost: 0,
|
||||
peering_cost: PEERING_COST,
|
||||
max_message_size: DELIVERY_LIMIT * 1024,
|
||||
max_offer_size: SYNC_LIMIT * 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,7 +153,8 @@ pub struct PropagationNode {
|
||||
sync_sessions: HashMap<[u8; 16], SyncSession>,
|
||||
pub dest_hash: [u8; 16],
|
||||
storage_path: Option<PathBuf>,
|
||||
/// Per-peer last offer time, for rate-limiting.
|
||||
/// Transitional pre-1.1 behavior; removed when the daemon-lifetime
|
||||
/// `PnInboundAdmission` becomes the live throttle owner.
|
||||
last_offer_times: HashMap<[u8; 16], f64>,
|
||||
}
|
||||
|
||||
@@ -586,49 +593,6 @@ impl PropagationNode {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Offer request with typed error responses. Python reference:
|
||||
/// LXMRouter.offer_request() (LXMRouter.py:2139-2189).
|
||||
///
|
||||
/// The returned `OfferResponse` distinguishes
|
||||
/// NoIdentity/Throttled/NoAccess/InvalidKey errors from
|
||||
/// HaveAll/WantAll/WantSome outcomes.
|
||||
pub fn offer_request_checked(
|
||||
&mut self,
|
||||
_peer_hash: [u8; 16],
|
||||
identity_known: bool,
|
||||
is_throttled: bool,
|
||||
access_allowed: bool,
|
||||
peering_key_valid: bool,
|
||||
offered_ids: &[PropagationTransientId],
|
||||
) -> OfferResponse {
|
||||
if !identity_known {
|
||||
return OfferResponse::ErrorNoIdentity;
|
||||
}
|
||||
if is_throttled {
|
||||
return OfferResponse::ErrorThrottled;
|
||||
}
|
||||
if !access_allowed {
|
||||
return OfferResponse::ErrorNoAccess;
|
||||
}
|
||||
if !peering_key_valid {
|
||||
return OfferResponse::ErrorInvalidKey;
|
||||
}
|
||||
|
||||
let wanted: Vec<PropagationTransientId> = offered_ids
|
||||
.iter()
|
||||
.filter(|id| !self.store.contains(id))
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
if wanted.is_empty() {
|
||||
OfferResponse::HaveAll
|
||||
} else if wanted.len() == offered_ids.len() {
|
||||
OfferResponse::WantAll
|
||||
} else {
|
||||
OfferResponse::WantSome(wanted.iter().map(|id| id.to_vec()).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire format matches Python: Boolean for WantAll/HaveAll, integer for
|
||||
/// error codes, array of binary IDs for WantSome.
|
||||
pub fn encode_offer_response(response: &OfferResponse) -> Vec<u8> {
|
||||
@@ -656,8 +620,10 @@ impl PropagationNode {
|
||||
/// LXMRouter.offer_request() (LXMRouter.py:2139-2189).
|
||||
///
|
||||
/// `request_data` is msgpack `[peering_key, [transient_id_1, ...]]`.
|
||||
/// Decodes, runs `offer_request_checked`, and returns an encoded
|
||||
/// `OfferResponse` ready for `link.create_response()`.
|
||||
/// Transitional compatibility wrapper for callers that still compute the
|
||||
/// outer identity/access/throttle gates. New daemon code must preflight a
|
||||
/// long-lived `PnInboundAdmission` and call `evaluate_offer_request`
|
||||
/// directly before committing the exact candidate.
|
||||
pub fn handle_offer_request(
|
||||
&mut self,
|
||||
request_data: &[u8],
|
||||
@@ -665,78 +631,65 @@ impl PropagationNode {
|
||||
) -> Vec<u8> {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64())
|
||||
.map(|duration| duration.as_secs_f64())
|
||||
.unwrap_or(0.0);
|
||||
if let Some(&last_time) = self.last_offer_times.get(&ctx.peer_hash)
|
||||
&& now - last_time < PN_STAMP_THROTTLE as f64
|
||||
if self
|
||||
.last_offer_times
|
||||
.get(&ctx.peer_hash)
|
||||
.is_some_and(|last_time| now - last_time < PN_STAMP_THROTTLE as f64)
|
||||
{
|
||||
return Self::encode_offer_response(&OfferResponse::ErrorThrottled);
|
||||
}
|
||||
|
||||
let (peering_key, offered_ids) = match Self::decode_offer_request(request_data) {
|
||||
Some(parsed) => parsed,
|
||||
None => {
|
||||
return Self::encode_offer_response(&OfferResponse::ErrorInvalidData);
|
||||
}
|
||||
let offer = match crate::propagation_offer::decode(request_data, self.config.max_offer_size)
|
||||
{
|
||||
Ok(offer) => offer,
|
||||
Err(error) => return Self::encode_offer_response(&error.wire_response()),
|
||||
};
|
||||
|
||||
// Python validates peering_id = local_identity.hash || remote_identity.hash.
|
||||
let peering_key_valid = if peering_key.is_empty() {
|
||||
self.config.peering_cost == 0
|
||||
} else if peering_key.len() == 32 {
|
||||
if let (Some(local_hash), Some(remote_hash)) =
|
||||
(ctx.local_identity_hash, ctx.remote_identity_hash)
|
||||
{
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&peering_key);
|
||||
let mut peering_id = Vec::with_capacity(32);
|
||||
peering_id.extend_from_slice(local_hash);
|
||||
peering_id.extend_from_slice(remote_hash);
|
||||
crate::stamper::validate_peering_key(&peering_id, &key, self.config.peering_cost)
|
||||
} else {
|
||||
false
|
||||
let response = if !ctx.identity_known {
|
||||
OfferResponse::ErrorNoIdentity
|
||||
} else if ctx.is_throttled {
|
||||
OfferResponse::ErrorThrottled
|
||||
} else if !ctx.access_allowed {
|
||||
OfferResponse::ErrorNoAccess
|
||||
} else if let (Some(local_hash), Some(remote_hash)) =
|
||||
(ctx.local_identity_hash, ctx.remote_identity_hash)
|
||||
{
|
||||
match crate::propagation_offer::evaluate_decoded(
|
||||
offer,
|
||||
local_hash,
|
||||
remote_hash,
|
||||
self.config.peering_cost,
|
||||
|transient_id| self.store.contains(transient_id),
|
||||
) {
|
||||
Ok(evaluation) => evaluation.into_wire_response(),
|
||||
Err(error) => error.wire_response(),
|
||||
}
|
||||
} else {
|
||||
false
|
||||
OfferResponse::ErrorInvalidKey
|
||||
};
|
||||
|
||||
let response = self.offer_request_checked(
|
||||
ctx.peer_hash,
|
||||
ctx.identity_known,
|
||||
ctx.is_throttled,
|
||||
ctx.access_allowed,
|
||||
peering_key_valid,
|
||||
&offered_ids,
|
||||
);
|
||||
|
||||
self.last_offer_times.insert(ctx.peer_hash, now);
|
||||
|
||||
Self::encode_offer_response(&response)
|
||||
}
|
||||
|
||||
/// Expected wire format: `[peering_key_bytes, [transient_id_1, ...]]`.
|
||||
fn decode_offer_request(data: &[u8]) -> Option<(Vec<u8>, Vec<PropagationTransientId>)> {
|
||||
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
|
||||
let arr = value.as_array()?;
|
||||
if arr.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let peering_key = arr[0].as_slice().unwrap_or(&[]).to_vec();
|
||||
|
||||
let ids_array = arr[1].as_array()?;
|
||||
let mut offered_ids = Vec::with_capacity(ids_array.len());
|
||||
for id_val in ids_array {
|
||||
if let Some(id_bytes) = id_val.as_slice()
|
||||
&& id_bytes.len() == 32
|
||||
{
|
||||
let mut tid = [0u8; 32];
|
||||
tid.copy_from_slice(id_bytes);
|
||||
offered_ids.push(tid);
|
||||
}
|
||||
}
|
||||
|
||||
Some((peering_key, offered_ids))
|
||||
/// Evaluate a preflighted `/offer` without mutating admission state.
|
||||
pub fn evaluate_offer_request(
|
||||
&self,
|
||||
request_data: &[u8],
|
||||
local_identity_hash: &[u8; 16],
|
||||
candidate: &PnOfferCandidate,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError> {
|
||||
let remote_identity_hash = candidate.peer_identity_hash();
|
||||
crate::propagation_offer::evaluate(
|
||||
request_data,
|
||||
local_identity_hash,
|
||||
&remote_identity_hash,
|
||||
self.config.peering_cost,
|
||||
self.config.max_offer_size,
|
||||
|transient_id| self.store.contains(transient_id),
|
||||
)
|
||||
}
|
||||
|
||||
/// Handle a Link REQUEST at the `/get` path for client download. Python
|
||||
@@ -1781,84 +1734,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_no_identity() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let resp = node.offer_request_checked([0xDD; 16], false, false, true, true, &[]);
|
||||
assert_eq!(resp, OfferResponse::ErrorNoIdentity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_throttled() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let resp = node.offer_request_checked([0xDD; 16], true, true, true, true, &[]);
|
||||
assert_eq!(resp, OfferResponse::ErrorThrottled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_no_access() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let resp = node.offer_request_checked([0xDD; 16], true, false, false, true, &[]);
|
||||
assert_eq!(resp, OfferResponse::ErrorNoAccess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_invalid_key() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let resp = node.offer_request_checked([0xDD; 16], true, false, true, false, &[]);
|
||||
assert_eq!(resp, OfferResponse::ErrorInvalidKey);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_have_all() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content");
|
||||
let tid = msg.transient_id.unwrap();
|
||||
node.accept_message(&msg);
|
||||
|
||||
let resp = node.offer_request_checked([0xDD; 16], true, false, true, true, &[tid]);
|
||||
assert_eq!(resp, OfferResponse::HaveAll);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_want_all() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
|
||||
let resp = node.offer_request_checked(
|
||||
[0xDD; 16],
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
&[tid(0x11), tid(0x22)],
|
||||
);
|
||||
assert_eq!(resp, OfferResponse::WantAll);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_request_checked_want_some() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content");
|
||||
let stored_tid = msg.transient_id.unwrap();
|
||||
node.accept_message(&msg);
|
||||
|
||||
let resp = node.offer_request_checked(
|
||||
[0xDD; 16],
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
&[stored_tid, tid(0x99)],
|
||||
);
|
||||
match resp {
|
||||
OfferResponse::WantSome(ids) => {
|
||||
assert_eq!(ids.len(), 1);
|
||||
assert_eq!(ids[0], id(0x99));
|
||||
}
|
||||
_ => panic!("expected WantSome"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_offer_response_roundtrip() {
|
||||
let encoded = PropagationNode::encode_offer_response(&OfferResponse::WantAll);
|
||||
@@ -1923,6 +1798,32 @@ mod tests {
|
||||
assert_eq!(response, OfferResponse::WantAll);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offer_evaluation_uses_preflight_candidate_identity() {
|
||||
let cost = 8;
|
||||
let local_identity = [0xAA; 16];
|
||||
let remote_identity = [0xBB; 16];
|
||||
let config = PropagationNodeConfig {
|
||||
peering_cost: cost,
|
||||
..Default::default()
|
||||
};
|
||||
let node = PropagationNode::new(config, [0xCC; 16]);
|
||||
let mut admission = crate::propagation_admission::PnInboundAdmission::default();
|
||||
let candidate = admission
|
||||
.preflight_offer([0xDD; 16], Some(remote_identity), std::time::Duration::ZERO)
|
||||
.unwrap();
|
||||
let key = peering_key(&local_identity, &remote_identity, cost);
|
||||
let request = crate::encode_value(&rmpv::Value::Array(vec![
|
||||
rmpv::Value::Binary(key.to_vec()),
|
||||
rmpv::Value::Array(vec![rmpv::Value::Binary(id(0x11))]),
|
||||
]));
|
||||
|
||||
assert_eq!(
|
||||
node.evaluate_offer_request(&request, &local_identity, &candidate),
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_offer_request_rejects_empty_peering_key_when_cost_required() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
@@ -2004,52 +1905,47 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_handle_offer_request_invalid_data() {
|
||||
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let mut node = PropagationNode::new(
|
||||
PropagationNodeConfig {
|
||||
peering_cost: 0,
|
||||
..Default::default()
|
||||
},
|
||||
[0xAA; 16],
|
||||
);
|
||||
let local_identity = [0xAA; 16];
|
||||
let remote_identity = [0xBB; 16];
|
||||
|
||||
let response_bytes = node.handle_offer_request(
|
||||
&[0xFF, 0xFF],
|
||||
offer_ctx([0xBB; 16], true, false, true, None, None),
|
||||
offer_ctx(
|
||||
[0xBB; 16],
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
Some(&local_identity),
|
||||
Some(&remote_identity),
|
||||
),
|
||||
);
|
||||
let response = OfferResponse::from_msgpack(&response_bytes);
|
||||
assert_eq!(response, OfferResponse::ErrorInvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_offer_request_valid() {
|
||||
use rmpv::Value;
|
||||
let offer = Value::Array(vec![
|
||||
Value::Binary(vec![0xAA; 32]),
|
||||
Value::Array(vec![Value::Binary(id(0x11)), Value::Binary(id(0x22))]),
|
||||
]);
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &offer).unwrap();
|
||||
|
||||
let result = PropagationNode::decode_offer_request(&buf);
|
||||
assert!(result.is_some());
|
||||
let (key, ids) = result.unwrap();
|
||||
assert_eq!(key, vec![0xAA; 32]);
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert_eq!(ids[0], tid(0x11));
|
||||
assert_eq!(ids[1], tid(0x22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_offer_request_filters_bad_ids() {
|
||||
use rmpv::Value;
|
||||
let offer = Value::Array(vec![
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![
|
||||
Value::Binary(vec![0x11; 16]),
|
||||
Value::Binary(vec![0x22; 8]),
|
||||
Value::Binary(id(0x33)),
|
||||
]),
|
||||
]);
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &offer).unwrap();
|
||||
|
||||
let (_, ids) = PropagationNode::decode_offer_request(&buf).unwrap();
|
||||
assert_eq!(ids.len(), 1);
|
||||
assert_eq!(ids[0], tid(0x33));
|
||||
let valid_request = crate::encode_value(&rmpv::Value::Array(vec![
|
||||
rmpv::Value::Binary(vec![]),
|
||||
rmpv::Value::Array(vec![rmpv::Value::Binary(id(0x11))]),
|
||||
]));
|
||||
let response_bytes = node.handle_offer_request(
|
||||
&valid_request,
|
||||
offer_ctx(
|
||||
[0xBB; 16],
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
Some(&local_identity),
|
||||
Some(&remote_identity),
|
||||
),
|
||||
);
|
||||
let response = OfferResponse::from_msgpack(&response_bytes);
|
||||
assert_eq!(response, OfferResponse::WantAll);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Typed evaluation of an inbound propagation-node `/offer` request.
|
||||
//!
|
||||
//! Admission policy and lifecycle accounting deliberately live in
|
||||
//! [`crate::propagation_admission`]. Callers must pass that cheap preflight
|
||||
//! before performing the peering-key work in this module, then commit the
|
||||
//! returned wanted outcome to the same admission candidate.
|
||||
|
||||
use crate::propagation_admission::PnOfferResponse;
|
||||
use crate::stamper;
|
||||
use crate::sync::OfferResponse;
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
|
||||
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
|
||||
|
||||
/// A peering-key-validated offer and the subset not present in local storage.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PnOfferEvaluation {
|
||||
HaveAll,
|
||||
WantAll,
|
||||
WantSome(Vec<PropagationTransientId>),
|
||||
}
|
||||
|
||||
impl PnOfferEvaluation {
|
||||
/// Lifecycle outcome recorded by [`crate::propagation_admission`].
|
||||
pub fn admission_response(&self) -> PnOfferResponse {
|
||||
match self {
|
||||
Self::HaveAll => PnOfferResponse::HaveAll,
|
||||
Self::WantAll => PnOfferResponse::WantAll,
|
||||
Self::WantSome(_) => PnOfferResponse::WantSome,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python-compatible response value for the `/offer` request.
|
||||
pub fn into_wire_response(self) -> OfferResponse {
|
||||
match self {
|
||||
Self::HaveAll => OfferResponse::HaveAll,
|
||||
Self::WantAll => OfferResponse::WantAll,
|
||||
Self::WantSome(ids) => {
|
||||
OfferResponse::WantSome(ids.into_iter().map(Vec::from).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure before an offer can be committed to admission accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PnOfferEvaluationError {
|
||||
InvalidData,
|
||||
InvalidKey,
|
||||
}
|
||||
|
||||
impl PnOfferEvaluationError {
|
||||
pub fn wire_response(self) -> OfferResponse {
|
||||
match self {
|
||||
Self::InvalidData => OfferResponse::ErrorInvalidData,
|
||||
Self::InvalidKey => OfferResponse::ErrorInvalidKey,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum DecodedPeeringKey {
|
||||
Empty,
|
||||
Key([u8; 32]),
|
||||
InvalidLength,
|
||||
}
|
||||
|
||||
pub(crate) struct DecodedOffer {
|
||||
peering_key: DecodedPeeringKey,
|
||||
transient_ids: Vec<PropagationTransientId>,
|
||||
}
|
||||
|
||||
/// Decode, validate, and determine the wanted subset without mutating
|
||||
/// admission state.
|
||||
pub(crate) fn evaluate<F>(
|
||||
request_data: &[u8],
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
max_offer_size: usize,
|
||||
contains: F,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
|
||||
where
|
||||
F: FnMut(&PropagationTransientId) -> bool,
|
||||
{
|
||||
let offer = decode(request_data, max_offer_size)?;
|
||||
evaluate_decoded(
|
||||
offer,
|
||||
local_identity_hash,
|
||||
remote_identity_hash,
|
||||
peering_cost,
|
||||
contains,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate_decoded<F>(
|
||||
offer: DecodedOffer,
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
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::Key(key) => {
|
||||
let mut peering_id = [0u8; 32];
|
||||
peering_id[..16].copy_from_slice(local_identity_hash);
|
||||
peering_id[16..].copy_from_slice(remote_identity_hash);
|
||||
stamper::validate_peering_key(&peering_id, &key, peering_cost)
|
||||
}
|
||||
DecodedPeeringKey::InvalidLength => false,
|
||||
};
|
||||
|
||||
if !peering_key_valid {
|
||||
return Err(PnOfferEvaluationError::InvalidKey);
|
||||
}
|
||||
|
||||
let wanted: Vec<PropagationTransientId> = offer
|
||||
.transient_ids
|
||||
.iter()
|
||||
.filter(|transient_id| !contains(transient_id))
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
if wanted.is_empty() {
|
||||
Ok(PnOfferEvaluation::HaveAll)
|
||||
} else if wanted.len() == offer.transient_ids.len() {
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
} else {
|
||||
Ok(PnOfferEvaluation::WantSome(wanted))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(
|
||||
data: &[u8],
|
||||
max_offer_size: usize,
|
||||
) -> Result<DecodedOffer, PnOfferEvaluationError> {
|
||||
use std::io::Read;
|
||||
|
||||
if data.len() > max_offer_size {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let mut remaining = data;
|
||||
let field_count = rmp::decode::read_array_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
|
||||
if field_count != 2 {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let peering_key_len = rmp::decode::read_bin_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if peering_key_len > remaining.len() {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
let peering_key = match peering_key_len {
|
||||
0 => DecodedPeeringKey::Empty,
|
||||
32 => {
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&remaining[..32]);
|
||||
DecodedPeeringKey::Key(key)
|
||||
}
|
||||
_ => DecodedPeeringKey::InvalidLength,
|
||||
};
|
||||
remaining = &remaining[peering_key_len..];
|
||||
|
||||
let transient_id_count = rmp::decode::read_array_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if transient_id_count > remaining.len() / ENCODED_TRANSIENT_ID_MIN_BYTES {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let mut transient_ids = Vec::with_capacity(transient_id_count);
|
||||
for _ in 0..transient_id_count {
|
||||
let encoded_len = rmp::decode::read_bin_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if encoded_len != 32 {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
let mut transient_id = [0u8; 32];
|
||||
remaining
|
||||
.read_exact(&mut transient_id)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
|
||||
transient_ids.push(transient_id);
|
||||
}
|
||||
|
||||
if !remaining.is_empty() {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
Ok(DecodedOffer {
|
||||
peering_key,
|
||||
transient_ids,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rmpv::Value;
|
||||
|
||||
fn encode_offer(key: Value, ids: Value) -> Vec<u8> {
|
||||
crate::encode_value(&Value::Array(vec![key, ids]))
|
||||
}
|
||||
|
||||
fn id(value: u8) -> PropagationTransientId {
|
||||
[value; 32]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_decode_rejects_malformed_fields_and_trailing_bytes() {
|
||||
let malformed = [
|
||||
vec![0xc1],
|
||||
crate::encode_value(&Value::Array(vec![])),
|
||||
crate::encode_value(&Value::Array(vec![
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![]),
|
||||
Value::Nil,
|
||||
])),
|
||||
encode_offer(Value::Nil, Value::Array(vec![])),
|
||||
encode_offer(Value::String("key".into()), Value::Array(vec![])),
|
||||
encode_offer(Value::Binary(vec![]), Value::Nil),
|
||||
encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::Binary(vec![1; 31])]),
|
||||
),
|
||||
encode_offer(Value::Binary(vec![]), Value::Array(vec![Value::from(1)])),
|
||||
encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::String(
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
|
||||
)]),
|
||||
),
|
||||
];
|
||||
|
||||
for request in malformed {
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
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),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_declared_id_count_before_allocating_entries() {
|
||||
let mut request = Vec::new();
|
||||
rmp::encode::write_array_len(&mut request, 2).unwrap();
|
||||
rmp::encode::write_bin_len(&mut request, 0).unwrap();
|
||||
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_key_is_valid_only_when_peering_work_is_disabled() {
|
||||
let request = encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::Binary(id(3).to_vec())]),
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidKey)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wanted_evaluation_preserves_offer_order_and_duplicates() {
|
||||
let request = encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![
|
||||
Value::Binary(id(1).to_vec()),
|
||||
Value::Binary(id(2).to_vec()),
|
||||
Value::Binary(id(2).to_vec()),
|
||||
Value::Binary(id(3).to_vec()),
|
||||
]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]),
|
||||
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outcomes_map_to_admission_and_wire_types() {
|
||||
assert_eq!(
|
||||
PnOfferEvaluation::HaveAll.admission_response(),
|
||||
PnOfferResponse::HaveAll
|
||||
);
|
||||
assert_eq!(
|
||||
PnOfferEvaluation::WantAll.admission_response(),
|
||||
PnOfferResponse::WantAll
|
||||
);
|
||||
let some = PnOfferEvaluation::WantSome(vec![id(7)]);
|
||||
assert_eq!(some.admission_response(), PnOfferResponse::WantSome);
|
||||
assert_eq!(
|
||||
some.into_wire_response(),
|
||||
OfferResponse::WantSome(vec![id(7).to_vec()])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -661,6 +661,7 @@ impl LxmdRunner {
|
||||
.message_storage_limit
|
||||
.unwrap_or(config.propagation_limit_kb * 1024),
|
||||
max_message_size: config.propagation_limit_kb * 1024,
|
||||
max_offer_size: config.sync_limit_kb.saturating_mul(1000),
|
||||
max_message_age: lxmf_core::constants::MESSAGE_EXPIRY,
|
||||
min_stamp_cost: config
|
||||
.propagation_stamp_cost
|
||||
@@ -682,6 +683,7 @@ impl LxmdRunner {
|
||||
.message_storage_limit
|
||||
.unwrap_or(config.propagation_limit_kb * 1024),
|
||||
max_message_size: config.propagation_limit_kb * 1024,
|
||||
max_offer_size: config.sync_limit_kb.saturating_mul(1000),
|
||||
max_message_age: lxmf_core::constants::MESSAGE_EXPIRY,
|
||||
min_stamp_cost: config
|
||||
.propagation_stamp_cost
|
||||
|
||||
Reference in new issue
Block a user