OXYGENHUB

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

83 of 83 lines run, 28 of 29 functions · run #303 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
1831028×
    pub fn is_zero(&self) -> bool {
1931028×
        *self == Self::ZERO
2031028×
    }
21108817×
    pub fn to_hex(&self) -> String {
22108817×
        hex::encode(self.0)
23108817×
    }
2434481×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2534481×
        let v = hex::decode(s).ok()?;
2634477×
        let a: [u8; 32] = v.try_into().ok()?;
2734477×
        Some(ObjectRef(a))
2834481×
    }
29157361×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30157361×
        let a: [u8; 32] = b.try_into().ok()?;
31157361×
        Some(ObjectRef(a))
32157361×
    }
33
    /// First `n` hex characters.
343376×
    pub fn short(&self, n: usize) -> String {
353376×
        let h = self.to_hex();
363376×
        h[..n.min(h.len())].to_string()
373376×
    }
38119×
    pub fn starts_with_hex(&self, prefix: &str) -> bool {
39119×
        self.to_hex().starts_with(prefix)
40119×
    }
41
}
42
43
impl fmt::Display for ObjectRef {
44121×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45121×
        f.write_str(&self.to_hex())
46121×
    }
47
}
48
49
impl fmt::Debug for ObjectRef {
502646×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512646×
        write!(f, "#{}", self.short(12))
522646×
    }
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
83326773×
    pub fn name(self) -> &'static str {
84326773×
        match self {
8581012×
            ObjectType::Chunk => "chunk",
8648117×
            ObjectType::Blob => "blob",
8776797×
            ObjectType::Change => "change",
8825213×
            ObjectType::Checkpoint => "checkpoint",
8952778×
            ObjectType::Op => "op",
909338×
            ObjectType::Attest => "attest",
918997×
            ObjectType::Identity => "identity",
926580×
            ObjectType::Policy => "policy",
9317888×
            ObjectType::State => "state",
9453×
            ObjectType::Receipt => "receipt",
95
        }
96326773×
    }
97
9847250×
    pub fn from_name(s: &str) -> Option<ObjectType> {
99209033×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10047250×
    }
101
}
102
103
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
104106010×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
105106010×
    let mut h = blake3::Hasher::new();
106106010×
    h.update(&header(ty, body.len()));
107106010×
    h.update(body);
108106010×
    ObjectRef(*h.finalize().as_bytes())
109106010×
}
110
111117642×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
112117642×
    let mut v = Vec::with_capacity(32);
113117642×
    v.extend_from_slice(b"oxy1 ");
114117642×
    v.extend_from_slice(ty.name().as_bytes());
115117642×
    v.push(b' ');
116117642×
    v.extend_from_slice(len.to_string().as_bytes());
117117642×
    v.push(0);
118117642×
    v
119117642×
}
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
}