1use std::{fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use sha2::{Digest as _, Sha256};
11use thiserror::Error;
12
13const SHA256_PREFIX: &str = "sha256:";
14const SHA256_TEXT_LEN: usize = SHA256_PREFIX.len() + (Digest::SHA256_LEN * 2);
15const SHA256_PATTERN: &str = "^sha256:[0-9a-f]{64}$";
16
17#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
19#[non_exhaustive]
20pub enum DigestAlgorithm {
21 Sha256,
23}
24
25impl DigestAlgorithm {
26 #[must_use]
28 pub const fn as_str(self) -> &'static str {
29 match self {
30 Self::Sha256 => "sha256",
31 }
32 }
33}
34
35impl fmt::Display for DigestAlgorithm {
36 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37 formatter.write_str(self.as_str())
38 }
39}
40
41#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
42enum DigestValue {
43 Sha256([u8; Digest::SHA256_LEN]),
44}
45
46#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
51pub struct Digest(DigestValue);
52
53impl Digest {
54 pub const SHA256_LEN: usize = 32;
56
57 #[must_use]
59 pub fn sha256(input: impl AsRef<[u8]>) -> Self {
60 let bytes: [u8; Self::SHA256_LEN] = Sha256::digest(input.as_ref()).into();
61 Self::from_sha256(bytes)
62 }
63
64 #[must_use]
66 pub const fn from_sha256(bytes: [u8; Self::SHA256_LEN]) -> Self {
67 Self(DigestValue::Sha256(bytes))
68 }
69
70 #[must_use]
72 pub const fn algorithm(self) -> DigestAlgorithm {
73 match self.0 {
74 DigestValue::Sha256(_) => DigestAlgorithm::Sha256,
75 }
76 }
77
78 #[must_use]
80 pub const fn as_bytes(&self) -> &[u8] {
81 match &self.0 {
82 DigestValue::Sha256(bytes) => bytes,
83 }
84 }
85}
86
87impl fmt::Debug for Digest {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 formatter
90 .debug_tuple("Digest")
91 .field(&format_args!("{self}"))
92 .finish()
93 }
94}
95
96impl fmt::Display for Digest {
97 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98 write!(formatter, "{}:", self.algorithm())?;
99 for byte in self.as_bytes() {
100 write!(formatter, "{byte:02x}")?;
101 }
102 Ok(())
103 }
104}
105
106impl FromStr for Digest {
107 type Err = DigestError;
108
109 fn from_str(value: &str) -> Result<Self, Self::Err> {
110 if value.len() > SHA256_TEXT_LEN {
111 return Err(DigestError::TooLong {
112 max: SHA256_TEXT_LEN,
113 actual: value.len(),
114 });
115 }
116
117 let (algorithm, encoded) = value.split_once(':').ok_or(DigestError::InvalidFormat)?;
118 if algorithm != DigestAlgorithm::Sha256.as_str() {
119 return if algorithm.eq_ignore_ascii_case(DigestAlgorithm::Sha256.as_str()) {
120 Err(DigestError::NonCanonical)
121 } else {
122 Err(DigestError::UnsupportedAlgorithm)
123 };
124 }
125 if encoded.len() != Self::SHA256_LEN * 2 {
126 return Err(DigestError::InvalidLength {
127 expected: Self::SHA256_LEN * 2,
128 actual: encoded.len(),
129 });
130 }
131
132 let mut bytes = [0_u8; Self::SHA256_LEN];
133 for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() {
134 let high = decode_nibble(pair[0], SHA256_PREFIX.len() + index * 2)?;
135 let low = decode_nibble(pair[1], SHA256_PREFIX.len() + index * 2 + 1)?;
136 bytes[index] = (high << 4) | low;
137 }
138 Ok(Self::from_sha256(bytes))
139 }
140}
141
142impl Serialize for Digest {
143 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
144 where
145 S: Serializer,
146 {
147 serializer.collect_str(self)
148 }
149}
150
151impl<'de> Deserialize<'de> for Digest {
152 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
153 where
154 D: Deserializer<'de>,
155 {
156 deserializer.deserialize_str(DigestVisitor)
157 }
158}
159
160impl JsonSchema for Digest {
161 fn schema_name() -> std::borrow::Cow<'static, str> {
162 "Digest".into()
163 }
164
165 fn schema_id() -> std::borrow::Cow<'static, str> {
166 concat!(module_path!(), "::Digest").into()
167 }
168
169 fn json_schema(_: &mut SchemaGenerator) -> Schema {
170 json_schema!({
171 "type": "string",
172 "minLength": 71,
173 "maxLength": 71,
174 "pattern": SHA256_PATTERN
175 })
176 }
177
178 fn inline_schema() -> bool {
179 true
180 }
181}
182
183#[derive(Clone, Debug, Eq, Error, PartialEq)]
185#[non_exhaustive]
186pub enum DigestError {
187 #[error("digest is {actual} bytes; maximum is {max}")]
189 TooLong {
190 max: usize,
192 actual: usize,
194 },
195
196 #[error("digest must contain an algorithm and encoded value")]
198 InvalidFormat,
199
200 #[error("digest algorithm is not supported")]
202 UnsupportedAlgorithm,
203
204 #[error("digest must use lowercase canonical text")]
206 NonCanonical,
207
208 #[error("digest value is {actual} bytes; expected {expected}")]
210 InvalidLength {
211 expected: usize,
213 actual: usize,
215 },
216
217 #[error("digest contains invalid hexadecimal text at offset {index}")]
219 InvalidHex {
220 index: usize,
222 },
223}
224
225struct DigestVisitor;
226
227impl de::Visitor<'_> for DigestVisitor {
228 type Value = Digest;
229
230 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231 formatter.write_str("a canonical StateKnot integrity digest")
232 }
233
234 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
235 where
236 E: de::Error,
237 {
238 value.parse().map_err(E::custom)
239 }
240}
241
242fn decode_nibble(value: u8, index: usize) -> Result<u8, DigestError> {
243 match value {
244 b'0'..=b'9' => Ok(value - b'0'),
245 b'a'..=b'f' => Ok(value - b'a' + 10),
246 b'A'..=b'F' => Err(DigestError::NonCanonical),
247 _ => Err(DigestError::InvalidHex { index }),
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use serde_json::{Value, from_str, from_value, to_string};
255
256 const EMPTY_SHA256: &str =
257 "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
258 const ABC_SHA256: &str =
259 "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
260
261 #[test]
262 fn sha256_matches_published_vectors_and_round_trips() {
263 let empty = Digest::sha256([]);
264 assert_eq!(empty.to_string(), EMPTY_SHA256);
265 assert_eq!(empty.algorithm(), DigestAlgorithm::Sha256);
266 assert_eq!(empty.as_bytes().len(), Digest::SHA256_LEN);
267 assert_eq!(EMPTY_SHA256.parse::<Digest>().unwrap(), empty);
268
269 let abc = Digest::sha256(b"abc");
270 assert_eq!(abc.to_string(), ABC_SHA256);
271 assert_eq!(ABC_SHA256.parse::<Digest>().unwrap(), abc);
272 }
273
274 #[test]
275 fn digest_rejects_noncanonical_or_malformed_text() {
276 assert_eq!("sha256".parse::<Digest>(), Err(DigestError::InvalidFormat));
277 assert_eq!(
278 ABC_SHA256.replace("sha256", "sha512").parse::<Digest>(),
279 Err(DigestError::UnsupportedAlgorithm)
280 );
281 assert_eq!(
282 ABC_SHA256.replace("sha256", "SHA256").parse::<Digest>(),
283 Err(DigestError::NonCanonical)
284 );
285 assert_eq!(
286 ABC_SHA256.to_ascii_uppercase().parse::<Digest>(),
287 Err(DigestError::NonCanonical)
288 );
289
290 let short = "sha256:00";
291 assert_eq!(
292 short.parse::<Digest>(),
293 Err(DigestError::InvalidLength {
294 expected: Digest::SHA256_LEN * 2,
295 actual: 2,
296 })
297 );
298
299 let invalid = ABC_SHA256.replacen('b', "g", 1);
300 assert_eq!(
301 invalid.parse::<Digest>(),
302 Err(DigestError::InvalidHex {
303 index: SHA256_PREFIX.len(),
304 })
305 );
306
307 let too_long = format!("{ABC_SHA256}0");
308 assert_eq!(
309 too_long.parse::<Digest>(),
310 Err(DigestError::TooLong {
311 max: SHA256_TEXT_LEN,
312 actual: too_long.len(),
313 })
314 );
315 }
316
317 #[test]
318 fn digest_serde_uses_and_enforces_canonical_text() {
319 let digest = Digest::sha256(b"serde");
320 let encoded = to_string(&digest).unwrap();
321 assert_eq!(from_str::<Digest>(&encoded).unwrap(), digest);
322 assert!(from_value::<Digest>(Value::Null).is_err());
323 assert!(from_str::<Digest>(&format!("\"{}\"", digest.to_string().to_uppercase())).is_err());
324 }
325
326 #[test]
327 fn digest_schema_matches_runtime_bounds() {
328 let schema = serde_json::to_value(schemars::schema_for!(Digest)).unwrap();
329 assert_eq!(schema["type"], "string");
330 assert_eq!(schema["minLength"], SHA256_TEXT_LEN);
331 assert_eq!(schema["maxLength"], SHA256_TEXT_LEN);
332 assert_eq!(schema["pattern"], SHA256_PATTERN);
333 }
334}