transport: persist the announce rate table in upstream's format

This commit is contained in:
DeFiDude committed 2026-11-18 12:39:28 -07:00
1 parent e1ce7f0064
commit 3811338f39
2 files changed
+336

No files matched your search

@@ -1,6 +1,18 @@
use super::*;
use tracing::info;
/// Python's `storagepath/announce_rate_table` (Transport.py).
const ANNOUNCE_RATE_TABLE_FILE: &str = "announce_rate_table";
/// Python `save_announce_rate_table`: write through a temporary file and a
/// rename, logging a failure (Transport.py, Storage.py).
fn save_announce_rate_table(dir: &std::path::Path, blob: &[u8]) {
let path = dir.join(ANNOUNCE_RATE_TABLE_FILE);
if let Err(e) = rns_identity::persistence::atomic_write(&path, blob) {
tracing::warn!(path = %path.display(), error = %e, "could not persist announce rate table");
}
}
/// Wall-clock helper kept here so tests can inject a fake clock without
/// dragging it through the actor.
fn now() -> f64 {
@@ -419,6 +431,7 @@ impl TransportActor {
} else {
info!(entries = hashes.len(), "flushed hashlist");
}
save_announce_rate_table(dir, &self.rate_table.to_bytes());
}
}
@@ -444,6 +457,7 @@ impl TransportActor {
self.hashlist_save_in_flight
.store(true, std::sync::atomic::Ordering::Release);
let hashes = self.packet_hashlist.current_hashes();
let rate_table = self.rate_table.to_bytes();
let in_flight = self.hashlist_save_in_flight.clone();
let entries = hashes.len();
let write = move || {
@@ -453,6 +467,7 @@ impl TransportActor {
} else {
info!(entries, "flushed hashlist");
}
save_announce_rate_table(&dir, &rate_table);
in_flight.store(false, std::sync::atomic::Ordering::Release);
};
match tokio::runtime::Handle::try_current() {
@@ -477,6 +492,29 @@ impl TransportActor {
self.is_transport_enabled && !self.storage_client()
}
/// Python `Transport.start` loads the table with the hashlist; a file it
/// rejects leaves the table empty (Transport.py).
fn load_announce_rate_table(&mut self, dir: &std::path::Path) {
let path = dir.join(ANNOUNCE_RATE_TABLE_FILE);
if !path.is_file() {
return;
}
match std::fs::read(&path)
.ok()
.and_then(|blob| crate::rate_limit::RateTable::from_bytes(&blob))
{
Some(loaded) => {
let entries = loaded.len();
self.rate_table.absorb(loaded);
debug!(entries, "loaded announce rate table from storage");
}
None => tracing::warn!(
path = %path.display(),
"could not load announce rate table from storage, initialized empty"
),
}
}
/// Restore the canonical packet hashlist once both storage and the
/// actor's transport authority are known. Shared-instance clients and
/// non-transport leaves must never load or overwrite the authoritative
@@ -489,6 +527,7 @@ impl TransportActor {
return;
};
self.hashlist_load_attempted = true;
self.load_announce_rate_table(&dir);
let raw_path = dir.join("packet_hashlist.raw");
if raw_path.exists() {
@@ -1652,4 +1691,46 @@ mod async_save_tests {
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Python 1.6.1 saves and loads `announce_rate_table` only on a transport
/// instance that owns its storage (Transport.py).
#[test]
fn a_transport_instance_keeps_its_announce_rate_table_across_restarts() {
let dir = temp_storage();
let file = dir.join(ANNOUNCE_RATE_TABLE_FILE);
let (mut leaf, _) = TransportActor::new();
leaf.storage_dir = Some(dir.clone());
leaf.rate_table
.check_interface_rate([0x31; 16], 60.0, 0, 0.0);
leaf.save_state();
assert!(!file.exists(), "a leaf persists no rate table");
let (mut actor, _) = TransportActor::new();
actor.is_transport_enabled = true;
actor.storage_dir = Some(dir.clone());
for _ in 0..2 {
actor
.rate_table
.check_interface_rate([0x31; 16], 60.0, 0, 0.0);
}
actor.save_state();
assert!(file.exists());
let (mut restarted, _) = TransportActor::new();
restarted.is_transport_enabled = true;
restarted.initialize_storage(dir.clone());
let (_, entry) = restarted.rate_table.iter().next().expect("loaded");
let (_, saved) = actor.rate_table.iter().next().unwrap();
assert_eq!(
(&entry.timestamps, entry.violations, entry.blocked_until),
(&saved.timestamps, 1, saved.blocked_until)
);
std::fs::write(&file, b"RNSART").unwrap();
let (mut damaged, _) = TransportActor::new();
damaged.is_transport_enabled = true;
damaged.initialize_storage(dir.clone());
assert_eq!(damaged.rate_table.len(), 0);
let _ = std::fs::remove_dir_all(&dir);
}
}
+255
View File
@@ -3,6 +3,12 @@ use std::collections::HashMap;
use crate::constants::MAX_RATE_TIMESTAMPS;
use rns_wire::types::DestHash;
/// Python `AnnounceRateTable.PERSIST_MAGIC` and `PERSIST_VERSION` (Storage.py).
const PERSIST_MAGIC: &[u8; 6] = b"RNSART";
const PERSIST_VERSION: u8 = 0x01;
const PERSIST_HEADER_LEN: usize = 16;
const KEY_LEN: usize = 16;
#[derive(Debug, Clone)]
pub struct RateEntry {
/// The last `MAX_RATE_TIMESTAMPS` checks, blocked ones included.
@@ -63,6 +69,140 @@ impl RateTable {
self.entries.iter()
}
/// Python `AnnounceRateTable.persist` (Storage.py): a 16-byte header, then
/// every entry in little-endian columns. Each ring is written oldest
/// first, so the bytes differ from upstream's ring order but load the same.
pub fn to_bytes(&self) -> Vec<u8> {
let count = self.entries.len();
let mut blob = Vec::with_capacity(
PERSIST_HEADER_LEN + count * (KEY_LEN + 22 + MAX_RATE_TIMESTAMPS * 8),
);
blob.extend_from_slice(PERSIST_MAGIC);
blob.extend_from_slice(&[
PERSIST_VERSION,
0,
MAX_RATE_TIMESTAMPS as u8,
KEY_LEN as u8,
0,
0,
]);
blob.extend_from_slice(&u32::try_from(count).unwrap_or(u32::MAX).to_le_bytes());
let entries: Vec<_> = self.entries.iter().take(u32::MAX as usize).collect();
for (key, _) in &entries {
blob.extend_from_slice(key.as_bytes());
}
for (_, entry) in &entries {
blob.extend_from_slice(&entry.last.to_le_bytes());
}
for (_, entry) in &entries {
blob.extend_from_slice(&entry.blocked_until.to_le_bytes());
}
for (_, entry) in &entries {
let violations = i32::try_from(entry.violations).unwrap_or(i32::MAX);
blob.extend_from_slice(&violations.to_le_bytes());
}
fn ring(entry: &RateEntry) -> &[f64] {
&entry.timestamps[entry.timestamps.len().saturating_sub(MAX_RATE_TIMESTAMPS)..]
}
for (_, entry) in &entries {
blob.push(ring(entry).len() as u8);
}
for (_, entry) in &entries {
blob.push((ring(entry).len() % MAX_RATE_TIMESTAMPS) as u8);
}
for (_, entry) in &entries {
let ring = ring(entry);
for slot in 0..MAX_RATE_TIMESTAMPS {
let timestamp = ring.get(slot).copied().unwrap_or(0.0);
blob.extend_from_slice(&timestamp.to_le_bytes());
}
}
blob
}
/// Python `AnnounceRateTable.load` (Storage.py): `None` for a file it
/// rejects whole, and also for keys that are not 16-byte destination
/// hashes, which upstream loads but can never match. A ring of another
/// size keeps its newest timestamps.
pub fn from_bytes(blob: &[u8]) -> Option<Self> {
if blob.len() < PERSIST_HEADER_LEN
|| &blob[..6] != PERSIST_MAGIC
|| blob[6] != PERSIST_VERSION
|| blob[7] != 0
{
return None;
}
let max_ts = usize::from(blob[8]);
let keylen = usize::from(blob[9]);
let count = u32::from_le_bytes(blob[12..16].try_into().ok()?) as usize;
if max_ts < 1 || keylen != KEY_LEN {
return None;
}
let entry_size = keylen + 22 + max_ts * 8;
if count
.checked_mul(entry_size)
.and_then(|size| size.checked_add(PERSIST_HEADER_LEN))
!= Some(blob.len())
{
return None;
}
let mut columns = &blob[PERSIST_HEADER_LEN..];
let mut take = |len: usize| {
let (column, rest) = columns.split_at(len);
columns = rest;
column
};
let keys = take(count * keylen);
let last = take(count * 8);
let blocked = take(count * 8);
let violations = take(count * 4);
let ts_len = take(count);
let ts_head = take(count);
let timestamps = take(count * max_ts * 8);
let f64_at = |column: &[u8], index: usize| {
f64::from_le_bytes(column[index * 8..index * 8 + 8].try_into().unwrap())
};
let mut entries = HashMap::with_capacity(count);
for slot in 0..count {
let (len, head) = (usize::from(ts_len[slot]), usize::from(ts_head[slot]));
if len > max_ts || head >= max_ts {
return None;
}
let ring = |index: usize| f64_at(timestamps, slot * max_ts + index);
let mut chronological: Vec<f64> = if len < max_ts {
(0..len).map(ring).collect()
} else {
(head..max_ts).chain(0..head).map(ring).collect()
};
chronological.drain(..chronological.len().saturating_sub(MAX_RATE_TIMESTAMPS));
let key: [u8; KEY_LEN] = keys[slot * keylen..(slot + 1) * keylen].try_into().ok()?;
let violations =
i32::from_le_bytes(violations[slot * 4..slot * 4 + 4].try_into().ok()?);
let entry = RateEntry {
timestamps: chronological,
last: f64_at(last, slot),
violations: violations.max(0) as u32,
blocked_until: f64_at(blocked, slot),
};
if entries.insert(DestHash::from(key), entry).is_some() {
return None;
}
}
Some(Self { entries })
}
/// Take loaded entries for destinations this table has not seen.
pub fn absorb(&mut self, loaded: Self) {
for (key, entry) in loaded.entries {
self.entries.entry(key).or_insert(entry);
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
/// Python `AnnounceRateTable.check_and_update` with the interface's
/// `(rate_target, rate_grace, rate_penalty)`. Every call after the first
/// records its timestamp. Outside a penalty, an interval shorter than
@@ -242,6 +382,121 @@ mod tests {
);
}
/// Upstream 1.6.1 `AnnounceRateTable.persist` after `check_and_update` at
/// 1000, 1010 and 1020 s (target 60, grace 0, penalty 30) for 0x11 × 16.
const UPSTREAM_SINGLE: &str = "524e5341525401001010000001000000111111111111111111111111111111110000000000408f4000000000000891400100000003030000000000408f400000000000908f400000000000e08f400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
/// The same after 20 checks 100 s apart from 2000 s (target 60, grace 1),
/// a wrapped ring with its head at 4, for 0x22 × 16.
const UPSTREAM_WRAPPED: &str = "524e534152540100101000000100000022222222222222222222222222222222000000000078ae400000000000000000000000001004000000000020ac400000000000e8ac400000000000b0ad40000000000078ae400000000000c0a240000000000088a340000000000050a440000000000018a5400000000000e0a5400000000000a8a640000000000070a740000000000038a840000000000000a9400000000000c8a940000000000090aa40000000000058ab40";
/// `AnnounceRateTable(max_timestamps=4)` after six checks 1 s apart from
/// 3000 s (target 60, grace 2, penalty 5), for 0x33 × 16.
const UPSTREAM_RING_OF_FOUR: &str = "524e534152540100041000000100000033333333333333333333333333333333000000000074a7400000000000f6a740030000000402000000000078a74000000000007aa740000000000074a740000000000076a740";
fn only(table: &RateTable) -> RateEntry {
assert_eq!(table.len(), 1);
table.iter().next().unwrap().1.clone()
}
#[test]
fn a_persisted_rate_table_matches_upstream_bytes() {
let clock = crate::test_clock::Clock::at(1000.0);
let mut table = RateTable::new();
for now in [1000.0, 1010.0, 1020.0] {
clock.set(now);
table.check_interface_rate([0x11; 16], 60.0, 0, 30.0);
}
assert_eq!(hex::encode(table.to_bytes()), UPSTREAM_SINGLE);
}
#[test]
fn upstream_rate_tables_load_oldest_first() {
let wrapped = RateTable::from_bytes(&hex::decode(UPSTREAM_WRAPPED).unwrap()).unwrap();
let entry = only(&wrapped);
let expected: Vec<f64> = (4..20).map(|i| 2000.0 + 100.0 * f64::from(i)).collect();
assert_eq!(entry.timestamps, expected);
assert_eq!(
(entry.last, entry.violations, entry.blocked_until),
(3900.0, 0, 0.0)
);
// Upstream's own load into a ring of 16 gives the same items.
let four = RateTable::from_bytes(&hex::decode(UPSTREAM_RING_OF_FOUR).unwrap()).unwrap();
let entry = only(&four);
assert_eq!(entry.timestamps, vec![3002.0, 3003.0, 3004.0, 3005.0]);
assert_eq!(
(entry.last, entry.violations, entry.blocked_until),
(3002.0, 3, 3067.0)
);
}
#[test]
fn a_wrapped_ring_round_trips() {
let clock = crate::test_clock::Clock::at(0.0);
let mut table = RateTable::new();
for i in 0..20 {
clock.set(2000.0 + 100.0 * f64::from(i));
table.check_interface_rate([0x22; 16], 60.0, 1, 0.0);
table.check_interface_rate([0x44; 16], 500.0, 1, 50.0);
}
let loaded = RateTable::from_bytes(&table.to_bytes()).unwrap();
assert_eq!(loaded.len(), 2);
for (key, entry) in table.iter() {
let got = &loaded.entries[key];
assert_eq!(got.timestamps, entry.timestamps);
assert_eq!(
(got.last, got.violations, got.blocked_until),
(entry.last, entry.violations, entry.blocked_until)
);
}
assert_eq!(RateTable::new().to_bytes().len(), 16);
assert_eq!(
RateTable::from_bytes(&RateTable::new().to_bytes()).map(|t| t.len()),
Some(0)
);
}
/// Storage.py rejects the whole file on any of these.
#[test]
fn a_malformed_rate_table_is_rejected_whole() {
let good = hex::decode(UPSTREAM_SINGLE).unwrap();
let altered = |at: usize, byte: u8| {
let mut blob = good.clone();
blob[at] = byte;
blob
};
let _clock = crate::test_clock::Clock::at(1000.0);
let mut pair = RateTable::new();
pair.check_interface_rate([0x55; 16], 60.0, 0, 0.0);
pair.check_interface_rate([0x66; 16], 60.0, 0, 0.0);
let mut twice = pair.to_bytes();
twice.copy_within(16..32, 32);
let rejected = [
good[..15].to_vec(),
altered(0, b'X'),
altered(6, 2),
altered(7, 1),
altered(8, 0),
altered(9, 0),
altered(9, 20),
altered(12, 2),
good[..good.len() - 1].to_vec(),
altered(16 + 16 + 8 + 8 + 4, 17),
altered(16 + 16 + 8 + 8 + 4 + 1, 16),
];
for (case, blob) in rejected.iter().enumerate() {
assert!(RateTable::from_bytes(blob).is_none(), "case {case}");
}
assert!(RateTable::from_bytes(&good).is_some());
assert_eq!(
RateTable::from_bytes(&pair.to_bytes()).map(|t| t.len()),
Some(2)
);
assert!(RateTable::from_bytes(&twice).is_none(), "a key twice");
for len in 0..good.len() {
let _ = RateTable::from_bytes(&good[..len]);
}
}
/// Cull removes only entries both older than the retain window and no longer
/// blocked (Storage.py).
#[test]