Skip to main content

platform_encryption/
compact_xpub.rs

1//! DIP-15 compact extended public key (`encryptedPublicKey`) — the 69-byte
2//! compact plaintext, its parse/serialize, and its AES-256-CBC encryption.
3
4use crate::aes::{decrypt_aes_256_cbc, encrypt_aes_256_cbc};
5use crate::error::CryptoError;
6
7/// Length of the DIP-15 compact extended-public-key plaintext, in bytes.
8///
9/// `parentFingerprint(4) ‖ chainCode(32) ‖ publicKey(33)` = 69 bytes. This is
10/// the plaintext layout DIP-15 specifies for `encryptedPublicKey` and the form
11/// both reference clients (iOS dash-shared-core, Android dashj) emit and
12/// hard-check on receive. Encrypting exactly 69 bytes yields a 96-byte
13/// ciphertext (16-byte IV + 80-byte AES-256-CBC/PKCS7 block), matching the
14/// deployed contract's `minItems/maxItems: 96`.
15pub const COMPACT_XPUB_LEN: usize = 69;
16
17/// Encrypt an extended public key for DashPay contact requests (DIP-15)
18///
19/// # Arguments
20/// * `shared_key` - 32-byte shared secret from ECDH
21/// * `iv` - 16-byte initialization vector (must be randomly generated)
22/// * `xpub` - Extended public key bytes to encrypt
23///
24/// # Returns
25/// Encrypted extended public key with IV prepended (96 bytes: 16-byte IV + 80-byte encrypted data)
26pub fn encrypt_extended_public_key(shared_key: &[u8; 32], iv: &[u8; 16], xpub: &[u8]) -> Vec<u8> {
27    let encrypted_data = encrypt_aes_256_cbc(shared_key, iv, xpub);
28
29    // Prepend IV to encrypted data as per DIP-15
30    let mut result = Vec::with_capacity(16 + encrypted_data.len());
31    result.extend_from_slice(iv);
32    result.extend_from_slice(&encrypted_data);
33    result
34}
35
36/// Decrypt an extended public key from DashPay contact requests (DIP-15)
37///
38/// # Arguments
39/// * `shared_key` - 32-byte shared secret from ECDH
40/// * `encrypted_data` - Encrypted extended public key with IV prepended (96 bytes total)
41///
42/// # Returns
43/// Decrypted extended public key bytes
44pub fn decrypt_extended_public_key(
45    shared_key: &[u8; 32],
46    encrypted_data: &[u8],
47) -> Result<Vec<u8>, CryptoError> {
48    if encrypted_data.len() < 16 {
49        return Err(CryptoError::InvalidCiphertextLength);
50    }
51
52    // Extract IV from first 16 bytes
53    let iv: [u8; 16] = encrypted_data[..16].try_into().unwrap();
54    let ciphertext = &encrypted_data[16..];
55
56    decrypt_aes_256_cbc(shared_key, &iv, ciphertext)
57}
58
59/// The three components of a DIP-15 compact extended public key.
60///
61/// `parent_fingerprint ‖ chain_code ‖ public_key` is the 69-byte compact
62/// form DIP-15 defines for `encryptedPublicKey`. A named struct (rather
63/// than a `([u8; 4], [u8; 32], [u8; 33])` tuple) keeps the component
64/// meaning explicit at every call site — the three byte arrays are
65/// otherwise easy to mis-read.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct CompactXpub {
68    /// 4-byte fingerprint of the parent key.
69    pub parent_fingerprint: [u8; 4],
70    /// 32-byte chain code of the shared (account) key.
71    pub chain_code: [u8; 32],
72    /// 33-byte compressed secp256k1 public key.
73    pub public_key: [u8; 33],
74}
75
76impl CompactXpub {
77    /// Serialize to the 69-byte DIP-15 compact plaintext
78    /// (`parent_fingerprint ‖ chain_code ‖ public_key`). This is the
79    /// plaintext fed to [`encrypt_extended_public_key`] — *not* a
80    /// BIP32/DIP-14 serialization, which carries extra
81    /// version/depth/child-number metadata the wire format omits.
82    pub fn to_bytes(&self) -> [u8; COMPACT_XPUB_LEN] {
83        let mut out = [0u8; COMPACT_XPUB_LEN];
84        out[0..4].copy_from_slice(&self.parent_fingerprint);
85        out[4..36].copy_from_slice(&self.chain_code);
86        out[36..69].copy_from_slice(&self.public_key);
87        out
88    }
89}
90
91/// Assemble the DIP-15 compact extended-public-key plaintext from its
92/// three components. Thin wrapper over [`CompactXpub::to_bytes`] kept for
93/// call sites that have the components loose rather than in a struct.
94pub fn compact_xpub_bytes(
95    parent_fingerprint: [u8; 4],
96    chain_code: [u8; 32],
97    public_key: [u8; 33],
98) -> [u8; COMPACT_XPUB_LEN] {
99    CompactXpub {
100        parent_fingerprint,
101        chain_code,
102        public_key,
103    }
104    .to_bytes()
105}
106
107/// Parse a DIP-15 compact extended-public-key plaintext into a
108/// [`CompactXpub`].
109///
110/// Inverse of [`CompactXpub::to_bytes`] / [`compact_xpub_bytes`]. Rejects
111/// any input whose length is not exactly [`COMPACT_XPUB_LEN`] (69) bytes —
112/// the reference clients hard-check this on receive, so a non-69-byte
113/// payload is not a valid DIP-15 compact xpub and must be handled
114/// separately (e.g. a legacy 78/107-byte BIP32/DIP-14 serialization) by
115/// the caller.
116///
117/// # Errors
118/// [`CryptoError::InvalidCompactXpubLength`] if `bytes.len() != 69`.
119pub fn parse_compact_xpub(bytes: &[u8]) -> Result<CompactXpub, CryptoError> {
120    if bytes.len() != COMPACT_XPUB_LEN {
121        return Err(CryptoError::InvalidCompactXpubLength(bytes.len()));
122    }
123
124    let mut parent_fingerprint = [0u8; 4];
125    let mut chain_code = [0u8; 32];
126    let mut public_key = [0u8; 33];
127    parent_fingerprint.copy_from_slice(&bytes[0..4]);
128    chain_code.copy_from_slice(&bytes[4..36]);
129    public_key.copy_from_slice(&bytes[36..69]);
130
131    Ok(CompactXpub {
132        parent_fingerprint,
133        chain_code,
134        public_key,
135    })
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use crate::ecdh::derive_shared_key_ecdh;
142    use secp256k1::generate_keypair;
143    use secp256k1::rand::rngs::StdRng;
144    use secp256k1::rand::{RngCore, SeedableRng};
145
146    #[test]
147    fn test_extended_public_key_encryption() {
148        let mut rng = StdRng::seed_from_u64(3);
149        let (secret1, _public1) = generate_keypair(&mut rng);
150        let (_secret2, public2) = generate_keypair(&mut rng);
151
152        // Derive shared key
153        let shared_key = derive_shared_key_ecdh(&secret1, &public2);
154
155        // Generate random IV
156        let mut iv = [0u8; 16];
157        rng.fill_bytes(&mut iv);
158
159        // DIP-15 compact xpub plaintext (69 bytes). 69 → PKCS7 → 80, + 16-byte
160        // IV = exactly 96 bytes, matching the contract's minItems/maxItems: 96.
161        let xpub_data = vec![0x04; COMPACT_XPUB_LEN];
162
163        // Encrypt and decrypt
164        let encrypted = encrypt_extended_public_key(&shared_key, &iv, &xpub_data);
165
166        // Verify size: 16 bytes (IV) + 80 bytes (encrypted data) = 96 bytes
167        assert_eq!(encrypted.len(), 96, "Encrypted xpub should be 96 bytes");
168
169        let decrypted = decrypt_extended_public_key(&shared_key, &encrypted).unwrap();
170
171        assert_eq!(xpub_data, decrypted);
172    }
173
174    #[test]
175    fn test_compact_xpub_round_trip() {
176        // Distinct byte patterns per field so a mis-sliced offset is caught.
177        let parent_fingerprint = [0x11u8, 0x22, 0x33, 0x44];
178        let chain_code = [0xAAu8; 32];
179        let mut pubkey = [0xBBu8; 33];
180        pubkey[0] = 0x02; // compressed-pubkey prefix
181
182        let compact = compact_xpub_bytes(parent_fingerprint, chain_code, pubkey);
183        assert_eq!(compact.len(), COMPACT_XPUB_LEN);
184        assert_eq!(compact.len(), 69);
185
186        // Byte-exact layout: fingerprint ‖ chaincode ‖ pubkey.
187        assert_eq!(&compact[0..4], &parent_fingerprint);
188        assert_eq!(&compact[4..36], &chain_code);
189        assert_eq!(&compact[36..69], &pubkey);
190
191        let parsed = parse_compact_xpub(&compact).expect("parse 69-byte compact");
192        assert_eq!(parsed.parent_fingerprint, parent_fingerprint);
193        assert_eq!(parsed.chain_code, chain_code);
194        assert_eq!(parsed.public_key, pubkey);
195        // Struct round-trips back to the same bytes.
196        assert_eq!(parsed.to_bytes(), compact);
197    }
198
199    #[test]
200    fn test_encrypt_compact_xpub_is_exactly_96_bytes() {
201        // The whole point of the 69-byte compact form: it encrypts to exactly
202        // 96 bytes (16-byte IV + 80-byte AES-256-CBC/PKCS7), which is what the
203        // deployed contract enforces. A 107-byte DIP-14 serialization would
204        // yield 128 bytes and fail the contract's maxItems: 96.
205        let shared_key = [0x07u8; 32];
206        let iv = [0x09u8; 16];
207        let plaintext = [0xCDu8; COMPACT_XPUB_LEN];
208
209        let encrypted = encrypt_extended_public_key(&shared_key, &iv, &plaintext);
210        assert_eq!(
211            encrypted.len(),
212            96,
213            "69-byte compact plaintext must encrypt to exactly 96 bytes"
214        );
215
216        let decrypted = decrypt_extended_public_key(&shared_key, &encrypted).unwrap();
217        assert_eq!(&decrypted[..], &plaintext[..]);
218    }
219
220    #[test]
221    fn test_parse_compact_xpub_rejects_wrong_length() {
222        // Lengths that are NOT 69 must be rejected — including the legacy 78/107
223        // BIP32/DIP-14 serializations and the empty case.
224        for bad_len in [0usize, 36, 68, 70, 78, 107, 128] {
225            let bytes = vec![0u8; bad_len];
226            let err = parse_compact_xpub(&bytes).expect_err("non-69-byte input must be rejected");
227            assert!(
228                matches!(err, CryptoError::InvalidCompactXpubLength(n) if n == bad_len),
229                "expected InvalidCompactXpubLength({}), got {:?}",
230                bad_len,
231                err
232            );
233        }
234    }
235}