qualia_core_db/net/qdnf/clinical/mailbox/
slot.rs1use crate::crypto::network::digest::sha384;
4use crate::net::peer::replication::custody::{mark_stored, CustodyState};
5use crate::net::qdnf::contracts::BoundGenerations;
6use crate::net::qdnf::errors::QdnfError;
7use crate::net::qdnf::types::{Generation, StrongDigest};
8
9pub const STREAM_PAGE_BYTES: u32 = 4096;
11
12pub const MAILBOX_CIPHERTEXT_BYTES: usize = STREAM_PAGE_BYTES as usize;
14
15#[inline]
17pub const fn network_asserts_clinical_review() -> bool {
18 false
19}
20
21#[repr(u8)]
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum MailboxState {
26 Stored = 1,
27 Delivered = 2,
28 ClinicianReviewed = 3,
29}
30
31#[repr(C)]
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct MailboxSlot {
35 pub ciphertext: [u8; MAILBOX_CIPHERTEXT_BYTES],
36 pub ciphertext_len: u32,
37 pub ciphertext_digest: StrongDigest,
38 pub recipient: StrongDigest,
39 pub key_generation: u64,
40 pub bound: BoundGenerations,
41 pub grant_revoked: bool,
42 pub state: MailboxState,
43 pub custody: CustodyState,
44}
45
46impl MailboxSlot {
47 pub(super) fn from_ciphertext(
49 ct: &[u8],
50 recipient: StrongDigest,
51 key_generation: u64,
52 ) -> Result<Self, QdnfError> {
53 if ct.is_empty() || recipient == StrongDigest::ZERO {
54 return Err(QdnfError::Malformed);
55 }
56 if ct.len() > MAILBOX_CIPHERTEXT_BYTES {
57 return Err(QdnfError::Capacity);
58 }
59 let custody = mark_stored(false, true)?;
60 let mut ciphertext = [0u8; MAILBOX_CIPHERTEXT_BYTES];
61 ciphertext[..ct.len()].copy_from_slice(ct);
62 Ok(Self {
63 ciphertext,
64 ciphertext_len: ct.len() as u32,
65 ciphertext_digest: sha384(ct),
66 recipient,
67 key_generation,
68 bound: BoundGenerations::new(
69 Generation(key_generation),
70 Generation(key_generation),
71 Generation(key_generation),
72 ),
73 grant_revoked: false,
74 state: MailboxState::Stored,
75 custody,
76 })
77 }
78
79 #[inline]
81 pub fn ciphertext_bytes(&self) -> &[u8] {
82 &self.ciphertext[..self.ciphertext_len as usize]
83 }
84
85 #[inline]
87 pub fn bytes_present(&self) -> bool {
88 self.ciphertext_len > 0 && (self.ciphertext_len as usize) <= MAILBOX_CIPHERTEXT_BYTES
89 }
90
91 #[inline]
93 pub fn is_application_acked(&self) -> bool {
94 self.custody == CustodyState::ApplicationAcked
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn from_ciphertext_copies_bytes() {
104 let mut rec = StrongDigest::ZERO;
105 rec.0[0] = 2;
106 let ct = b"slot-ct";
107 let slot = MailboxSlot::from_ciphertext(ct, rec, 1).expect("slot");
108 assert_eq!(slot.state, MailboxState::Stored);
109 assert_eq!(slot.custody, CustodyState::Stored);
110 assert_eq!(slot.ciphertext_bytes(), ct);
111 assert!(slot.bytes_present());
112 assert!(!slot.is_application_acked());
113 assert!(!network_asserts_clinical_review());
114 }
115}