OXYGENHUB
# 8b3c9b2ba502 oxygen / crates / oxy-core / src / hash.rs
4.3 KiB · Rust · last changed Execution receipts: the receipt object and attestation 1 month ago source blame history raw
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
18
    pub fn is_zero(&self) -> bool {
19
        *self == Self::ZERO
20
    }
21
    pub fn to_hex(&self) -> String {
22
        hex::encode(self.0)
23
    }
24
    pub fn from_hex(s: &str) -> Option<ObjectRef> {
25
        let v = hex::decode(s).ok()?;
26
        let a: [u8; 32] = v.try_into().ok()?;
27
        Some(ObjectRef(a))
28
    }
29
    pub fn from_slice(b: &[u8]) -> Option<ObjectRef> {
30
        let a: [u8; 32] = b.try_into().ok()?;
31
        Some(ObjectRef(a))
32
    }
33
    /// First `n` hex characters.
34
    pub fn short(&self, n: usize) -> String {
35
        let h = self.to_hex();
36
        h[..n.min(h.len())].to_string()
37
    }
38
    pub fn starts_with_hex(&self, prefix: &str) -> bool {
39
        self.to_hex().starts_with(prefix)
40
    }
41
}
42
43
impl fmt::Display for ObjectRef {
44
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45
        f.write_str(&self.to_hex())
46
    }
47
}
48
49
impl fmt::Debug for ObjectRef {
50
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51
        write!(f, "#{}", self.short(12))
52
    }
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
83
    pub fn name(self) -> &'static str {
84
        match self {
85
            ObjectType::Chunk => "chunk",
86
            ObjectType::Blob => "blob",
87
            ObjectType::Change => "change",
88
            ObjectType::Checkpoint => "checkpoint",
89
            ObjectType::Op => "op",
90
            ObjectType::Attest => "attest",
91
            ObjectType::Identity => "identity",
92
            ObjectType::Policy => "policy",
93
            ObjectType::State => "state",
94
            ObjectType::Receipt => "receipt",
95
        }
96
    }
97
98
    pub fn from_name(s: &str) -> Option<ObjectType> {
99
        Self::ALL.iter().copied().find(|t| t.name() == s)
100
    }
101
}
102
103
/// `ObjectRef = BLAKE3-256("oxy1 " || type || " " || decimal(len) || 0x00 || body)`.
104
pub fn hash_object(ty: ObjectType, body: &[u8]) -> ObjectRef {
105
    let mut h = blake3::Hasher::new();
106
    h.update(&header(ty, body.len()));
107
    h.update(body);
108
    ObjectRef(*h.finalize().as_bytes())
109
}
110
111
pub fn header(ty: ObjectType, len: usize) -> Vec<u8> {
112
    let mut v = Vec::with_capacity(32);
113
    v.extend_from_slice(b"oxy1 ");
114
    v.extend_from_slice(ty.name().as_bytes());
115
    v.push(b' ');
116
    v.extend_from_slice(len.to_string().as_bytes());
117
    v.push(0);
118
    v
119
}
120
121
#[cfg(test)]
122
mod tests {
123
    use super::*;
124
125
    #[test]
126
    fn header_matches_spec() {
127
        assert_eq!(header(ObjectType::Chunk, 5), b"oxy1 chunk 5\0");
128
        assert_eq!(header(ObjectType::Change, 1234), b"oxy1 change 1234\0");
129
    }
130
131
    #[test]
132
    fn types_are_domain_separated() {
133
        let body = b"same bytes";
134
        let a = hash_object(ObjectType::Chunk, body);
135
        let b = hash_object(ObjectType::Blob, body);
136
        assert_ne!(a, b);
137
        assert_eq!(a, hash_object(ObjectType::Chunk, body));
138
        // Reference vector: pin so the format cannot drift silently.
139
        assert_eq!(
140
            hash_object(ObjectType::Chunk, b"").to_hex(),
141
            blake3::hash(b"oxy1 chunk 0\0").to_hex().as_str()
142
        );
143
    }
144
145
    #[test]
146
    fn hex_round_trip() {
147
        let r = hash_object(ObjectType::Chunk, b"x");
148
        assert_eq!(ObjectRef::from_hex(&r.to_hex()), Some(r));
149
        assert_eq!(ObjectRef::from_hex("zz"), None);
150
        assert!(r.starts_with_hex(&r.short(7)));
151
        assert!(ObjectRef::ZERO.is_zero());
152
        for t in ObjectType::ALL {
153
            assert_eq!(ObjectType::from_name(t.name()), Some(t));
154
        }
155
    }
156
}