Skip to main content

rns_net/common/
destination.rs

1//! Application-facing Destination and AnnouncedIdentity types.
2//!
3//! `Destination` is a pure data struct representing a network endpoint.
4//! `AnnouncedIdentity` captures the result of a received announce.
5
6use rns_core::destination::destination_hash;
7use rns_core::transport::types::InterfaceId;
8use rns_core::types::{DestHash, DestinationType, Direction, IdentityHash, ProofStrategy};
9use rns_crypto::token::Token;
10use rns_crypto::OsRng;
11use rns_crypto::Rng;
12
13/// Errors related to GROUP destination key operations.
14#[derive(Debug, PartialEq)]
15pub enum GroupKeyError {
16    /// No symmetric key has been loaded or generated.
17    NoKey,
18    /// Key must be 32 bytes (AES-128) or 64 bytes (AES-256).
19    InvalidKeyLength,
20    /// Encryption failed.
21    EncryptionFailed,
22    /// Decryption failed (wrong key, tampered data, or invalid format).
23    DecryptionFailed,
24}
25
26impl core::fmt::Display for GroupKeyError {
27    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
28        match self {
29            GroupKeyError::NoKey => write!(f, "No GROUP key loaded"),
30            GroupKeyError::InvalidKeyLength => write!(f, "Key must be 32 or 64 bytes"),
31            GroupKeyError::EncryptionFailed => write!(f, "Encryption failed"),
32            GroupKeyError::DecryptionFailed => write!(f, "Decryption failed"),
33        }
34    }
35}
36
37/// A network destination (endpoint) for sending or receiving packets.
38///
39/// This is a pure data struct with no behavior — all operations
40/// (register, announce, send) are methods on `RnsNode`.
41#[derive(Debug, Clone)]
42pub struct Destination {
43    /// Computed destination hash.
44    pub hash: DestHash,
45    /// Type: Single, Group, or Plain.
46    pub dest_type: DestinationType,
47    /// Direction: In (receiving) or Out (sending).
48    pub direction: Direction,
49    /// Application name (e.g. "echo_app").
50    pub app_name: String,
51    /// Aspects (e.g. ["echo", "request"]).
52    pub aspects: Vec<String>,
53    /// Identity hash of the owner (for SINGLE destinations).
54    pub identity_hash: Option<IdentityHash>,
55    /// Full public key (64 bytes) of the remote peer (for OUT SINGLE destinations).
56    pub public_key: Option<[u8; 64]>,
57    /// Symmetric key for GROUP destinations (32 or 64 bytes).
58    pub group_key: Option<Vec<u8>>,
59    /// How to handle proofs for incoming packets.
60    pub proof_strategy: ProofStrategy,
61}
62
63impl Destination {
64    /// Create an inbound SINGLE destination (for receiving encrypted packets).
65    ///
66    /// `identity_hash` is the local identity that owns this destination.
67    pub fn single_in(app_name: &str, aspects: &[&str], identity_hash: IdentityHash) -> Self {
68        let dh = destination_hash(app_name, aspects, Some(&identity_hash.0));
69        Destination {
70            hash: DestHash(dh),
71            dest_type: DestinationType::Single,
72            direction: Direction::In,
73            app_name: app_name.into(),
74            aspects: aspects.iter().map(|s| s.to_string()).collect(),
75            identity_hash: Some(identity_hash),
76            public_key: None,
77            group_key: None,
78            proof_strategy: ProofStrategy::ProveNone,
79        }
80    }
81
82    /// Create an outbound SINGLE destination (for sending encrypted packets).
83    ///
84    /// `recalled` contains the remote peer's identity data (from announce/recall).
85    pub fn single_out(app_name: &str, aspects: &[&str], recalled: &AnnouncedIdentity) -> Self {
86        let dh = destination_hash(app_name, aspects, Some(&recalled.identity_hash.0));
87        Destination {
88            hash: DestHash(dh),
89            dest_type: DestinationType::Single,
90            direction: Direction::Out,
91            app_name: app_name.into(),
92            aspects: aspects.iter().map(|s| s.to_string()).collect(),
93            identity_hash: Some(recalled.identity_hash),
94            public_key: Some(recalled.public_key),
95            group_key: None,
96            proof_strategy: ProofStrategy::ProveNone,
97        }
98    }
99
100    /// Create a PLAIN destination (unencrypted, no identity).
101    pub fn plain(app_name: &str, aspects: &[&str]) -> Self {
102        let dh = destination_hash(app_name, aspects, None);
103        Destination {
104            hash: DestHash(dh),
105            dest_type: DestinationType::Plain,
106            direction: Direction::In,
107            app_name: app_name.into(),
108            aspects: aspects.iter().map(|s| s.to_string()).collect(),
109            identity_hash: None,
110            public_key: None,
111            group_key: None,
112            proof_strategy: ProofStrategy::ProveNone,
113        }
114    }
115
116    /// Create a GROUP destination (symmetric encryption with pre-shared key).
117    ///
118    /// No identity needed — the hash is based only on app_name + aspects,
119    /// same as PLAIN. All members sharing the same key can encrypt/decrypt.
120    pub fn group(app_name: &str, aspects: &[&str]) -> Self {
121        let dh = destination_hash(app_name, aspects, None);
122        Destination {
123            hash: DestHash(dh),
124            dest_type: DestinationType::Group,
125            direction: Direction::In,
126            app_name: app_name.into(),
127            aspects: aspects.iter().map(|s| s.to_string()).collect(),
128            identity_hash: None,
129            public_key: None,
130            group_key: None,
131            proof_strategy: ProofStrategy::ProveNone,
132        }
133    }
134
135    /// Generate a new random 64-byte symmetric key (AES-256) for this GROUP destination.
136    pub fn create_keys(&mut self) {
137        let mut key = vec![0u8; 64];
138        OsRng.fill_bytes(&mut key);
139        self.group_key = Some(key);
140    }
141
142    /// Load an existing symmetric key for this GROUP destination.
143    ///
144    /// Key must be 32 bytes (AES-128) or 64 bytes (AES-256).
145    pub fn load_private_key(&mut self, key: Vec<u8>) -> Result<(), GroupKeyError> {
146        if key.len() != 32 && key.len() != 64 {
147            return Err(GroupKeyError::InvalidKeyLength);
148        }
149        self.group_key = Some(key);
150        Ok(())
151    }
152
153    /// Retrieve the symmetric key bytes, if set.
154    pub fn get_private_key(&self) -> Option<&[u8]> {
155        self.group_key.as_deref()
156    }
157
158    /// Encrypt plaintext using this destination's GROUP key.
159    pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, GroupKeyError> {
160        let key = self.group_key.as_ref().ok_or(GroupKeyError::NoKey)?;
161        let token = Token::new(key).map_err(|_| GroupKeyError::EncryptionFailed)?;
162        Ok(token.encrypt(plaintext, &mut OsRng))
163    }
164
165    /// Decrypt ciphertext using this destination's GROUP key.
166    pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, GroupKeyError> {
167        let key = self.group_key.as_ref().ok_or(GroupKeyError::NoKey)?;
168        let token = Token::new(key).map_err(|_| GroupKeyError::DecryptionFailed)?;
169        token.decrypt(ciphertext).map_err(|_| GroupKeyError::DecryptionFailed)
170    }
171
172    /// Set the proof strategy for this destination.
173    pub fn set_proof_strategy(mut self, strategy: ProofStrategy) -> Self {
174        self.proof_strategy = strategy;
175        self
176    }
177}
178
179/// Information about an announced identity, received via announce or recalled from cache.
180#[derive(Debug, Clone)]
181pub struct AnnouncedIdentity {
182    /// Destination hash that was announced.
183    pub dest_hash: DestHash,
184    /// Identity hash (truncated SHA-256 of public key).
185    pub identity_hash: IdentityHash,
186    /// Full public key (X25519 32 bytes + Ed25519 32 bytes).
187    pub public_key: [u8; 64],
188    /// Optional application data included in the announce.
189    pub app_data: Option<Vec<u8>>,
190    /// Number of hops this announce has traveled.
191    pub hops: u8,
192    /// Timestamp when this announce was received.
193    pub received_at: f64,
194    /// The interface on which this announce was received.
195    pub receiving_interface: InterfaceId,
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    fn test_identity_hash() -> IdentityHash {
203        IdentityHash([0x42; 16])
204    }
205
206    fn test_announced() -> AnnouncedIdentity {
207        AnnouncedIdentity {
208            dest_hash: DestHash([0xAA; 16]),
209            identity_hash: IdentityHash([0x42; 16]),
210            public_key: [0xBB; 64],
211            app_data: Some(b"test_data".to_vec()),
212            hops: 3,
213            received_at: 1234567890.0,
214            receiving_interface: InterfaceId(0),
215        }
216    }
217
218    #[test]
219    fn single_in_hash_matches_raw() {
220        let ih = test_identity_hash();
221        let dest = Destination::single_in("echo", &["app"], ih);
222
223        let raw = destination_hash("echo", &["app"], Some(&ih.0));
224        assert_eq!(dest.hash.0, raw);
225        assert_eq!(dest.dest_type, DestinationType::Single);
226        assert_eq!(dest.direction, Direction::In);
227        assert_eq!(dest.app_name, "echo");
228        assert_eq!(dest.aspects, vec!["app".to_string()]);
229        assert_eq!(dest.identity_hash, Some(ih));
230        assert!(dest.public_key.is_none());
231    }
232
233    #[test]
234    fn single_out_from_recalled() {
235        let recalled = test_announced();
236        let dest = Destination::single_out("echo", &["app"], &recalled);
237
238        let raw = destination_hash("echo", &["app"], Some(&recalled.identity_hash.0));
239        assert_eq!(dest.hash.0, raw);
240        assert_eq!(dest.dest_type, DestinationType::Single);
241        assert_eq!(dest.direction, Direction::Out);
242        assert_eq!(dest.public_key, Some([0xBB; 64]));
243    }
244
245    #[test]
246    fn plain_destination() {
247        let dest = Destination::plain("broadcast", &["test"]);
248
249        let raw = destination_hash("broadcast", &["test"], None);
250        assert_eq!(dest.hash.0, raw);
251        assert_eq!(dest.dest_type, DestinationType::Plain);
252        assert!(dest.identity_hash.is_none());
253        assert!(dest.public_key.is_none());
254    }
255
256    #[test]
257    fn destination_deterministic() {
258        let ih = test_identity_hash();
259        let d1 = Destination::single_in("app", &["a", "b"], ih);
260        let d2 = Destination::single_in("app", &["a", "b"], ih);
261        assert_eq!(d1.hash, d2.hash);
262    }
263
264    #[test]
265    fn different_identity_different_hash() {
266        let d1 = Destination::single_in("app", &["a"], IdentityHash([1; 16]));
267        let d2 = Destination::single_in("app", &["a"], IdentityHash([2; 16]));
268        assert_ne!(d1.hash, d2.hash);
269    }
270
271    #[test]
272    fn proof_strategy_builder() {
273        let dest = Destination::plain("app", &["a"])
274            .set_proof_strategy(ProofStrategy::ProveAll);
275        assert_eq!(dest.proof_strategy, ProofStrategy::ProveAll);
276    }
277
278    #[test]
279    fn announced_identity_fields() {
280        let ai = test_announced();
281        assert_eq!(ai.dest_hash, DestHash([0xAA; 16]));
282        assert_eq!(ai.identity_hash, IdentityHash([0x42; 16]));
283        assert_eq!(ai.public_key, [0xBB; 64]);
284        assert_eq!(ai.app_data, Some(b"test_data".to_vec()));
285        assert_eq!(ai.hops, 3);
286        assert_eq!(ai.received_at, 1234567890.0);
287        assert_eq!(ai.receiving_interface, InterfaceId(0));
288    }
289
290    #[test]
291    fn announced_identity_receiving_interface_nonzero() {
292        let ai = AnnouncedIdentity {
293            receiving_interface: InterfaceId(42),
294            ..test_announced()
295        };
296        assert_eq!(ai.receiving_interface, InterfaceId(42));
297    }
298
299    #[test]
300    fn announced_identity_clone_preserves_receiving_interface() {
301        let ai = AnnouncedIdentity {
302            receiving_interface: InterfaceId(7),
303            ..test_announced()
304        };
305        let cloned = ai.clone();
306        assert_eq!(cloned.receiving_interface, ai.receiving_interface);
307    }
308
309    #[test]
310    fn single_out_from_recalled_with_interface() {
311        let recalled = AnnouncedIdentity {
312            receiving_interface: InterfaceId(5),
313            ..test_announced()
314        };
315        // Destination::single_out should work regardless of receiving_interface value
316        let dest = Destination::single_out("echo", &["app"], &recalled);
317        assert_eq!(dest.dest_type, DestinationType::Single);
318        assert_eq!(dest.direction, Direction::Out);
319        assert_eq!(dest.public_key, Some([0xBB; 64]));
320    }
321
322    #[test]
323    fn multiple_aspects() {
324        let dest = Destination::plain("app", &["one", "two", "three"]);
325        assert_eq!(dest.aspects, vec!["one", "two", "three"]);
326    }
327
328    // --- GROUP destination tests ---
329
330    #[test]
331    fn group_destination_hash_deterministic() {
332        let d1 = Destination::group("myapp", &["chat", "room"]);
333        let d2 = Destination::group("myapp", &["chat", "room"]);
334        assert_eq!(d1.hash, d2.hash);
335        assert_eq!(d1.dest_type, DestinationType::Group);
336        assert_eq!(d1.direction, Direction::In);
337        assert!(d1.identity_hash.is_none());
338        assert!(d1.public_key.is_none());
339        assert!(d1.group_key.is_none());
340    }
341
342    #[test]
343    fn group_destination_hash_matches_plain_hash() {
344        let group = Destination::group("broadcast", &["test"]);
345        let plain = Destination::plain("broadcast", &["test"]);
346        // GROUP and PLAIN with same name produce the same hash (no identity component)
347        assert_eq!(group.hash, plain.hash);
348    }
349
350    #[test]
351    fn group_create_keys() {
352        let mut dest = Destination::group("app", &["g"]);
353        assert!(dest.group_key.is_none());
354        dest.create_keys();
355        let key = dest.group_key.as_ref().unwrap();
356        assert_eq!(key.len(), 64);
357        // Key should not be all zeros (astronomically unlikely with real RNG)
358        assert!(key.iter().any(|&b| b != 0));
359    }
360
361    #[test]
362    fn group_load_private_key_64() {
363        let mut dest = Destination::group("app", &["g"]);
364        let key = vec![0x42u8; 64];
365        assert!(dest.load_private_key(key.clone()).is_ok());
366        assert_eq!(dest.get_private_key(), Some(key.as_slice()));
367    }
368
369    #[test]
370    fn group_load_private_key_32() {
371        let mut dest = Destination::group("app", &["g"]);
372        let key = vec![0xAB; 32];
373        assert!(dest.load_private_key(key.clone()).is_ok());
374        assert_eq!(dest.get_private_key(), Some(key.as_slice()));
375    }
376
377    #[test]
378    fn group_load_private_key_invalid_length() {
379        let mut dest = Destination::group("app", &["g"]);
380        assert_eq!(
381            dest.load_private_key(vec![0; 48]),
382            Err(GroupKeyError::InvalidKeyLength)
383        );
384        assert_eq!(
385            dest.load_private_key(vec![0; 16]),
386            Err(GroupKeyError::InvalidKeyLength)
387        );
388    }
389
390    #[test]
391    fn group_encrypt_decrypt_roundtrip() {
392        let mut dest = Destination::group("app", &["secure"]);
393        dest.load_private_key(vec![0x42u8; 64]).unwrap();
394
395        let plaintext = b"Hello, GROUP destination!";
396        let ciphertext = dest.encrypt(plaintext).unwrap();
397        assert_ne!(ciphertext.as_slice(), plaintext);
398        assert!(ciphertext.len() > plaintext.len()); // includes IV + HMAC overhead
399
400        let decrypted = dest.decrypt(&ciphertext).unwrap();
401        assert_eq!(decrypted, plaintext);
402    }
403
404    #[test]
405    fn group_decrypt_wrong_key_fails() {
406        let mut dest1 = Destination::group("app", &["a"]);
407        dest1.load_private_key(vec![0x42u8; 64]).unwrap();
408
409        let mut dest2 = Destination::group("app", &["a"]);
410        dest2.load_private_key(vec![0xBBu8; 64]).unwrap();
411
412        let ciphertext = dest1.encrypt(b"secret").unwrap();
413        assert_eq!(dest2.decrypt(&ciphertext), Err(GroupKeyError::DecryptionFailed));
414    }
415
416    #[test]
417    fn group_encrypt_without_key_fails() {
418        let dest = Destination::group("app", &["a"]);
419        assert_eq!(dest.encrypt(b"test"), Err(GroupKeyError::NoKey));
420        assert_eq!(dest.decrypt(b"test"), Err(GroupKeyError::NoKey));
421    }
422
423    #[test]
424    fn group_key_interop_with_token() {
425        // Encrypt with Token directly, decrypt with Destination (and vice versa)
426        let key = vec![0x42u8; 64];
427
428        let token = Token::new(&key).unwrap();
429        let ciphertext = token.encrypt(b"from token", &mut OsRng);
430
431        let mut dest = Destination::group("app", &["a"]);
432        dest.load_private_key(key.clone()).unwrap();
433        let decrypted = dest.decrypt(&ciphertext).unwrap();
434        assert_eq!(decrypted, b"from token");
435
436        // And the other direction
437        let ciphertext2 = dest.encrypt(b"from dest").unwrap();
438        let decrypted2 = token.decrypt(&ciphertext2).unwrap();
439        assert_eq!(decrypted2, b"from dest");
440    }
441
442    #[test]
443    fn group_encrypt_decrypt_32byte_key() {
444        let mut dest = Destination::group("app", &["aes128"]);
445        dest.load_private_key(vec![0xABu8; 32]).unwrap();
446
447        let plaintext = b"AES-128 mode";
448        let ciphertext = dest.encrypt(plaintext).unwrap();
449        let decrypted = dest.decrypt(&ciphertext).unwrap();
450        assert_eq!(decrypted, plaintext);
451    }
452}