mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
router: keep delivered ids, stamp costs, and tickets in LXMF's state.db
Cache files from earlier versions are imported once. A file that cannot be used never stops the router.
This commit is contained in:
1 parent
c90b371c3d
commit
146ade134c
12 files changed
+2358
-986
No files matched your search
Generated
+1
@@ -743,6 +743,7 @@ dependencies = [
|
||||
"rns-protocol",
|
||||
"rns-transport",
|
||||
"rns-wire",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
|
||||
@@ -55,6 +55,9 @@ tracing-subscriber = "0.3"
|
||||
# Error handling
|
||||
thiserror = "2"
|
||||
|
||||
# SQLite (router state, LXMF 1.3.0 state.db)
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
|
||||
# Misc
|
||||
hex = "0.4"
|
||||
tempfile = "3"
|
||||
|
||||
@@ -7,6 +7,12 @@ edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["sqlite-store"]
|
||||
# SQLite router state at lxmf/state.db, as LXMF 1.3.0 keeps it. Without it the
|
||||
# router keeps that state in memory only.
|
||||
sqlite-store = ["dep:rusqlite"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
rns-crypto = { workspace = true }
|
||||
@@ -28,6 +34,7 @@ rand = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
unicode-normalization = { workspace = true }
|
||||
unicode-general-category = { workspace = true }
|
||||
rusqlite = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
|
||||
@@ -84,6 +84,7 @@ pub mod propagation_store_v2;
|
||||
pub mod propagation_sync;
|
||||
pub mod router;
|
||||
pub mod stamper;
|
||||
pub mod state_store;
|
||||
pub mod sync;
|
||||
pub mod ticket;
|
||||
pub mod types;
|
||||
|
||||
@@ -19,7 +19,6 @@ pub struct LxMessageDraft {
|
||||
pub include_ticket: bool,
|
||||
pub outbound_ticket: Option<[u8; 16]>,
|
||||
pub stamp_cost: Option<f64>,
|
||||
ticket_barrier: Option<Arc<()>>,
|
||||
}
|
||||
impl Deref for LxMessageDraft {
|
||||
type Target = MessageMetadata;
|
||||
@@ -100,7 +99,6 @@ impl LxMessageDraft {
|
||||
include_ticket: false,
|
||||
outbound_ticket: None,
|
||||
stamp_cost: None,
|
||||
ticket_barrier: None,
|
||||
};
|
||||
draft.checked_wire_len()?;
|
||||
Ok(draft)
|
||||
@@ -123,21 +121,6 @@ impl LxMessageDraft {
|
||||
pub fn fields(&self) -> &BTreeMap<FieldId, FieldValue> {
|
||||
&self.fields
|
||||
}
|
||||
pub(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) {
|
||||
self.ticket_barrier = Some(owner);
|
||||
}
|
||||
pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool {
|
||||
if self
|
||||
.ticket_barrier
|
||||
.as_ref()
|
||||
.is_some_and(|pending| Arc::ptr_eq(pending, owner))
|
||||
{
|
||||
self.ticket_barrier = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
|
||||
self.fields.get(&id.into())
|
||||
}
|
||||
@@ -292,9 +275,6 @@ impl LxMessageDraft {
|
||||
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
|
||||
E: std::fmt::Display,
|
||||
{
|
||||
if self.ticket_barrier.is_some() {
|
||||
return Err(MessageError::TicketNotCommitted);
|
||||
}
|
||||
let size = self.checked_wire_len()?;
|
||||
let mut signed = Vec::with_capacity(size);
|
||||
signed.extend_from_slice(&self.destination);
|
||||
|
||||
@@ -608,22 +608,6 @@ fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
|
||||
&[2]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn signed_body_finalization_ticket_barrier_blocks_signer() {
|
||||
let owner = Arc::new(());
|
||||
let mut d = draft();
|
||||
d.mark_ticket_pending(owner.clone());
|
||||
assert!(!d.release_ticket_barrier(&Arc::new(())));
|
||||
assert!(matches!(
|
||||
d.clone()
|
||||
.sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }),
|
||||
Err(MessageError::TicketNotCommitted)
|
||||
));
|
||||
assert!(d.release_ticket_barrier(&owner));
|
||||
assert!(!d.release_ticket_barrier(&owner));
|
||||
assert!(d.sign(&key()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() {
|
||||
for bytes in [
|
||||
|
||||
+18
-278
@@ -1,77 +1,32 @@
|
||||
//! Router state files in a caller-supplied directory.
|
||||
//!
|
||||
//! Files:
|
||||
//! * `outbound_stamp_costs` — destination stamp costs and observation times
|
||||
//! * `available_tickets` — versioned directional ticket state
|
||||
//! * `local_deliveries` — delivered transient IDs and timestamps
|
||||
//! * `locally_processed` — processed transient IDs and timestamps
|
||||
//! * `node_stats` — propagation-node counters
|
||||
//! * `delivery_claims` — delivered/processed IDs appended since the last full save
|
||||
//! * `propagation_suppression_v1` — bounded download suppression records
|
||||
//! * `propagation_node_policies_v1` — recorded propagation-node policies
|
||||
//!
|
||||
//! These files use the Rust types' MessagePack representations; matching Python
|
||||
//! filenames does not establish interchangeable contents. Missing files yield
|
||||
//! empty/default state. Other I/O, malformed-data and capacity errors propagate
|
||||
//! to the caller.
|
||||
//! Stamp costs, tickets, and delivered and processed transient IDs live in
|
||||
//! `state.db` ([`crate::state_store`]). `delivery_claims`, which earlier
|
||||
//! releases appended to, is only read here so its records can be imported.
|
||||
//!
|
||||
//! Missing files yield empty/default state. Other I/O, malformed-data and
|
||||
//! capacity errors propagate to the caller.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::router::StampCostEntry;
|
||||
use crate::ticket::{Ticket, TicketStoreSnapshot};
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
|
||||
pub const TICKETS_FILE: &str = "available_tickets";
|
||||
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
|
||||
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
|
||||
pub const NODE_STATS_FILE: &str = "node_stats";
|
||||
/// Append-only delivered/processed claims written before delivery callbacks run.
|
||||
pub const DELIVERY_CLAIMS_FILE: &str = "delivery_claims";
|
||||
/// Delivered/processed claims that earlier releases appended before delivery callbacks ran.
|
||||
const DELIVERY_CLAIMS_FILE: &str = "delivery_claims";
|
||||
|
||||
const CLAIM_DELIVERED: u8 = 0;
|
||||
const CLAIM_PROCESSED: u8 = 1;
|
||||
const CLAIM_RECORD_LEN: usize = 1 + 32 + 8;
|
||||
|
||||
/// Durably append a claim (`processed = false` for delivered IDs).
|
||||
pub(crate) fn append_delivery_claim(
|
||||
dir: &Path,
|
||||
id: &PropagationTransientId,
|
||||
processed: bool,
|
||||
at: f64,
|
||||
) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let mut record = [0u8; CLAIM_RECORD_LEN];
|
||||
record[0] = if processed {
|
||||
CLAIM_PROCESSED
|
||||
} else {
|
||||
CLAIM_DELIVERED
|
||||
};
|
||||
record[1..33].copy_from_slice(id);
|
||||
record[33..].copy_from_slice(&at.to_le_bytes());
|
||||
let mut file = open_claims_for_append(&dir.join(DELIVERY_CLAIMS_FILE), true)?;
|
||||
file.write_all(&record)?;
|
||||
file.sync_data()
|
||||
}
|
||||
|
||||
/// Open a claims file for appending, first dropping a torn trailing record so
|
||||
/// later records stay aligned.
|
||||
fn open_claims_for_append(path: &Path, create: bool) -> io::Result<fs::File> {
|
||||
let file = fs::OpenOptions::new()
|
||||
.create(create)
|
||||
.append(true)
|
||||
.open(path)?;
|
||||
let len = file.metadata()?.len();
|
||||
let torn = len % CLAIM_RECORD_LEN as u64;
|
||||
if torn != 0 {
|
||||
file.set_len(len - torn)?;
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Read appended claims as (delivered, processed). A torn trailing record is ignored.
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) fn load_delivery_claims(
|
||||
@@ -108,36 +63,15 @@ fn claims_saving(dir: &Path) -> std::path::PathBuf {
|
||||
dir.join(format!("{DELIVERY_CLAIMS_FILE}.saving"))
|
||||
}
|
||||
|
||||
/// Set the claims appended so far aside for the snapshot being saved; later
|
||||
/// claims start a new file. Claims set aside by an unfinished save are kept.
|
||||
pub(crate) fn rotate_delivery_claims(dir: &Path) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let current = dir.join(DELIVERY_CLAIMS_FILE);
|
||||
let saving = claims_saving(dir);
|
||||
if !saving.exists() {
|
||||
return match fs::rename(¤t, &saving) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
|
||||
_ => Ok(()),
|
||||
};
|
||||
}
|
||||
let bytes = match fs::read(¤t) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let whole = bytes.len() - bytes.len() % CLAIM_RECORD_LEN;
|
||||
let mut file = open_claims_for_append(&saving, false)?;
|
||||
file.write_all(&bytes[..whole])?;
|
||||
file.sync_data()?;
|
||||
fs::remove_file(current)
|
||||
}
|
||||
|
||||
/// Drop the claims set aside once the caches holding them are saved.
|
||||
pub(crate) fn clear_rotated_delivery_claims(dir: &Path) -> io::Result<()> {
|
||||
match fs::remove_file(claims_saving(dir)) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
|
||||
_ => Ok(()),
|
||||
/// Remove every claim file once its records are committed to the LXMF state store.
|
||||
pub(crate) fn clear_delivery_claims(dir: &Path) -> io::Result<()> {
|
||||
for path in [claims_saving(dir), dir.join(DELIVERY_CLAIMS_FILE)] {
|
||||
match fs::remove_file(path) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
|
||||
@@ -259,130 +193,6 @@ fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> {
|
||||
write_mpk(&dir.join(STAMP_COSTS_FILE), costs)
|
||||
}
|
||||
|
||||
pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEntry>> {
|
||||
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Process-local revision of a captured ticket state. All production ticket
|
||||
/// writes pass through the same path coordinator, so a delayed checkpoint can
|
||||
/// never replace a ticket that a newer signing intent already committed.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct TicketPersistenceSnapshot {
|
||||
revision: u64,
|
||||
snapshot: std::sync::Arc<TicketStoreSnapshot>,
|
||||
}
|
||||
impl TicketPersistenceSnapshot {
|
||||
pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
// Rust 1.99 renamed this operation; keep the identical Rust 1.89 API.
|
||||
#[allow(deprecated)]
|
||||
let revision = NEXT
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
|
||||
.expect("ticket checkpoint revision exhausted");
|
||||
Self {
|
||||
revision,
|
||||
snapshot: std::sync::Arc::new(snapshot),
|
||||
}
|
||||
}
|
||||
pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> {
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
struct Latest {
|
||||
revision: u64,
|
||||
committed: bool,
|
||||
}
|
||||
static WRITERS: OnceLock<Mutex<HashMap<std::path::PathBuf, Latest>>> = OnceLock::new();
|
||||
fs::create_dir_all(dir)?;
|
||||
let path = fs::canonicalize(dir)?.join(TICKETS_FILE);
|
||||
let mut writers = WRITERS
|
||||
.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?;
|
||||
if !writers.contains_key(&path) && writers.len() >= 4096 {
|
||||
return Err(io::Error::other("ticket persistence path quota exhausted"));
|
||||
}
|
||||
let latest = writers.entry(path.clone()).or_insert(Latest {
|
||||
revision: self.revision,
|
||||
committed: false,
|
||||
});
|
||||
if self.revision < latest.revision {
|
||||
if !latest.committed {
|
||||
return Err(io::Error::other(
|
||||
"newer ticket checkpoint is uncertain and must be retried",
|
||||
));
|
||||
}
|
||||
if let Some(required) = required {
|
||||
let (stored, _) = load_tickets(dir)?;
|
||||
if !stored.inbound.contains(required) {
|
||||
return Err(io::Error::other(
|
||||
"newer ticket state no longer contains this signing intent",
|
||||
));
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) {
|
||||
return Err(io::Error::other(
|
||||
"ticket snapshot does not contain this signing intent",
|
||||
));
|
||||
}
|
||||
latest.revision = self.revision;
|
||||
latest.committed = false;
|
||||
// Even an uncertain publication raises the revision floor. Older
|
||||
// snapshots fail closed until this or a newly captured current state
|
||||
// reestablishes the strict barrier. No failed payload is retained by
|
||||
// this bounded process-wide metadata coordinator.
|
||||
write_mpk(&path, &*self.snapshot)?;
|
||||
latest.committed = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
|
||||
TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum PersistedTickets {
|
||||
Directional(TicketStoreSnapshot),
|
||||
Legacy(Vec<Ticket>),
|
||||
}
|
||||
|
||||
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
|
||||
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
|
||||
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
|
||||
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
|
||||
None => (TicketStoreSnapshot::default(), None),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save_local_deliveries(
|
||||
dir: &Path,
|
||||
ids: &HashMap<PropagationTransientId, f64>,
|
||||
) -> io::Result<()> {
|
||||
write_mpk(&dir.join(LOCAL_DELIVERIES_FILE), ids)
|
||||
}
|
||||
|
||||
pub fn load_local_deliveries(dir: &Path) -> io::Result<HashMap<PropagationTransientId, f64>> {
|
||||
Ok(read_mpk(&dir.join(LOCAL_DELIVERIES_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn save_locally_processed(
|
||||
dir: &Path,
|
||||
ids: &HashMap<PropagationTransientId, f64>,
|
||||
) -> io::Result<()> {
|
||||
write_mpk(&dir.join(LOCALLY_PROCESSED_FILE), ids)
|
||||
}
|
||||
|
||||
pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTransientId, f64>> {
|
||||
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
|
||||
let bytes = rmp_serde::to_vec_named(stats)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
@@ -399,85 +209,15 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn claims_after_a_torn_record_stay_readable() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
append_delivery_claim(tmp.path(), &[1; 32], false, 1.0).unwrap();
|
||||
let path = tmp.path().join(DELIVERY_CLAIMS_FILE);
|
||||
let mut bytes = fs::read(&path).unwrap();
|
||||
bytes.extend_from_slice(&[0xFF; 7]);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
append_delivery_claim(tmp.path(), &[2; 32], true, 2.0).unwrap();
|
||||
let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap();
|
||||
assert_eq!(delivered, vec![([1; 32], 1.0)]);
|
||||
assert_eq!(processed, vec![([2; 32], 2.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamp_costs_roundtrip() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let mut costs = HashMap::new();
|
||||
costs.insert(
|
||||
[0xAA; 16],
|
||||
StampCostEntry {
|
||||
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, Some(12.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tickets_roundtrip() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let tickets = TicketStoreSnapshot {
|
||||
version: 1,
|
||||
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
|
||||
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
|
||||
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
|
||||
};
|
||||
save_tickets(tmp.path(), &tickets).unwrap();
|
||||
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
|
||||
assert!(legacy.is_none());
|
||||
assert_eq!(loaded, tickets);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_flat_tickets_are_detected_for_migration() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
|
||||
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
|
||||
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
|
||||
assert_eq!(snapshot, TicketStoreSnapshot::default());
|
||||
assert_eq!(legacy.unwrap(), tickets);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_deliveries_roundtrip() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let mut ids = HashMap::new();
|
||||
ids.insert([0x03; 32], 1_700_000_000.0);
|
||||
save_local_deliveries(tmp.path(), &ids).unwrap();
|
||||
let loaded = load_local_deliveries(tmp.path()).unwrap();
|
||||
assert_eq!(loaded.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_returns_default() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
|
||||
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
|
||||
assert_eq!(tickets, TicketStoreSnapshot::default());
|
||||
assert!(legacy.is_none());
|
||||
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
load_node_stats(tmp.path()).unwrap(),
|
||||
PersistedNodeStats::default()
|
||||
);
|
||||
let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap();
|
||||
assert!(delivered.is_empty() && processed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+618
-465
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -263,28 +263,23 @@ fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
|
||||
assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
fn tickets_and_delivered_claims_are_in_the_state_store_before_they_are_acted_on() {
|
||||
use lxmf_core::state_store::{FILE_NAME, SqliteStateStore, StateStore};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
|
||||
router.load_state(temp.path()).unwrap();
|
||||
let stale = router.state_snapshot();
|
||||
let mut draft =
|
||||
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
|
||||
draft.include_ticket = true;
|
||||
let intent = router.prepare_outbound(&mut draft).unwrap();
|
||||
assert!(intent.requires_persistence());
|
||||
assert!(
|
||||
draft
|
||||
.clone()
|
||||
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
|
||||
.is_err()
|
||||
);
|
||||
let mut other =
|
||||
LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap();
|
||||
other.include_ticket = true;
|
||||
assert!(matches!(
|
||||
router.prepare_outbound(&mut other),
|
||||
Err(lxmf_core::router::TicketPreparationError::PendingPersistence)
|
||||
));
|
||||
intent.persist(temp.path(), &mut draft).unwrap();
|
||||
router.prepare_outbound(&mut draft).unwrap();
|
||||
// A second connection reads the committed ticket while the router still runs.
|
||||
let issued = SqliteStateStore::open(&temp.path().join(FILE_NAME))
|
||||
.unwrap()
|
||||
.get_inbound_tickets(&[1; 16])
|
||||
.unwrap()
|
||||
.expect("ticket committed before prepare_outbound returned");
|
||||
let msg = draft
|
||||
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
|
||||
.unwrap()
|
||||
@@ -295,9 +290,25 @@ fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
|
||||
.get(lxmf_core::constants::FIELD_TICKET)
|
||||
.is_some()
|
||||
);
|
||||
let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap();
|
||||
assert!(!loaded.0.inbound.is_empty());
|
||||
assert!(router.prepare_outbound(&mut other).is_ok());
|
||||
// The delivered claim is in the file before the delivery callback runs.
|
||||
let db = temp.path().join(FILE_NAME);
|
||||
let claimed_first = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = claimed_first.clone();
|
||||
router.register_delivery_callback(move |delivered| {
|
||||
let claimed = SqliteStateStore::open(&db)
|
||||
.unwrap()
|
||||
.has_delivered(&delivered.message_id())
|
||||
.unwrap();
|
||||
seen.store(claimed, std::sync::atomic::Ordering::Relaxed);
|
||||
});
|
||||
assert!(router.deliver_inbound(&msg, false));
|
||||
assert!(claimed_first.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// An older checkpoint written afterwards cannot take the ticket away.
|
||||
stale.save_state(temp.path()).unwrap();
|
||||
drop(router);
|
||||
let mut restarted = lxmf_core::router::LxmRouter::new(Default::default());
|
||||
restarted.load_state(temp.path()).unwrap();
|
||||
assert_eq!(restarted.get_inbound_tickets(&[1; 16]), Some(issued));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -452,132 +463,3 @@ fn canceled_download_closes_exact_request_admission_reply() {
|
||||
}
|
||||
assert!(found);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
|
||||
let stale = router.state_snapshot();
|
||||
let mut draft =
|
||||
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
|
||||
draft.include_ticket = true;
|
||||
let intent = router.prepare_outbound(&mut draft).unwrap();
|
||||
intent.persist(temp.path(), &mut draft).unwrap();
|
||||
let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0;
|
||||
assert_eq!(committed.inbound.len(), 1);
|
||||
stale.save_state(temp.path()).unwrap();
|
||||
assert_eq!(
|
||||
lxmf_core::persist::load_tickets(temp.path()).unwrap().0,
|
||||
committed
|
||||
);
|
||||
// A newer checkpoint can commit while a draft is waiting for its exact
|
||||
// intent. The old intent verifies that its ticket is still present.
|
||||
drop(draft);
|
||||
let mut next =
|
||||
LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap();
|
||||
next.include_ticket = true;
|
||||
let intent = router.prepare_outbound(&mut next).unwrap();
|
||||
router.state_snapshot().save_state(temp.path()).unwrap();
|
||||
intent.persist(temp.path(), &mut next).unwrap();
|
||||
assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok());
|
||||
assert_eq!(
|
||||
lxmf_core::persist::load_tickets(temp.path())
|
||||
.unwrap()
|
||||
.0
|
||||
.inbound
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut ledger = SuppressionLedger::default();
|
||||
ledger
|
||||
.record_failure(
|
||||
scope(1),
|
||||
SuppressionReason::Malformed,
|
||||
AdmissionEpochs::default(),
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap();
|
||||
assert_eq!(
|
||||
lxmf_core::persist::load_suppression(temp.path())
|
||||
.unwrap()
|
||||
.records()
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let path = temp.path().join("propagation_suppression_v1");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
|
||||
let rmpv::Value::Array(fields) = &mut value else {
|
||||
panic!("ledger wrapper")
|
||||
};
|
||||
let rmpv::Value::Map(rows) = &mut fields[0] else {
|
||||
panic!("ledger records")
|
||||
};
|
||||
rows.push(rows[0].clone());
|
||||
let mut duplicate = Vec::new();
|
||||
rmpv::encode::write_value(&mut duplicate, &value).unwrap();
|
||||
std::fs::write(&path, duplicate).unwrap();
|
||||
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
|
||||
std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap();
|
||||
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() {
|
||||
use rns_identity::{
|
||||
announce_state::RatchetControlState,
|
||||
identity::Identity,
|
||||
ratchet::{RatchetRing, ReceivedRatchet},
|
||||
};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut ring = RatchetRing::new();
|
||||
let public = ring.rotate_at(100.);
|
||||
let ring_path = temp.path().join("ring");
|
||||
ring.save_verified_durable(&ring_path, &identity).unwrap();
|
||||
assert_eq!(
|
||||
RatchetRing::load_verified(&ring_path, &identity)
|
||||
.unwrap()
|
||||
.ring()
|
||||
.current_public_key(),
|
||||
Some(public)
|
||||
);
|
||||
let control = RatchetControlState::new(identity.hash, [2; 16])
|
||||
.prepare_announce(100)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let control_path = temp.path().join("control");
|
||||
control
|
||||
.save_verified_durable(&control_path, &identity)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(),
|
||||
control
|
||||
);
|
||||
let received = ReceivedRatchet::new_at(public, 100.);
|
||||
let received_path = temp.path().join("received");
|
||||
received.save_durable(&received_path).unwrap();
|
||||
assert_eq!(
|
||||
ReceivedRatchet::load(&received_path).unwrap().ratchet_pub,
|
||||
public
|
||||
);
|
||||
let blocker = temp.path().join("not-a-directory");
|
||||
std::fs::write(&blocker, b"preserve").unwrap();
|
||||
assert!(
|
||||
ring.save_verified_durable(&blocker.join("ring"), &identity)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
control
|
||||
.save_verified_durable(&blocker.join("control"), &identity)
|
||||
.is_err()
|
||||
);
|
||||
assert!(received.save_durable(&blocker.join("received")).is_err());
|
||||
assert_eq!(std::fs::read(blocker).unwrap(), b"preserve");
|
||||
}
|
||||
@@ -364,9 +364,12 @@ fn apply_propagation_store_commit(
|
||||
};
|
||||
// LXMRouter keeps one processed-ID store; stored entries are claimed there at once.
|
||||
let now = now_f64();
|
||||
let mut claims = Vec::with_capacity(result.committed.len());
|
||||
for (transient_id, _) in &result.committed {
|
||||
router.propagation_store.claim_processed(*transient_id, now);
|
||||
claims.push((*transient_id, now));
|
||||
}
|
||||
router.record_processed_claims(&claims);
|
||||
distribution.extend(
|
||||
result
|
||||
.committed
|
||||
@@ -1794,9 +1797,17 @@ impl LxmdRunner {
|
||||
return;
|
||||
};
|
||||
node.merge_processed_ids(self.router.propagation_store.locally_processed_ids());
|
||||
for (id, seen) in node.processed_ids() {
|
||||
let claimed_by_node: Vec<_> = node
|
||||
.processed_ids()
|
||||
.iter()
|
||||
.filter(|(id, _)| !self.router.propagation_store.is_locally_processed(id))
|
||||
.map(|(id, seen)| (*id, *seen))
|
||||
.collect();
|
||||
drop(node);
|
||||
for (id, seen) in &claimed_by_node {
|
||||
self.router.propagation_store.claim_processed(*id, *seen);
|
||||
}
|
||||
self.router.record_processed_claims(&claimed_by_node);
|
||||
}
|
||||
|
||||
/// A transient ID claimed by local delivery is a duplicate for propagation intake.
|
||||
@@ -5247,8 +5258,8 @@ impl LxmdRunner {
|
||||
.copied();
|
||||
let tickets = self
|
||||
.router
|
||||
.ticket_store
|
||||
.inbound_tokens(&msg.source_hash(), now_f64());
|
||||
.get_inbound_tickets(&msg.source_hash())
|
||||
.unwrap_or_default();
|
||||
let cost = if self.config.enforce_stamps {
|
||||
self.config.stamp_cost.unwrap_or(0.0)
|
||||
} else {
|
||||
@@ -6905,13 +6916,8 @@ pub(crate) async fn main() {
|
||||
}
|
||||
}
|
||||
msg.include_ticket = true;
|
||||
let prepared = runner.router.prepare_outbound(&mut msg).and_then(|intent| {
|
||||
intent.persist(&runner.data_dir, &mut msg).map_err(|e| {
|
||||
lxmf_core::router::TicketPreparationError::Encode(e.to_string())
|
||||
})
|
||||
});
|
||||
if let Err(error) = prepared {
|
||||
tracing::error!(%error,"reply ticket persistence failed");
|
||||
if let Err(error) = runner.router.prepare_outbound(&mut msg) {
|
||||
tracing::error!(%error, "reply ticket preparation failed");
|
||||
break 'one_shot;
|
||||
}
|
||||
let Some(signing_key) = runner.identity.get_signing_key() else {
|
||||
@@ -7558,6 +7564,8 @@ mod tests {
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
initialize_storage_namespace(temp.path()).unwrap();
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap();
|
||||
let data_dir = runner.data_dir.clone();
|
||||
runner.router.load_state(&data_dir).unwrap();
|
||||
let deliveries = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let observed = deliveries.clone();
|
||||
runner.router.register_delivery_callback(move |_| {
|
||||
@@ -7661,46 +7669,6 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn control_unpeer_leaves_claims_rotated_by_a_running_checkpoint() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
|
||||
initialize_storage_namespace(temp.path()).unwrap();
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap();
|
||||
let data_dir = runner.data_dir.clone();
|
||||
runner.router.load_state(&data_dir).unwrap();
|
||||
let message = signed_fixture(
|
||||
runner.lxmf_dest_hash,
|
||||
[0xCD; 16],
|
||||
"",
|
||||
"claimed",
|
||||
DeliveryMethod::Direct,
|
||||
);
|
||||
assert!(runner.router.deliver_inbound(&message, false));
|
||||
let checkpoint = runner.router.state_snapshot();
|
||||
let saving = data_dir.join(format!(
|
||||
"{}.saving",
|
||||
lxmf_core::persist::DELIVERY_CLAIMS_FILE
|
||||
));
|
||||
assert!(saving.exists());
|
||||
|
||||
let peer_hash = [0x44; 16];
|
||||
runner
|
||||
.router
|
||||
.peers
|
||||
.insert(peer_hash, LxmPeer::new(peer_hash));
|
||||
let (command_tx, command_rx) = mpsc::unbounded_channel();
|
||||
runner.control_command_rx = command_rx;
|
||||
command_tx.send(ControlCommand::Unpeer(peer_hash)).unwrap();
|
||||
runner.drain_control_commands();
|
||||
|
||||
assert!(!runner.router.peers.contains_key(&peer_hash));
|
||||
// The checkpoint that rotated the claims still owns them until it commits.
|
||||
assert!(saving.exists());
|
||||
checkpoint.save_state(&data_dir).unwrap();
|
||||
assert!(!saving.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_directly_connected_peer_keeps_its_zero_hop_distance() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -88,7 +88,6 @@ pub struct LocalStatusView {
|
||||
pub propagation_size: usize,
|
||||
pub pending_outbound: usize,
|
||||
pub pending_deferred_stamps: usize,
|
||||
pub stamp_costs_cached: usize,
|
||||
}
|
||||
|
||||
impl LocalStatusView {
|
||||
@@ -105,7 +104,6 @@ impl LocalStatusView {
|
||||
propagation_size: stats.propagation_size,
|
||||
pending_outbound: stats.pending_outbound,
|
||||
pending_deferred_stamps: stats.pending_deferred_stamps,
|
||||
stamp_costs_cached: stats.stamp_costs_cached,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,8 +116,7 @@ pub fn format_local_status(status: &LocalStatusView) -> String {
|
||||
Propagation messages: {}\n\
|
||||
Propagation storage bytes: {}\n\
|
||||
Pending outbound: {}\n\
|
||||
Pending deferred stamps: {}\n\
|
||||
Cached stamp costs: {}\n",
|
||||
Pending deferred stamps: {}\n",
|
||||
hex::encode(status.lxmf_dest_hash),
|
||||
if status.propagation_enabled {
|
||||
"enabled"
|
||||
@@ -131,7 +128,6 @@ pub fn format_local_status(status: &LocalStatusView) -> String {
|
||||
status.propagation_size,
|
||||
status.pending_outbound,
|
||||
status.pending_deferred_stamps,
|
||||
status.stamp_costs_cached,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -427,7 +423,6 @@ mod tests {
|
||||
propagation_size: 4096,
|
||||
pending_outbound: 4,
|
||||
pending_deferred_stamps: 5,
|
||||
stamp_costs_cached: 6,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
@@ -438,8 +433,7 @@ mod tests {
|
||||
Propagation messages: 3\n\
|
||||
Propagation storage bytes: 4096\n\
|
||||
Pending outbound: 4\n\
|
||||
Pending deferred stamps: 5\n\
|
||||
Cached stamp costs: 6\n"
|
||||
Pending deferred stamps: 5\n"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user