~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
88 lines · 2.6 KB Raw History
//! LtHash, the set hash a space repo's commit sums its records with
//! (`spec/SPACES.md`, "The set hash, records and commits").

use sha2::{Digest, Sha256};

const LANES: usize = 1024;

/// The state: 1024 unsigned 16-bit lanes, starting all zeros. It depends
/// only on which elements are in it, not the order they came in.
#[derive(Clone, PartialEq, Eq)]
pub struct LtHash(Box<[u16; LANES]>);

impl Default for LtHash {
    fn default() -> LtHash {
        LtHash(Box::new([0; LANES]))
    }
}

impl std::fmt::Debug for LtHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LtHash({:?})", self.digest())
    }
}

/// An element's 2048 bytes: BLAKE3's extendable output of its UTF-8, read
/// as little-endian lanes.
fn expand(element: &str) -> [u16; LANES] {
    let mut bytes = [0u8; LANES * 2];
    blake3::Hasher::new()
        .update(element.as_bytes())
        .finalize_xof()
        .fill(&mut bytes);
    std::array::from_fn(|i| u16::from_le_bytes([bytes[2 * i], bytes[2 * i + 1]]))
}

impl LtHash {
    pub fn new() -> LtHash {
        LtHash::default()
    }

    /// Add an element: each lane its own, modulo 65536.
    pub fn add(&mut self, element: &str) {
        for (s, e) in self.0.iter_mut().zip(expand(element)) {
            *s = s.wrapping_add(e);
        }
    }

    /// Remove an element: each lane less its own, modulo 65536.
    pub fn remove(&mut self, element: &str) {
        for (s, e) in self.0.iter_mut().zip(expand(element)) {
            *s = s.wrapping_sub(e);
        }
    }

    /// The state's 2048 bytes, the lanes little-endian.
    pub fn state(&self) -> [u8; LANES * 2] {
        let mut out = [0u8; LANES * 2];
        for (chunk, lane) in out.as_chunks_mut::<2>().0.iter_mut().zip(self.0.iter()) {
            *chunk = lane.to_le_bytes();
        }
        out
    }

    /// The hash whose state is `bytes`, as `state` gives them, if they are
    /// one's: 2048 of them.
    pub fn from_state(bytes: &[u8]) -> Option<LtHash> {
        let (lanes, rest) = bytes.as_chunks::<2>();
        if lanes.len() != LANES || !rest.is_empty() {
            return None;
        }
        let mut h = LtHash::new();
        for (lane, bytes) in h.0.iter_mut().zip(lanes) {
            *lane = u16::from_le_bytes(*bytes);
        }
        Some(h)
    }

    /// SHA-256 of the state's bytes: a commit's `data`.
    pub fn digest(&self) -> [u8; 32] {
        Sha256::digest(self.state()).into()
    }
}

/// A record's element: `{collection}/{rkey}/{cid}`, given its path
/// `{collection}/{rkey}` and its CID as a string.
pub fn element(path: &str, cid: &str) -> String {
    format!("{path}/{cid}")
}