Skip to main content

qualia_core_db/sensing/local_custody/
read.rs

1use super::{
2    entry_size, filename, validate_root, CustodyAuthority, CustodyError, SidecarReceipt,
3    HEADER_BYTES, MAGIC, SIDECAR_BYTES, SIDECAR_RECEIPT_BYTES,
4};
5use std::{io::Read, path::Path};
6
7pub struct ReadBundle {
8    pub receipt: SidecarReceipt,
9    pub payload_bytes: usize,
10}
11
12/// Read and verify one complete bundle into caller-owned buffers. Output is
13/// cleared on failure or unwind. Host read permission precedes I/O and is
14/// rechecked after receipt verification. The budget limits encoded entry size;
15/// an additional byte may be read to reject trailing data. This does not
16/// establish chain completeness.
17pub fn read_bundle(
18    root: &Path,
19    checkpoint: &[u8; 32],
20    byte_budget: usize,
21    sidecar: &mut [u8; SIDECAR_BYTES],
22    payload: &mut [u8],
23    authority: &mut impl CustodyAuthority,
24) -> Result<ReadBundle, CustodyError> {
25    sidecar.fill(0);
26    payload.fill(0);
27    let mut output = ClearOnDrop {
28        sidecar,
29        payload,
30        keep: false,
31    };
32    let result = read_inner(
33        root,
34        checkpoint,
35        byte_budget,
36        output.sidecar,
37        output.payload,
38        authority,
39    );
40    if result.is_ok() {
41        output.keep = true;
42    }
43    result
44}
45
46struct ClearOnDrop<'a> {
47    sidecar: &'a mut [u8; SIDECAR_BYTES],
48    payload: &'a mut [u8],
49    keep: bool,
50}
51
52impl Drop for ClearOnDrop<'_> {
53    fn drop(&mut self) {
54        if !self.keep {
55            self.sidecar.fill(0);
56            self.payload.fill(0);
57        }
58    }
59}
60
61fn read_inner(
62    root: &Path,
63    checkpoint: &[u8; 32],
64    byte_budget: usize,
65    sidecar: &mut [u8; SIDECAR_BYTES],
66    payload: &mut [u8],
67    authority: &mut impl CustodyAuthority,
68) -> Result<ReadBundle, CustodyError> {
69    validate_root(root)?;
70    entry_size(0, byte_budget)?;
71    if !authority.permit_read(root, checkpoint, byte_budget) {
72        return Err(CustodyError::PermissionDenied);
73    }
74    let name = filename(checkpoint);
75    let path = root.join(std::str::from_utf8(&name).map_err(|_| CustodyError::InvalidEncoding)?);
76    let mut file = super::open_checked::open_regular(&path)?;
77    let mut header = [0u8; HEADER_BYTES];
78    file.read_exact(&mut header)?;
79    if &header[..4] != MAGIC
80        || u16::from_le_bytes([header[4], header[5]]) != 1
81        || u16::from_le_bytes([header[6], header[7]]) as usize != HEADER_BYTES
82    {
83        return Err(CustodyError::InvalidEncoding);
84    }
85    let len = usize::try_from(u64::from_le_bytes(
86        header[8..16]
87            .try_into()
88            .map_err(|_| CustodyError::InvalidEncoding)?,
89    ))
90    .map_err(|_| CustodyError::TooLarge)?;
91    entry_size(len, byte_budget)?;
92    if len > payload.len() {
93        return Err(CustodyError::TooLarge);
94    }
95    file.read_exact(sidecar)?;
96    let mut encoded = [0u8; SIDECAR_RECEIPT_BYTES];
97    file.read_exact(&mut encoded)?;
98    let receipt = SidecarReceipt::decode(&encoded).map_err(CustodyError::Receipt)?;
99    if receipt.checkpoint() != *checkpoint {
100        return Err(CustodyError::CheckpointMismatch);
101    }
102    file.read_exact(&mut payload[..len])?;
103    let mut trailing = [0u8; 1];
104    if file.read(&mut trailing)? != 0 {
105        return Err(CustodyError::InvalidEncoding);
106    }
107    receipt
108        .verify_with_authority(sidecar, &payload[..len], len, authority)
109        .map_err(CustodyError::Receipt)?;
110    if !authority.permit_read(root, checkpoint, byte_budget) {
111        return Err(CustodyError::PermissionDenied);
112    }
113    Ok(ReadBundle {
114        receipt,
115        payload_bytes: len,
116    })
117}