1use 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#[derive(Debug, PartialEq)]
15pub enum GroupKeyError {
16 NoKey,
18 InvalidKeyLength,
20 EncryptionFailed,
22 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#[derive(Debug, Clone)]
42pub struct Destination {
43 pub hash: DestHash,
45 pub dest_type: DestinationType,
47 pub direction: Direction,
49 pub app_name: String,
51 pub aspects: Vec<String>,
53 pub identity_hash: Option<IdentityHash>,
55 pub public_key: Option<[u8; 64]>,
57 pub group_key: Option<Vec<u8>>,
59 pub proof_strategy: ProofStrategy,
61}
62
63impl Destination {
64 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 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 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 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 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 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 pub fn get_private_key(&self) -> Option<&[u8]> {
155 self.group_key.as_deref()
156 }
157
158 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 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
170 .decrypt(ciphertext)
171 .map_err(|_| GroupKeyError::DecryptionFailed)
172 }
173
174 pub fn set_proof_strategy(mut self, strategy: ProofStrategy) -> Self {
176 self.proof_strategy = strategy;
177 self
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct AnnouncedIdentity {
184 pub dest_hash: DestHash,
186 pub identity_hash: IdentityHash,
188 pub public_key: [u8; 64],
190 pub app_data: Option<Vec<u8>>,
192 pub hops: u8,
194 pub received_at: f64,
196 pub receiving_interface: InterfaceId,
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 fn test_identity_hash() -> IdentityHash {
205 IdentityHash([0x42; 16])
206 }
207
208 fn test_announced() -> AnnouncedIdentity {
209 AnnouncedIdentity {
210 dest_hash: DestHash([0xAA; 16]),
211 identity_hash: IdentityHash([0x42; 16]),
212 public_key: [0xBB; 64],
213 app_data: Some(b"test_data".to_vec()),
214 hops: 3,
215 received_at: 1234567890.0,
216 receiving_interface: InterfaceId(0),
217 }
218 }
219
220 #[test]
221 fn single_in_hash_matches_raw() {
222 let ih = test_identity_hash();
223 let dest = Destination::single_in("echo", &["app"], ih);
224
225 let raw = destination_hash("echo", &["app"], Some(&ih.0));
226 assert_eq!(dest.hash.0, raw);
227 assert_eq!(dest.dest_type, DestinationType::Single);
228 assert_eq!(dest.direction, Direction::In);
229 assert_eq!(dest.app_name, "echo");
230 assert_eq!(dest.aspects, vec!["app".to_string()]);
231 assert_eq!(dest.identity_hash, Some(ih));
232 assert!(dest.public_key.is_none());
233 }
234
235 #[test]
236 fn single_out_from_recalled() {
237 let recalled = test_announced();
238 let dest = Destination::single_out("echo", &["app"], &recalled);
239
240 let raw = destination_hash("echo", &["app"], Some(&recalled.identity_hash.0));
241 assert_eq!(dest.hash.0, raw);
242 assert_eq!(dest.dest_type, DestinationType::Single);
243 assert_eq!(dest.direction, Direction::Out);
244 assert_eq!(dest.public_key, Some([0xBB; 64]));
245 }
246
247 #[test]
248 fn plain_destination() {
249 let dest = Destination::plain("broadcast", &["test"]);
250
251 let raw = destination_hash("broadcast", &["test"], None);
252 assert_eq!(dest.hash.0, raw);
253 assert_eq!(dest.dest_type, DestinationType::Plain);
254 assert!(dest.identity_hash.is_none());
255 assert!(dest.public_key.is_none());
256 }
257
258 #[test]
259 fn destination_deterministic() {
260 let ih = test_identity_hash();
261 let d1 = Destination::single_in("app", &["a", "b"], ih);
262 let d2 = Destination::single_in("app", &["a", "b"], ih);
263 assert_eq!(d1.hash, d2.hash);
264 }
265
266 #[test]
267 fn different_identity_different_hash() {
268 let d1 = Destination::single_in("app", &["a"], IdentityHash([1; 16]));
269 let d2 = Destination::single_in("app", &["a"], IdentityHash([2; 16]));
270 assert_ne!(d1.hash, d2.hash);
271 }
272
273 #[test]
274 fn proof_strategy_builder() {
275 let dest = Destination::plain("app", &["a"]).set_proof_strategy(ProofStrategy::ProveAll);
276 assert_eq!(dest.proof_strategy, ProofStrategy::ProveAll);
277 }
278
279 #[test]
280 fn announced_identity_fields() {
281 let ai = test_announced();
282 assert_eq!(ai.dest_hash, DestHash([0xAA; 16]));
283 assert_eq!(ai.identity_hash, IdentityHash([0x42; 16]));
284 assert_eq!(ai.public_key, [0xBB; 64]);
285 assert_eq!(ai.app_data, Some(b"test_data".to_vec()));
286 assert_eq!(ai.hops, 3);
287 assert_eq!(ai.received_at, 1234567890.0);
288 assert_eq!(ai.receiving_interface, InterfaceId(0));
289 }
290
291 #[test]
292 fn announced_identity_receiving_interface_nonzero() {
293 let ai = AnnouncedIdentity {
294 receiving_interface: InterfaceId(42),
295 ..test_announced()
296 };
297 assert_eq!(ai.receiving_interface, InterfaceId(42));
298 }
299
300 #[test]
301 fn announced_identity_clone_preserves_receiving_interface() {
302 let ai = AnnouncedIdentity {
303 receiving_interface: InterfaceId(7),
304 ..test_announced()
305 };
306 let cloned = ai.clone();
307 assert_eq!(cloned.receiving_interface, ai.receiving_interface);
308 }
309
310 #[test]
311 fn single_out_from_recalled_with_interface() {
312 let recalled = AnnouncedIdentity {
313 receiving_interface: InterfaceId(5),
314 ..test_announced()
315 };
316 let dest = Destination::single_out("echo", &["app"], &recalled);
318 assert_eq!(dest.dest_type, DestinationType::Single);
319 assert_eq!(dest.direction, Direction::Out);
320 assert_eq!(dest.public_key, Some([0xBB; 64]));
321 }
322
323 #[test]
324 fn multiple_aspects() {
325 let dest = Destination::plain("app", &["one", "two", "three"]);
326 assert_eq!(dest.aspects, vec!["one", "two", "three"]);
327 }
328
329 #[test]
332 fn group_destination_hash_deterministic() {
333 let d1 = Destination::group("myapp", &["chat", "room"]);
334 let d2 = Destination::group("myapp", &["chat", "room"]);
335 assert_eq!(d1.hash, d2.hash);
336 assert_eq!(d1.dest_type, DestinationType::Group);
337 assert_eq!(d1.direction, Direction::In);
338 assert!(d1.identity_hash.is_none());
339 assert!(d1.public_key.is_none());
340 assert!(d1.group_key.is_none());
341 }
342
343 #[test]
344 fn group_destination_hash_matches_plain_hash() {
345 let group = Destination::group("broadcast", &["test"]);
346 let plain = Destination::plain("broadcast", &["test"]);
347 assert_eq!(group.hash, plain.hash);
349 }
350
351 #[test]
352 fn group_create_keys() {
353 let mut dest = Destination::group("app", &["g"]);
354 assert!(dest.group_key.is_none());
355 dest.create_keys();
356 let key = dest.group_key.as_ref().unwrap();
357 assert_eq!(key.len(), 64);
358 assert!(key.iter().any(|&b| b != 0));
360 }
361
362 #[test]
363 fn group_load_private_key_64() {
364 let mut dest = Destination::group("app", &["g"]);
365 let key = vec![0x42u8; 64];
366 assert!(dest.load_private_key(key.clone()).is_ok());
367 assert_eq!(dest.get_private_key(), Some(key.as_slice()));
368 }
369
370 #[test]
371 fn group_load_private_key_32() {
372 let mut dest = Destination::group("app", &["g"]);
373 let key = vec![0xAB; 32];
374 assert!(dest.load_private_key(key.clone()).is_ok());
375 assert_eq!(dest.get_private_key(), Some(key.as_slice()));
376 }
377
378 #[test]
379 fn group_load_private_key_invalid_length() {
380 let mut dest = Destination::group("app", &["g"]);
381 assert_eq!(
382 dest.load_private_key(vec![0; 48]),
383 Err(GroupKeyError::InvalidKeyLength)
384 );
385 assert_eq!(
386 dest.load_private_key(vec![0; 16]),
387 Err(GroupKeyError::InvalidKeyLength)
388 );
389 }
390
391 #[test]
392 fn group_encrypt_decrypt_roundtrip() {
393 let mut dest = Destination::group("app", &["secure"]);
394 dest.load_private_key(vec![0x42u8; 64]).unwrap();
395
396 let plaintext = b"Hello, GROUP destination!";
397 let ciphertext = dest.encrypt(plaintext).unwrap();
398 assert_ne!(ciphertext.as_slice(), plaintext);
399 assert!(ciphertext.len() > plaintext.len()); let decrypted = dest.decrypt(&ciphertext).unwrap();
402 assert_eq!(decrypted, plaintext);
403 }
404
405 #[test]
406 fn group_decrypt_wrong_key_fails() {
407 let mut dest1 = Destination::group("app", &["a"]);
408 dest1.load_private_key(vec![0x42u8; 64]).unwrap();
409
410 let mut dest2 = Destination::group("app", &["a"]);
411 dest2.load_private_key(vec![0xBBu8; 64]).unwrap();
412
413 let ciphertext = dest1.encrypt(b"secret").unwrap();
414 assert_eq!(
415 dest2.decrypt(&ciphertext),
416 Err(GroupKeyError::DecryptionFailed)
417 );
418 }
419
420 #[test]
421 fn group_encrypt_without_key_fails() {
422 let dest = Destination::group("app", &["a"]);
423 assert_eq!(dest.encrypt(b"test"), Err(GroupKeyError::NoKey));
424 assert_eq!(dest.decrypt(b"test"), Err(GroupKeyError::NoKey));
425 }
426
427 #[test]
428 fn group_key_interop_with_token() {
429 let key = vec![0x42u8; 64];
431
432 let token = Token::new(&key).unwrap();
433 let ciphertext = token.encrypt(b"from token", &mut OsRng);
434
435 let mut dest = Destination::group("app", &["a"]);
436 dest.load_private_key(key.clone()).unwrap();
437 let decrypted = dest.decrypt(&ciphertext).unwrap();
438 assert_eq!(decrypted, b"from token");
439
440 let ciphertext2 = dest.encrypt(b"from dest").unwrap();
442 let decrypted2 = token.decrypt(&ciphertext2).unwrap();
443 assert_eq!(decrypted2, b"from dest");
444 }
445
446 #[test]
447 fn group_encrypt_decrypt_32byte_key() {
448 let mut dest = Destination::group("app", &["aes128"]);
449 dest.load_private_key(vec![0xABu8; 32]).unwrap();
450
451 let plaintext = b"AES-128 mode";
452 let ciphertext = dest.encrypt(plaintext).unwrap();
453 let decrypted = dest.decrypt(&ciphertext).unwrap();
454 assert_eq!(decrypted, plaintext);
455 }
456}