Skip to main content

adk_vision/
digest.rs

1//! [`Digest`]: the `sha256:<hex>` identity that travels instead of pixels.
2
3use std::fmt;
4use std::io::Read;
5use std::path::Path;
6use std::str::FromStr;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use sha2::{Digest as _, Sha256};
10
11use crate::error::{Result, VisionError};
12
13/// A SHA-256 digest in the form `sha256:<64 lowercase hex digits>`.
14///
15/// Images are identified by the digest of their encoded bytes; approvals, caches, ledgers,
16/// audit records and wake payloads carry the digest, never the pixels (V-I15).
17///
18/// # Example
19///
20/// ```
21/// use adk_vision::Digest;
22///
23/// let digest = Digest::of(b"abc");
24/// assert_eq!(
25///     digest.to_string(),
26///     "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
27/// );
28/// assert_eq!(digest.to_string().parse::<Digest>().unwrap(), digest);
29/// assert!("md5:abc".parse::<Digest>().is_err());
30/// ```
31#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
32pub struct Digest([u8; 32]);
33
34impl Digest {
35    /// The digest of `bytes`.
36    pub fn of(bytes: &[u8]) -> Self {
37        Self(Sha256::digest(bytes).into())
38    }
39
40    /// The digest of a value's canonical JSON form: object keys sorted, no whitespace.
41    ///
42    /// Used to identify operations (`Provenance::Derived::operation`), so the same edit of the
43    /// same image always has the same digest.
44    pub fn of_json<T: Serialize>(value: &T) -> Self {
45        let value = serde_json::to_value(value).unwrap_or(serde_json::Value::Null);
46        Self::of(canonical_json(&value).as_bytes())
47    }
48
49    /// Streams a file through SHA-256 without holding it in memory.
50    ///
51    /// # Errors
52    ///
53    /// Returns [`VisionError::Io`] when the file cannot be read.
54    pub fn of_file(path: &Path) -> Result<(Self, u64)> {
55        let mut file =
56            std::fs::File::open(path).map_err(|e| VisionError::io("could not open", path, e))?;
57        let mut hasher = Sha256::new();
58        let mut buffer = vec![0u8; 1 << 20];
59        let mut size = 0u64;
60        loop {
61            let read =
62                file.read(&mut buffer).map_err(|e| VisionError::io("could not read", path, e))?;
63            if read == 0 {
64                break;
65            }
66            size += read as u64;
67            hasher.update(&buffer[..read]);
68        }
69        Ok((Self(hasher.finalize().into()), size))
70    }
71
72    /// Parses 64 hex digits, with or without the `sha256:` prefix.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`VisionError::InvalidInput`] for anything else.
77    pub fn from_hex(hex_digits: &str) -> Result<Self> {
78        let digits = hex_digits.strip_prefix("sha256:").unwrap_or(hex_digits);
79        if digits.len() != 64 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
80            return Err(VisionError::InvalidInput(format!(
81                "`{hex_digits}` is not a SHA-256 digest; expected `sha256:` and 64 hex digits"
82            )));
83        }
84        let mut bytes = [0u8; 32];
85        hex::decode_to_slice(digits.to_ascii_lowercase(), &mut bytes)
86            .map_err(|e| VisionError::InvalidInput(format!("`{hex_digits}`: {e}")))?;
87        Ok(Self(bytes))
88    }
89
90    /// The 64 lowercase hex digits, without the prefix.
91    pub fn hex(&self) -> String {
92        hex::encode(self.0)
93    }
94
95    /// The raw 32 bytes.
96    pub fn as_bytes(&self) -> &[u8; 32] {
97        &self.0
98    }
99}
100
101impl fmt::Display for Digest {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "sha256:{}", self.hex())
104    }
105}
106
107impl fmt::Debug for Digest {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        write!(f, "Digest({self})")
110    }
111}
112
113impl FromStr for Digest {
114    type Err = VisionError;
115
116    fn from_str(s: &str) -> Result<Self> {
117        if !s.starts_with("sha256:") {
118            return Err(VisionError::InvalidInput(format!(
119                "`{s}` is not a digest; expected `sha256:` and 64 hex digits"
120            )));
121        }
122        Self::from_hex(s)
123    }
124}
125
126impl Serialize for Digest {
127    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
128        serializer.collect_str(self)
129    }
130}
131
132impl<'de> Deserialize<'de> for Digest {
133    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
134        let text = String::deserialize(deserializer)?;
135        text.parse().map_err(serde::de::Error::custom)
136    }
137}
138
139/// Serializes `value` with object keys sorted and no insignificant whitespace.
140pub(crate) fn canonical_json(value: &serde_json::Value) -> String {
141    match value {
142        serde_json::Value::Object(map) => {
143            let mut keys: Vec<&String> = map.keys().collect();
144            keys.sort();
145            let fields: Vec<String> = keys
146                .into_iter()
147                .map(|key| {
148                    let name = serde_json::Value::String(key.clone()).to_string();
149                    format!("{name}:{}", canonical_json(&map[key]))
150                })
151                .collect();
152            format!("{{{}}}", fields.join(","))
153        }
154        serde_json::Value::Array(items) => {
155            let items: Vec<String> = items.iter().map(canonical_json).collect();
156            format!("[{}]", items.join(","))
157        }
158        other => other.to_string(),
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn json_digests_ignore_key_order() {
168        let a = serde_json::json!({"b": 1, "a": [1, {"y": 2, "x": 1}]});
169        let b = serde_json::json!({"a": [1, {"x": 1, "y": 2}], "b": 1});
170        assert_eq!(Digest::of_json(&a), Digest::of_json(&b));
171        assert_eq!(canonical_json(&a), r#"{"a":[1,{"x":1,"y":2}],"b":1}"#);
172    }
173
174    #[test]
175    fn upper_case_hex_parses_to_the_same_digest() {
176        let digest = Digest::of(b"x");
177        let upper = format!("sha256:{}", digest.hex().to_uppercase());
178        assert_eq!(upper.parse::<Digest>().unwrap(), digest);
179        assert!(Digest::from_hex("abc").is_err());
180    }
181
182    #[test]
183    fn files_hash_like_bytes() {
184        let dir = tempfile::tempdir().unwrap();
185        let path = dir.path().join("f");
186        std::fs::write(&path, b"hello").unwrap();
187        assert_eq!(Digest::of_file(&path).unwrap(), (Digest::of(b"hello"), 5));
188    }
189}