OXYGENHUB

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

85 of 85 lines run, 28 of 29 functions · run #360 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
1832304×
    pub fn is_zero(&self) -> bool {
1932304×
        *self == Self::ZERO
2032304×
    }
21127081×
    pub fn to_hex(&self) -> String {
22127081×
        hex::encode(self.0)
23127081×
    }
2436032×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2536032×
        let v = hex::decode(s).ok()?;
2636028×
        let a: [u8; 32] = v.try_into().ok()?;
2736028×
        Some(ObjectRef(a))
2836032×
    }
29169259×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30169259×
        let a: [u8; 32] = b.try_into().ok()?;
31169259×
        Some(ObjectRef(a))
32169259×
    }
33
    /// First `n` hex characters.
343506×
    pub fn short(&self, n: usize) -> String {
353506×
        let h = self.to_hex();
363506×
        h[..n.min(h.len())].to_string()
373506×
    }
38122×
    pub fn starts_with_hex(&self, prefix: &str) -> bool {
39122×
        self.to_hex().starts_with(prefix)
40122×
    }
41
}
42
43
impl fmt::Display for ObjectRef {
44122×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45122×
        f.write_str(&self.to_hex())
46122×
    }
47
}
48
49
impl fmt::Debug for ObjectRef {
502738×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512738×
        write!(f, "#{}", self.short(12))
522738×
    }
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
    /// A short-lived key's certificate (oxygenhub#241).
68
    Certificate,
69
    /// An author's grant to a certified subject (§14.7).
70
    Grant,
71
}
72
73
impl ObjectType {
74
    pub const ALL: [ObjectType; 12] = [
75
        ObjectType::Chunk,
76
        ObjectType::Blob,
77
        ObjectType::Change,
78
        ObjectType::Checkpoint,
79
        ObjectType::Op,
80
        ObjectType::Attest,
81
        ObjectType::Identity,
82
        ObjectType::Policy,
83
        ObjectType::State,
84
        ObjectType::Receipt,
85
        ObjectType::Certificate,
86
        ObjectType::Grant,
87
    ];
88
89367162×
    pub fn name(self) -> &'static str {
90367162×
        match self {
9191199×
            ObjectType::Chunk => "chunk",
9253185×
            ObjectType::Blob => "blob",
9384720×
            ObjectType::Change => "change",
9428494×
            ObjectType::Checkpoint => "checkpoint",
9559212×
            ObjectType::Op => "op",
9611222×
            ObjectType::Attest => "attest",
9711419×
            ObjectType::Identity => "identity",
987768×
            ObjectType::Policy => "policy",
9919460×
            ObjectType::State => "state",
100147×
            ObjectType::Receipt => "receipt",
101323×
            ObjectType::Certificate => "certificate",
10213×
            ObjectType::Grant => "grant",
103
        }
104367162×
    }
105
10652648×
    pub fn from_name(s: &str) -> Option<ObjectType> {
107234687×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10852648×
    }
109
}
110
111
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
112119485×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
113119485×
    let mut h = blake3::Hasher::new();
114119485×
    h.update(&header(ty, body.len()));
115119485×
    h.update(body);
116119485×
    ObjectRef(*h.finalize().as_bytes())
117119485×
}
118
119132366×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
120132366×
    let mut v = Vec::with_capacity(32);
121132366×
    v.extend_from_slice(b"oxy1 ");
122132366×
    v.extend_from_slice(ty.name().as_bytes());
123132366×
    v.push(b' ');
124132366×
    v.extend_from_slice(len.to_string().as_bytes());
125132366×
    v.push(0);
126132366×
    v
127132366×
}
128
129
#[cfg(test)]
130
mod tests {
131
    use super::*;
132
133
    #[test]
1341×
    fn header_matches_spec() {
1351×
        assert_eq!(header(ObjectType::Chunk, 5), b"oxy1 chunk 5\0");
1361×
        assert_eq!(header(ObjectType::Change, 1234), b"oxy1 change 1234\0");
1371×
    }
138
139
    #[test]
1401×
    fn types_are_domain_separated() {
1411×
        let body = b"same bytes";
1421×
        let a = hash_object(ObjectType::Chunk, body);
1431×
        let b = hash_object(ObjectType::Blob, body);
1441×
        assert_ne!(a, b);
1451×
        assert_eq!(a, hash_object(ObjectType::Chunk, body));
146
        // Reference vector: pin so the format cannot drift silently.
1471×
        assert_eq!(
1481×
            hash_object(ObjectType::Chunk, b"").to_hex(),
1491×
            blake3::hash(b"oxy1 chunk 0\0").to_hex().as_str()
150
        );
1511×
    }
152
153
    #[test]
1541×
    fn hex_round_trip() {
1551×
        let r = hash_object(ObjectType::Chunk, b"x");
1561×
        assert_eq!(ObjectRef::from_hex(&r.to_hex()), Some(r));
1571×
        assert_eq!(ObjectRef::from_hex("zz"), None);
1581×
        assert!(r.starts_with_hex(&r.short(7)));
1591×
        assert!(ObjectRef::ZERO.is_zero());
16012×
        for t in ObjectType::ALL {
16112×
            assert_eq!(ObjectType::from_name(t.name()), Some(t));
162
        }
1631×
    }
164
}