OXYGENHUB

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

83 of 83 lines run, 28 of 29 functions · run #302 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
1831228×
    pub fn is_zero(&self) -> bool {
1931228×
        *self == Self::ZERO
2031228×
    }
21111161×
    pub fn to_hex(&self) -> String {
22111161×
        hex::encode(self.0)
23111161×
    }
2434983×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2534983×
        let v = hex::decode(s).ok()?;
2634979×
        let a: [u8; 32] = v.try_into().ok()?;
2734979×
        Some(ObjectRef(a))
2834983×
    }
29159935×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30159935×
        let a: [u8; 32] = b.try_into().ok()?;
31159935×
        Some(ObjectRef(a))
32159935×
    }
33
    /// First `n` hex characters.
343382×
    pub fn short(&self, n: usize) -> String {
353382×
        let h = self.to_hex();
363382×
        h[..n.min(h.len())].to_string()
373382×
    }
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 {
502642×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512642×
        write!(f, "#{}", self.short(12))
522642×
    }
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
83332878×
    pub fn name(self) -> &'static str {
84332878×
        match self {
8581963×
            ObjectType::Chunk => "chunk",
8649068×
            ObjectType::Blob => "blob",
8778623×
            ObjectType::Change => "change",
8825717×
            ObjectType::Checkpoint => "checkpoint",
8953884×
            ObjectType::Op => "op",
909462×
            ObjectType::Attest => "attest",
919125×
            ObjectType::Identity => "identity",
926704×
            ObjectType::Policy => "policy",
9318279×
            ObjectType::State => "state",
9453×
            ObjectType::Receipt => "receipt",
95
        }
96332878×
    }
97
9848201×
    pub fn from_name(s: &str) -> Option<ObjectType> {
99213390×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10048201×
    }
101
}
102
103
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
104107551×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
105107551×
    let mut h = blake3::Hasher::new();
106107551×
    h.update(&header(ty, body.len()));
107107551×
    h.update(body);
108107551×
    ObjectRef(*h.finalize().as_bytes())
109107551×
}
110
111119393×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
112119393×
    let mut v = Vec::with_capacity(32);
113119393×
    v.extend_from_slice(b"oxy1 ");
114119393×
    v.extend_from_slice(ty.name().as_bytes());
115119393×
    v.push(b' ');
116119393×
    v.extend_from_slice(len.to_string().as_bytes());
117119393×
    v.push(0);
118119393×
    v
119119393×
}
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
}