OXYGENHUB
# c7161ec1a607 spectra / crates / spectra-core / src / attachments.rs
970 B · Rust · last changed Spectra stands alone: its own identities, signatures and CBOR; projects of any kind of work (#26, #27) 1 day ago source blame history raw
1
//! Bytes kept beside the ledger, named by their BLAKE3 (spec §7.2): tool
2
//! call arguments and results in full, so the audit is never truncated;
3
//! retention drops old bodies and keeps the hashes (spec §22.1).
4
5
use anyhow::Result;
6
use std::path::Path;
7
8
/// Store `bytes` under `<data>/attachments/` and return their hash (hex).
9
pub fn put(data: &Path, bytes: &[u8]) -> Result<String> {
10
    let hash = blake3::hash(bytes).to_hex().to_string();
11
    let dir = data.join("attachments").join(&hash[..2]);
12
    let path = dir.join(&hash);
13
    if !path.exists() {
14
        std::fs::create_dir_all(&dir)?;
15
        crate::durable::write_atomic(&path, bytes)?;
16
    }
17
    Ok(hash)
18
}
19
20
/// The bytes stored under `hash`, if they are still kept.
21
pub fn get(data: &Path, hash: &str) -> Option<Vec<u8>> {
22
    if hash.len() < 3 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
23
        return None;
24
    }
25
    std::fs::read(data.join("attachments").join(&hash[..2]).join(hash)).ok()
26
}