Skip to main content

platform_encryption/
account_reference.rs

1//! DIP-15 `accountReference` (masked account index).
2
3/// Bit position of the rotation `version` in a masked `accountReference`:
4/// the top 4 bits carry the version, the low 28 bits the masked account index.
5pub const ACCOUNT_REFERENCE_VERSION_SHIFT: u32 = 28;
6
7/// Mask selecting the low 28 bits (the masked account index) of an
8/// `accountReference`; the complement of the version bits.
9const ACCOUNT_INDEX_MASK: u32 = (1 << ACCOUNT_REFERENCE_VERSION_SHIFT) - 1;
10
11/// Rotation `version` of a masked `accountReference`. Unlike
12/// [`unmask_account_reference`] it needs no secret: the version bits are not
13/// masked, so any party can tell whether a request is a re-key (`version > 0`).
14pub const fn account_reference_version(account_reference: u32) -> u32 {
15    account_reference >> ACCOUNT_REFERENCE_VERSION_SHIFT
16}
17
18/// `ASK28 = (HMAC-SHA256(sender_secret_key, compact_xpub))[28..32] big-endian >> 4`.
19///
20/// HMAC input is the 69-byte DIP-15 compact form (the `encryptedPublicKey`
21/// plaintext). The ASK28 byte order matches iOS dash-shared-core
22/// (`be(ASK[28..32]) >> 4`); see [`extract_ask28`] for the full four-convention
23/// split (Android, dash-evo-tool, and the DIP literal all differ). Since
24/// `accountReference` is a one-time-pad obfuscation that recipients ignore (only
25/// the original sender un-masks it on re-send), every convention round-trips for
26/// its own sender; we match iOS so our sent requests are bit-identical to the
27/// incumbent wallet's.
28fn account_secret_key_28(sender_secret_key: &[u8; 32], compact_xpub: &[u8]) -> u32 {
29    use hmac::{Hmac, Mac};
30    use sha2::Sha256;
31    let mut mac = Hmac::<Sha256>::new_from_slice(sender_secret_key)
32        .expect("HMAC accepts a key of any length");
33    mac.update(compact_xpub);
34    let mut ask = [0u8; 32];
35    ask.copy_from_slice(&mac.finalize().into_bytes());
36    extract_ask28(&ask)
37}
38
39/// Extract `ASK28` from the 32-byte HMAC digest using the iOS dash-shared-core
40/// convention: `be(ASK[28..32]) >> 4`. DIP-15 leaves the extraction ambiguous
41/// ("28 most significant bits of ASK"); four readings exist in the wild and
42/// give different values, but since the field is a sender-private one-time pad
43/// there is no on-chain interop failure — we lock to iOS (the most-deployed
44/// DashPay wallet) for bit-identical sent requests.
45fn extract_ask28(ask_bytes: &[u8; 32]) -> u32 {
46    u32::from_be_bytes([ask_bytes[28], ask_bytes[29], ask_bytes[30], ask_bytes[31]]) >> 4
47}
48
49/// Calculate the masked DIP-15 `accountReference`:
50/// `result = (version << 28) | (ASK28 ^ (account_index & 0x0FFF_FFFF))`.
51///
52/// Top 4 bits carry the rotation `version` (bumped on each friendship re-key);
53/// the low 28 bits are the account index masked by a PRF of the contact xpub so
54/// observers can't correlate accounts across requests. Keyed by the sender's
55/// 32-byte ECDH private key (the same key that encrypts the xpub).
56pub fn calculate_account_reference(
57    sender_secret_key: &[u8; 32],
58    compact_xpub: &[u8],
59    account_index: u32,
60    version: u32,
61) -> u32 {
62    let ask28 = account_secret_key_28(sender_secret_key, compact_xpub);
63    let shortened_account_bits = account_index & ACCOUNT_INDEX_MASK;
64    let version_bits = version << ACCOUNT_REFERENCE_VERSION_SHIFT;
65    version_bits | (ask28 ^ shortened_account_bits)
66}
67
68/// Recover `(version, account_index)` from a masked `accountReference`. Inverse
69/// of [`calculate_account_reference`] for the same `(sender_secret_key,
70/// compact_xpub)` — only the original sender can un-mask (the PRF key is their
71/// ECDH private key). Used on re-send to read the previous rotation version.
72pub fn unmask_account_reference(
73    account_reference: u32,
74    sender_secret_key: &[u8; 32],
75    compact_xpub: &[u8],
76) -> (u32, u32) {
77    let ask28 = account_secret_key_28(sender_secret_key, compact_xpub);
78    let version = account_reference_version(account_reference);
79    let account_index = (account_reference & ACCOUNT_INDEX_MASK) ^ ask28;
80    (version, account_index)
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    /// Deterministic 69-byte compact xpub fixture for the account-reference
88    /// tests (the helper only HMACs the bytes, so a synthetic buffer of the
89    /// right length keeps the vectors stable).
90    fn test_compact_xpub() -> [u8; 69] {
91        std::array::from_fn(|i| i as u8)
92    }
93
94    #[test]
95    fn account_reference_version_bits() {
96        let secret_key = [1u8; 32];
97        let compact = test_compact_xpub();
98        assert_eq!(
99            account_reference_version(calculate_account_reference(&secret_key, &compact, 0, 0)),
100            0
101        );
102        assert_eq!(
103            account_reference_version(calculate_account_reference(&secret_key, &compact, 0, 1)),
104            1
105        );
106        assert_eq!(
107            account_reference_version(calculate_account_reference(&secret_key, &compact, 0, 15)),
108            15
109        );
110    }
111
112    #[test]
113    fn account_reference_deterministic() {
114        let secret_key = [0xABu8; 32];
115        let compact = test_compact_xpub();
116        assert_eq!(
117            calculate_account_reference(&secret_key, &compact, 0, 0),
118            calculate_account_reference(&secret_key, &compact, 0, 0),
119            "same inputs → same account reference"
120        );
121    }
122
123    /// ASK28 must come from HMAC digest bytes `[28..32]` big-endian `>> 4` (iOS
124    /// dash-shared-core) — not the head-of-digest reading (the old bug).
125    #[test]
126    fn account_reference_ask28_uses_digest_tail_big_endian() {
127        use hmac::{Hmac, Mac};
128        use sha2::Sha256;
129        let secret_key = [0x42u8; 32];
130        let compact = test_compact_xpub();
131
132        let mut mac = Hmac::<Sha256>::new_from_slice(&secret_key).expect("hmac key");
133        mac.update(&compact);
134        let mut digest = [0u8; 32];
135        digest.copy_from_slice(&mac.finalize().into_bytes());
136        let expected_ask28 =
137            u32::from_be_bytes([digest[28], digest[29], digest[30], digest[31]]) >> 4;
138
139        let reference = calculate_account_reference(&secret_key, &compact, 0, 0);
140        assert_eq!(
141            reference & ACCOUNT_INDEX_MASK,
142            expected_ask28,
143            "ASK28 must be digest bytes [28..32] big-endian >> 4 (iOS dash-shared-core)"
144        );
145        let old_ask28 = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]) >> 4;
146        assert_ne!(
147            reference & ACCOUNT_INDEX_MASK,
148            old_ask28,
149            "head-of-digest extraction is the old bug"
150        );
151    }
152
153    /// Mask → unmask round-trips `(version, account_index)` for the sender.
154    #[test]
155    fn account_reference_round_trips_version_and_account() {
156        let secret_key = [0x07u8; 32];
157        let compact = test_compact_xpub();
158        for version in [0u32, 1, 7, 15] {
159            for account in [0u32, 1, 5, 0x0FFF_FFFF] {
160                let reference =
161                    calculate_account_reference(&secret_key, &compact, account, version);
162                let (got_version, got_account) =
163                    unmask_account_reference(reference, &secret_key, &compact);
164                assert_eq!(got_version, version, "version round-trip");
165                assert_eq!(got_account, account, "account round-trip");
166            }
167        }
168        let reference = calculate_account_reference(&secret_key, &compact, 5, 0);
169        let (_, wrong) = unmask_account_reference(reference, &[0x08u8; 32], &compact);
170        assert_ne!(wrong, 5, "a different PRF key must not unmask the account");
171    }
172
173    /// Known-answer pin for the ASK28 extraction conventions (iOS vs the others).
174    #[test]
175    fn ask28_extraction_matches_ios_and_diverges_from_others() {
176        let ask: [u8; 32] = std::array::from_fn(|i| i as u8);
177        assert_eq!(
178            extract_ask28(&ask),
179            0x01c1_d1e1,
180            "iOS dash-shared-core: be(ASK[28..32])>>4"
181        );
182        let android = u32::from_le_bytes([ask[0], ask[1], ask[2], ask[3]]) >> 4;
183        let dip_literal = u32::from_be_bytes([ask[0], ask[1], ask[2], ask[3]]) >> 4;
184        assert_eq!(android, 0x0030_2010, "kotlin-platform: le(ASK[0..4])>>4");
185        assert_eq!(
186            dip_literal, 0x0000_1020,
187            "dash-evo-tool / DIP literal: be(ASK[0..4])>>4"
188        );
189        assert_ne!(extract_ask28(&ask), android);
190        assert_ne!(extract_ask28(&ask), dip_literal);
191    }
192}