OXYGENHUB

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

84 of 84 lines run, 28 of 29 functions · run #311 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
1830873×
    pub fn is_zero(&self) -> bool {
1930873×
        *self == Self::ZERO
2030873×
    }
21109551×
    pub fn to_hex(&self) -> String {
22109551×
        hex::encode(self.0)
23109551×
    }
2434909×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2534909×
        let v = hex::decode(s).ok()?;
2634905×
        let a: [u8; 32] = v.try_into().ok()?;
2734905×
        Some(ObjectRef(a))
2834909×
    }
29158046×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30158046×
        let a: [u8; 32] = b.try_into().ok()?;
31158046×
        Some(ObjectRef(a))
32158046×
    }
33
    /// First `n` hex characters.
343379×
    pub fn short(&self, n: usize) -> String {
353379×
        let h = self.to_hex();
363379×
        h[..n.min(h.len())].to_string()
373379×
    }
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
    /// A short-lived key's certificate (oxygenhub#241).
68
    Certificate,
69
}
70
71
impl ObjectType {
72
    pub const ALL: [ObjectType; 11] = [
73
        ObjectType::Chunk,
74
        ObjectType::Blob,
75
        ObjectType::Change,
76
        ObjectType::Checkpoint,
77
        ObjectType::Op,
78
        ObjectType::Attest,
79
        ObjectType::Identity,
80
        ObjectType::Policy,
81
        ObjectType::State,
82
        ObjectType::Receipt,
83
        ObjectType::Certificate,
84
    ];
85
86328811×
    pub fn name(self) -> &'static str {
87328811×
        match self {
8881326×
            ObjectType::Chunk => "chunk",
8948423×
            ObjectType::Blob => "blob",
9077542×
            ObjectType::Change => "change",
9125320×
            ObjectType::Checkpoint => "checkpoint",
9253025×
            ObjectType::Op => "op",
939386×
            ObjectType::Attest => "attest",
949142×
            ObjectType::Identity => "identity",
956607×
            ObjectType::Policy => "policy",
9617924×
            ObjectType::State => "state",
9781×
            ObjectType::Receipt => "receipt",
9835×
            ObjectType::Certificate => "certificate",
99
        }
100328811×
    }
101
10247558×
    pub fn from_name(s: &str) -> Option<ObjectType> {
103210266×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10447558×
    }
105
}
106
107
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
108106738×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
109106738×
    let mut h = blake3::Hasher::new();
110106738×
    h.update(&header(ty, body.len()));
111106738×
    h.update(body);
112106738×
    ObjectRef(*h.finalize().as_bytes())
113106738×
}
114
115118450×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
116118450×
    let mut v = Vec::with_capacity(32);
117118450×
    v.extend_from_slice(b"oxy1 ");
118118450×
    v.extend_from_slice(ty.name().as_bytes());
119118450×
    v.push(b' ');
120118450×
    v.extend_from_slice(len.to_string().as_bytes());
121118450×
    v.push(0);
122118450×
    v
123118450×
}
124
125
#[cfg(test)]
126
mod tests {
127
    use super::*;
128
129
    #[test]
1301×
    fn header_matches_spec() {
1311×
        assert_eq!(header(ObjectType::Chunk, 5), b"oxy1 chunk 5\0");
1321×
        assert_eq!(header(ObjectType::Change, 1234), b"oxy1 change 1234\0");
1331×
    }
134
135
    #[test]
1361×
    fn types_are_domain_separated() {
1371×
        let body = b"same bytes";
1381×
        let a = hash_object(ObjectType::Chunk, body);
1391×
        let b = hash_object(ObjectType::Blob, body);
1401×
        assert_ne!(a, b);
1411×
        assert_eq!(a, hash_object(ObjectType::Chunk, body));
142
        // Reference vector: pin so the format cannot drift silently.
1431×
        assert_eq!(
1441×
            hash_object(ObjectType::Chunk, b"").to_hex(),
1451×
            blake3::hash(b"oxy1 chunk 0\0").to_hex().as_str()
146
        );
1471×
    }
148
149
    #[test]
1501×
    fn hex_round_trip() {
1511×
        let r = hash_object(ObjectType::Chunk, b"x");
1521×
        assert_eq!(ObjectRef::from_hex(&r.to_hex()), Some(r));
1531×
        assert_eq!(ObjectRef::from_hex("zz"), None);
1541×
        assert!(r.starts_with_hex(&r.short(7)));
1551×
        assert!(ObjectRef::ZERO.is_zero());
15611×
        for t in ObjectType::ALL {
15711×
            assert_eq!(ObjectType::from_name(t.name()), Some(t));
158
        }
1591×
    }
160
}