1use std::collections::{HashMap, HashSet};
9use std::fs;
10use std::io::{self, Write};
11use std::path::{Path, PathBuf};
12use std::sync::Mutex;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use rns_crypto::identity::Identity;
16use rns_crypto::OsRng;
17
18#[derive(Debug, Clone)]
20pub struct StoragePaths {
21 pub config_dir: PathBuf,
22 pub storage: PathBuf,
23 pub cache: PathBuf,
24 pub identities: PathBuf,
25 pub ratchets: PathBuf,
26 pub discovered_interfaces: PathBuf,
28}
29
30#[derive(Debug, Clone)]
32pub struct KnownDestination {
33 pub identity_hash: [u8; 16],
34 pub public_key: [u8; 64],
35 pub app_data: Option<Vec<u8>>,
36 pub hops: u8,
37 pub received_at: f64,
38 pub receiving_interface: u64,
39 pub was_used: bool,
40 pub last_used_at: Option<f64>,
41 pub retained: bool,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq)]
45pub struct RatchetEntry {
46 pub ratchet: [u8; 32],
47 pub received_at: f64,
48}
49
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
51pub struct RatchetCleanupStats {
52 pub processed: usize,
53 pub not_known: usize,
54 pub removed: usize,
55}
56
57pub trait RatchetStore: Send + Sync {
58 fn remember(&self, dest_hash: [u8; 16], entry: RatchetEntry) -> io::Result<()>;
59 fn current(
60 &self,
61 dest_hash: &[u8; 16],
62 now: f64,
63 expiry_secs: f64,
64 ) -> io::Result<Option<RatchetEntry>>;
65 fn cleanup(
66 &self,
67 known_destinations: &HashSet<[u8; 16]>,
68 now: f64,
69 expiry_secs: f64,
70 ) -> io::Result<RatchetCleanupStats>;
71}
72
73#[derive(Debug)]
74pub struct FsRatchetStore {
75 dir: PathBuf,
76 cache: Mutex<HashMap<[u8; 16], RatchetEntry>>,
77}
78
79impl FsRatchetStore {
80 pub fn new(dir: PathBuf) -> Self {
81 Self {
82 dir,
83 cache: Mutex::new(HashMap::new()),
84 }
85 }
86
87 fn path_for(&self, dest_hash: &[u8; 16]) -> PathBuf {
88 self.dir.join(hex_lower(dest_hash))
89 }
90
91 fn read_entry(path: &Path) -> io::Result<RatchetEntry> {
92 use rns_core::msgpack;
93
94 let data = fs::read(path)?;
95 let (value, _) = msgpack::unpack(&data).map_err(|e| {
96 io::Error::new(io::ErrorKind::InvalidData, format!("msgpack error: {}", e))
97 })?;
98 let ratchet = value
99 .map_get("ratchet")
100 .and_then(|v| v.as_bin())
101 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing ratchet"))?;
102 if ratchet.len() != 32 {
103 return Err(io::Error::new(
104 io::ErrorKind::InvalidData,
105 format!("ratchet must be 32 bytes, got {}", ratchet.len()),
106 ));
107 }
108 let mut ratchet_bytes = [0u8; 32];
109 ratchet_bytes.copy_from_slice(ratchet);
110 let received_at = value
111 .map_get("received")
112 .and_then(|v| v.as_number())
113 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing received"))?;
114
115 Ok(RatchetEntry {
116 ratchet: ratchet_bytes,
117 received_at,
118 })
119 }
120
121 fn write_entry(&self, path: &Path, entry: RatchetEntry) -> io::Result<()> {
122 use rns_core::msgpack::{self, Value};
123
124 fs::create_dir_all(&self.dir)?;
125 let value = Value::Map(vec![
126 (
127 Value::Str("ratchet".into()),
128 Value::Bin(entry.ratchet.to_vec()),
129 ),
130 (
131 Value::Str("received".into()),
132 Value::Float(entry.received_at),
133 ),
134 ]);
135 let packed = msgpack::pack(&value);
136 let tmp = path.with_extension("out");
137 fs::write(&tmp, packed)?;
138 fs::rename(tmp, path)
139 }
140}
141
142impl RatchetStore for FsRatchetStore {
143 fn remember(&self, dest_hash: [u8; 16], entry: RatchetEntry) -> io::Result<()> {
144 if self
145 .cache
146 .lock()
147 .map(|cache| cache.get(&dest_hash).copied() == Some(entry))
148 .unwrap_or(false)
149 {
150 return Ok(());
151 }
152
153 let path = self.path_for(&dest_hash);
154 self.write_entry(&path, entry)?;
155 if let Ok(mut cache) = self.cache.lock() {
156 cache.insert(dest_hash, entry);
157 }
158 Ok(())
159 }
160
161 fn current(
162 &self,
163 dest_hash: &[u8; 16],
164 now: f64,
165 expiry_secs: f64,
166 ) -> io::Result<Option<RatchetEntry>> {
167 if let Ok(cache) = self.cache.lock() {
168 if let Some(entry) = cache.get(dest_hash).copied() {
169 if now <= entry.received_at + expiry_secs {
170 return Ok(Some(entry));
171 }
172 }
173 }
174
175 let path = self.path_for(dest_hash);
176 if !path.is_file() {
177 return Ok(None);
178 }
179
180 let entry = Self::read_entry(&path)?;
181 if now > entry.received_at + expiry_secs {
182 let _ = fs::remove_file(path);
183 if let Ok(mut cache) = self.cache.lock() {
184 cache.remove(dest_hash);
185 }
186 return Ok(None);
187 }
188
189 if let Ok(mut cache) = self.cache.lock() {
190 cache.insert(*dest_hash, entry);
191 }
192 Ok(Some(entry))
193 }
194
195 fn cleanup(
196 &self,
197 known_destinations: &HashSet<[u8; 16]>,
198 now: f64,
199 expiry_secs: f64,
200 ) -> io::Result<RatchetCleanupStats> {
201 let mut stats = RatchetCleanupStats::default();
202 if !self.dir.is_dir() {
203 return Ok(stats);
204 }
205
206 for entry in fs::read_dir(&self.dir)? {
207 let entry = entry?;
208 if !entry.file_type()?.is_file() {
209 continue;
210 }
211 stats.processed += 1;
212 let path = entry.path();
213 let Some(filename) = path.file_name().and_then(|name| name.to_str()) else {
214 let _ = fs::remove_file(&path);
215 stats.removed += 1;
216 continue;
217 };
218
219 let Some(dest_hash) = parse_dest_hash_hex(filename) else {
220 let _ = fs::remove_file(&path);
221 stats.removed += 1;
222 continue;
223 };
224
225 let unknown = !known_destinations.contains(&dest_hash);
226 if unknown {
227 stats.not_known += 1;
228 }
229
230 let expired_or_corrupt = match Self::read_entry(&path) {
231 Ok(entry) => now > entry.received_at + expiry_secs,
232 Err(_) => true,
233 };
234
235 if unknown || expired_or_corrupt {
236 let _ = fs::remove_file(&path);
237 stats.removed += 1;
238 if let Ok(mut cache) = self.cache.lock() {
239 cache.remove(&dest_hash);
240 }
241 }
242 }
243
244 Ok(stats)
245 }
246}
247
248pub fn ensure_storage_dirs(config_dir: &Path) -> io::Result<StoragePaths> {
250 let storage = config_dir.join("storage");
251 let cache = config_dir.join("cache");
252 let identities = storage.join("identities");
253 let ratchets = storage.join("ratchets");
254 let announces = cache.join("announces");
255 let discovered_interfaces = storage.join("discovery").join("interfaces");
256
257 fs::create_dir_all(&storage)?;
258 fs::create_dir_all(&cache)?;
259 fs::create_dir_all(&identities)?;
260 fs::create_dir_all(&ratchets)?;
261 fs::create_dir_all(&announces)?;
262 fs::create_dir_all(&discovered_interfaces)?;
263
264 Ok(StoragePaths {
265 config_dir: config_dir.to_path_buf(),
266 storage,
267 cache,
268 identities,
269 ratchets,
270 discovered_interfaces,
271 })
272}
273
274fn hex_lower(bytes: &[u8]) -> String {
275 let mut out = String::with_capacity(bytes.len() * 2);
276 for byte in bytes {
277 use std::fmt::Write;
278 let _ = write!(&mut out, "{:02x}", byte);
279 }
280 out
281}
282
283fn parse_dest_hash_hex(s: &str) -> Option<[u8; 16]> {
284 if s.len() != 32 {
285 return None;
286 }
287 let mut out = [0u8; 16];
288 for i in 0..16 {
289 out[i] = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).ok()?;
290 }
291 Some(out)
292}
293
294pub fn save_identity(identity: &Identity, path: &Path) -> io::Result<()> {
296 let private_key = identity
297 .get_private_key()
298 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Identity has no private key"))?;
299 let mut options = fs::OpenOptions::new();
300 options.write(true).create(true).truncate(true);
301 #[cfg(unix)]
302 {
303 use std::os::unix::fs::OpenOptionsExt;
304 options.mode(0o600);
305 }
306 options.open(path)?.write_all(&private_key)
307}
308
309pub fn load_identity(path: &Path) -> io::Result<Identity> {
311 let data = fs::read(path)?;
312 if data.len() != 64 {
313 return Err(io::Error::new(
314 io::ErrorKind::InvalidData,
315 format!("Identity file must be 64 bytes, got {}", data.len()),
316 ));
317 }
318 let mut key = [0u8; 64];
319 key.copy_from_slice(&data);
320 Ok(Identity::from_private_key(&key))
321}
322
323pub fn save_known_destinations(
330 destinations: &HashMap<[u8; 16], KnownDestination>,
331 path: &Path,
332) -> io::Result<()> {
333 use rns_core::msgpack::{self, Value};
334
335 let entries: Vec<(Value, Value)> = destinations
336 .iter()
337 .map(|(hash, dest)| {
338 let key = Value::Bin(hash.to_vec());
339 let app_data = match &dest.app_data {
340 Some(d) => Value::Bin(d.clone()),
341 None => Value::Nil,
342 };
343 let value = Value::Array(vec![
344 Value::UInt(dest.received_at as u64),
345 Value::Bin(dest.public_key.to_vec()),
346 app_data,
347 Value::Bin(dest.identity_hash.to_vec()),
348 Value::UInt(dest.hops as u64),
349 Value::UInt(dest.receiving_interface),
350 Value::Bool(dest.was_used),
351 match dest.last_used_at {
352 Some(last_used_at) => Value::UInt(last_used_at as u64),
353 None => Value::Nil,
354 },
355 Value::Bool(dest.retained),
356 ]);
357 (key, value)
358 })
359 .collect();
360
361 let packed = msgpack::pack(&Value::Map(entries));
362 atomic_write(path, &packed)
363}
364
365fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> {
366 let parent = path.parent().unwrap_or_else(|| Path::new("."));
367 let file_name = path
368 .file_name()
369 .and_then(|name| name.to_str())
370 .unwrap_or("known_destinations");
371 let nonce = SystemTime::now()
372 .duration_since(UNIX_EPOCH)
373 .map(|duration| duration.as_nanos())
374 .unwrap_or_default();
375 let temp_path = parent.join(format!(".{file_name}.tmp.{}.{}", std::process::id(), nonce));
376 match fs::write(&temp_path, data).and_then(|_| replace_file(&temp_path, path)) {
377 Ok(()) => Ok(()),
378 Err(err) => {
379 let _ = fs::remove_file(&temp_path);
380 Err(err)
381 }
382 }
383}
384
385fn replace_file(temp_path: &Path, path: &Path) -> io::Result<()> {
386 #[cfg(windows)]
387 if path.exists() {
388 fs::remove_file(path)?;
389 }
390 fs::rename(temp_path, path)
391}
392
393pub fn load_known_destinations(path: &Path) -> io::Result<HashMap<[u8; 16], KnownDestination>> {
395 use rns_core::msgpack;
396
397 let data = fs::read(path)?;
398 if data.is_empty() {
399 return Ok(HashMap::new());
400 }
401
402 let (value, _) = msgpack::unpack(&data)
403 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("msgpack error: {}", e)))?;
404
405 let map = value
406 .as_map()
407 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Expected msgpack map"))?;
408
409 let mut result = HashMap::new();
410
411 for (k, v) in map {
412 let hash_bytes = k
413 .as_bin()
414 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Expected bin key"))?;
415
416 if hash_bytes.len() != 16 {
417 continue; }
419
420 let mut dest_hash = [0u8; 16];
421 dest_hash.copy_from_slice(hash_bytes);
422
423 let arr = v
424 .as_array()
425 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Expected array value"))?;
426
427 if arr.len() < 3 {
428 continue;
429 }
430
431 let received_at = arr[0].as_uint().unwrap_or(0) as f64;
432
433 let pub_key_bytes = arr[1]
434 .as_bin()
435 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Expected bin public_key"))?;
436 if pub_key_bytes.len() != 64 {
437 continue;
438 }
439 let mut public_key = [0u8; 64];
440 public_key.copy_from_slice(pub_key_bytes);
441
442 let app_data = if arr.len() > 2 {
443 arr[2].as_bin().map(|b| b.to_vec())
444 } else {
445 None
446 };
447
448 let identity_hash = if arr.len() > 3 {
449 let hash_bytes = arr[3]
450 .as_bin()
451 .filter(|bytes| bytes.len() == 16)
452 .map(|bytes| {
453 let mut hash = [0u8; 16];
454 hash.copy_from_slice(bytes);
455 hash
456 });
457 hash_bytes.unwrap_or_else(|| {
458 let identity = Identity::from_public_key(&public_key);
459 *identity.hash()
460 })
461 } else {
462 let identity = Identity::from_public_key(&public_key);
463 *identity.hash()
464 };
465 let hops = arr.get(4).and_then(|value| value.as_uint()).unwrap_or(0) as u8;
466 let receiving_interface = arr.get(5).and_then(|value| value.as_uint()).unwrap_or(0);
467 let was_used = arr
468 .get(6)
469 .and_then(|value| value.as_bool())
470 .unwrap_or(false);
471 let last_used_at = arr
472 .get(7)
473 .and_then(|value| value.as_uint())
474 .map(|value| value as f64);
475 let retained = arr
476 .get(8)
477 .and_then(|value| value.as_bool())
478 .unwrap_or(false);
479
480 result.insert(
481 dest_hash,
482 KnownDestination {
483 identity_hash,
484 public_key,
485 app_data,
486 hops,
487 received_at,
488 receiving_interface,
489 was_used,
490 last_used_at,
491 retained,
492 },
493 );
494 }
495
496 Ok(result)
497}
498
499pub fn save_transport_state(
502 snapshot: &rns_core::transport::persistence::TransportStateSnapshot,
503 storage_dir: &Path,
504 low_priority: bool,
505) -> io::Result<()> {
506 let mut round_started = std::time::Instant::now();
507 save_transport_state_with_checkpoint(snapshot, storage_dir, || {
508 if low_priority && round_started.elapsed() > std::time::Duration::from_millis(10) {
509 std::thread::sleep(std::time::Duration::from_millis(1));
510 round_started = std::time::Instant::now();
511 }
512 })
513}
514
515fn save_transport_state_with_checkpoint<F>(
516 snapshot: &rns_core::transport::persistence::TransportStateSnapshot,
517 storage_dir: &Path,
518 mut checkpoint: F,
519) -> io::Result<()>
520where
521 F: FnMut(),
522{
523 use rns_core::msgpack::{self, Value};
524
525 fs::create_dir_all(storage_dir)?;
526
527 let mut hashes = Vec::with_capacity(snapshot.packet_hashes.len() * 32);
528 for hash in &snapshot.packet_hashes {
529 checkpoint();
530 hashes.extend_from_slice(hash);
531 }
532 atomic_write(&storage_dir.join("packet_hashlist.raw"), &hashes)?;
533
534 let paths = snapshot
535 .paths
536 .iter()
537 .map(|path| {
538 checkpoint();
539 encode_persisted_path(path)
540 })
541 .collect();
542 atomic_write(
543 &storage_dir.join("destination_table"),
544 &msgpack::pack(&Value::Array(paths)),
545 )?;
546
547 let tunnels = snapshot
548 .tunnels
549 .iter()
550 .map(|tunnel| {
551 checkpoint();
552 let paths = tunnel
553 .paths
554 .iter()
555 .map(|path| {
556 checkpoint();
557 encode_persisted_path(path)
558 })
559 .collect();
560 Value::Array(vec![
561 Value::Bin(tunnel.tunnel_id.to_vec()),
562 optional_hash_value(tunnel.interface_hash),
563 Value::Array(paths),
564 Value::Float(tunnel.expires),
565 ])
566 })
567 .collect();
568 atomic_write(
569 &storage_dir.join("tunnels"),
570 &msgpack::pack(&Value::Array(tunnels)),
571 )
572}
573
574fn encode_persisted_path(
575 path: &rns_core::transport::persistence::PersistedPath,
576) -> rns_core::msgpack::Value {
577 use rns_core::msgpack::Value;
578
579 Value::Array(vec![
580 Value::Bin(path.destination_hash.to_vec()),
581 Value::Float(path.timestamp),
582 Value::Bin(path.received_from.to_vec()),
583 Value::UInt(path.hops as u64),
584 Value::Float(path.expires),
585 Value::Array(
586 path.random_blobs
587 .iter()
588 .map(|blob| Value::Bin(blob.to_vec()))
589 .collect(),
590 ),
591 optional_hash_value(path.interface_hash),
592 Value::Bin(path.packet_hash.to_vec()),
593 ])
594}
595
596fn optional_hash_value(hash: Option<[u8; 32]>) -> rns_core::msgpack::Value {
597 match hash {
598 Some(hash) => rns_core::msgpack::Value::Bin(hash.to_vec()),
599 None => rns_core::msgpack::Value::Nil,
600 }
601}
602
603pub fn load_transport_state(
606 storage_dir: &Path,
607) -> io::Result<rns_core::transport::persistence::TransportStateSnapshot> {
608 use rns_core::transport::persistence::TransportStateSnapshot;
609
610 let packet_hashes = load_packet_hashlist(&storage_dir.join("packet_hashlist.raw"))?;
611 let paths = load_path_table(&storage_dir.join("destination_table"))?;
612 let tunnels = load_tunnel_table(&storage_dir.join("tunnels"))?;
613 Ok(TransportStateSnapshot {
614 packet_hashes,
615 paths,
616 tunnels,
617 })
618}
619
620fn load_packet_hashlist(path: &Path) -> io::Result<Vec<[u8; 32]>> {
621 let data = match fs::read(path) {
622 Ok(data) => data,
623 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
624 Err(err) => return Err(err),
625 };
626 Ok(data
627 .chunks_exact(32)
628 .map(|chunk| {
629 let mut hash = [0u8; 32];
630 hash.copy_from_slice(chunk);
631 hash
632 })
633 .collect())
634}
635
636fn load_path_table(
637 path: &Path,
638) -> io::Result<Vec<rns_core::transport::persistence::PersistedPath>> {
639 let Some(value) = load_optional_msgpack(path)? else {
640 return Ok(Vec::new());
641 };
642 value
643 .as_array()
644 .ok_or_else(|| invalid_transport_data("destination table must be an array"))?
645 .iter()
646 .map(decode_persisted_path)
647 .collect()
648}
649
650fn load_tunnel_table(
651 path: &Path,
652) -> io::Result<Vec<rns_core::transport::persistence::PersistedTunnel>> {
653 use rns_core::transport::persistence::PersistedTunnel;
654
655 let Some(value) = load_optional_msgpack(path)? else {
656 return Ok(Vec::new());
657 };
658 value
659 .as_array()
660 .ok_or_else(|| invalid_transport_data("tunnel table must be an array"))?
661 .iter()
662 .map(|value| {
663 let fields = value
664 .as_array()
665 .filter(|fields| fields.len() == 4)
666 .ok_or_else(|| invalid_transport_data("tunnel entry must contain 4 fields"))?;
667 let tunnel_id = fixed_bin::<32>(&fields[0], "tunnel id")?;
668 let interface_hash = optional_fixed_bin::<32>(&fields[1], "tunnel interface hash")?;
669 let paths = fields[2]
670 .as_array()
671 .ok_or_else(|| invalid_transport_data("tunnel paths must be an array"))?
672 .iter()
673 .map(decode_persisted_path)
674 .collect::<io::Result<Vec<_>>>()?;
675 let expires = fields[3]
676 .as_number()
677 .ok_or_else(|| invalid_transport_data("tunnel expiry must be numeric"))?;
678 Ok(PersistedTunnel {
679 tunnel_id,
680 interface_hash,
681 paths,
682 expires,
683 })
684 })
685 .collect()
686}
687
688fn decode_persisted_path(
689 value: &rns_core::msgpack::Value,
690) -> io::Result<rns_core::transport::persistence::PersistedPath> {
691 use rns_core::transport::persistence::PersistedPath;
692
693 let fields = value
694 .as_array()
695 .filter(|fields| fields.len() == 8)
696 .ok_or_else(|| invalid_transport_data("path entry must contain 8 fields"))?;
697 let random_blobs = fields[5]
698 .as_array()
699 .ok_or_else(|| invalid_transport_data("random blobs must be an array"))?
700 .iter()
701 .map(|value| fixed_bin::<10>(value, "random blob"))
702 .collect::<io::Result<Vec<_>>>()?;
703 let hops = fields[3]
704 .as_uint()
705 .and_then(|value| u8::try_from(value).ok())
706 .ok_or_else(|| invalid_transport_data("hop count must fit in a byte"))?;
707 Ok(PersistedPath {
708 destination_hash: fixed_bin::<16>(&fields[0], "destination hash")?,
709 timestamp: fields[1]
710 .as_number()
711 .ok_or_else(|| invalid_transport_data("path timestamp must be numeric"))?,
712 received_from: fixed_bin::<16>(&fields[2], "received-from hash")?,
713 hops,
714 expires: fields[4]
715 .as_number()
716 .ok_or_else(|| invalid_transport_data("path expiry must be numeric"))?,
717 random_blobs,
718 interface_hash: optional_fixed_bin::<32>(&fields[6], "interface hash")?,
719 packet_hash: fixed_bin::<32>(&fields[7], "packet hash")?,
720 })
721}
722
723fn load_optional_msgpack(path: &Path) -> io::Result<Option<rns_core::msgpack::Value>> {
724 let data = match fs::read(path) {
725 Ok(data) => data,
726 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
727 Err(err) => return Err(err),
728 };
729 rns_core::msgpack::unpack_exact(&data)
730 .map(Some)
731 .map_err(|err| invalid_transport_data(&format!("msgpack error: {err}")))
732}
733
734fn fixed_bin<const N: usize>(value: &rns_core::msgpack::Value, field: &str) -> io::Result<[u8; N]> {
735 let bytes = value
736 .as_bin()
737 .filter(|bytes| bytes.len() == N)
738 .ok_or_else(|| invalid_transport_data(&format!("{field} must be {N} bytes")))?;
739 let mut result = [0u8; N];
740 result.copy_from_slice(bytes);
741 Ok(result)
742}
743
744fn optional_fixed_bin<const N: usize>(
745 value: &rns_core::msgpack::Value,
746 field: &str,
747) -> io::Result<Option<[u8; N]>> {
748 if matches!(value, rns_core::msgpack::Value::Nil) {
749 Ok(None)
750 } else {
751 fixed_bin(value, field).map(Some)
752 }
753}
754
755fn invalid_transport_data(message: &str) -> io::Error {
756 io::Error::new(io::ErrorKind::InvalidData, message)
757}
758
759pub fn resolve_config_dir(explicit: Option<&Path>) -> PathBuf {
762 if let Some(p) = explicit {
763 p.to_path_buf()
764 } else {
765 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
766 PathBuf::from(home).join(".reticulum")
767 }
768}
769
770pub fn load_or_create_identity(identities_dir: &Path) -> io::Result<Identity> {
772 let id_path = identities_dir.join("identity");
773 if id_path.exists() {
774 load_identity(&id_path)
775 } else {
776 let identity = Identity::new(&mut OsRng);
777 save_identity(&identity, &id_path)?;
778 Ok(identity)
779 }
780}
781
782#[cfg(test)]
783mod tests {
784 use super::*;
785
786 use std::sync::atomic::{AtomicU64, Ordering};
787 static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
788
789 fn temp_dir() -> PathBuf {
790 let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
791 let dir = std::env::temp_dir().join(format!("rns-test-{}-{}", std::process::id(), id));
792 let _ = fs::remove_dir_all(&dir);
793 fs::create_dir_all(&dir).unwrap();
794 dir
795 }
796
797 #[test]
798 fn save_load_identity_roundtrip() {
799 let dir = temp_dir();
800 let path = dir.join("test_identity");
801
802 let identity = Identity::new(&mut OsRng);
803 let original_hash = *identity.hash();
804
805 save_identity(&identity, &path).unwrap();
806 #[cfg(unix)]
807 {
808 use std::os::unix::fs::PermissionsExt;
809 assert_eq!(
810 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
811 0o600
812 );
813 }
814 let loaded = load_identity(&path).unwrap();
815
816 assert_eq!(*loaded.hash(), original_hash);
817
818 let _ = fs::remove_dir_all(&dir);
819 }
820
821 #[test]
822 fn identity_file_format() {
823 let dir = temp_dir();
824 let path = dir.join("test_identity_fmt");
825
826 let identity = Identity::new(&mut OsRng);
827 save_identity(&identity, &path).unwrap();
828
829 let data = fs::read(&path).unwrap();
830 assert_eq!(data.len(), 64, "Identity file must be exactly 64 bytes");
831
832 let private_key = identity.get_private_key();
835 let private_key = private_key.unwrap();
836 assert_eq!(&data[..], &private_key[..]);
837
838 let _ = fs::remove_dir_all(&dir);
839 }
840
841 #[test]
842 fn save_load_known_destinations_empty() {
843 let dir = temp_dir();
844 let path = dir.join("known_destinations");
845
846 let empty: HashMap<[u8; 16], KnownDestination> = HashMap::new();
847 save_known_destinations(&empty, &path).unwrap();
848
849 let loaded = load_known_destinations(&path).unwrap();
850 assert!(loaded.is_empty());
851
852 let _ = fs::remove_dir_all(&dir);
853 }
854
855 #[test]
856 fn save_load_known_destinations_roundtrip() {
857 let dir = temp_dir();
858 let path = dir.join("known_destinations");
859
860 let mut dests = HashMap::new();
861 dests.insert(
862 [0x01u8; 16],
863 KnownDestination {
864 identity_hash: [0x11u8; 16],
865 public_key: [0xABu8; 64],
866 app_data: Some(vec![0x01, 0x02, 0x03]),
867 hops: 2,
868 received_at: 1700000000.0,
869 receiving_interface: 7,
870 was_used: true,
871 last_used_at: Some(1700000010.0),
872 retained: true,
873 },
874 );
875 dests.insert(
876 [0x02u8; 16],
877 KnownDestination {
878 identity_hash: [0x22u8; 16],
879 public_key: [0xCDu8; 64],
880 app_data: None,
881 hops: 1,
882 received_at: 1700000001.0,
883 receiving_interface: 0,
884 was_used: false,
885 last_used_at: None,
886 retained: false,
887 },
888 );
889
890 save_known_destinations(&dests, &path).unwrap();
891 let loaded = load_known_destinations(&path).unwrap();
892
893 assert_eq!(loaded.len(), 2);
894
895 let d1 = &loaded[&[0x01u8; 16]];
896 assert_eq!(d1.identity_hash, [0x11u8; 16]);
897 assert_eq!(d1.public_key, [0xABu8; 64]);
898 assert_eq!(d1.app_data, Some(vec![0x01, 0x02, 0x03]));
899 assert_eq!(d1.hops, 2);
900 assert_eq!(d1.received_at as u64, 1700000000);
901 assert_eq!(d1.receiving_interface, 7);
902 assert!(d1.was_used);
903 assert_eq!(d1.last_used_at, Some(1700000010.0));
904 assert!(d1.retained);
905
906 let d2 = &loaded[&[0x02u8; 16]];
907 assert_eq!(d2.app_data, None);
908 assert!(!d2.was_used);
909 assert_eq!(d2.last_used_at, None);
910 assert!(!d2.retained);
911
912 let _ = fs::remove_dir_all(&dir);
913 }
914
915 #[test]
916 fn save_known_destinations_replaces_existing_file_atomically() {
917 let dir = temp_dir();
918 let path = dir.join("known_destinations");
919 fs::write(&path, b"old").unwrap();
920
921 let mut dests = HashMap::new();
922 dests.insert(
923 [0x03u8; 16],
924 KnownDestination {
925 identity_hash: [0x33u8; 16],
926 public_key: [0xEFu8; 64],
927 app_data: None,
928 hops: 3,
929 received_at: 1700000002.0,
930 receiving_interface: 9,
931 was_used: false,
932 last_used_at: None,
933 retained: false,
934 },
935 );
936
937 save_known_destinations(&dests, &path).unwrap();
938
939 let loaded = load_known_destinations(&path).unwrap();
940 assert_eq!(loaded.len(), 1);
941 assert!(loaded.contains_key(&[0x03u8; 16]));
942 let leftover_temp = fs::read_dir(&dir)
943 .unwrap()
944 .filter_map(Result::ok)
945 .any(|entry| entry.file_name().to_string_lossy().contains(".tmp."));
946 assert!(!leftover_temp);
947
948 let _ = fs::remove_dir_all(&dir);
949 }
950
951 #[test]
952 fn ratchet_store_roundtrip() {
953 let dir = temp_dir();
954 let store = FsRatchetStore::new(dir.join("ratchets"));
955 let dest = [0xAA; 16];
956 let entry = RatchetEntry {
957 ratchet: [0xBB; 32],
958 received_at: 1700000000.25,
959 };
960
961 store.remember(dest, entry).unwrap();
962 let loaded = store.current(&dest, 1700000001.0, 60.0).unwrap();
963
964 assert_eq!(loaded, Some(entry));
965 assert!(dir.join("ratchets").join(hex_lower(&dest)).exists());
966
967 let _ = fs::remove_dir_all(&dir);
968 }
969
970 #[test]
971 fn ratchet_cleanup_removes_expired_corrupt_unknown_and_temp() {
972 let dir = temp_dir();
973 let ratchets = dir.join("ratchets");
974 fs::create_dir_all(&ratchets).unwrap();
975 let store = FsRatchetStore::new(ratchets.clone());
976
977 let known_live = [0x01; 16];
978 let known_expired = [0x02; 16];
979 let unknown = [0x03; 16];
980 store
981 .remember(
982 known_live,
983 RatchetEntry {
984 ratchet: [0x11; 32],
985 received_at: 1000.0,
986 },
987 )
988 .unwrap();
989 store
990 .remember(
991 known_expired,
992 RatchetEntry {
993 ratchet: [0x22; 32],
994 received_at: 100.0,
995 },
996 )
997 .unwrap();
998 store
999 .remember(
1000 unknown,
1001 RatchetEntry {
1002 ratchet: [0x33; 32],
1003 received_at: 1000.0,
1004 },
1005 )
1006 .unwrap();
1007 fs::write(ratchets.join(hex_lower(&[0x04; 16])), b"not msgpack").unwrap();
1008 fs::write(ratchets.join("0102.out"), b"temp").unwrap();
1009
1010 let known = HashSet::from([known_live, known_expired, [0x04; 16]]);
1011 let stats = store.cleanup(&known, 1000.0, 300.0).unwrap();
1012
1013 assert_eq!(stats.processed, 5);
1014 assert_eq!(stats.not_known, 1);
1015 assert_eq!(stats.removed, 4);
1016 assert!(ratchets.join(hex_lower(&known_live)).exists());
1017 assert!(!ratchets.join(hex_lower(&known_expired)).exists());
1018 assert!(!ratchets.join(hex_lower(&unknown)).exists());
1019 assert!(!ratchets.join(hex_lower(&[0x04; 16])).exists());
1020 assert!(!ratchets.join("0102.out").exists());
1021
1022 let _ = fs::remove_dir_all(&dir);
1023 }
1024
1025 #[test]
1026 fn ensure_dirs_creates() {
1027 let dir = temp_dir().join("new_config");
1028 let _ = fs::remove_dir_all(&dir);
1029
1030 let paths = ensure_storage_dirs(&dir).unwrap();
1031
1032 assert!(paths.storage.exists());
1033 assert!(paths.cache.exists());
1034 assert!(paths.identities.exists());
1035 assert!(paths.ratchets.exists());
1036 assert!(paths.discovered_interfaces.exists());
1037
1038 let _ = fs::remove_dir_all(&dir);
1039 }
1040
1041 #[test]
1042 fn ensure_dirs_existing() {
1043 let dir = temp_dir().join("existing_config");
1044 fs::create_dir_all(dir.join("storage")).unwrap();
1045 fs::create_dir_all(dir.join("cache")).unwrap();
1046
1047 let paths = ensure_storage_dirs(&dir).unwrap();
1048 assert!(paths.storage.exists());
1049 assert!(paths.identities.exists());
1050
1051 let _ = fs::remove_dir_all(&dir);
1052 }
1053
1054 #[test]
1055 fn load_or_create_identity_new() {
1056 let dir = temp_dir().join("load_or_create");
1057 fs::create_dir_all(&dir).unwrap();
1058
1059 let identity = load_or_create_identity(&dir).unwrap();
1060 let id_path = dir.join("identity");
1061 assert!(id_path.exists());
1062
1063 let loaded = load_or_create_identity(&dir).unwrap();
1065 assert_eq!(*identity.hash(), *loaded.hash());
1066
1067 let _ = fs::remove_dir_all(&dir);
1068 }
1069
1070 fn transport_snapshot() -> rns_core::transport::persistence::TransportStateSnapshot {
1071 use rns_core::transport::persistence::{
1072 PersistedPath, PersistedTunnel, TransportStateSnapshot,
1073 };
1074
1075 let path = PersistedPath {
1076 destination_hash: [0x11; 16],
1077 timestamp: 10.25,
1078 received_from: [0x22; 16],
1079 hops: 3,
1080 expires: 20.5,
1081 random_blobs: vec![[0x33; 10], [0x44; 10]],
1082 interface_hash: Some([0x55; 32]),
1083 packet_hash: [0x66; 32],
1084 };
1085 TransportStateSnapshot {
1086 packet_hashes: vec![[1; 32], [2; 32]],
1087 paths: vec![path.clone()],
1088 tunnels: vec![PersistedTunnel {
1089 tunnel_id: [0x77; 32],
1090 interface_hash: None,
1091 paths: vec![PersistedPath {
1092 destination_hash: [0x88; 16],
1093 interface_hash: None,
1094 ..path
1095 }],
1096 expires: 30.75,
1097 }],
1098 }
1099 }
1100
1101 #[test]
1102 fn packet_hashlist_raw_is_fixed_width_fifo_and_ignores_partial_tail() {
1103 let dir = temp_dir();
1104 let snapshot = transport_snapshot();
1105 save_transport_state(&snapshot, &dir, false).unwrap();
1106
1107 let path = dir.join("packet_hashlist.raw");
1108 let mut raw = fs::read(&path).unwrap();
1109 assert_eq!(raw.len(), 64);
1110 assert_eq!(&raw[..32], &[1; 32]);
1111 assert_eq!(&raw[32..], &[2; 32]);
1112 raw.extend_from_slice(&[0xFF; 17]);
1113 fs::write(&path, raw).unwrap();
1114
1115 assert_eq!(load_packet_hashlist(&path).unwrap(), vec![[1; 32], [2; 32]]);
1116 let _ = fs::remove_dir_all(&dir);
1117 }
1118
1119 #[test]
1120 fn path_and_tunnel_tables_round_trip_python_compatible_fields() {
1121 let dir = temp_dir();
1122 let expected = transport_snapshot();
1123 save_transport_state(&expected, &dir, false).unwrap();
1124 let loaded = load_transport_state(&dir).unwrap();
1125 assert_eq!(loaded, expected);
1126
1127 let packed = fs::read(dir.join("destination_table")).unwrap();
1128 let value = rns_core::msgpack::unpack_exact(&packed).unwrap();
1129 let entry = &value.as_array().unwrap()[0];
1130 assert_eq!(entry.as_array().unwrap().len(), 8);
1131 assert_eq!(entry.as_array().unwrap()[0].as_bin().unwrap().len(), 16);
1132 assert_eq!(entry.as_array().unwrap()[6].as_bin().unwrap().len(), 32);
1133
1134 let packed = fs::read(dir.join("tunnels")).unwrap();
1135 let value = rns_core::msgpack::unpack_exact(&packed).unwrap();
1136 let tunnel = &value.as_array().unwrap()[0];
1137 assert_eq!(tunnel.as_array().unwrap().len(), 4);
1138 assert!(matches!(
1139 tunnel.as_array().unwrap()[1],
1140 rns_core::msgpack::Value::Nil
1141 ));
1142 let _ = fs::remove_dir_all(&dir);
1143 }
1144
1145 #[test]
1146 fn missing_transport_state_files_load_as_empty_tables() {
1147 let dir = temp_dir();
1148 assert_eq!(
1149 load_transport_state(&dir).unwrap(),
1150 rns_core::transport::persistence::TransportStateSnapshot::default()
1151 );
1152 let _ = fs::remove_dir_all(&dir);
1153 }
1154
1155 #[test]
1156 fn low_priority_save_checkpoints_each_collection_without_temp_leaks() {
1157 let dir = temp_dir();
1158 let snapshot = transport_snapshot();
1159 let mut checkpoints = 0;
1160 save_transport_state_with_checkpoint(&snapshot, &dir, || checkpoints += 1).unwrap();
1161
1162 assert_eq!(checkpoints, 5);
1164 assert!(!fs::read_dir(&dir)
1165 .unwrap()
1166 .filter_map(Result::ok)
1167 .any(|entry| entry.file_name().to_string_lossy().contains(".tmp.")));
1168 let _ = fs::remove_dir_all(&dir);
1169 }
1170
1171 #[test]
1172 fn malformed_transport_table_reports_invalid_data_without_panicking() {
1173 let dir = temp_dir();
1174 fs::write(dir.join("destination_table"), b"not-msgpack").unwrap();
1175 let error = load_transport_state(&dir).unwrap_err();
1176 assert_eq!(error.kind(), io::ErrorKind::InvalidData);
1177 let _ = fs::remove_dir_all(&dir);
1178 }
1179}