1use crate::aes::{decrypt_aes_256_cbc, encrypt_aes_256_cbc};
21use crate::error::CryptoError;
22use hmac::{Hmac, Mac};
23use sha2::Sha256;
24
25pub const SHIELDED_ADDRESS_LEN: usize = 43;
28
29pub const ENCRYPTED_SHIELDED_ADDRESS_LEN: usize = 64;
33
34pub const SHIELDED_FULL_VIEWING_KEY_LEN: usize = 96;
36
37pub const SHIELDED_DIVERSIFIER_INDEX_LEN: usize = 11;
39
40const CONTACT_INDEX_KEY_LABEL: &[u8] = b"DashPay/shielded/contact-index-key/v1";
42
43const CONTACT_INDEX_LABEL: &[u8] = b"DashPay/shielded/contact-index/v1";
45
46const CONTACT_INDEX_HIGH_BIT: u8 = 0x80;
49
50fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
51 let mut mac =
52 <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC takes a key of any length");
53 for part in parts {
54 mac.update(part);
55 }
56 mac.finalize().into_bytes().into()
57}
58
59pub fn shielded_contact_index_key(
65 full_viewing_key: &[u8; SHIELDED_FULL_VIEWING_KEY_LEN],
66) -> [u8; 32] {
67 hmac_sha256(CONTACT_INDEX_KEY_LABEL, &[full_viewing_key])
68}
69
70pub fn shielded_contact_index(
87 index_key: &[u8; 32],
88 owner_id: &[u8; 32],
89 to_user_id: &[u8; 32],
90 account_reference: u64,
91) -> [u8; SHIELDED_DIVERSIFIER_INDEX_LEN] {
92 let t = hmac_sha256(
93 index_key,
94 &[
95 CONTACT_INDEX_LABEL,
96 owner_id,
97 to_user_id,
98 &account_reference.to_le_bytes(),
99 ],
100 );
101 let mut index = [0u8; SHIELDED_DIVERSIFIER_INDEX_LEN];
102 index.copy_from_slice(&t[..SHIELDED_DIVERSIFIER_INDEX_LEN]);
103 index[SHIELDED_DIVERSIFIER_INDEX_LEN - 1] |= CONTACT_INDEX_HIGH_BIT;
104 index
105}
106
107pub fn is_shielded_contact_index(index: &[u8; SHIELDED_DIVERSIFIER_INDEX_LEN]) -> bool {
111 index[SHIELDED_DIVERSIFIER_INDEX_LEN - 1] & CONTACT_INDEX_HIGH_BIT != 0
112}
113
114pub fn encrypt_shielded_address(
120 shared_key: &[u8; 32],
121 iv: &[u8; 16],
122 address: &[u8; SHIELDED_ADDRESS_LEN],
123) -> [u8; ENCRYPTED_SHIELDED_ADDRESS_LEN] {
124 let ciphertext = encrypt_aes_256_cbc(shared_key, iv, address);
125 let mut field = [0u8; ENCRYPTED_SHIELDED_ADDRESS_LEN];
126 field[..16].copy_from_slice(iv);
127 field[16..].copy_from_slice(&ciphertext);
128 field
129}
130
131pub fn decrypt_shielded_address(
140 shared_key: &[u8; 32],
141 field: &[u8],
142) -> Result<[u8; SHIELDED_ADDRESS_LEN], CryptoError> {
143 let (iv, ciphertext) = field
144 .split_first_chunk::<16>()
145 .filter(|_| field.len() == ENCRYPTED_SHIELDED_ADDRESS_LEN)
146 .ok_or(CryptoError::InvalidEncryptedShieldedAddressLength(
147 field.len(),
148 ))?;
149 let plaintext = decrypt_aes_256_cbc(shared_key, iv, ciphertext)?;
150 plaintext
151 .as_slice()
152 .try_into()
153 .map_err(|_| CryptoError::InvalidShieldedAddressLength(plaintext.len()))
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159
160 fn hex<const N: usize>(text: &str) -> [u8; N] {
161 let bytes: Vec<u8> = (0..text.len())
162 .step_by(2)
163 .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("a hex digit pair"))
164 .collect();
165 bytes.try_into().expect("the expected length")
166 }
167
168 const FULL_VIEWING_KEY: &str =
171 "c0120eb660f8dd2f769e199bcc540476fec169b60f3e7508ffd42a21bd274337\
172 b2301310b489575eb68a8adacfed66b88fd07b961d1ca366c7e7e6e619b29a2b\
173 fce2cf9cb05a6439997f6f7ad4d9eb4b3d5a0672e571036cff9c8a600439063d";
174 const INDEX_KEY: &str = "7233ea974f99a772e1f7cfeef7d1626f9d24cba429b32f5ecdabed7b14867791";
175 const OWNER: [u8; 32] = [0x11; 32];
176 const BOB: [u8; 32] = [0x22; 32];
177 const CAROL: [u8; 32] = [0x33; 32];
178 const BOB_ADDRESS: &str =
179 "25611685f1aa7c3b7a2f7a758ea2f98ca16e32e20e0d3b403a1d81421f1185d67f47054ae98e55e05e839c";
180
181 #[test]
182 fn should_derive_the_contact_index_key_from_the_full_viewing_key() {
183 assert_eq!(
184 shielded_contact_index_key(&hex(FULL_VIEWING_KEY)),
185 hex::<32>(INDEX_KEY)
186 );
187 }
188
189 #[test]
190 fn should_derive_the_index_of_each_contact_request() {
191 let key = hex(INDEX_KEY);
192 for (to_user_id, account_reference, index) in [
193 (BOB, 0x0123_4567, "f90d5349d8530cf76835d0"),
194 (CAROL, 0x0123_4567, "a5ca8646a33e3db572ca94"),
196 (BOB, 0x1123_4567, "4d2ff123168ee0a07ff5b2"),
198 ] {
199 let derived = shielded_contact_index(&key, &OWNER, &to_user_id, account_reference);
200 assert_eq!(derived, hex::<11>(index));
201 assert!(is_shielded_contact_index(&derived));
202 }
203 }
204
205 #[test]
206 fn should_give_two_contacts_and_two_senders_different_indices() {
207 let key = hex(INDEX_KEY);
208 let to_bob = shielded_contact_index(&key, &OWNER, &BOB, 7);
209 assert_ne!(to_bob, shielded_contact_index(&key, &OWNER, &CAROL, 7));
210 assert_ne!(to_bob, shielded_contact_index(&key, &CAROL, &BOB, 7));
211 assert_ne!(to_bob, shielded_contact_index(&key, &OWNER, &BOB, 8));
212 assert_ne!(to_bob, shielded_contact_index(&[9; 32], &OWNER, &BOB, 7));
213 assert_eq!(to_bob, shielded_contact_index(&key, &OWNER, &BOB, 7));
215 }
216
217 #[test]
218 fn should_keep_profile_and_wallet_indices_out_of_the_contact_range() {
219 assert!(!is_shielded_contact_index(&[0; 11]));
220 assert!(!is_shielded_contact_index(&hex("ffffffff00000000000000")));
223 assert!(!is_shielded_contact_index(&hex("ffffffffffffffffffff7f")));
224 assert!(is_shielded_contact_index(&hex("0000000000000000000080")));
226 }
227
228 #[test]
229 fn should_encrypt_an_address_to_the_64_byte_field() {
230 let shared_key: [u8; 32] = core::array::from_fn(|i| i as u8);
231 let iv: [u8; 16] = core::array::from_fn(|i| 0xa0 + i as u8);
232 let field = encrypt_shielded_address(&shared_key, &iv, &hex(BOB_ADDRESS));
233 assert_eq!(
234 field,
235 hex::<64>(
236 "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb00fd785cffaf9bd43b25189363352d5\
237 4462f4fc18e0ca7108e1effc6d615026025a763f29384d39e5b0c29020d62e97"
238 )
239 );
240 assert_eq!(
241 decrypt_shielded_address(&shared_key, &field).expect("the field decrypts"),
242 hex::<43>(BOB_ADDRESS)
243 );
244 }
245
246 #[test]
247 fn should_refuse_a_field_of_any_other_length() {
248 let shared_key = [1u8; 32];
249 let field = encrypt_shielded_address(&shared_key, &[2; 16], &[3; 43]);
250 for length in [0, 15, 16, 48, 63, 65, 80] {
251 let mut other = field.to_vec();
252 other.resize(length, 0);
253 assert!(
254 matches!(
255 decrypt_shielded_address(&shared_key, &other),
256 Err(CryptoError::InvalidEncryptedShieldedAddressLength(l)) if l == length
257 ),
258 "a field of {length} bytes"
259 );
260 }
261 }
262
263 #[test]
264 fn should_refuse_a_plaintext_that_is_not_43_bytes() {
265 let shared_key = [1u8; 32];
266 let iv = [2u8; 16];
267 for length in [33, 42, 44, 47] {
269 let mut field = iv.to_vec();
270 field.extend(encrypt_aes_256_cbc(&shared_key, &iv, &vec![3; length]));
271 assert_eq!(field.len(), ENCRYPTED_SHIELDED_ADDRESS_LEN);
272 assert!(
273 matches!(
274 decrypt_shielded_address(&shared_key, &field),
275 Err(CryptoError::InvalidShieldedAddressLength(l)) if l == length
276 ),
277 "a plaintext of {length} bytes"
278 );
279 }
280 }
281
282 #[test]
283 fn should_refuse_a_field_whose_padding_does_not_decrypt() {
284 let field = encrypt_shielded_address(&[1; 32], &[2; 16], &[3; 43]);
285 assert!(matches!(
288 decrypt_shielded_address(&[4; 32], &field),
289 Err(CryptoError::DecryptionFailed)
290 ));
291 }
292}