Skip to main content

platform_encryption/
shielded_address.rs

1//! The per-contact shielded payment address of a DashPay contact request: the
2//! diversifier index a wallet derives it at, and the field that carries it.
3//!
4//! A DashPay identity gives every contact a different shielded payment address, each
5//! a diversified address of the identity's shielded account, so a payment that
6//! arrives on one is attributed to the contact it was given to. The address is never
7//! allocated or stored. Its diversifier index is a keyed hash of the contact request's
8//! unique key (`$ownerId`, `toUserId`, `accountReference`), under a key derived from
9//! the account's full viewing key. Two devices restored from one seed derive the same
10//! address for the same request, with no state to keep in step or to lose. Two
11//! requests get the same address only if their indices collide in the 87 bits the
12//! hash leaves free, which is negligible, and the sender checks for it before sending
13//! (see [`shielded_contact_index`]). A counter cannot give that: two devices would
14//! hand the same index to different contacts as a matter of course.
15//!
16//! This module holds what needs no shielded pool types: the index and the encoding of
17//! `encryptedShieldedAddress`. The wallet turns an index into an address with the
18//! account's full viewing key, and checks that a decrypted value is an address.
19
20use crate::aes::{decrypt_aes_256_cbc, encrypt_aes_256_cbc};
21use crate::error::CryptoError;
22use hmac::{Hmac, Mac};
23use sha2::Sha256;
24
25/// A raw shielded payment address: an 11-byte diversifier followed by a 32-byte
26/// diversified transmission key.
27pub const SHIELDED_ADDRESS_LEN: usize = 43;
28
29/// `encryptedShieldedAddress` as this module writes it: a 16-byte IV followed by the
30/// three AES blocks a 43-byte address pads to. The contract also admits 80 bytes,
31/// kept for a later encoding, which [`decrypt_shielded_address`] refuses.
32pub const ENCRYPTED_SHIELDED_ADDRESS_LEN: usize = 64;
33
34/// A raw full viewing key of a shielded account: `ak || nk || rivk`.
35pub const SHIELDED_FULL_VIEWING_KEY_LEN: usize = 96;
36
37/// A diversifier index: an 88-bit little-endian integer.
38pub const SHIELDED_DIVERSIFIER_INDEX_LEN: usize = 11;
39
40/// The HMAC key that turns a full viewing key into a contact index key.
41const CONTACT_INDEX_KEY_LABEL: &[u8] = b"DashPay/shielded/contact-index-key/v1";
42
43/// What a contact index key hashes ahead of the contact request's unique key.
44const CONTACT_INDEX_LABEL: &[u8] = b"DashPay/shielded/contact-index/v1";
45
46/// Bit 87 of a diversifier index, in its last byte. Every per-contact index has it
47/// set, and no profile or wallet-local index does.
48const 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
59/// The key a shielded account derives its per-contact indices under:
60/// `HMAC-SHA256(key = "DashPay/shielded/contact-index-key/v1", msg = full viewing key)`.
61///
62/// It needs the full viewing key, so a holder of the account's incoming viewing key
63/// alone can see which index a payment arrived on but not which contact it belongs to.
64pub 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
70/// The diversifier index of the shielded address a contact request carries, from the
71/// request's unique key:
72///
73/// ```text
74/// t = HMAC-SHA256(key = index_key,
75///                 msg = "DashPay/shielded/contact-index/v1" || owner_id || to_user_id
76///                       || account_reference as u64 little-endian)
77/// j = t[0..11], with bit 87 set
78/// ```
79///
80/// `owner_id` is the identity that sends the request and owns the address, `to_user_id`
81/// the contact, and `account_reference` the value the request publishes, never one
82/// recomputed locally. The index always lies in the per-contact range, from 2^87.
83///
84/// Before sending, the caller compares the index with those it has given to other
85/// contacts and, on a match, sends the request under another `account_reference`.
86pub 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
107/// Whether a diversifier index lies in the per-contact range (2^87 and above), where
108/// only [`shielded_contact_index`] places addresses. An index below it is a profile
109/// address or one the wallet uses for itself, never one given to a contact.
110pub 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
114/// Encrypt a shielded payment address as a contact request's
115/// `encryptedShieldedAddress`: the IV, then the address under AES-256-CBC with the
116/// request's DIP-15 shared key, the key that encrypts its `encryptedPublicKey`.
117///
118/// `iv` is drawn at random for this field alone: no two fields of a request share one.
119pub 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
131/// Decrypt a contact request's `encryptedShieldedAddress` to the 43 bytes it carries.
132///
133/// A value of any length but 64 is refused, the 80 bytes the contract keeps for a later
134/// encoding included, and so is one whose plaintext is not exactly 43 bytes. CBC does
135/// not authenticate, so a value decrypted under the wrong key can still pass: the caller
136/// uses the result only if the same key decrypts the request's `encryptedPublicKey` to a
137/// well-formed key and the bytes are a valid address that is neither its own nor the
138/// sender's profile address.
139pub 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    // The vectors of the DashPay shielded payment addresses DIP: mnemonic "abandon ...
169    // about", mainnet, the shielded account of identity index 0 (account 0x40000000).
170    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            // Bit 87 is clear in the hash here (its eleventh byte is 0x14) and is set.
195            (CAROL, 0x0123_4567, "a5ca8646a33e3db572ca94"),
196            // The same contact under the next DIP-15 version: another address.
197            (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        // The inputs alone decide it.
214        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        // 2^32 - 1, an index a wallet may use for itself, and 2^87 - 1, the last below the
221        // range.
222        assert!(!is_shielded_contact_index(&hex("ffffffff00000000000000")));
223        assert!(!is_shielded_contact_index(&hex("ffffffffffffffffffff7f")));
224        // 2^87, the first per-contact index.
225        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        // 33 to 47 bytes all pad to three blocks, so the field length cannot tell them apart.
268        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        // Under another key the last block almost never ends in valid padding; this one
286        // does not.
287        assert!(matches!(
288            decrypt_shielded_address(&[4; 32], &field),
289            Err(CryptoError::DecryptionFailed)
290        ));
291    }
292}