mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
router: resume a stored signed message under its own id
This commit is contained in:
1 parent
9bb80d754b
commit
e674b3f24b
10 files changed
+521
-4
No files matched your search
@@ -6,6 +6,7 @@
|
||||
- Space `lxmd` announces like Python lxmd: the propagation and control announces follow their trigger by 20 seconds instead of going out together with the delivery announce, so Python transport nodes no longer hold the control announce after a restart. A node set not to announce at start now waits a full interval before its first periodic announce.
|
||||
- Fall back from opportunistic to direct delivery whenever a message's content does not fit one encrypted packet, over 287 bytes, as in Python LXMF 1.2.0.
|
||||
- `lxmd` learns the identities Reticulum validated before it subscribed to announces, and asks Reticulum for a missing identity before a propagation download, a delivery or a peer sync, as Python LXMF recalls them.
|
||||
- Store a signed message so its delivery can resume after a restart under the same id. A message that is already queued is no longer queued twice.
|
||||
|
||||
## 1.4.0 - 2026-10-12
|
||||
|
||||
|
||||
@@ -161,6 +161,23 @@ content limit, 287 bytes, which `LxmRouter::try_send` applies to opportunistic
|
||||
messages. Applications that choose a delivery method themselves should compare
|
||||
against it rather than a hard-coded limit.
|
||||
|
||||
## Resuming a signed message
|
||||
|
||||
`SignedLxMessage::to_resumable()` returns a `ResumableLxMessage` to store before
|
||||
`submit_signed`; `as_bytes()` and `ResumableLxMessage::from_bytes` move it
|
||||
through storage. It keeps the signed, unstamped message and the stamp cost it
|
||||
was signed under. It is not a wire message, and `LxMessage::unpack` rejects it.
|
||||
After a restart, `LxmRouter::restore_signed(&stored, &active_public_key,
|
||||
method)` verifies the message as sent by the active identity, so no signing key
|
||||
is needed. It attaches the current outbound ticket and uses the larger of the
|
||||
stored and current stamp costs. Set delivery metadata such as `auto_compress`,
|
||||
then call `submit_signed`. The message keeps its id, so recipients deduplicate a
|
||||
copy that was already delivered.
|
||||
|
||||
`submit_signed` now refuses a message whose id is already queued, awaiting its
|
||||
stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as
|
||||
already sent.
|
||||
|
||||
The API ledger retains its original compatibility floor and lists exact removed
|
||||
rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary
|
||||
field access through Deref; duplicate `message_api` snapshot paths describe the
|
||||
|
||||
@@ -732,6 +732,7 @@ pub fn lxmf_core::message::FieldValue::serialize<S: serde_core::ser::Serializer>
|
||||
impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldValue
|
||||
pub fn lxmf_core::message::FieldValue::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
|
||||
pub enum lxmf_core::message::MessageError
|
||||
pub lxmf_core::message::MessageError::AlreadyQueued
|
||||
pub lxmf_core::message::MessageError::DuplicateField
|
||||
pub lxmf_core::message::MessageError::HistoricalHashMismatch
|
||||
pub lxmf_core::message::MessageError::InvalidByte
|
||||
@@ -941,6 +942,12 @@ pub lxmf_core::message::MessagePayload::title: alloc::string::String
|
||||
pub struct lxmf_core::message::OwnedVerifiedLxMessage
|
||||
impl lxmf_core::message::OwnedVerifiedLxMessage
|
||||
pub fn lxmf_core::message::OwnedVerifiedLxMessage::as_verified(&self) -> lxmf_core::message::VerifiedLxMessage<'_>
|
||||
pub struct lxmf_core::message::ResumableLxMessage
|
||||
impl lxmf_core::message::ResumableLxMessage
|
||||
pub fn lxmf_core::message::ResumableLxMessage::as_bytes(&self) -> &[u8]
|
||||
pub fn lxmf_core::message::ResumableLxMessage::from_bytes(impl core::convert::Into<bytes::bytes::Bytes>) -> core::result::Result<Self, lxmf_core::message::MessageError>
|
||||
impl core::fmt::Debug for lxmf_core::message::ResumableLxMessage
|
||||
pub fn lxmf_core::message::ResumableLxMessage::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct lxmf_core::message::SignedLxMessage
|
||||
impl lxmf_core::message::SignedLxMessage
|
||||
pub fn lxmf_core::message::SignedLxMessage::content_bytes(&self) -> &[u8]
|
||||
@@ -958,6 +965,7 @@ pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::O
|
||||
pub fn lxmf_core::message::SignedLxMessage::timestamp(&self) -> f64
|
||||
pub fn lxmf_core::message::SignedLxMessage::title_bytes(&self) -> &[u8]
|
||||
pub fn lxmf_core::message::SignedLxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str>
|
||||
pub fn lxmf_core::message::SignedLxMessage::to_resumable(&self) -> lxmf_core::message::ResumableLxMessage
|
||||
impl core::ops::deref::Deref for lxmf_core::message::SignedLxMessage
|
||||
pub type lxmf_core::message::SignedLxMessage::Target = lxmf_core::message::MessageMetadata
|
||||
pub fn lxmf_core::message::SignedLxMessage::deref(&self) -> &Self::Target
|
||||
@@ -998,6 +1006,7 @@ pub fn lxmf_core::message::FieldValue::serialize<S: serde_core::ser::Serializer>
|
||||
impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldValue
|
||||
pub fn lxmf_core::message::FieldValue::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
|
||||
pub enum lxmf_core::message_api::MessageError
|
||||
pub lxmf_core::message_api::MessageError::AlreadyQueued
|
||||
pub lxmf_core::message_api::MessageError::DuplicateField
|
||||
pub lxmf_core::message_api::MessageError::HistoricalHashMismatch
|
||||
pub lxmf_core::message_api::MessageError::InvalidByte
|
||||
@@ -1208,6 +1217,12 @@ pub fn lxmf_core::message::MessageMetadata::default() -> Self
|
||||
pub struct lxmf_core::message_api::OwnedVerifiedLxMessage
|
||||
impl lxmf_core::message::OwnedVerifiedLxMessage
|
||||
pub fn lxmf_core::message::OwnedVerifiedLxMessage::as_verified(&self) -> lxmf_core::message::VerifiedLxMessage<'_>
|
||||
pub struct lxmf_core::message_api::ResumableLxMessage
|
||||
impl lxmf_core::message::ResumableLxMessage
|
||||
pub fn lxmf_core::message::ResumableLxMessage::as_bytes(&self) -> &[u8]
|
||||
pub fn lxmf_core::message::ResumableLxMessage::from_bytes(impl core::convert::Into<bytes::bytes::Bytes>) -> core::result::Result<Self, lxmf_core::message::MessageError>
|
||||
impl core::fmt::Debug for lxmf_core::message::ResumableLxMessage
|
||||
pub fn lxmf_core::message::ResumableLxMessage::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct lxmf_core::message_api::SignedLxMessage
|
||||
impl lxmf_core::message::SignedLxMessage
|
||||
pub fn lxmf_core::message::SignedLxMessage::content_bytes(&self) -> &[u8]
|
||||
@@ -1225,6 +1240,7 @@ pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::O
|
||||
pub fn lxmf_core::message::SignedLxMessage::timestamp(&self) -> f64
|
||||
pub fn lxmf_core::message::SignedLxMessage::title_bytes(&self) -> &[u8]
|
||||
pub fn lxmf_core::message::SignedLxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str>
|
||||
pub fn lxmf_core::message::SignedLxMessage::to_resumable(&self) -> lxmf_core::message::ResumableLxMessage
|
||||
impl core::ops::deref::Deref for lxmf_core::message::SignedLxMessage
|
||||
pub type lxmf_core::message::SignedLxMessage::Target = lxmf_core::message::MessageMetadata
|
||||
pub fn lxmf_core::message::SignedLxMessage::deref(&self) -> &Self::Target
|
||||
@@ -1974,6 +1990,7 @@ pub fn lxmf_core::router::LxmRouter::remember_ticket(&mut self, [u8; 16], [u8; 1
|
||||
pub fn lxmf_core::router::LxmRouter::remove_peer(&mut self, &[u8; 16])
|
||||
pub fn lxmf_core::router::LxmRouter::requires_authentication(&self) -> bool
|
||||
pub fn lxmf_core::router::LxmRouter::reserve_inbound(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::router::InboundReservation>
|
||||
pub fn lxmf_core::router::LxmRouter::restore_signed(&self, &lxmf_core::message::ResumableLxMessage, &[u8; 64], lxmf_core::constants::DeliveryMethod) -> core::result::Result<lxmf_core::message::SignedLxMessage, lxmf_core::message::MessageError>
|
||||
pub fn lxmf_core::router::LxmRouter::retain_node_lxms(&self) -> bool
|
||||
pub fn lxmf_core::router::LxmRouter::rotate_peers(&mut self)
|
||||
pub fn lxmf_core::router::LxmRouter::run_jobs_tick(&mut self)
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxmf-core.txt",
|
||||
"itemCount": 2209,
|
||||
"sha256": "3983790769c9ae44c1b2665cbf894720b39fa03635575a04b3d0f19e412de83e"
|
||||
"itemCount": 2226,
|
||||
"sha256": "67e48ebcad7cdc46b04dd04ec2f38e153bf55f119c6b0ccb914d442ccd67fcdc"
|
||||
},
|
||||
{
|
||||
"name": "lxmf-tools",
|
||||
|
||||
@@ -93,7 +93,8 @@ pub mod message_api {
|
||||
pub use crate::message::{
|
||||
AudioField, EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields,
|
||||
LxMessage, LxMessageDraft, MessageDecodeLimits, MessageError, MessageMetadata,
|
||||
OwnedVerifiedLxMessage, RecipientStamp, SignedLxMessage, UniqueFieldMap, VerifiedLxMessage,
|
||||
OwnedVerifiedLxMessage, RecipientStamp, ResumableLxMessage, SignedLxMessage,
|
||||
UniqueFieldMap, VerifiedLxMessage,
|
||||
};
|
||||
pub use crate::types::{DestinationHash, IdentityHash, MessageId};
|
||||
}
|
||||
|
||||
@@ -16,11 +16,13 @@ use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
mod draft;
|
||||
mod field;
|
||||
mod resumable;
|
||||
pub use draft::{LxMessageDraft, SignedLxMessage};
|
||||
use field::FieldIndex;
|
||||
pub use field::{
|
||||
EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields, UniqueFieldMap,
|
||||
};
|
||||
pub use resumable::ResumableLxMessage;
|
||||
|
||||
/// Lossy projection with a single exact-sized allocation. Standard UTF-8
|
||||
/// replacement semantics are preserved, but geometric String growth cannot
|
||||
@@ -1486,6 +1488,8 @@ pub enum MessageError {
|
||||
InvalidSignature,
|
||||
#[error("public key does not bind claimed source")]
|
||||
SourceMismatch,
|
||||
#[error("message is already queued")]
|
||||
AlreadyQueued,
|
||||
|
||||
#[error("message too short: {0} bytes")]
|
||||
TooShort(usize),
|
||||
|
||||
@@ -315,6 +315,22 @@ impl LxMessageDraft {
|
||||
}
|
||||
}
|
||||
impl SignedLxMessage {
|
||||
pub(crate) fn restored(
|
||||
message: LxMessage,
|
||||
outbound_ticket: Option<[u8; 16]>,
|
||||
stamp_cost: Option<u8>,
|
||||
) -> Self {
|
||||
Self {
|
||||
message,
|
||||
outbound_ticket,
|
||||
stamp_cost,
|
||||
}
|
||||
}
|
||||
/// Store this message so its delivery can resume after a restart, under
|
||||
/// the same id. The stored form keeps the signing stamp cost as a floor.
|
||||
pub fn to_resumable(&self) -> ResumableLxMessage {
|
||||
ResumableLxMessage::new(&self.message.wire, self.stamp_cost)
|
||||
}
|
||||
pub fn timestamp(&self) -> f64 {
|
||||
self.message.timestamp()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Durable form of a signed message that has not finished delivery.
|
||||
use super::*;
|
||||
|
||||
/// The signed header (destination, source, signature) ends here, and an LXMF
|
||||
/// payload would begin.
|
||||
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 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:
|
||||
/// - 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;
|
||||
/// - 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
|
||||
/// this version ignores filled slots and redoes that work;
|
||||
/// - the signed payload;
|
||||
/// - the first 16 bytes of the SHA-256 of everything before them.
|
||||
///
|
||||
/// It is not a wire message: [`LxMessage::unpack`] rejects it, because byte
|
||||
/// 96 is `0xC1`. Restore it with
|
||||
/// [`LxmRouter::restore_signed`](crate::router::LxmRouter::restore_signed).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ResumableLxMessage {
|
||||
bytes: Bytes,
|
||||
stamp_cost_floor: Option<u8>,
|
||||
payload_at: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResumableLxMessage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResumableLxMessage")
|
||||
.field("len", &self.bytes.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ResumableLxMessage {
|
||||
pub(super) fn new(wire: &[u8], stamp_cost: Option<u8>) -> Self {
|
||||
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.push(0);
|
||||
bytes.extend_from_slice(&0u32.to_be_bytes());
|
||||
let payload_at = bytes.len();
|
||||
bytes.extend_from_slice(&wire[HEADER_LEN..]);
|
||||
let digest = sha256(&bytes);
|
||||
bytes.extend_from_slice(&digest[..DIGEST_LEN]);
|
||||
Self {
|
||||
bytes: bytes.into(),
|
||||
stamp_cost_floor: stamp_cost,
|
||||
payload_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a stored form's structure and digest. The signature is checked
|
||||
/// when the message is restored, against the sender's key.
|
||||
pub fn from_bytes(bytes: impl Into<Bytes>) -> Result<Self, MessageError> {
|
||||
let bytes = bytes.into();
|
||||
let invalid =
|
||||
|reason: &str| MessageError::UnpackFailed(format!("resumable message: {reason}"));
|
||||
if bytes.len() < STAMP_AT + 5 + 1 + DIGEST_LEN {
|
||||
return Err(invalid("too short"));
|
||||
}
|
||||
if bytes[HEADER_LEN..HEADER_LEN + MAGIC.len()] != MAGIC {
|
||||
return Err(invalid("not a stored message"));
|
||||
}
|
||||
if bytes[HEADER_LEN + MAGIC.len()] != VERSION {
|
||||
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),
|
||||
_ => return Err(invalid("invalid stamp cost")),
|
||||
};
|
||||
let stamp_len = usize::from(bytes[STAMP_AT]);
|
||||
if !matches!(stamp_len, 0 | 16 | 32) {
|
||||
return Err(invalid("invalid recipient stamp"));
|
||||
}
|
||||
let envelope_len_at = STAMP_AT + 1 + stamp_len;
|
||||
let envelope_len = bytes
|
||||
.get(envelope_len_at..envelope_len_at + 4)
|
||||
.map(|len| u32::from_be_bytes(len.try_into().expect("four bytes")) as usize)
|
||||
.ok_or_else(|| invalid("truncated"))?;
|
||||
let payload_at = (envelope_len_at + 4)
|
||||
.checked_add(envelope_len)
|
||||
.filter(|at| *at < digest_at)
|
||||
.ok_or_else(|| invalid("truncated"))?;
|
||||
if bytes[payload_at] != 0x94 {
|
||||
return Err(invalid("payload is not a signed, unstamped body"));
|
||||
}
|
||||
Ok(Self {
|
||||
bytes,
|
||||
stamp_cost_floor,
|
||||
payload_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
pub(crate) fn stamp_cost_floor(&self) -> Option<u8> {
|
||||
self.stamp_cost_floor
|
||||
}
|
||||
|
||||
/// The signed, unstamped message. Its signature is not yet checked.
|
||||
pub(crate) fn unverified_message(&self) -> Result<LxMessage, MessageError> {
|
||||
let digest_at = self.bytes.len() - DIGEST_LEN;
|
||||
let mut wire = Vec::with_capacity(HEADER_LEN + digest_at - self.payload_at);
|
||||
wire.extend_from_slice(&self.bytes[..HEADER_LEN]);
|
||||
wire.extend_from_slice(&self.bytes[self.payload_at..digest_at]);
|
||||
LxMessage::unpack_owned(wire.into(), MessageDecodeLimits::default())
|
||||
}
|
||||
}
|
||||
@@ -731,3 +731,117 @@ fn bounded_propagation_wrapper_rejects_forged_counts_and_lengths_before_allocati
|
||||
trailing.push(0);
|
||||
assert!(LxMessage::unpack_propagation_wrapper_bounded(&trailing, trailing.len()).is_err());
|
||||
}
|
||||
|
||||
fn resumable_identity() -> rns_identity::identity::Identity {
|
||||
let mut key = [0x11; 64];
|
||||
key[32..].fill(0x22);
|
||||
rns_identity::identity::Identity::from_private_key(&key).unwrap()
|
||||
}
|
||||
|
||||
fn resumable_signed(
|
||||
identity: &rns_identity::identity::Identity,
|
||||
cost: Option<u8>,
|
||||
) -> SignedLxMessage {
|
||||
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"lxmf.delivery",
|
||||
Some(&identity.hash),
|
||||
);
|
||||
let mut draft = LxMessageDraft::new(
|
||||
[0x5a; 16],
|
||||
source,
|
||||
"Resume",
|
||||
"Hello",
|
||||
DeliveryMethod::Direct,
|
||||
)
|
||||
.unwrap();
|
||||
draft.set_timestamp(1_700_000_000.).unwrap();
|
||||
draft.stamp_cost = cost;
|
||||
draft.sign(&identity.get_signing_key().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resumable_form_bytes_are_pinned() {
|
||||
let signed = resumable_signed(&resumable_identity(), Some(8));
|
||||
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[103], 0, "no recipient stamp yet");
|
||||
assert_eq!(bytes[104..108], [0; 4], "no propagation envelope yet");
|
||||
let digest_at = bytes.len() - 16;
|
||||
assert_eq!(
|
||||
bytes[108..digest_at],
|
||||
wire[96..],
|
||||
"the signed payload follows"
|
||||
);
|
||||
assert_eq!(bytes[digest_at..], sha256(&bytes[..digest_at])[..16]);
|
||||
// Source hash and signature checked against Python RNS 1.5.5.
|
||||
assert_eq!(
|
||||
hex::encode(&bytes),
|
||||
concat!(
|
||||
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
|
||||
"58ead48e0227a546df7a9712ea53572c",
|
||||
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
|
||||
"8a900be403ca81baac788cf29bd9d64cab486ff0c3923571f11e4a21b4c34005",
|
||||
"c14c5852",
|
||||
"01",
|
||||
"0108",
|
||||
"00",
|
||||
"00000000",
|
||||
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
|
||||
"370fdcdb14f43dd52931349474302403",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resumable_form_is_not_a_wire_message() {
|
||||
for _ in 0..64 {
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let stored = resumable_signed(&identity, None).to_resumable();
|
||||
assert!(LxMessage::unpack(stored.as_bytes()).is_err());
|
||||
assert!(
|
||||
LxMessage::unpack_owned(
|
||||
Bytes::copy_from_slice(stored.as_bytes()),
|
||||
MessageDecodeLimits::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resumable_form_round_trips_and_rejects_damage() {
|
||||
let stored = resumable_signed(&resumable_identity(), Some(8)).to_resumable();
|
||||
let bytes = stored.as_bytes().to_vec();
|
||||
assert_eq!(
|
||||
ResumableLxMessage::from_bytes(bytes.clone()).unwrap(),
|
||||
stored
|
||||
);
|
||||
for at in 0..bytes.len() {
|
||||
let mut damaged = bytes.clone();
|
||||
damaged[at] ^= 0x01;
|
||||
assert!(
|
||||
ResumableLxMessage::from_bytes(damaged).is_err(),
|
||||
"flipped byte {at} accepted"
|
||||
);
|
||||
assert!(ResumableLxMessage::from_bytes(bytes[..at].to_vec()).is_err());
|
||||
}
|
||||
let redigest = |mut bytes: Vec<u8>| {
|
||||
let at = bytes.len() - 16;
|
||||
let digest = sha256(&bytes[..at]);
|
||||
bytes[at..].copy_from_slice(&digest[..16]);
|
||||
bytes
|
||||
};
|
||||
for (at, value) in [(100, 2), (101, 2), (103, 7), (108, 0x95)] {
|
||||
let mut unknown = bytes.clone();
|
||||
unknown[at] = value;
|
||||
assert!(
|
||||
ResumableLxMessage::from_bytes(redigest(unknown)).is_err(),
|
||||
"byte {at} = {value:#x} accepted"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ use crate::inbound_resource::{
|
||||
InboundResourceTracker,
|
||||
};
|
||||
use crate::message::{
|
||||
LxMessage, LxMessageDraft, MessageError, RecipientStamp, SignedLxMessage, VerifiedLxMessage,
|
||||
LxMessage, LxMessageDraft, MessageError, MessageMetadata, RecipientStamp, ResumableLxMessage,
|
||||
SignedLxMessage, VerifiedLxMessage,
|
||||
};
|
||||
use crate::peer::{LxmPeer, OutboundOfferPolicy};
|
||||
use crate::propagation::PropagationStore;
|
||||
@@ -643,7 +644,16 @@ impl LxmRouter {
|
||||
|
||||
/// Signatures freeze the body before recipient work; only finalized messages
|
||||
/// enter outbound queues. Deferred completion can never mutate another body.
|
||||
///
|
||||
/// A message whose id is already queued, awaiting either its stamp or
|
||||
/// delivery, is refused with [`MessageError::AlreadyQueued`].
|
||||
pub fn submit_signed(&mut self, message: SignedLxMessage) -> Result<(), MessageError> {
|
||||
let id = message.message_id();
|
||||
if self.pending_deferred_stamps.contains_key(&id)
|
||||
|| self.pending_outbound.iter().any(|m| m.message_id() == id)
|
||||
{
|
||||
return Err(MessageError::AlreadyQueued);
|
||||
}
|
||||
if message.method == DeliveryMethod::Propagated && self.outbound_propagation_node.is_none()
|
||||
{
|
||||
return Err(MessageError::PackFailed(
|
||||
@@ -662,6 +672,37 @@ impl LxmRouter {
|
||||
.map_err(|e| MessageError::PackFailed(e.to_string()))
|
||||
}
|
||||
|
||||
/// Restore a stored message for another delivery under the same id.
|
||||
///
|
||||
/// `source_public_key` is the active identity's: the message must verify
|
||||
/// as sent by it. The outbound ticket is the current one, and the stamp
|
||||
/// cost is the larger of the cost the message was signed under and the
|
||||
/// destination's current cost. Finish the message as for a fresh send,
|
||||
/// then pass it to [`Self::submit_signed`].
|
||||
pub fn restore_signed(
|
||||
&self,
|
||||
stored: &ResumableLxMessage,
|
||||
source_public_key: &[u8; 64],
|
||||
method: DeliveryMethod,
|
||||
) -> Result<SignedLxMessage, MessageError> {
|
||||
let mut message = stored.unverified_message()?;
|
||||
message.verify(source_public_key)?;
|
||||
message.metadata = MessageMetadata {
|
||||
state: MessageState::Outbound,
|
||||
method,
|
||||
..MessageMetadata::default()
|
||||
};
|
||||
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);
|
||||
Ok(SignedLxMessage::restored(
|
||||
message,
|
||||
outbound_ticket,
|
||||
stamp_cost,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn defer_stamp(&mut self, mut message: SignedLxMessage) {
|
||||
message.state = MessageState::Outbound;
|
||||
self.pending_deferred_stamps
|
||||
@@ -4591,4 +4632,181 @@ mod tests {
|
||||
"core tick without a Direct adapter must not claim link sending started"
|
||||
);
|
||||
}
|
||||
|
||||
fn resumable_sender() -> (rns_identity::identity::Identity, [u8; 16]) {
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"lxmf.delivery",
|
||||
Some(&identity.hash),
|
||||
);
|
||||
(identity, source)
|
||||
}
|
||||
|
||||
fn resumable_draft(source: [u8; 16], content: &str) -> LxMessageDraft {
|
||||
LxMessageDraft::new(
|
||||
[0xA7; 16],
|
||||
source,
|
||||
"resume",
|
||||
content,
|
||||
DeliveryMethod::Direct,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn stored_form(
|
||||
router: &mut LxmRouter,
|
||||
identity: &rns_identity::identity::Identity,
|
||||
draft: &mut LxMessageDraft,
|
||||
) -> crate::message::ResumableLxMessage {
|
||||
router.prepare_outbound(draft).unwrap();
|
||||
let signed = draft
|
||||
.clone()
|
||||
.sign(&identity.get_signing_key().unwrap())
|
||||
.unwrap();
|
||||
let stored = signed.to_resumable();
|
||||
crate::message::ResumableLxMessage::from_bytes(stored.as_bytes().to_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restored_message_keeps_its_id_and_signed_wire() {
|
||||
let (identity, source) = resumable_sender();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let mut draft = resumable_draft(source, "same bytes");
|
||||
router.prepare_outbound(&mut draft).unwrap();
|
||||
let signed = draft.sign(&identity.get_signing_key().unwrap()).unwrap();
|
||||
let stored = signed.to_resumable();
|
||||
let original = signed.finalize(None).unwrap();
|
||||
|
||||
// Only the public key is needed to restore and finish the message.
|
||||
let public_key = identity.get_public_key();
|
||||
let restarted = LxmRouter::new(RouterConfig::default());
|
||||
let restored = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Opportunistic)
|
||||
.unwrap();
|
||||
assert_eq!(restored.message_id(), original.message_id());
|
||||
assert_eq!(restored.method, DeliveryMethod::Opportunistic);
|
||||
assert_eq!(restored.state, MessageState::Outbound);
|
||||
assert!(!restored.incoming);
|
||||
let finished = restored.finalize(None).unwrap();
|
||||
assert_eq!(finished.wire_bytes(), original.wire_bytes());
|
||||
assert!(finished.verify(&public_key).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_refuses_another_identity_and_a_bad_signature() {
|
||||
let (identity, source) = resumable_sender();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let stored = stored_form(&mut router, &identity, &mut resumable_draft(source, "x"));
|
||||
|
||||
let other = rns_identity::identity::Identity::new();
|
||||
assert!(matches!(
|
||||
router.restore_signed(&stored, &other.get_public_key(), DeliveryMethod::Direct),
|
||||
Err(MessageError::SourceMismatch)
|
||||
));
|
||||
|
||||
let mut forged = stored.as_bytes().to_vec();
|
||||
forged[40] ^= 0x01;
|
||||
let at = forged.len() - 16;
|
||||
let digest = rns_crypto::sha::sha256(&forged[..at]);
|
||||
forged[at..].copy_from_slice(&digest[..16]);
|
||||
let forged = crate::message::ResumableLxMessage::from_bytes(forged).unwrap();
|
||||
assert!(matches!(
|
||||
router.restore_signed(&forged, &identity.get_public_key(), DeliveryMethod::Direct),
|
||||
Err(MessageError::InvalidSignature)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_refreshes_the_ticket_and_keeps_the_signing_cost_as_a_floor() {
|
||||
let (identity, source) = resumable_sender();
|
||||
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);
|
||||
let mut draft = resumable_draft(source, "ticketed");
|
||||
sender.prepare_outbound(&mut draft).unwrap();
|
||||
assert!(draft.outbound_ticket.is_some());
|
||||
let stored = draft
|
||||
.sign(&identity.get_signing_key().unwrap())
|
||||
.unwrap()
|
||||
.to_resumable();
|
||||
let public_key = identity.get_public_key();
|
||||
|
||||
// After a restart the ticket has expired and the cost entry is gone:
|
||||
// the message proves work at the cost it was signed under.
|
||||
let mut restarted = LxmRouter::new(RouterConfig::default());
|
||||
restarted.remember_ticket(destination, [0x42; 16], now_f64() - 1.0);
|
||||
let restored = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(restored.outbound_ticket(), None);
|
||||
assert_eq!(restored.stamp_cost(), Some(8));
|
||||
let id = restored.message_id();
|
||||
restarted.submit_signed(restored).unwrap();
|
||||
assert!(restarted.pending_deferred_stamps.contains_key(&id));
|
||||
|
||||
restarted.set_stamp_cost(destination, 12);
|
||||
let raised = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(raised.stamp_cost(), Some(12));
|
||||
restarted.set_stamp_cost(destination, 4);
|
||||
let lowered = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(lowered.stamp_cost(), Some(8));
|
||||
|
||||
restarted.remember_ticket(destination, [0x43; 16], now_f64() + 60.0);
|
||||
let ticketed = restarted
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
assert_eq!(ticketed.outbound_ticket(), Some([0x43; 16]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submit_signed_refuses_a_message_already_queued() {
|
||||
let (identity, source) = resumable_sender();
|
||||
let key = identity.get_signing_key().unwrap();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let draft = resumable_draft(source, "once");
|
||||
router
|
||||
.submit_signed(draft.clone().sign(&key).unwrap())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
router.submit_signed(draft.sign(&key).unwrap()),
|
||||
Err(MessageError::AlreadyQueued)
|
||||
));
|
||||
assert_eq!(router.pending_outbound.len(), 1);
|
||||
|
||||
let mut stamped = resumable_draft(source, "stamped once");
|
||||
stamped.stamp_cost = Some(8);
|
||||
router
|
||||
.submit_signed(stamped.clone().sign(&key).unwrap())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
router.submit_signed(stamped.sign(&key).unwrap()),
|
||||
Err(MessageError::AlreadyQueued)
|
||||
));
|
||||
assert_eq!(router.pending_deferred_stamps.len(), 1);
|
||||
assert_eq!(router.pending_outbound.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_one_message_twice_queues_it_once() {
|
||||
let (identity, source) = resumable_sender();
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let stored = stored_form(
|
||||
&mut router,
|
||||
&identity,
|
||||
&mut resumable_draft(source, "twice"),
|
||||
);
|
||||
let public_key = identity.get_public_key();
|
||||
for _ in 0..2 {
|
||||
let restored = router
|
||||
.restore_signed(&stored, &public_key, DeliveryMethod::Direct)
|
||||
.unwrap();
|
||||
let _ = router.submit_signed(restored);
|
||||
}
|
||||
assert_eq!(router.pending_outbound.len(), 1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user