diff --git a/api/snapshots/rns-transport.txt b/api/snapshots/rns-transport.txt index e927790..ce92916 100644 --- a/api/snapshots/rns-transport.txt +++ b/api/snapshots/rns-transport.txt @@ -2020,6 +2020,7 @@ pub struct rns_transport::store::SqliteKnownDestinations impl rns_transport::store::SqliteKnownDestinations pub fn rns_transport::store::SqliteKnownDestinations::open_ro(&std::path::Path) -> core::result::Result pub fn rns_transport::store::SqliteKnownDestinations::open_rw(&std::path::Path) -> core::result::Result +pub fn rns_transport::store::SqliteKnownDestinations::stored_public_key(&self, &rns_transport::store::DestHash) -> core::result::Result>, rns_transport::store::StoreError> impl rns_transport::store::KnownDestinationStore for rns_transport::store::SqliteKnownDestinations pub fn rns_transport::store::SqliteKnownDestinations::apply(&mut self, &rns_transport::store::KdBatch, &dyn core::ops::function::Fn(&rns_transport::store::DestHash) -> bool) -> core::result::Result pub fn rns_transport::store::SqliteKnownDestinations::expire_ratchets(&mut self, f64) -> core::result::Result, rns_transport::store::StoreError> diff --git a/api/stability.json b/api/stability.json index 6dcc386..735bb9a 100644 --- a/api/stability.json +++ b/api/stability.json @@ -51,8 +51,8 @@ "tier": "provisional", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/rns-transport.txt", - "itemCount": 2159, - "sha256": "a79bdab640e1b5ca88060bd159a4379102121aac0c89ab8e03cbad1cdd27de23" + "itemCount": 2160, + "sha256": "18a2a12e0f5ab6de901b7d439708e131e1756db23dafabd117153229067ca882" }, { "name": "rns-link", diff --git a/crates/rns-transport/src/actor/store_worker.rs b/crates/rns-transport/src/actor/store_worker.rs index 2282c51..ee8ec32 100644 --- a/crates/rns-transport/src/actor/store_worker.rs +++ b/crates/rns-transport/src/actor/store_worker.rs @@ -23,7 +23,7 @@ use crate::store::{ RejectedTable, StoreError, }; #[cfg(feature = "sqlite-store")] -use crate::store::{SqliteAnnounceCache, SqliteKnownDestinations, legacy}; +use crate::store::{KeepUnloadable, SqliteAnnounceCache, SqliteKnownDestinations, legacy}; #[derive(Clone)] enum StoreSource { @@ -396,7 +396,7 @@ impl LegacyFiles { fn import_known_sources( legacy: &LegacyFiles, now: f64, - store: &mut dyn KnownDestinationStore, + store: &mut impl KeepUnloadable, finish: bool, ) { if legacy.rust_cache.is_file() { @@ -429,8 +429,12 @@ fn import_known_sources( debug!( rows = imported.imported(), rejected = imported.rejected(), + unloadable = imported.unloadable().len(), "imported Python known destinations" ); + if let Err(e) = store.keep_unloadable(imported.unloadable()) { + error!("could not keep the known destinations whose keys do not load: {e}"); + } if finish { rename_imported(&legacy.python_kd, ".imported"); } diff --git a/crates/rns-transport/src/store/legacy.rs b/crates/rns-transport/src/store/legacy.rs index 5111189..6c29ddb 100644 --- a/crates/rns-transport/src/store/legacy.rs +++ b/crates/rns-transport/src/store/legacy.rs @@ -23,9 +23,30 @@ pub struct LegacyImport { imported: usize, rejected: usize, removable: Vec, + unloadable: Vec, +} + +/// A legacy known-destination row as upstream imports it (Storage.py +/// `import_legacy`), whatever the length of its public key. +#[derive(Debug)] +pub(crate) struct RawKnownRow { + pub(crate) destination_hash: DestHash, + pub(crate) last_heard: f64, + pub(crate) packet_hash: Option, + pub(crate) public_key: Vec, + pub(crate) app_data: Option>, + pub(crate) used: f64, + pub(crate) stamp: Option>, + pub(crate) stamp_value: f64, + pub(crate) lr_cost: Option, } impl LegacyImport { + /// Rows whose public key is not 64 bytes: the database keeps them, the table cannot load them. + pub(crate) fn unloadable(&self) -> &[RawKnownRow] { + &self.unloadable + } + /// Rows the store accepted. pub fn imported(&self) -> usize { self.imported @@ -130,13 +151,15 @@ fn write_rows( imported: batch.upserts.len() - rejected, rejected, removable, + unloadable: Vec::new(), }) } /// Imports `storage/known_destinations`, a msgpack map of destination hash to /// the 8-field entry Python 1.5.x writes, with the padding of upstream `KnownDestinationsStore.import_legacy`. -/// Entries with fewer than five fields, or a public key other than 64 bytes, are -/// skipped. A last-heard time that is missing or not positive becomes `now`. +/// Entries with fewer than five fields are skipped. One whose public key is not +/// 64 bytes cannot enter the table; upstream imports it anyway, so this crate's +/// database keeps it. A last-heard time that is missing or not positive becomes `now`. pub fn import_python_known_destinations( path: &Path, now: f64, @@ -151,6 +174,7 @@ pub fn import_python_known_destinations( }; let mut rows = Vec::new(); + let mut unloadable = Vec::new(); for (key, value) in entries { let (Some(dest), Value::Array(fields)) = (bin::<16>(&key), value) else { continue; @@ -159,26 +183,40 @@ pub fn import_python_known_destinations( continue; } let field = |i: usize| fields.get(i).unwrap_or(&Value::Nil); - let Some(public_key) = bin::<64>(field(2)) else { + let blob = |i: usize| match field(i) { + Value::Binary(b) => Some(b.clone()), + _ => None, + }; + let Some(public_key) = blob(2) else { continue; }; - let last_heard = num(field(0)).filter(|t| *t > 0.0).unwrap_or(now); - let mut row = KnownDestinationRow::new(dest, last_heard, public_key); - row.packet_hash = bin::<32>(field(1)); - row.app_data = match field(3) { - Value::Binary(b) => Some(b.clone()), - _ => None, + let entry = RawKnownRow { + destination_hash: dest, + last_heard: num(field(0)).filter(|t| *t > 0.0).unwrap_or(now), + packet_hash: bin::<32>(field(1)), + public_key, + app_data: blob(3), + used: num(field(4)).unwrap_or(0.0), + stamp: blob(5), + stamp_value: num(field(6)).unwrap_or(0.0), + lr_cost: num(field(7)), }; - row.used = num(field(4)).unwrap_or(0.0); - row.stamp = match field(5) { - Value::Binary(b) => Some(b.clone()), - _ => None, + let Ok(public_key) = <[u8; 64]>::try_from(entry.public_key.as_slice()) else { + unloadable.push(entry); + continue; }; - row.stamp_value = num(field(6)).unwrap_or(0.0); - row.lr_cost = num(field(7)); + let mut row = KnownDestinationRow::new(dest, entry.last_heard, public_key); + row.packet_hash = entry.packet_hash; + row.app_data = entry.app_data; + row.used = entry.used; + row.stamp = entry.stamp; + row.stamp_value = entry.stamp_value; + row.lr_cost = entry.lr_cost; rows.push(LegacyRow { row, ratchet: None }); } - write_rows(rows, vec![path.to_path_buf()], store) + let mut imported = write_rows(rows, vec![path.to_path_buf()], store)?; + imported.unloadable = unloadable; + Ok(imported) } /// Imports the ratchets in `storage/ratchets/` files, with the filter of @@ -250,6 +288,7 @@ pub fn import_python_ratchets( imported: report.written, rejected: report.rejected.len(), removable, + unloadable: Vec::new(), }) } @@ -305,6 +344,7 @@ pub fn import_python_announce_cache( imported, rejected: 0, removable: Vec::new(), + unloadable: Vec::new(), }) } diff --git a/crates/rns-transport/src/store/mod.rs b/crates/rns-transport/src/store/mod.rs index d2d63e5..fc1b304 100644 --- a/crates/rns-transport/src/store/mod.rs +++ b/crates/rns-transport/src/store/mod.rs @@ -268,6 +268,18 @@ pub trait KnownDestinationStore: Send { fn expire_ratchets(&mut self, cutoff: f64) -> Result, StoreError>; } +/// A store that keeps the legacy rows its table cannot load, as upstream's import does. +pub(crate) trait KeepUnloadable: KnownDestinationStore { + fn keep_unloadable(&mut self, rows: &[legacy::RawKnownRow]) -> Result<(), StoreError>; +} + +impl KeepUnloadable for MemoryStore { + /// Only a database holds them. + fn keep_unloadable(&mut self, _rows: &[legacy::RawKnownRow]) -> Result<(), StoreError> { + Ok(()) + } +} + /// Persistent announce cache keyed by packet hash. pub trait AnnounceCacheStore: Send { /// Inserts or replaces the given announces in one transaction. diff --git a/crates/rns-transport/src/store/sqlite.rs b/crates/rns-transport/src/store/sqlite.rs index 1647c25..79881fa 100644 --- a/crates/rns-transport/src/store/sqlite.rs +++ b/crates/rns-transport/src/store/sqlite.rs @@ -9,9 +9,10 @@ use std::time::Duration; use rusqlite::{Connection, ErrorCode, OpenFlags, OptionalExtension, Statement, params}; use tracing::warn; +use super::legacy::RawKnownRow; use super::{ ANNOUNCE_CACHE_USER_VERSION, AnnounceCacheStore, AnnounceFacts, AnnounceRow, ApplyReport, - CHUNK_ROWS, CachedAnnounce, DestHash, KNOWN_DESTINATIONS_USER_VERSION, KdBatch, + CHUNK_ROWS, CachedAnnounce, DestHash, KNOWN_DESTINATIONS_USER_VERSION, KdBatch, KeepUnloadable, KnownDestinationRow, KnownDestinationStore, PacketHash, Ratchet, RatchetRow, RejectedTable, Rejection, StoreError, }; @@ -49,6 +50,8 @@ const KD_SELECT_SQL: &str = "SELECT destination_hash, last_heard, packet_hash, p const KD_SELECT_WITH_FACTS_SQL: &str = "SELECT k.destination_hash, k.last_heard, k.packet_hash, k.public_key, k.app_data, k.used, k.stamp, k.stamp_value, k.lr_cost, f.hops, f.name_hash, f.path_response FROM known_destinations k LEFT JOIN rs_announce_facts f ON f.destination_hash = k.destination_hash AND f.last_heard = k.last_heard"; const KD_UPSERT_SQL: &str = "INSERT INTO known_destinations (destination_hash, last_heard, packet_hash, public_key, app_data, used, stamp, stamp_value, lr_cost, identity_hash) VALUES (?,?,?,?,?,?,?,?,?,?) ON CONFLICT(destination_hash) DO UPDATE SET last_heard=excluded.last_heard, packet_hash=excluded.packet_hash, public_key=excluded.public_key, app_data=excluded.app_data, used=excluded.used, stamp=excluded.stamp, stamp_value=excluded.stamp_value, lr_cost=excluded.lr_cost, identity_hash=excluded.identity_hash"; +// A row heard later than the legacy one stays. +const KD_KEEP_UNLOADABLE_SQL: &str = "INSERT INTO known_destinations (destination_hash, last_heard, packet_hash, public_key, app_data, used, stamp, stamp_value, lr_cost, identity_hash) VALUES (?,?,?,?,?,?,?,?,?,?) ON CONFLICT(destination_hash) DO UPDATE SET last_heard=excluded.last_heard, packet_hash=excluded.packet_hash, public_key=excluded.public_key, app_data=excluded.app_data, used=excluded.used, stamp=excluded.stamp, stamp_value=excluded.stamp_value, lr_cost=excluded.lr_cost, identity_hash=excluded.identity_hash WHERE excluded.last_heard >= known_destinations.last_heard"; const KD_DELETE_SQL: &str = "DELETE FROM known_destinations WHERE destination_hash=?"; const RATCHET_UPSERT_SQL: &str = "INSERT INTO ratchets VALUES (?,?,?) ON CONFLICT(destination_hash) DO UPDATE SET ratchet=excluded.ratchet, received=excluded.received"; const RATCHET_DELETE_SQL: &str = "DELETE FROM ratchets WHERE destination_hash=?"; @@ -106,7 +109,7 @@ fn fixed(bytes: Vec, table: &'static str) -> Result<[u8; N], }) } -fn identity_hash(public_key: &[u8; 64]) -> [u8; 16] { +fn identity_hash(public_key: &[u8]) -> [u8; 16] { let digest = rns_crypto::sha::sha256(public_key); let mut out = [0u8; 16]; out.copy_from_slice(&digest[..16]); @@ -320,6 +323,47 @@ impl SqliteKnownDestinations { read_only: true, }) } + + /// The public key stored for `destination`, whatever its length: upstream + /// recalls a row whose key does not load, which this crate's table skips. + pub fn stored_public_key(&self, destination: &DestHash) -> Result>, StoreError> { + db(self + .conn + .query_row( + "SELECT public_key FROM known_destinations WHERE destination_hash=?1", + params![destination.as_slice()], + |r| r.get(0), + ) + .optional()) + } +} + +impl KeepUnloadable for SqliteKnownDestinations { + fn keep_unloadable(&mut self, rows: &[RawKnownRow]) -> Result<(), StoreError> { + if self.read_only { + return Err(StoreError::ReadOnly); + } + if rows.is_empty() { + return Ok(()); + } + with_txn(&self.conn, |conn| { + db(run_all(conn, KD_KEEP_UNLOADABLE_SQL, rows, &|s, r| { + s.execute(params![ + r.destination_hash.as_slice(), + r.last_heard, + r.packet_hash.as_ref().map(|h| h.as_slice()), + r.public_key.as_slice(), + r.app_data.as_deref(), + r.used, + r.stamp.as_deref(), + r.stamp_value, + r.lr_cost, + identity_hash(&r.public_key).as_slice(), + ]) + })) + .map(|_| ()) + }) + } } impl KnownDestinationStore for SqliteKnownDestinations {