1use 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#[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
111pub 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
122pub const PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN: usize =
125 COMMITMENT_LEN + EPHEMERAL_KEY_LEN + TAG_LEN + SENDER_RECOVERY_LEN;
126
127pub const PRIVATE_DOCUMENT_ENVELOPE_BODY_HEADER_LEN: usize = 1 + 1 + 32 + 4 + AUTH_LEN + 32 + 2;
129
130pub 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
143const COMPACT_SIGNATURE_HEADER_BASE: u8 = 31;
145
146#[derive(Clone, Copy, Debug)]
149pub struct PrivateDocumentTarget<'a> {
150 pub contract_id: [u8; 32],
151 pub document_type_name: &'a str,
152}
153
154#[derive(Clone, Copy, Debug)]
158pub struct PrivateDocumentRecipient<'a> {
159 pub identity_id: [u8; 32],
160 pub public_key: &'a PublicKey,
161}
162
163#[derive(Clone, Copy, Debug)]
165pub enum PrivateDocumentSender<'a> {
166 Anonymous,
168 DeniableMac {
173 identity_id: [u8; 32],
174 key_id: u32,
175 secret_key: &'a SecretKey,
176 },
177 Signature {
184 identity_id: [u8; 32],
185 key_id: u32,
186 signature: &'a [u8; 65],
187 },
188}
189
190#[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#[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 pub fn contract_id(&self) -> &[u8; 32] {
235 &self.contract_id
236 }
237
238 pub fn document_type_name(&self) -> &str {
240 &self.document_type_name
241 }
242
243 pub fn commitment(&self) -> &[u8; 32] {
245 &self.commitment
246 }
247
248 pub fn recipient_key_index(&self) -> Option<usize> {
251 self.recipient_key_index
252 }
253
254 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 pub fn sender_identity_id(&self) -> &[u8; 32] {
269 &self.sender_identity_id
270 }
271
272 pub fn sender_key_id(&self) -> u32 {
274 self.sender_key_id
275 }
276
277 pub fn payload(&self) -> &[u8] {
280 &self.payload
281 }
282
283 pub fn into_payload(self) -> Vec<u8> {
285 self.payload
286 }
287
288 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 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
340pub 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
361pub 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
376fn signed_digest(signing_data: &[u8; 32]) -> Message {
378 Message::from_digest(Sha256::digest(Sha256::digest(signing_data)).into())
379}
380
381pub 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
398pub fn private_document_outgoing_viewing_key(wallet_secret: &[u8; 32]) -> [u8; 32] {
401 hash(&[DOMAIN_OVK, wallet_secret])
402}
403
404pub 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 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
513pub 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 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 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 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
604pub 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
619pub 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
658struct 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
685fn 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
769fn 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 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 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 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 #[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 #[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 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 #[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 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 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: ¬_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 #[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 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 #[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), (136, 2), (ENTRY_SIZE - 163, 1), (2, 1), (40, 1), ] {
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 #[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}