OXYGENHUB

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

83 of 83 lines run, 28 of 29 functions · run #275 on carry-identical · 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
1830899×
    pub fn is_zero(&self) -> bool {
1930899×
        *self == Self::ZERO
2030899×
    }
21121988×
    pub fn to_hex(&self) -> String {
22121988×
        hex::encode(self.0)
23121988×
    }
2433879×
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
2533879×
        let v = hex::decode(s).ok()?;
2633875×
        let a: [u8; 32] = v.try_into().ok()?;
2733875×
        Some(ObjectRef(a))
2833879×
    }
29155093×
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30155093×
        let a: [u8; 32] = b.try_into().ok()?;
31155093×
        Some(ObjectRef(a))
32155093×
    }
33
    /// First `n` hex characters.
343355×
    pub fn short(&self, n: usize) -> String {
353355×
        let h = self.to_hex();
363355×
        h[..n.min(h.len())].to_string()
373355×
    }
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 {
502634×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512634×
        write!(f, "#{}", self.short(12))
522634×
    }
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
83320044×
    pub fn name(self) -> &'static str {
84320044×
        match self {
8580091×
            ObjectType::Chunk => "chunk",
8647272×
            ObjectType::Blob => "blob",
8775860×
            ObjectType::Change => "change",
8824463×
            ObjectType::Checkpoint => "checkpoint",
8951440×
            ObjectType::Op => "op",
908835×
            ObjectType::Attest => "attest",
918297×
            ObjectType::Identity => "identity",
926309×
            ObjectType::Policy => "policy",
9317430×
            ObjectType::State => "state",
9447×
            ObjectType::Receipt => "receipt",
95
        }
96320044×
    }
97
9846406×
    pub fn from_name(s: &str) -> Option<ObjectType> {
99203926×
        Self::ALL.iter().copied().find(|t| t.name() == s)
10046406×
    }
101
}
102
103
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
104104579×
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
105104579×
    let mut h = blake3::Hasher::new();
106104579×
    h.update(&header(ty, body.len()));
107104579×
    h.update(body);
108104579×
    ObjectRef(*h.finalize().as_bytes())
109104579×
}
110
111116023×
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
112116023×
    let mut v = Vec::with_capacity(32);
113116023×
    v.extend_from_slice(b"oxy1 ");
114116023×
    v.extend_from_slice(ty.name().as_bytes());
115116023×
    v.push(b' ');
116116023×
    v.extend_from_slice(len.to_string().as_bytes());
117116023×
    v.push(0);
118116023×
    v
119116023×
}
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
}