Skip to main content

sim_lib_journal/
object.rs

1use sha2::{Digest, Sha256};
2use sim_kernel::{ContentId, Symbol};
3
4use crate::JournalError;
5
6/// Immutable canonical bytes and their content identity.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct JournalObject {
9    pub id: ContentId,
10    pub bytes: Vec<u8>,
11}
12
13impl JournalObject {
14    /// Constructs an object using the journal's canonical byte identity.
15    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
16        let bytes = bytes.into();
17        let digest: [u8; 32] = Sha256::digest(&bytes).into();
18        Self {
19            id: ContentId::from_bytes(Symbol::qualified("journal", "sha256-bytes-v1"), digest),
20            bytes,
21        }
22    }
23
24    /// Rejects bytes that do not match their claimed identity.
25    pub fn verify(&self) -> Result<(), JournalError> {
26        if Self::from_bytes(self.bytes.clone()).id == self.id {
27            Ok(())
28        } else {
29            Err(JournalError::CorruptObject(self.id.clone()))
30        }
31    }
32}