Skip to main content

rns_core/
destination.rs

1use alloc::string::String;
2use core::fmt;
3
4use crate::constants;
5use crate::hash;
6
7#[derive(Debug)]
8pub enum DestinationError {
9    DotInAppName,
10    DotInAspect,
11}
12
13impl fmt::Display for DestinationError {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        match self {
16            DestinationError::DotInAppName => write!(f, "Dots can't be used in app names"),
17            DestinationError::DotInAspect => write!(f, "Dots can't be used in aspects"),
18        }
19    }
20}
21
22/// Expand name: "app_name.aspect1.aspect2[.hexhash]"
23///
24/// If identity_hash is provided, appends its hex representation.
25pub fn expand_name(
26    app_name: &str,
27    aspects: &[&str],
28    identity_hash: Option<&[u8; 16]>,
29) -> Result<String, DestinationError> {
30    if app_name.contains('.') {
31        return Err(DestinationError::DotInAppName);
32    }
33
34    let mut name = String::from(app_name);
35    for aspect in aspects {
36        if aspect.contains('.') {
37            return Err(DestinationError::DotInAspect);
38        }
39        name.push('.');
40        name.push_str(aspect);
41    }
42
43    if let Some(hash) = identity_hash {
44        name.push('.');
45        for b in hash {
46            use core::fmt::Write;
47            write!(name, "{:02x}", b).unwrap();
48        }
49    }
50
51    Ok(name)
52}
53
54/// Compute name hash from app_name and aspects.
55///
56/// = SHA-256("app_name.aspect1.aspect2".as_bytes())[:10]
57pub fn name_hash(app_name: &str, aspects: &[&str]) -> [u8; constants::NAME_HASH_LENGTH / 8] {
58    hash::name_hash(app_name, aspects)
59}
60
61/// Compute destination hash.
62///
63/// 1. name_hash = SHA256(expand_name(None, app_name, aspects))[:10]
64/// 2. addr_material = name_hash || identity_hash (if present)
65/// 3. destination_hash = SHA256(addr_material)[:16]
66pub fn destination_hash(
67    app_name: &str,
68    aspects: &[&str],
69    identity_hash: Option<&[u8; 16]>,
70) -> [u8; constants::TRUNCATED_HASHLENGTH / 8] {
71    let nh = name_hash(app_name, aspects);
72
73    let mut addr_material = alloc::vec::Vec::new();
74    addr_material.extend_from_slice(&nh);
75    if let Some(ih) = identity_hash {
76        addr_material.extend_from_slice(ih);
77    }
78
79    hash::truncated_hash(&addr_material)
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn test_expand_name_basic() {
88        let name = expand_name("app", &["aspect"], None).unwrap();
89        assert_eq!(name, "app.aspect");
90    }
91
92    #[test]
93    fn test_expand_name_multiple_aspects() {
94        let name = expand_name("app", &["a", "b"], None).unwrap();
95        assert_eq!(name, "app.a.b");
96    }
97
98    #[test]
99    fn test_expand_name_with_identity() {
100        let hash = [
101            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
102            0x0f, 0x10,
103        ];
104        let name = expand_name("app", &["a", "b"], Some(&hash)).unwrap();
105        assert_eq!(name, "app.a.b.0102030405060708090a0b0c0d0e0f10");
106    }
107
108    #[test]
109    fn test_expand_name_dot_in_app_name() {
110        assert!(expand_name("app.bad", &["aspect"], None).is_err());
111    }
112
113    #[test]
114    fn test_expand_name_dot_in_aspect() {
115        assert!(expand_name("app", &["bad.aspect"], None).is_err());
116    }
117
118    #[test]
119    fn test_destination_hash_plain() {
120        // PLAIN destination: no identity hash
121        let dh = destination_hash("app", &["aspect"], None);
122        assert_eq!(dh.len(), 16);
123
124        // Should be deterministic
125        let dh2 = destination_hash("app", &["aspect"], None);
126        assert_eq!(dh, dh2);
127    }
128
129    #[test]
130    fn test_destination_hash_with_identity() {
131        let id_hash = [0x42; 16];
132        let dh = destination_hash("app", &["aspect"], Some(&id_hash));
133        assert_eq!(dh.len(), 16);
134
135        // Different identity hash should give different destination hash
136        let id_hash2 = [0x43; 16];
137        let dh2 = destination_hash("app", &["aspect"], Some(&id_hash2));
138        assert_ne!(dh, dh2);
139    }
140
141    #[test]
142    fn test_destination_hash_computation() {
143        // Manually verify the computation
144        let nh = name_hash("app", &["aspect"]);
145        let id_hash = [0xAA; 16];
146
147        let mut material = alloc::vec::Vec::new();
148        material.extend_from_slice(&nh);
149        material.extend_from_slice(&id_hash);
150
151        let expected = crate::hash::truncated_hash(&material);
152        let actual = destination_hash("app", &["aspect"], Some(&id_hash));
153        assert_eq!(actual, expected);
154    }
155}