Skip to main content

platform_encryption/
private_document_envelope.rs

1//! The standard private document envelope, version 1.
2//!
3//! A private document type (protocol version 15) stores fixed-size entries that Platform never
4//! reads. Clients fill each one with this envelope: a payload encrypted to one recipient key,
5//! which the recipient finds by trying to open every entry of the type, and which the sender can
6//! recover later from its outgoing viewing key alone. An entry of `entry_size` bytes is
7//!
8//! ```text
9//! cm (32) | epk (33) | body_ct (B + 16) | out_ct (81)        B = entry_size - 162
10//! ```
11//!
12//! derived from a fresh 32-byte `esk_seed`, the recipient's secp256k1 key `R` and the sender's
13//! outgoing viewing key `ovk` (`H` is SHA-256, `ser` a compressed point, `||` concatenation):
14//!
15//! ```text
16//! esk     = H("Dash/PrivDoc/v1/esk" || esk_seed), refused if not a valid secret key
17//! epk     = esk * G
18//! key     = H("Dash/PrivDoc/v1/key" || ser(esk * R) || ser(epk) || ser(R))
19//! cm      = H("Dash/PrivDoc/v1/cm" || key || contract_id || u32le(len(type)) || type || ser(R)
20//!             || body)
21//! body_ct = ChaCha20-Poly1305(key, nonce 0, aad cm, body)
22//! ock     = H("Dash/PrivDoc/v1/ock" || ovk || ser(epk))
23//! out_ct  = ChaCha20-Poly1305(ock, nonce 0, aad cm, ser(R) || esk_seed)
24//! ```
25//!
26//! `cm` is keyed, so nobody without `key` can confirm a guess about an entry, and commits to
27//! `R`, so a ciphertext that would also open under another key is refused there. It commits to
28//! the contract and type too, so an entry copied into another type does not open. A zero nonce is
29//! safe because each key encrypts once: `esk_seed` must be fresh for every entry built.
30//!
31//! The body, `B` bytes, is
32//!
33//! ```text
34//! version (1) | auth mode (1) | sender identity id (32) | sender key id (u32le) | auth (65)
35//!   | recipient identity id (32) | payload length (u16le) | payload | zero padding
36//! ```
37//!
38//! and the authentication covers
39//!
40//! ```text
41//! m = H("Dash/PrivDoc/v1/auth" || version || auth mode || contract_id || u32le(len(type))
42//!       || type || sender identity id || sender key id || recipient identity id || ser(R)
43//!       || payload length || payload)
44//! ```
45//!
46//! `m` names the recipient key, so an entry re-encrypted to another key of the same identity
47//! carries no valid authentication.
48//!
49//! - anonymous (0): sender fields and `auth` are zeros;
50//! - deniable MAC (1): `auth` is
51//!   `HMAC-SHA256(H("Dash/PrivDoc/v1/mac" || ser(sender key * R)), m)`, then zeros. The
52//!   recipient learns who sent the entry but could have computed the MAC itself, so it cannot
53//!   prove it to anyone;
54//! - signature (2): `auth` is a recoverable ECDSA signature of `SHA-256(SHA-256(m))`, in the
55//!   compact form (header byte `31 + recovery id`, then `r || s`), which anyone who reads the
56//!   body can check. That is how a Dash identity signer signs the data `m`, so a wallet signs an
57//!   entry with the signer it signs transitions with. `m` is a 32-byte hash, which no
58//!   transition's signable bytes can be. The signing key is recovered from the signature. Which keys may sign, and what the sender key id names,
59//!   is the application's rule: the signer may be the named key, or another key of the sender
60//!   identity. DashPay contact requests name the sender's encryption key, which the pair's
61//!   shared key is derived from, and are signed by one of the sender's signing keys.
62//!
63//! Every auth mode sits inside the encrypted body: only the recipient, and the sender with its
64//! outgoing viewing key, see who wrote an entry or its signature.
65
66use chacha20poly1305::aead::{Aead, KeyInit, Payload};
67use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
68use hmac::{Hmac, Mac};
69use secp256k1::ecdh::shared_secret_point;
70use secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
71use secp256k1::{Message, PublicKey, SecretKey};
72use sha2::{Digest, Sha256};
73
74/// Why an entry could not be built, opened, recovered or checked.
75#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
76pub enum PrivateDocumentEnvelopeError {
77    #[error("a private document payload of {payload_len} bytes does not fit an entry that holds {capacity}")]
78    PayloadTooLarge { payload_len: usize, capacity: usize },
79
80    #[error("a private document entry of {0} bytes is shorter than the envelope's 299")]
81    InvalidEntryLength(usize),
82
83    #[error("the ephemeral seed derives no valid secret key; draw another")]
84    InvalidEphemeralSeed,
85
86    #[error("a private document ciphertext does not decrypt")]
87    DecryptionFailed,
88
89    #[error("malformed private document entry: {0}")]
90    Malformed(&'static str),
91
92    #[error("private document envelope version {0} is not supported")]
93    UnsupportedVersion(u8),
94
95    #[error("the private document entry names another recipient identity")]
96    WrongRecipient,
97
98    #[error("the private document entry is anonymous: it names no sender to check")]
99    AnonymousSender,
100
101    #[error("the private document entry's sender authentication does not verify")]
102    SenderNotAuthenticated,
103
104    #[error("a deniable MAC is checked with the recipient's secret key, and none was given")]
105    RecipientSecretKeyRequired,
106
107    #[error("the private document entry carries a deniable MAC, not a signature")]
108    NotSigned,
109}
110
111/// The envelope version this module builds and opens.
112pub const PRIVATE_DOCUMENT_ENVELOPE_VERSION: u8 = 1;
113
114const COMMITMENT_LEN: usize = 32;
115const EPHEMERAL_KEY_LEN: usize = 33;
116const TAG_LEN: usize = 16;
117const SENDER_RECOVERY_PLAINTEXT_LEN: usize = 33 + 32;
118const SENDER_RECOVERY_LEN: usize = SENDER_RECOVERY_PLAINTEXT_LEN + TAG_LEN;
119const AUTH_LEN: usize = 65;
120const MAC_LEN: usize = 32;
121
122/// The bytes around the encrypted body: the commitment, the ephemeral key, the body's tag and
123/// the sender-recovery ciphertext.
124pub const PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN: usize =
125    COMMITMENT_LEN + EPHEMERAL_KEY_LEN + TAG_LEN + SENDER_RECOVERY_LEN;
126
127/// The bytes of the body before the payload.
128pub const PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN: usize = 1 + 1 + 32 + 4 + AUTH_LEN + 32 + 2;
129
130/// Every byte of an entry besides its payload: 299. An entry holds a payload of at most its
131/// size minus this.
132pub const PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN: usize =
133    PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN + PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN;
134
135const DOMAIN_ESK: &[u8] = b"Dash/PrivDoc/v1/esk";
136const DOMAIN_KEY: &[u8] = b"Dash/PrivDoc/v1/key";
137const DOMAIN_CM: &[u8] = b"Dash/PrivDoc/v1/cm";
138const DOMAIN_OVK: &[u8] = b"Dash/PrivDoc/v1/ovk";
139const DOMAIN_OCK: &[u8] = b"Dash/PrivDoc/v1/ock";
140const DOMAIN_AUTH: &[u8] = b"Dash/PrivDoc/v1/auth";
141const DOMAIN_MAC: &[u8] = b"Dash/PrivDoc/v1/mac";
142
143/// The compact signature header of a compressed key: 27 + 4, plus the recovery id.
144const COMPACT_SIGNATURE_HEADER_BASE: u8 = 31;
145
146/// The private document type an entry belongs to. Both are bound into the commitment, so an
147/// entry opens only for the type it was built for.
148#[derive(Clone, Copy, Debug)]
149pub struct PrivateDocumentTarget<'a> {
150    pub contract_id: [u8; 32],
151    pub document_type_name: &'a str,
152}
153
154/// Whom an entry is for: the identity, written in the body so that an entry cannot be replayed
155/// to another identity holding the same key, and the key it is encrypted to. For DashPay, the
156/// recipient's DashPay decryption key.
157#[derive(Clone, Copy, Debug)]
158pub struct PrivateDocumentRecipient<'a> {
159    pub identity_id: [u8; 32],
160    pub public_key: &'a PublicKey,
161}
162
163/// How an entry tells its recipient who wrote it.
164#[derive(Clone, Copy, Debug)]
165pub enum PrivateDocumentSender<'a> {
166    /// Nobody: the recipient learns nothing of the writer.
167    Anonymous,
168    /// The sender's identity and key, with a MAC under the static ECDH of that key and the
169    /// recipient's. The recipient learns who wrote the entry, but could have computed the MAC
170    /// itself, so it cannot prove that to anyone. Anyone holding the recipient's key can compute
171    /// it as well, so a stolen recipient key forges entries from any sender.
172    DeniableMac {
173        identity_id: [u8; 32],
174        key_id: u32,
175        secret_key: &'a SecretKey,
176    },
177    /// The sender's identity and a key id, with a signature anyone who reads the body can
178    /// check: an identity signer's signature of [`private_document_signing_data`] for this
179    /// entry, or [`sign_private_document_signing_data`]'s. `key_id` names the signing key, or
180    /// another key of the sender identity when the application finds the signer with
181    /// [`OpenedPrivateDocumentEntry::recover_signer`]: DashPay names the sender's encryption key
182    /// and signs with one of its signing keys.
183    Signature {
184        identity_id: [u8; 32],
185        key_id: u32,
186        signature: &'a [u8; 65],
187    },
188}
189
190/// The authentication an opened entry carries.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum PrivateDocumentAuthMode {
193    Anonymous = 0,
194    DeniableMac = 1,
195    Signature = 2,
196}
197
198impl PrivateDocumentAuthMode {
199    fn from_byte(byte: u8) -> Option<Self> {
200        match byte {
201            0 => Some(Self::Anonymous),
202            1 => Some(Self::DeniableMac),
203            2 => Some(Self::Signature),
204            _ => None,
205        }
206    }
207}
208
209/// An entry its recipient opened, or its sender recovered.
210///
211/// The sender fields are what the entry claims; [`Self::verify_sender`] checks the claim
212/// against the key the sender's identity holds under `sender_key_id`, and
213/// [`Self::recover_signer`] gives the key that signed a signed entry. The fields are read-only,
214/// so what a caller reads is what was authenticated.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct OpenedPrivateDocumentEntry {
217    contract_id: [u8; 32],
218    document_type_name: String,
219    commitment: [u8; 32],
220    recipient_key_index: Option<usize>,
221    recipient_public_key: PublicKey,
222    recipient_identity_id: [u8; 32],
223    auth_mode: PrivateDocumentAuthMode,
224    sender_identity_id: [u8; 32],
225    sender_key_id: u32,
226    payload: Vec<u8>,
227    auth: [u8; AUTH_LEN],
228    auth_message: [u8; 32],
229}
230
231impl OpenedPrivateDocumentEntry {
232    /// The contract of the store the entry was opened for: its commitment binds that store, so
233    /// it opens for no other.
234    pub fn contract_id(&self) -> &[u8; 32] {
235        &self.contract_id
236    }
237
238    /// The private document type of the store the entry was opened for.
239    pub fn document_type_name(&self) -> &str {
240        &self.document_type_name
241    }
242
243    /// The entry's commitment: two entries with the same one are copies.
244    pub fn commitment(&self) -> &[u8; 32] {
245        &self.commitment
246    }
247
248    /// Which of the keys given to [`open_private_document_entry`] opened it; `None` when the
249    /// sender recovered it.
250    pub fn recipient_key_index(&self) -> Option<usize> {
251        self.recipient_key_index
252    }
253
254    /// The key the entry is encrypted to.
255    pub fn recipient_public_key(&self) -> &PublicKey {
256        &self.recipient_public_key
257    }
258
259    pub fn recipient_identity_id(&self) -> &[u8; 32] {
260        &self.recipient_identity_id
261    }
262
263    pub fn auth_mode(&self) -> PrivateDocumentAuthMode {
264        self.auth_mode
265    }
266
267    /// Zeros when the entry is anonymous.
268    pub fn sender_identity_id(&self) -> &[u8; 32] {
269        &self.sender_identity_id
270    }
271
272    /// Zero when the entry is anonymous.
273    pub fn sender_key_id(&self) -> u32 {
274        self.sender_key_id
275    }
276
277    /// The type's properties in the document property encoding, for the type's schema to
278    /// decode and validate.
279    pub fn payload(&self) -> &[u8] {
280        &self.payload
281    }
282
283    /// The payload, taking the entry.
284    pub fn into_payload(self) -> Vec<u8> {
285        self.payload
286    }
287
288    /// Checks that the key the entry names wrote it: `sender_public_key` is the key the sender
289    /// identity holds under `sender_key_id`, as it was when the entry was written (keys are
290    /// disabled, never removed). A deniable MAC is checked with the recipient's own secret key,
291    /// the one that opened the entry, and is refused with `RecipientSecretKeyRequired` without
292    /// it; a signature needs only the sender's key, so a sender checks its own recovered entry
293    /// with `None`.
294    pub fn verify_sender(
295        &self,
296        sender_public_key: &PublicKey,
297        recipient_secret_key: Option<&SecretKey>,
298    ) -> Result<(), PrivateDocumentEnvelopeError> {
299        match self.auth_mode {
300            PrivateDocumentAuthMode::Anonymous => {
301                Err(PrivateDocumentEnvelopeError::AnonymousSender)
302            }
303            PrivateDocumentAuthMode::DeniableMac => {
304                let recipient_secret_key = recipient_secret_key
305                    .ok_or(PrivateDocumentEnvelopeError::RecipientSecretKeyRequired)?;
306                let mac_key = mac_key(&shared_point(recipient_secret_key, sender_public_key));
307                let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&mac_key)
308                    .expect("HMAC takes a key of any length");
309                mac.update(&self.auth_message);
310                mac.verify_slice(&self.auth[..MAC_LEN])
311                    .map_err(|_| PrivateDocumentEnvelopeError::SenderNotAuthenticated)
312            }
313            PrivateDocumentAuthMode::Signature => {
314                if self.recover_signer()? == *sender_public_key {
315                    Ok(())
316                } else {
317                    Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
318                }
319            }
320        }
321    }
322
323    /// The key that signed a signed entry, recovered from its signature. The signature is
324    /// valid under the key returned, so the caller's check is that the key is one the sender
325    /// identity may sign with, as it was when the entry was written. An anonymous entry is
326    /// refused with `AnonymousSender`, and one carrying a deniable MAC with `NotSigned`.
327    pub fn recover_signer(&self) -> Result<PublicKey, PrivateDocumentEnvelopeError> {
328        match self.auth_mode {
329            PrivateDocumentAuthMode::Anonymous => {
330                Err(PrivateDocumentEnvelopeError::AnonymousSender)
331            }
332            PrivateDocumentAuthMode::DeniableMac => Err(PrivateDocumentEnvelopeError::NotSigned),
333            PrivateDocumentAuthMode::Signature => {
334                recover_private_document_signer(&self.auth, &self.auth_message)
335            }
336        }
337    }
338}
339
340/// What the sender of a signed entry signs, `m` above: an identity signer signs it as data,
341/// that is its double SHA-256. The fields are the entry's, `recipient` included, so it is
342/// computed before sealing.
343pub fn private_document_signing_data(
344    target: &PrivateDocumentTarget,
345    sender_identity_id: &[u8; 32],
346    sender_key_id: u32,
347    recipient: &PrivateDocumentRecipient,
348    payload: &[u8],
349) -> [u8; 32] {
350    auth_message(
351        target,
352        PrivateDocumentAuthMode::Signature,
353        sender_identity_id,
354        sender_key_id,
355        &recipient.identity_id,
356        &recipient.public_key.serialize(),
357        payload,
358    )
359}
360
361/// Signs `signing_data` with `secret_key` as a Dash identity signer does: a recoverable ECDSA
362/// signature of its double SHA-256, in the compact form.
363pub fn sign_private_document_signing_data(
364    signing_data: &[u8; 32],
365    secret_key: &SecretKey,
366) -> [u8; 65] {
367    let (recovery_id, compact) =
368        RecoverableSignature::sign_ecdsa_recoverable(signed_digest(signing_data), secret_key)
369            .serialize_compact();
370    let mut signature = [0u8; AUTH_LEN];
371    signature[0] = COMPACT_SIGNATURE_HEADER_BASE + u8::from(recovery_id);
372    signature[1..].copy_from_slice(&compact);
373    signature
374}
375
376/// The digest a signature of `signing_data` signs: its double SHA-256.
377fn signed_digest(signing_data: &[u8; 32]) -> Message {
378    Message::from_digest(Sha256::digest(Sha256::digest(signing_data)).into())
379}
380
381/// The key a compact signature of `signing_data` recovers to, refused with
382/// `SenderNotAuthenticated` when it is no signature. A signer checks its own signature with it
383/// before sealing.
384pub fn recover_private_document_signer(
385    signature: &[u8; AUTH_LEN],
386    signing_data: &[u8; 32],
387) -> Result<PublicKey, PrivateDocumentEnvelopeError> {
388    if !(COMPACT_SIGNATURE_HEADER_BASE..COMPACT_SIGNATURE_HEADER_BASE + 4).contains(&signature[0]) {
389        return Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated);
390    }
391    let recovery_id =
392        RecoveryId::from_u8_masked(signature[0].wrapping_sub(COMPACT_SIGNATURE_HEADER_BASE));
393    RecoverableSignature::from_compact(&signature[1..], recovery_id)
394        .and_then(|signature| signature.recover_ecdsa(signed_digest(signing_data)))
395        .map_err(|_| PrivateDocumentEnvelopeError::SenderNotAuthenticated)
396}
397
398/// The outgoing viewing key a sender derives from a secret of its wallet: with it, and nothing
399/// else, the sender recovers every entry it built from the entries alone.
400pub fn private_document_outgoing_viewing_key(wallet_secret: &[u8; 32]) -> [u8; 32] {
401    hash(&[DOMAIN_OVK, wallet_secret])
402}
403
404/// Builds an entry of `entry_size` bytes carrying `payload` to `recipient`, for the private
405/// document type `target`.
406///
407/// `esk_seed` must be 32 fresh random bytes for every entry built, never reused, not even on a
408/// retry: the entry's keys are derived from it, and a zero nonce is safe only because each key
409/// encrypts once. A seed whose hash is not a valid secret key (a chance of about 2^-128) is
410/// refused with [`PrivateDocumentEnvelopeError::InvalidEphemeralSeed`]; draw another.
411pub fn seal_private_document_entry(
412    target: &PrivateDocumentTarget,
413    entry_size: usize,
414    recipient: &PrivateDocumentRecipient,
415    sender: &PrivateDocumentSender,
416    payload: &[u8],
417    outgoing_viewing_key: &[u8; 32],
418    esk_seed: &[u8; 32],
419) -> Result<Vec<u8>, PrivateDocumentEnvelopeError> {
420    if entry_size < PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN {
421        return Err(PrivateDocumentEnvelopeError::InvalidEntryLength(entry_size));
422    }
423    let capacity = entry_size - PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN;
424    let payload_len = u16::try_from(payload.len())
425        .ok()
426        .filter(|_| payload.len() <= capacity)
427        .ok_or(PrivateDocumentEnvelopeError::PayloadTooLarge {
428            payload_len: payload.len(),
429            capacity,
430        })?;
431    let body_len = entry_size - PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN;
432
433    let esk = ephemeral_secret_key(esk_seed)?;
434    let epk = PublicKey::from_secret_key(&esk).serialize();
435    let recipient_key = recipient.public_key.serialize();
436    let key = entry_key(
437        &shared_point(&esk, recipient.public_key),
438        &epk,
439        &recipient_key,
440    );
441
442    let (auth_mode, sender_identity_id, sender_key_id) = match sender {
443        PrivateDocumentSender::Anonymous => (PrivateDocumentAuthMode::Anonymous, [0; 32], 0),
444        PrivateDocumentSender::DeniableMac {
445            identity_id,
446            key_id,
447            ..
448        } => (PrivateDocumentAuthMode::DeniableMac, *identity_id, *key_id),
449        PrivateDocumentSender::Signature {
450            identity_id,
451            key_id,
452            ..
453        } => (PrivateDocumentAuthMode::Signature, *identity_id, *key_id),
454    };
455    let auth_message = auth_message(
456        target,
457        auth_mode,
458        &sender_identity_id,
459        sender_key_id,
460        &recipient.identity_id,
461        &recipient_key,
462        payload,
463    );
464    let mut auth = [0u8; AUTH_LEN];
465    match sender {
466        PrivateDocumentSender::Anonymous => {}
467        PrivateDocumentSender::DeniableMac { secret_key, .. } => {
468            let mac_key = mac_key(&shared_point(secret_key, recipient.public_key));
469            let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&mac_key)
470                .expect("HMAC takes a key of any length");
471            mac.update(&auth_message);
472            auth[..MAC_LEN].copy_from_slice(&mac.finalize().into_bytes());
473        }
474        PrivateDocumentSender::Signature { signature, .. } => {
475            // A signature of other data would recover to some other key: the caller checks the
476            // key, and this that the signature is one.
477            recover_private_document_signer(signature, &auth_message)?;
478            auth.copy_from_slice(*signature);
479        }
480    }
481
482    let mut body = Vec::with_capacity(body_len);
483    body.push(PRIVATE_DOCUMENT_ENVELOPE_VERSION);
484    body.push(auth_mode as u8);
485    body.extend_from_slice(&sender_identity_id);
486    body.extend_from_slice(&sender_key_id.to_le_bytes());
487    body.extend_from_slice(&auth);
488    body.extend_from_slice(&recipient.identity_id);
489    body.extend_from_slice(&payload_len.to_le_bytes());
490    body.extend_from_slice(payload);
491    body.resize(body_len, 0);
492
493    let commitment = commitment(&key, target, &recipient_key, &body);
494    let body_ct = encrypt(&key, &commitment, &body)?;
495    let mut sender_recovery = Vec::with_capacity(SENDER_RECOVERY_PLAINTEXT_LEN);
496    sender_recovery.extend_from_slice(&recipient_key);
497    sender_recovery.extend_from_slice(esk_seed);
498    let out_ct = encrypt(
499        &outgoing_cipher_key(outgoing_viewing_key, &epk),
500        &commitment,
501        &sender_recovery,
502    )?;
503
504    let mut entry = Vec::with_capacity(entry_size);
505    entry.extend_from_slice(&commitment);
506    entry.extend_from_slice(&epk);
507    entry.extend_from_slice(&body_ct);
508    entry.extend_from_slice(&out_ct);
509    debug_assert_eq!(entry.len(), entry_size);
510    Ok(entry)
511}
512
513/// A wallet's decryption keys, prepared to open many entries: each key's public key is derived
514/// and serialized once, rather than for every entry a scan tries, which for nearly every entry
515/// opens none. The keys keep their order, which [`OpenedPrivateDocumentEntry::recipient_key_index`]
516/// reports.
517pub struct PrivateDocumentRecipientKeys {
518    keys: Vec<(SecretKey, PublicKey, [u8; 33])>,
519}
520
521impl PrivateDocumentRecipientKeys {
522    pub fn new(secret_keys: &[SecretKey]) -> Self {
523        Self {
524            keys: secret_keys
525                .iter()
526                .map(|secret_key| {
527                    let public_key = PublicKey::from_secret_key(secret_key);
528                    (*secret_key, public_key, public_key.serialize())
529                })
530                .collect(),
531        }
532    }
533
534    /// Opens `entry` of the private document type `target` with the first of these keys it is
535    /// encrypted to, for the identity `recipient_identity_id`.
536    ///
537    /// `Ok(None)` when it is for none of the keys, the case of nearly every entry a wallet scans:
538    /// a key whose decryption fails, or whose commitment does not match, is passed over for the
539    /// next. An entry that opens but is malformed, or names another recipient identity, is
540    /// refused with an error. The sender is not yet checked: see
541    /// [`OpenedPrivateDocumentEntry::verify_sender`].
542    pub fn open(
543        &self,
544        entry: &[u8],
545        target: &PrivateDocumentTarget,
546        recipient_identity_id: &[u8; 32],
547    ) -> Result<Option<OpenedPrivateDocumentEntry>, PrivateDocumentEnvelopeError> {
548        let parts = EntryParts::split(entry)?;
549        let Ok(epk) = PublicKey::from_slice(parts.epk) else {
550            // No key opens an entry whose ephemeral key is not a point.
551            return Ok(None);
552        };
553        for (index, (secret_key, recipient_public_key, recipient_key)) in
554            self.keys.iter().enumerate()
555        {
556            let key = entry_key(&shared_point(secret_key, &epk), parts.epk, recipient_key);
557            let Ok(body) = decrypt(&key, parts.commitment, parts.body_ct) else {
558                continue;
559            };
560            if commitment(&key, target, recipient_key, &body) != *parts.commitment {
561                continue;
562            }
563            let opened = parse_body(
564                &body,
565                target,
566                *parts.commitment,
567                *recipient_public_key,
568                Some(index),
569            )?;
570            if opened.recipient_identity_id != *recipient_identity_id {
571                return Err(PrivateDocumentEnvelopeError::WrongRecipient);
572            }
573            return Ok(Some(opened));
574        }
575        Ok(None)
576    }
577
578    /// [`OpenedPrivateDocumentEntry::verify_sender`] with the one of these keys that opened
579    /// `entry`, which a deniable MAC is checked with. An entry these keys did not open (one a
580    /// sender recovered, or that other keys opened) is refused with
581    /// `RecipientSecretKeyRequired`.
582    pub fn verify_sender(
583        &self,
584        entry: &OpenedPrivateDocumentEntry,
585        sender_public_key: &PublicKey,
586    ) -> Result<(), PrivateDocumentEnvelopeError> {
587        let (secret_key, _, _) = entry
588            .recipient_key_index
589            .and_then(|index| self.keys.get(index))
590            .filter(|(_, public_key, _)| *public_key == entry.recipient_public_key)
591            .ok_or(PrivateDocumentEnvelopeError::RecipientSecretKeyRequired)?;
592        entry.verify_sender(sender_public_key, Some(secret_key))
593    }
594}
595
596impl Drop for PrivateDocumentRecipientKeys {
597    fn drop(&mut self) {
598        for (secret_key, _, _) in &mut self.keys {
599            secret_key.non_secure_erase();
600        }
601    }
602}
603
604/// [`PrivateDocumentRecipientKeys::open`] with keys prepared for this one entry; a scan of many
605/// entries prepares them once instead.
606pub fn open_private_document_entry(
607    entry: &[u8],
608    target: &PrivateDocumentTarget,
609    recipient_identity_id: &[u8; 32],
610    recipient_secret_keys: &[SecretKey],
611) -> Result<Option<OpenedPrivateDocumentEntry>, PrivateDocumentEnvelopeError> {
612    PrivateDocumentRecipientKeys::new(recipient_secret_keys).open(
613        entry,
614        target,
615        recipient_identity_id,
616    )
617}
618
619/// Recovers `entry` of the private document type `target` that the holder of
620/// `outgoing_viewing_key` built, as after a restore from seed: `Ok(None)` when it built another
621/// sender's entry. An entry whose sender recovery opens but whose body does not is refused.
622pub fn recover_sent_private_document_entry(
623    entry: &[u8],
624    target: &PrivateDocumentTarget,
625    outgoing_viewing_key: &[u8; 32],
626) -> Result<Option<OpenedPrivateDocumentEntry>, PrivateDocumentEnvelopeError> {
627    let parts = EntryParts::split(entry)?;
628    let Ok(sender_recovery) = decrypt(
629        &outgoing_cipher_key(outgoing_viewing_key, parts.epk),
630        parts.commitment,
631        parts.out_ct,
632    ) else {
633        return Ok(None);
634    };
635    let malformed = || PrivateDocumentEnvelopeError::Malformed("sender recovery");
636    let recipient_public_key =
637        PublicKey::from_slice(&sender_recovery[..EPHEMERAL_KEY_LEN]).map_err(|_| malformed())?;
638    let esk_seed: [u8; 32] = sender_recovery[EPHEMERAL_KEY_LEN..]
639        .try_into()
640        .map_err(|_| malformed())?;
641    let esk = ephemeral_secret_key(&esk_seed).map_err(|_| malformed())?;
642    if PublicKey::from_secret_key(&esk).serialize() != *parts.epk {
643        return Err(malformed());
644    }
645    let recipient_key = recipient_public_key.serialize();
646    let key = entry_key(
647        &shared_point(&esk, &recipient_public_key),
648        parts.epk,
649        &recipient_key,
650    );
651    let body = decrypt(&key, parts.commitment, parts.body_ct).map_err(|_| malformed())?;
652    if commitment(&key, target, &recipient_key, &body) != *parts.commitment {
653        return Err(malformed());
654    }
655    parse_body(&body, target, *parts.commitment, recipient_public_key, None).map(Some)
656}
657
658/// An entry cut into its four parts.
659struct EntryParts<'a> {
660    commitment: &'a [u8; 32],
661    epk: &'a [u8; 33],
662    body_ct: &'a [u8],
663    out_ct: &'a [u8],
664}
665
666impl<'a> EntryParts<'a> {
667    fn split(entry: &'a [u8]) -> Result<Self, PrivateDocumentEnvelopeError> {
668        if entry.len() < PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN {
669            return Err(PrivateDocumentEnvelopeError::InvalidEntryLength(
670                entry.len(),
671            ));
672        }
673        let (commitment, rest) = entry.split_at(COMMITMENT_LEN);
674        let (epk, rest) = rest.split_at(EPHEMERAL_KEY_LEN);
675        let (body_ct, out_ct) = rest.split_at(rest.len() - SENDER_RECOVERY_LEN);
676        Ok(Self {
677            commitment: commitment.try_into().expect("32 bytes"),
678            epk: epk.try_into().expect("33 bytes"),
679            body_ct,
680            out_ct,
681        })
682    }
683}
684
685/// Reads a decrypted body, refusing one no sender of this version writes.
686fn parse_body(
687    body: &[u8],
688    target: &PrivateDocumentTarget,
689    commitment: [u8; 32],
690    recipient_public_key: PublicKey,
691    recipient_key_index: Option<usize>,
692) -> Result<OpenedPrivateDocumentEntry, PrivateDocumentEnvelopeError> {
693    let malformed = PrivateDocumentEnvelopeError::Malformed;
694    if body.len() < PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN {
695        return Err(malformed("body shorter than its header"));
696    }
697    if body[0] != PRIVATE_DOCUMENT_ENVELOPE_VERSION {
698        return Err(PrivateDocumentEnvelopeError::UnsupportedVersion(body[0]));
699    }
700    let auth_mode =
701        PrivateDocumentAuthMode::from_byte(body[1]).ok_or(malformed("unknown auth mode"))?;
702    let sender_identity_id: [u8; 32] = body[2..34].try_into().expect("32 bytes");
703    let sender_key_id = u32::from_le_bytes(body[34..38].try_into().expect("4 bytes"));
704    let auth: [u8; AUTH_LEN] = body[38..103].try_into().expect("65 bytes");
705    let recipient_identity_id: [u8; 32] = body[103..135].try_into().expect("32 bytes");
706    let payload_len = u16::from_le_bytes(body[135..137].try_into().expect("2 bytes")) as usize;
707    let rest = &body[PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN..];
708    if payload_len > rest.len() {
709        return Err(malformed("payload longer than the body"));
710    }
711    let (payload, padding) = rest.split_at(payload_len);
712    if padding.iter().any(|byte| *byte != 0) {
713        return Err(malformed("padding is not zeros"));
714    }
715    let well_formed_auth = match auth_mode {
716        PrivateDocumentAuthMode::Anonymous => {
717            sender_identity_id == [0; 32] && sender_key_id == 0 && auth == [0; AUTH_LEN]
718        }
719        PrivateDocumentAuthMode::DeniableMac => auth[MAC_LEN..].iter().all(|byte| *byte == 0),
720        PrivateDocumentAuthMode::Signature => {
721            (COMPACT_SIGNATURE_HEADER_BASE..COMPACT_SIGNATURE_HEADER_BASE + 4).contains(&auth[0])
722        }
723    };
724    if !well_formed_auth {
725        return Err(malformed("sender fields do not match the auth mode"));
726    }
727    let auth_message = auth_message(
728        target,
729        auth_mode,
730        &sender_identity_id,
731        sender_key_id,
732        &recipient_identity_id,
733        &recipient_public_key.serialize(),
734        payload,
735    );
736    Ok(OpenedPrivateDocumentEntry {
737        contract_id: target.contract_id,
738        document_type_name: target.document_type_name.to_string(),
739        commitment,
740        recipient_key_index,
741        recipient_public_key,
742        recipient_identity_id,
743        auth_mode,
744        sender_identity_id,
745        sender_key_id,
746        payload: payload.to_vec(),
747        auth,
748        auth_message,
749    })
750}
751
752fn hash(parts: &[&[u8]]) -> [u8; 32] {
753    let mut hasher = Sha256::new();
754    for part in parts {
755        hasher.update(part);
756    }
757    hasher.finalize().into()
758}
759
760fn type_name_length(target: &PrivateDocumentTarget) -> [u8; 4] {
761    (target.document_type_name.len() as u32).to_le_bytes()
762}
763
764fn ephemeral_secret_key(esk_seed: &[u8; 32]) -> Result<SecretKey, PrivateDocumentEnvelopeError> {
765    SecretKey::from_secret_bytes(hash(&[DOMAIN_ESK, esk_seed]))
766        .map_err(|_| PrivateDocumentEnvelopeError::InvalidEphemeralSeed)
767}
768
769/// `secret_key * public_key`, compressed, computed in constant time: the secret keys are a
770/// wallet's long-lived keys and the points are an attacker's, so the multiplication must not leak
771/// the key through timing. libsecp256k1's ECDH multiplies in constant time; it hands back the
772/// point's coordinates, compressed here as `0x02 | (y & 1)` then `x`.
773fn shared_point(secret_key: &SecretKey, public_key: &PublicKey) -> [u8; 33] {
774    let xy = shared_secret_point(public_key, secret_key);
775    let mut point = [0u8; 33];
776    point[0] = 0x02 | (xy[63] & 1);
777    point[1..].copy_from_slice(&xy[..32]);
778    point
779}
780
781fn entry_key(shared_point: &[u8; 33], epk: &[u8; 33], recipient_key: &[u8; 33]) -> [u8; 32] {
782    hash(&[DOMAIN_KEY, shared_point, epk, recipient_key])
783}
784
785fn commitment(
786    key: &[u8; 32],
787    target: &PrivateDocumentTarget,
788    recipient_key: &[u8; 33],
789    body: &[u8],
790) -> [u8; 32] {
791    hash(&[
792        DOMAIN_CM,
793        key,
794        &target.contract_id,
795        &type_name_length(target),
796        target.document_type_name.as_bytes(),
797        recipient_key,
798        body,
799    ])
800}
801
802fn outgoing_cipher_key(outgoing_viewing_key: &[u8; 32], epk: &[u8; 33]) -> [u8; 32] {
803    hash(&[DOMAIN_OCK, outgoing_viewing_key, epk])
804}
805
806fn mac_key(shared_point: &[u8; 33]) -> [u8; 32] {
807    hash(&[DOMAIN_MAC, shared_point])
808}
809
810fn auth_message(
811    target: &PrivateDocumentTarget,
812    auth_mode: PrivateDocumentAuthMode,
813    sender_identity_id: &[u8; 32],
814    sender_key_id: u32,
815    recipient_identity_id: &[u8; 32],
816    recipient_key: &[u8; 33],
817    payload: &[u8],
818) -> [u8; 32] {
819    hash(&[
820        DOMAIN_AUTH,
821        &[PRIVATE_DOCUMENT_ENVELOPE_VERSION, auth_mode as u8],
822        &target.contract_id,
823        &type_name_length(target),
824        target.document_type_name.as_bytes(),
825        sender_identity_id,
826        &sender_key_id.to_le_bytes(),
827        recipient_identity_id,
828        recipient_key,
829        &(payload.len() as u16).to_le_bytes(),
830        payload,
831    ])
832}
833
834fn encrypt(
835    key: &[u8; 32],
836    aad: &[u8; 32],
837    plaintext: &[u8],
838) -> Result<Vec<u8>, PrivateDocumentEnvelopeError> {
839    ChaCha20Poly1305::new(Key::from_slice(key))
840        .encrypt(
841            Nonce::from_slice(&[0; 12]),
842            Payload {
843                msg: plaintext,
844                aad,
845            },
846        )
847        .map_err(|_| PrivateDocumentEnvelopeError::Malformed("encryption failed"))
848}
849
850fn decrypt(
851    key: &[u8; 32],
852    aad: &[u8; 32],
853    ciphertext: &[u8],
854) -> Result<Vec<u8>, PrivateDocumentEnvelopeError> {
855    ChaCha20Poly1305::new(Key::from_slice(key))
856        .decrypt(
857            Nonce::from_slice(&[0; 12]),
858            Payload {
859                msg: ciphertext,
860                aad,
861            },
862        )
863        .map_err(|_| PrivateDocumentEnvelopeError::DecryptionFailed)
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    /// DashPay's `privateContactRequest`: 589-byte entries, whose largest payload is 290 bytes.
871    const ENTRY_SIZE: usize = 589;
872    const LARGEST_PAYLOAD: usize = 290;
873    const SENDER_IDENTITY: [u8; 32] = [0xA0; 32];
874    const RECIPIENT_IDENTITY: [u8; 32] = [0xB0; 32];
875
876    fn target() -> PrivateDocumentTarget<'static> {
877        PrivateDocumentTarget {
878            contract_id: [7; 32],
879            document_type_name: "privateContactRequest",
880        }
881    }
882
883    fn secret_key(byte: u8) -> SecretKey {
884        SecretKey::from_secret_bytes([byte; 32]).expect("a valid secret key")
885    }
886
887    fn public_key(byte: u8) -> PublicKey {
888        PublicKey::from_secret_key(&secret_key(byte))
889    }
890
891    fn payload() -> Vec<u8> {
892        (0..LARGEST_PAYLOAD).map(|i| i as u8).collect()
893    }
894
895    fn outgoing_viewing_key() -> [u8; 32] {
896        private_document_outgoing_viewing_key(&[0x0F; 32])
897    }
898
899    /// The signature by `secret_key` of the test entry's signing data, naming sender key 4.
900    fn signature(secret_key: &SecretKey) -> [u8; 65] {
901        sign_private_document_signing_data(
902            &private_document_signing_data(
903                &target(),
904                &SENDER_IDENTITY,
905                4,
906                &PrivateDocumentRecipient {
907                    identity_id: RECIPIENT_IDENTITY,
908                    public_key: &public_key(2),
909                },
910                &payload(),
911            ),
912            secret_key,
913        )
914    }
915
916    /// An entry to the recipient key `secret_key(2)` from `sender`, built from `esk_seed`.
917    fn seal(sender: &PrivateDocumentSender, esk_seed: u8) -> Vec<u8> {
918        seal_private_document_entry(
919            &target(),
920            ENTRY_SIZE,
921            &PrivateDocumentRecipient {
922                identity_id: RECIPIENT_IDENTITY,
923                public_key: &public_key(2),
924            },
925            sender,
926            &payload(),
927            &outgoing_viewing_key(),
928            &[esk_seed; 32],
929        )
930        .expect("the payload fits")
931    }
932
933    fn open(entry: &[u8], keys: &[SecretKey]) -> Option<OpenedPrivateDocumentEntry> {
934        open_private_document_entry(entry, &target(), &RECIPIENT_IDENTITY, keys)
935            .expect("the entry is well formed")
936    }
937
938    fn deniable_mac_sender(secret_key: &SecretKey) -> PrivateDocumentSender<'_> {
939        PrivateDocumentSender::DeniableMac {
940            identity_id: SENDER_IDENTITY,
941            key_id: 4,
942            secret_key,
943        }
944    }
945
946    /// The recipient opens an entry with whichever of its keys it is encrypted to, reads the
947    /// payload and the sender it claims, and checks the deniable MAC against the sender's key.
948    #[test]
949    fn should_open_an_entry_with_its_key_and_check_a_deniable_mac() {
950        let sender_key = secret_key(1);
951        let entry = seal(&deniable_mac_sender(&sender_key), 9);
952        assert_eq!(entry.len(), ENTRY_SIZE);
953
954        let opened =
955            open(&entry, &[secret_key(3), secret_key(2)]).expect("the second key opens it");
956        assert_eq!(opened.recipient_key_index(), Some(1));
957        assert_eq!(opened.recipient_public_key(), &public_key(2));
958        assert_eq!(opened.recipient_identity_id(), &RECIPIENT_IDENTITY);
959        assert_eq!(opened.auth_mode(), PrivateDocumentAuthMode::DeniableMac);
960        assert_eq!(opened.sender_identity_id(), &SENDER_IDENTITY);
961        assert_eq!(opened.sender_key_id(), 4);
962        assert_eq!(opened.payload(), payload().as_slice());
963
964        opened
965            .verify_sender(&public_key(1), Some(&secret_key(2)))
966            .expect("the sender's key wrote the MAC");
967        assert!(matches!(
968            opened.verify_sender(&public_key(5), Some(&secret_key(2))),
969            Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
970        ));
971        assert!(matches!(
972            opened.verify_sender(&public_key(1), Some(&secret_key(3))),
973            Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
974        ));
975        assert_eq!(
976            opened.verify_sender(&public_key(1), None),
977            Err(PrivateDocumentEnvelopeError::RecipientSecretKeyRequired)
978        );
979    }
980
981    /// A signed entry is checked against the sender's key alone.
982    #[test]
983    fn should_check_a_signature_against_the_sender_key() {
984        let signature = signature(&secret_key(1));
985        let entry = seal(
986            &PrivateDocumentSender::Signature {
987                identity_id: SENDER_IDENTITY,
988                key_id: 4,
989                signature: &signature,
990            },
991            9,
992        );
993        let opened = open(&entry, &[secret_key(2)]).expect("it opens");
994        assert_eq!(opened.auth_mode(), PrivateDocumentAuthMode::Signature);
995        opened
996            .verify_sender(&public_key(1), Some(&secret_key(2)))
997            .expect("the sender's key signed it");
998        assert!(matches!(
999            opened.verify_sender(&public_key(5), Some(&secret_key(2))),
1000            Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
1001        ));
1002        // A signature needs no recipient key: the sender checks its own recovered entry with
1003        // `None`, and the recipient may too.
1004        opened
1005            .verify_sender(&public_key(1), None)
1006            .expect("the signature needs only the sender's key");
1007        recover_sent_private_document_entry(&entry, &target(), &outgoing_viewing_key())
1008            .expect("well formed")
1009            .expect("the sender built it")
1010            .verify_sender(&public_key(1), None)
1011            .expect("the sender checks its recovered entry with its own key alone");
1012    }
1013
1014    /// The signer of a signed entry is recovered from its signature, whichever key the entry
1015    /// names: DashPay names the encryption key and signs with a signing key.
1016    #[test]
1017    fn should_recover_the_signer_of_a_signed_entry() {
1018        let signature = signature(&secret_key(1));
1019        let entry = seal(
1020            &PrivateDocumentSender::Signature {
1021                identity_id: SENDER_IDENTITY,
1022                key_id: 4,
1023                signature: &signature,
1024            },
1025            9,
1026        );
1027        let opened = open(&entry, &[secret_key(2)]).expect("it opens");
1028        assert_eq!(opened.sender_key_id(), 4);
1029        assert_eq!(opened.recover_signer(), Ok(public_key(1)));
1030        let recovered =
1031            recover_sent_private_document_entry(&entry, &target(), &outgoing_viewing_key())
1032                .expect("well formed")
1033                .expect("the sender built it");
1034        assert_eq!(recovered.recover_signer(), Ok(public_key(1)));
1035
1036        // A signature of other data recovers to another key, which the caller's check refuses;
1037        // bytes that are no signature are refused when sealing.
1038        let other_data = sign_private_document_signing_data(&[0x77; 32], &secret_key(1));
1039        let entry = seal(
1040            &PrivateDocumentSender::Signature {
1041                identity_id: SENDER_IDENTITY,
1042                key_id: 4,
1043                signature: &other_data,
1044            },
1045            9,
1046        );
1047        let opened = open(&entry, &[secret_key(2)]).expect("it opens");
1048        assert_ne!(opened.recover_signer(), Ok(public_key(1)));
1049        // The signature names the recipient key: the same body sealed to another key of the
1050        // recipient identity is signed by no one.
1051        let retargeted = seal_private_document_entry(
1052            &target(),
1053            ENTRY_SIZE,
1054            &PrivateDocumentRecipient {
1055                identity_id: RECIPIENT_IDENTITY,
1056                public_key: &public_key(3),
1057            },
1058            &PrivateDocumentSender::Signature {
1059                identity_id: SENDER_IDENTITY,
1060                key_id: 4,
1061                signature: &signature,
1062            },
1063            &payload(),
1064            &outgoing_viewing_key(),
1065            &[9; 32],
1066        )
1067        .expect("the payload fits");
1068        let opened = open(&retargeted, &[secret_key(3)]).expect("it opens");
1069        assert_ne!(opened.recover_signer(), Ok(public_key(1)));
1070        let mut not_a_signature = signature;
1071        not_a_signature[0] = 27;
1072        assert_eq!(
1073            seal_private_document_entry(
1074                &target(),
1075                ENTRY_SIZE,
1076                &PrivateDocumentRecipient {
1077                    identity_id: RECIPIENT_IDENTITY,
1078                    public_key: &public_key(2),
1079                },
1080                &PrivateDocumentSender::Signature {
1081                    identity_id: SENDER_IDENTITY,
1082                    key_id: 4,
1083                    signature: &not_a_signature,
1084                },
1085                &payload(),
1086                &outgoing_viewing_key(),
1087                &[9; 32],
1088            ),
1089            Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
1090        );
1091
1092        let mac_key = secret_key(3);
1093        let mac_entry = seal(
1094            &PrivateDocumentSender::DeniableMac {
1095                identity_id: SENDER_IDENTITY,
1096                key_id: 4,
1097                secret_key: &mac_key,
1098            },
1099            9,
1100        );
1101        let opened = open(&mac_entry, &[secret_key(2)]).expect("it opens");
1102        assert_eq!(
1103            opened.recover_signer(),
1104            Err(PrivateDocumentEnvelopeError::NotSigned)
1105        );
1106        let anonymous = open(
1107            &seal(&PrivateDocumentSender::Anonymous, 9),
1108            &[secret_key(2)],
1109        )
1110        .expect("it opens");
1111        assert_eq!(
1112            anonymous.recover_signer(),
1113            Err(PrivateDocumentEnvelopeError::AnonymousSender)
1114        );
1115    }
1116
1117    /// An anonymous entry names no sender, and there is nothing to check.
1118    #[test]
1119    fn should_open_an_anonymous_entry_without_a_sender() {
1120        let entry = seal(&PrivateDocumentSender::Anonymous, 9);
1121        let opened = open(&entry, &[secret_key(2)]).expect("it opens");
1122        assert_eq!(opened.auth_mode(), PrivateDocumentAuthMode::Anonymous);
1123        assert_eq!(opened.sender_identity_id(), &[0; 32]);
1124        assert_eq!(opened.sender_key_id(), 0);
1125        assert_eq!(opened.payload(), payload().as_slice());
1126        assert!(matches!(
1127            opened.verify_sender(&public_key(1), Some(&secret_key(2))),
1128            Err(PrivateDocumentEnvelopeError::AnonymousSender)
1129        ));
1130    }
1131
1132    /// Keys prepared once open every entry of a scan as the single-entry function does, and keep
1133    /// their order in the index they report.
1134    #[test]
1135    fn should_open_entries_with_keys_prepared_once() {
1136        let sender_key = secret_key(1);
1137        let keys = [secret_key(3), secret_key(2)];
1138        let prepared = PrivateDocumentRecipientKeys::new(&keys);
1139        let entries = [
1140            seal(&deniable_mac_sender(&sender_key), 9),
1141            seal(&PrivateDocumentSender::Anonymous, 10),
1142        ];
1143        for entry in &entries {
1144            let opened = prepared
1145                .open(entry, &target(), &RECIPIENT_IDENTITY)
1146                .expect("well formed")
1147                .expect("for the second key");
1148            assert_eq!(opened.recipient_key_index(), Some(1));
1149            assert_eq!(
1150                Some(opened),
1151                open(entry, &keys),
1152                "prepared keys open the entry as the function does"
1153            );
1154        }
1155        // The first key opens an entry too: the scan tries every key, from the first.
1156        let first_key = PrivateDocumentRecipientKeys::new(&[secret_key(2), secret_key(3)]);
1157        let opened = first_key
1158            .open(&entries[0], &target(), &RECIPIENT_IDENTITY)
1159            .expect("well formed")
1160            .expect("for the first key");
1161        assert_eq!(opened.recipient_key_index(), Some(0));
1162        let others = PrivateDocumentRecipientKeys::new(&[secret_key(4)]);
1163        assert_eq!(
1164            others
1165                .open(&entries[0], &target(), &RECIPIENT_IDENTITY)
1166                .expect("well formed"),
1167            None
1168        );
1169    }
1170
1171    /// Prepared keys check a deniable MAC with the key that opened the entry, without the caller
1172    /// holding the secret key, and refuse an entry they did not open.
1173    #[test]
1174    fn should_check_the_sender_with_the_prepared_key_that_opened_the_entry() {
1175        let sender_key = secret_key(1);
1176        let entry = seal(&deniable_mac_sender(&sender_key), 9);
1177        let prepared = PrivateDocumentRecipientKeys::new(&[secret_key(3), secret_key(2)]);
1178        let opened = prepared
1179            .open(&entry, &target(), &RECIPIENT_IDENTITY)
1180            .expect("well formed")
1181            .expect("for the second key");
1182        prepared
1183            .verify_sender(&opened, &public_key(1))
1184            .expect("the sender's key wrote the MAC");
1185        assert_eq!(
1186            prepared.verify_sender(&opened, &public_key(5)),
1187            Err(PrivateDocumentEnvelopeError::SenderNotAuthenticated)
1188        );
1189
1190        // Other prepared keys do not check it, though they hold a key at the index it reports.
1191        let others = PrivateDocumentRecipientKeys::new(&[secret_key(4), secret_key(5)]);
1192        assert_eq!(
1193            others.verify_sender(&opened, &public_key(1)),
1194            Err(PrivateDocumentEnvelopeError::RecipientSecretKeyRequired)
1195        );
1196        // Nor do they for an entry the sender recovered.
1197        let recovered =
1198            recover_sent_private_document_entry(&entry, &target(), &outgoing_viewing_key())
1199                .expect("well formed")
1200                .expect("the sender built it");
1201        assert_eq!(
1202            prepared.verify_sender(&recovered, &public_key(1)),
1203            Err(PrivateDocumentEnvelopeError::RecipientSecretKeyRequired)
1204        );
1205    }
1206
1207    /// Nearly every entry a wallet scans is for someone else: it is passed over, not refused.
1208    #[test]
1209    fn should_pass_over_an_entry_for_other_keys() {
1210        let sender_key = secret_key(1);
1211        let entry = seal(&deniable_mac_sender(&sender_key), 9);
1212        assert_eq!(open(&entry, &[secret_key(3), secret_key(1)]), None);
1213        assert_eq!(open(&entry, &[]), None);
1214    }
1215
1216    /// A byte changed in the commitment, the ephemeral key or the body, or the entry read as one
1217    /// of another contract or type, opens for nobody.
1218    #[test]
1219    fn should_not_open_an_entry_changed_or_moved_to_another_type() {
1220        let sender_key = secret_key(1);
1221        let entry = seal(&deniable_mac_sender(&sender_key), 9);
1222        for position in [0, 31, 33, 64, 65, 300, ENTRY_SIZE - 82] {
1223            let mut changed = entry.clone();
1224            changed[position] ^= 1;
1225            assert_eq!(open(&changed, &[secret_key(2)]), None, "byte {position}");
1226        }
1227        for moved in [
1228            PrivateDocumentTarget {
1229                contract_id: [8; 32],
1230                ..target()
1231            },
1232            PrivateDocumentTarget {
1233                document_type_name: "contactRequest",
1234                ..target()
1235            },
1236        ] {
1237            assert_eq!(
1238                open_private_document_entry(&entry, &moved, &RECIPIENT_IDENTITY, &[secret_key(2)])
1239                    .expect("well formed"),
1240                None
1241            );
1242        }
1243    }
1244
1245    /// An entry that opens under the identity's key but names another identity is a replay,
1246    /// and is refused.
1247    #[test]
1248    fn should_refuse_an_entry_naming_another_recipient_identity() {
1249        let sender_key = secret_key(1);
1250        let entry = seal(&deniable_mac_sender(&sender_key), 9);
1251        assert!(matches!(
1252            open_private_document_entry(&entry, &target(), &[0xC0; 32], &[secret_key(2)]),
1253            Err(PrivateDocumentEnvelopeError::WrongRecipient)
1254        ));
1255    }
1256
1257    /// The sender recovers its own entry, recipient and payload included, from its outgoing
1258    /// viewing key alone; another sender's key recovers nothing, and nor does a changed
1259    /// sender-recovery ciphertext.
1260    #[test]
1261    fn should_recover_a_sent_entry_with_the_outgoing_viewing_key() {
1262        let sender_key = secret_key(1);
1263        let entry = seal(&deniable_mac_sender(&sender_key), 9);
1264        let recovered =
1265            recover_sent_private_document_entry(&entry, &target(), &outgoing_viewing_key())
1266                .expect("well formed")
1267                .expect("the sender built it");
1268        assert_eq!(recovered.recipient_key_index(), None);
1269        assert_eq!(recovered.recipient_public_key(), &public_key(2));
1270        assert_eq!(recovered.payload(), payload().as_slice());
1271        let opened = open(&entry, &[secret_key(2)]).expect("it opens");
1272        assert_eq!(
1273            OpenedPrivateDocumentEntry {
1274                recipient_key_index: Some(0),
1275                ..recovered.clone()
1276            },
1277            opened,
1278            "the sender recovers what the recipient opens"
1279        );
1280
1281        let other_sender = private_document_outgoing_viewing_key(&[0x1F; 32]);
1282        assert_eq!(
1283            recover_sent_private_document_entry(&entry, &target(), &other_sender)
1284                .expect("well formed"),
1285            None
1286        );
1287        let mut changed = entry.clone();
1288        changed[ENTRY_SIZE - 1] ^= 1;
1289        assert_eq!(
1290            recover_sent_private_document_entry(&changed, &target(), &outgoing_viewing_key())
1291                .expect("well formed"),
1292            None
1293        );
1294    }
1295
1296    /// An entry holds a payload of at most its size minus 299 bytes: a larger payload is refused,
1297    /// an entry smaller than the envelope is refused for its size, and the smallest entry, 299
1298    /// bytes, carries an empty payload.
1299    #[test]
1300    fn should_refuse_a_payload_the_entry_cannot_hold() {
1301        assert_eq!(PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN, 162);
1302        assert_eq!(PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN, 137);
1303        assert_eq!(PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN, 299);
1304        let seal_into = |entry_size: usize, payload: &[u8]| {
1305            seal_private_document_entry(
1306                &target(),
1307                entry_size,
1308                &PrivateDocumentRecipient {
1309                    identity_id: RECIPIENT_IDENTITY,
1310                    public_key: &public_key(2),
1311                },
1312                &PrivateDocumentSender::Anonymous,
1313                payload,
1314                &outgoing_viewing_key(),
1315                &[9; 32],
1316            )
1317        };
1318        assert_eq!(
1319            seal_into(ENTRY_SIZE, &vec![1; LARGEST_PAYLOAD + 1]),
1320            Err(PrivateDocumentEnvelopeError::PayloadTooLarge {
1321                payload_len: LARGEST_PAYLOAD + 1,
1322                capacity: LARGEST_PAYLOAD,
1323            })
1324        );
1325        assert_eq!(
1326            seal_into(298, &[]),
1327            Err(PrivateDocumentEnvelopeError::InvalidEntryLength(298))
1328        );
1329        let smallest = seal_into(299, &[]).expect("an empty payload fills the smallest entry");
1330        assert_eq!(smallest.len(), 299);
1331        assert_eq!(
1332            open(&smallest, &[secret_key(2)])
1333                .expect("it opens")
1334                .payload(),
1335            &[] as &[u8]
1336        );
1337        assert_eq!(
1338            open_private_document_entry(&[0; 298], &target(), &RECIPIENT_IDENTITY, &[]),
1339            Err(PrivateDocumentEnvelopeError::InvalidEntryLength(298))
1340        );
1341    }
1342
1343    /// A body no sender of this version writes is refused once it decrypts: another version,
1344    /// an unknown auth mode, a payload longer than the body, padding that is not zeros, and
1345    /// sender fields an anonymous entry does not carry.
1346    #[test]
1347    fn should_refuse_a_body_no_sender_writes() {
1348        let well_formed = || {
1349            let mut body = vec![0u8; ENTRY_SIZE - PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN];
1350            body[0] = PRIVATE_DOCUMENT_ENVELOPE_VERSION;
1351            body[135..137].copy_from_slice(&3u16.to_le_bytes());
1352            body
1353        };
1354        let parse = |body: &[u8]| parse_body(body, &target(), [0; 32], public_key(2), Some(0));
1355        parse(&well_formed()).expect("an anonymous body of 3 zero bytes");
1356
1357        let mut other_version = well_formed();
1358        other_version[0] = 2;
1359        assert!(matches!(
1360            parse(&other_version),
1361            Err(PrivateDocumentEnvelopeError::UnsupportedVersion(2))
1362        ));
1363        for (position, value) in [
1364            (1, 3u8),              // auth mode
1365            (136, 2),              // a payload length over the body
1366            (ENTRY_SIZE - 163, 1), // the last padding byte
1367            (2, 1),                // a sender identity on an anonymous entry
1368            (40, 1),               // an auth on an anonymous entry
1369        ] {
1370            let mut body = well_formed();
1371            body[position] = value;
1372            assert!(
1373                matches!(
1374                    parse(&body),
1375                    Err(PrivateDocumentEnvelopeError::Malformed(_))
1376                ),
1377                "byte {position}"
1378            );
1379        }
1380    }
1381
1382    /// The same inputs build the same entry, byte for byte, in every mode; another seed builds
1383    /// an unlinkable one. The hashes pin version 1 of the format.
1384    #[test]
1385    fn should_build_the_same_entry_from_the_same_inputs() {
1386        let sender_key = secret_key(1);
1387        let signature = signature(&sender_key);
1388        let senders = [
1389            PrivateDocumentSender::Anonymous,
1390            deniable_mac_sender(&sender_key),
1391            PrivateDocumentSender::Signature {
1392                identity_id: SENDER_IDENTITY,
1393                key_id: 4,
1394                signature: &signature,
1395            },
1396        ];
1397        let pinned: Vec<String> = senders
1398            .iter()
1399            .map(|sender| {
1400                let entry = seal(sender, 9);
1401                assert_eq!(entry, seal(sender, 9));
1402                let other = seal(sender, 10);
1403                assert_ne!(entry[..COMMITMENT_LEN], other[..COMMITMENT_LEN]);
1404                assert_ne!(entry[COMMITMENT_LEN..65], other[COMMITMENT_LEN..65]);
1405                hex(&hash(&[&entry]))
1406            })
1407            .collect();
1408        assert_eq!(
1409            pinned,
1410            [
1411                "abb644128f3e73aade8b6210573fba942709e7e44eaeffef92dc02d5187f37d3",
1412                "7250a6613ff5aa57f28cc57bd3cdd37824e4f2d3ae634e623e53d032387ce261",
1413                "05f544901039b5b112a0c55863db0bfd37951156f0639e94d65eb209da106502",
1414            ]
1415        );
1416    }
1417
1418    fn hex(bytes: &[u8]) -> String {
1419        bytes.iter().map(|byte| format!("{byte:02x}")).collect()
1420    }
1421}