Skip to main content

platform_encryption/
account_label.rs

1//! DIP-15 DashPay `encryptedAccountLabel` encryption.
2
3use crate::aes::{decrypt_aes_256_cbc, encrypt_aes_256_cbc};
4use crate::error::CryptoError;
5
6/// Minimum label length in characters before encryption. DIP-15 fixes
7/// `encryptedAccountLabel` at ≥48 bytes (16-byte IV + ≥32-byte AES-CBC
8/// ciphertext); a plaintext shorter than 16 bytes encrypts to a single 16-byte
9/// block (48 bytes total only at exactly 16). kotlin/dashj pad the label to
10/// ≥16 chars with trailing spaces so even a short or empty label clears the
11/// floor, and strip the padding on read. Matching this is required for a valid
12/// document and for cross-client interop. (≥16 chars ⟹ ≥16 bytes, since each
13/// char is ≥1 byte, so this guarantees the ciphertext clears 48 bytes.)
14const ACCOUNT_LABEL_MIN_CHARS: usize = 16;
15
16/// Maximum plaintext length in bytes after padding. DIP-15 caps
17/// `encryptedAccountLabel` at 80 bytes (16-byte IV + ≤64-byte ciphertext); via
18/// PKCS7, ≤64 ciphertext bytes means ≤63 plaintext bytes. A longer label is
19/// truncated (on a char boundary) so no host-supplied string — however long —
20/// can push the ciphertext past the contract's cap and error the broadcast.
21/// kotlin/dashj likewise bound the label.
22const ACCOUNT_LABEL_MAX_BYTES: usize = 63;
23
24/// Normalize `label` to the DIP-15 plaintext bounds: pad to
25/// ≥[`ACCOUNT_LABEL_MIN_CHARS`] chars with trailing spaces (the floor; ≥16
26/// chars ⟹ ≥16 bytes), then truncate to ≤[`ACCOUNT_LABEL_MAX_BYTES`] bytes on a
27/// char boundary (the ceiling). The result is always 16..=63 plaintext bytes,
28/// so the encrypted field is always 48..=80 bytes for any input. Mirrors
29/// kotlin's `padEnd(16, ' ')` plus a length cap.
30fn fit_account_label(label: &str) -> String {
31    // Floor: pad short labels to ≥16 chars.
32    let deficit = ACCOUNT_LABEL_MIN_CHARS.saturating_sub(label.chars().count());
33    let mut padded = if deficit == 0 {
34        label.to_string()
35    } else {
36        let mut s = String::with_capacity(label.len() + deficit);
37        s.push_str(label);
38        s.extend(std::iter::repeat_n(' ', deficit));
39        s
40    };
41
42    // Ceiling: truncate long labels to ≤63 bytes on a char boundary. (Padding
43    // only ever reaches 16 chars ≤ 63 bytes, so truncation only fires on a
44    // genuinely long input, and the truncated prefix is still ≥16 bytes.)
45    padded.truncate(padded.floor_char_boundary(ACCOUNT_LABEL_MAX_BYTES));
46    padded
47}
48
49/// Encrypt an account label for DashPay (DIP-15)
50///
51/// The label is normalized to the DIP-15 plaintext bounds before encryption
52/// (see [`fit_account_label`]): short labels are space-padded so the output
53/// clears the 48-byte floor, and over-long labels are truncated so it never
54/// exceeds the 80-byte cap. The output is therefore always a valid
55/// `encryptedAccountLabel` for any input. [`decrypt_account_label`] strips the
56/// padding.
57///
58/// # Arguments
59/// * `shared_key` - 32-byte shared secret from ECDH
60/// * `iv` - 16-byte initialization vector (must be randomly generated, different from xpub IV)
61/// * `label` - Account label string to encrypt
62///
63/// # Returns
64/// Encrypted label with IV prepended (48-80 bytes: 16-byte IV + 32-64 byte encrypted data)
65pub fn encrypt_account_label(shared_key: &[u8; 32], iv: &[u8; 16], label: &str) -> Vec<u8> {
66    let fitted = fit_account_label(label);
67    let encrypted_data = encrypt_aes_256_cbc(shared_key, iv, fitted.as_bytes());
68
69    // Prepend IV to encrypted data as per DIP-15
70    let mut result = Vec::with_capacity(16 + encrypted_data.len());
71    result.extend_from_slice(iv);
72    result.extend_from_slice(&encrypted_data);
73    result
74}
75
76/// Decrypt an account label from DashPay (DIP-15)
77///
78/// Trailing spaces — the padding [`encrypt_account_label`] adds to clear the
79/// 48-byte floor — are stripped, recovering the original label. (A label that
80/// intentionally ended in spaces cannot round-trip those spaces; this is
81/// inherent to the DIP-15 space-padding convention and matches kotlin/dashj.)
82///
83/// # Arguments
84/// * `shared_key` - 32-byte shared secret from ECDH
85/// * `encrypted_data` - Encrypted label with IV prepended (48-80 bytes total)
86///
87/// # Returns
88/// Decrypted label string
89pub fn decrypt_account_label(
90    shared_key: &[u8; 32],
91    encrypted_data: &[u8],
92) -> Result<String, CryptoError> {
93    if encrypted_data.len() < 16 {
94        return Err(CryptoError::InvalidCiphertextLength);
95    }
96
97    // Extract IV from first 16 bytes
98    let iv: [u8; 16] = encrypted_data[..16].try_into().unwrap();
99    let ciphertext = &encrypted_data[16..];
100
101    let decrypted = decrypt_aes_256_cbc(shared_key, &iv, ciphertext)?;
102    let label = String::from_utf8(decrypted).map_err(|_| CryptoError::InvalidUtf8)?;
103    Ok(label.trim_end_matches(' ').to_string())
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::ecdh::derive_shared_key_ecdh;
110    use secp256k1::generate_keypair;
111    use secp256k1::rand::rngs::StdRng;
112    use secp256k1::rand::{RngCore, SeedableRng};
113
114    #[test]
115    fn test_account_label_encryption() {
116        let mut rng = StdRng::seed_from_u64(4);
117        let (secret1, _public1) = generate_keypair(&mut rng);
118        let (_secret2, public2) = generate_keypair(&mut rng);
119
120        // Derive shared key
121        let shared_key = derive_shared_key_ecdh(&secret1, &public2);
122
123        // Generate random IV
124        let mut iv = [0u8; 16];
125        rng.fill_bytes(&mut iv);
126
127        let label = "My DashPay Account";
128
129        // Encrypt and decrypt
130        let encrypted = encrypt_account_label(&shared_key, &iv, label);
131
132        // Verify size is in valid range: 48-80 bytes (16-byte IV + 32-64 bytes encrypted)
133        assert!(
134            encrypted.len() >= 48 && encrypted.len() <= 80,
135            "Encrypted label should be 48-80 bytes, got {}",
136            encrypted.len()
137        );
138
139        let decrypted = decrypt_account_label(&shared_key, &encrypted).unwrap();
140
141        assert_eq!(label, decrypted);
142    }
143
144    /// DIP-15 fixes `encryptedAccountLabel` at 48..=80 bytes, and the primitive
145    /// must produce a valid field for ANY input. Short/empty/multi-byte labels
146    /// are padded to clear the 48-byte floor and round-trip exactly (padding
147    /// stripped on decrypt); the exactly-16-char case sits on the lower edge;
148    /// over-long labels are truncated to stay under the 80-byte cap (and so do
149    /// not round-trip in full — the documented trade-off). The original bug:
150    /// a <16-char label produced a 32-byte blob and a ≥64-byte label a 96-byte
151    /// blob, either of which the contract rejects and fails the broadcast.
152    #[test]
153    fn account_label_is_always_a_valid_48_to_80_byte_field() {
154        let key = [0x42u8; 32];
155        let iv = [0x11u8; 16];
156
157        // Floor + exact round-trip for short / empty / multi-byte labels.
158        for label in ["", "hi", "lunch fund", "café ☕", "🍕🍕🍕"] {
159            let blob = encrypt_account_label(&key, &iv, label);
160            assert!(
161                (48..=80).contains(&blob.len()),
162                "label {label:?} -> {} bytes, expected 48..=80",
163                blob.len()
164            );
165            assert_eq!(decrypt_account_label(&key, &blob).unwrap(), label);
166        }
167
168        // Lower boundary: exactly 16 ASCII chars = 16 bytes -> 32 ciphertext + 16
169        // IV = exactly 48.
170        assert_eq!(
171            encrypt_account_label(&key, &iv, "sixteen-chars-16").len(),
172            48
173        );
174
175        // Ceiling: an over-long label (ASCII and multi-byte) must never exceed 80.
176        assert!(encrypt_account_label(&key, &iv, &"x".repeat(500)).len() <= 80);
177        assert!(encrypt_account_label(&key, &iv, &"🍕".repeat(50)).len() <= 80);
178    }
179}