OXYGENHUB

Coverage / crates/oxy-core/src/hash.rs 100.0%

83 of 83 lines run, 28 of 29 functions · run #263 on main · run missed

1
//! Object references: BLAKE3-256 over a domain-separating header and the body
2
//! (spec §5.2).
3
4
use std::fmt;
5
6
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
7
pub struct ObjectRef(pub [u8; 32]);
8
9
/// A change is referenced by the ObjectRef of its encoding.
10
pub type ChangeHash = ObjectRef;
11
/// An identity is referenced by the ObjectRef of its encoding.
12
pub type KeyId = ObjectRef;
13
14
impl ObjectRef {
15
    /// Reserved: means "this change" inside a change (spec §5.2, §7.4).
16
    pub const ZERO: ObjectRef = ObjectRef([0; 32]);
17
1830569×
    pub fn is_zero(&self) -> bool {
1930569×
        *self == Self::ZERO
2030569×
    }
21120728×
    pub fn to_hex(&self) -> String {
22120728×
        hex::encode(self.0)
23120728×
    }
2433407×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2533407×
        let v = hex::decode(s).ok()?;
2633403×
        let a: [u8; 32] = v.try_into().ok()?;
2733403×
        Some(ObjectRef(a))
2833407×
    }
29153859×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30153859×
        let a: [u8; 32] = b.try_into().ok()?;
31153859×
        Some(ObjectRef(a))
32153859×
    }
33
    /// First `n` hex characters.
343336×
    pub fn short(&self, n: usize) -> String {
353336×
        let h = self.to_hex();
363336×
        h[..n.min(h.len())].to_string()
373336×
    }
38113×
    pub fn starts_with_hex(&self, prefix: &str) -> bool {
39113×
        self.to_hex().starts_with(prefix)
40113×
    }
41
}
42
43
impl fmt::Display for ObjectRef {
44120×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45120×
        f.write_str(&self.to_hex())
46120×
    }
47
}
48
49
impl fmt::Debug for ObjectRef {
502606×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512606×
        write!(f, "#{}", self.short(12))
522606×
    }
53
}
54
55
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56
pub enum ObjectType {
57
    Chunk,
58
    Blob,
59
    Change,
60
    Checkpoint,
61
    Op,
62
    Attest,
63
    Identity,
64
    Policy,
65
    State,
66
    Receipt,
67
}
68
69
impl ObjectType {
70
    pub const ALL: [ObjectType; 10] = [
71
        ObjectType::Chunk,
72
        ObjectType::Blob,
73
        ObjectType::Change,
74
        ObjectType::Checkpoint,
75
        ObjectType::Op,
76
        ObjectType::Attest,
77
        ObjectType::Identity,
78
        ObjectType::Policy,
79
        ObjectType::State,
80
        ObjectType::Receipt,
81
    ];
82
83317070×
    pub fn name(self) -> &'static str {
84317070×
        match self {
8579481×
            ObjectType::Chunk => "chunk",
8646806×
            ObjectType::Blob => "blob",
8774703×
            ObjectType::Change => "change",
8824325×
            ObjectType::Checkpoint => "checkpoint",
8951053×
            ObjectType::Op => "op",
908801×
            ObjectType::Attest => "attest",
918263×
            ObjectType::Identity => "identity",
926276×
            ObjectType::Policy => "policy",
9317315×
            ObjectType::State => "state",
9447×
            ObjectType::Receipt => "receipt",
95
        }
96317070×
    }
97
9845948×
    pub fn from_name(s: &str) -> Option<ObjectType> {
99202196×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10045948×
    }
101
}
102
103
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
104103530×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
105103530×
    let mut h = blake3::Hasher::new();
106103530×
    h.update(&header(ty, body.len()));
107103530×
    h.update(body);
108103530×
    ObjectRef(*h.finalize().as_bytes())
109103530×
}
110
111114784×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
112114784×
    let mut v = Vec::with_capacity(32);
113114784×
    v.extend_from_slice(b"oxy1 ");
114114784×
    v.extend_from_slice(ty.name().as_bytes());
115114784×
    v.push(b' ');
116114784×
    v.extend_from_slice(len.to_string().as_bytes());
117114784×
    v.push(0);
118114784×
    v
119114784×
}
120
121
#[cfg(test)]
122
mod tests {
123
    use super::*;
124
125
    #[test]
1261×
    fn header_matches_spec() {
1271×
        assert_eq!(header(ObjectType::Chunk, 5), b"oxy1 chunk 5\0");
1281×
        assert_eq!(header(ObjectType::Change, 1234), b"oxy1 change 1234\0");
1291×
    }
130
131
    #[test]
1321×
    fn types_are_domain_separated() {
1331×
        let body = b"same bytes";
1341×
        let a = hash_object(ObjectType::Chunk, body);
1351×
        let b = hash_object(ObjectType::Blob, body);
1361×
        assert_ne!(a, b);
1371×
        assert_eq!(a, hash_object(ObjectType::Chunk, body));
138
        // Reference vector: pin so the format cannot drift silently.
1391×
        assert_eq!(
1401×
            hash_object(ObjectType::Chunk, b"").to_hex(),
1411×
            blake3::hash(b"oxy1 chunk 0\0").to_hex().as_str()
142
        );
1431×
    }
144
145
    #[test]
1461×
    fn hex_round_trip() {
1471×
        let r = hash_object(ObjectType::Chunk, b"x");
1481×
        assert_eq!(ObjectRef::from_hex(&r.to_hex()), Some(r));
1491×
        assert_eq!(ObjectRef::from_hex("zz"), None);
1501×
        assert!(r.starts_with_hex(&r.short(7)));
1511×
        assert!(ObjectRef::ZERO.is_zero());
15210×
        for t in ObjectType::ALL {
15310×
            assert_eq!(ObjectType::from_name(t.name()), Some(t));
154
        }
1551×
    }
156
}