1use ostrya_gvariant::{GvEncode, GvType};
11
12use crate::error::{Error, Result};
13
14#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct Checksum([u8; 32]);
21
22const STD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23const MOD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
24
25impl Checksum {
26 pub fn from_bytes(b: [u8; 32]) -> Checksum {
28 Checksum(b)
29 }
30
31 pub fn sha256(data: &[u8]) -> Checksum {
34 use sha2::{Digest, Sha256};
35 Checksum(Sha256::digest(data).into())
36 }
37
38 pub fn as_bytes(&self) -> &[u8; 32] {
40 &self.0
41 }
42
43 pub fn from_hex_lower(s: &str) -> Result<Checksum> {
52 if s.bytes().any(|b| b.is_ascii_uppercase()) {
53 return Err(Error::InvalidChecksum("hex checksum is not lowercase"));
54 }
55 Checksum::from_hex(s)
56 }
57
58 pub fn from_hex(s: &str) -> Result<Checksum> {
60 let bytes = s.as_bytes();
61 if bytes.len() != 64 {
62 return Err(Error::InvalidChecksum("hex checksum is not 64 characters"));
63 }
64 let mut out = [0u8; 32];
65 for (i, pair) in bytes.chunks_exact(2).enumerate() {
66 let hi = hex_val(pair[0])?;
67 let lo = hex_val(pair[1])?;
68 out[i] = (hi << 4) | lo;
69 }
70 Ok(Checksum(out))
71 }
72
73 pub fn to_hex(&self) -> String {
75 const HEX: &[u8; 16] = b"0123456789abcdef";
76 let mut s = String::with_capacity(64);
77 for &b in &self.0 {
78 s.push(HEX[(b >> 4) as usize] as char);
79 s.push(HEX[(b & 0x0f) as usize] as char);
80 }
81 s
82 }
83
84 pub fn from_ay(b: &[u8]) -> Result<Checksum> {
87 let arr: [u8; 32] = b
88 .try_into()
89 .map_err(|_| Error::InvalidChecksum("ay checksum is not 32 bytes"))?;
90 Ok(Checksum(arr))
91 }
92
93 pub fn to_base64(&self) -> String {
95 base64_encode(&self.0, STD_ALPHABET, true)
96 }
97
98 pub fn from_base64(s: &str) -> Result<Checksum> {
100 Ok(Checksum(base64_decode_checksum(s, STD_ALPHABET, true)?))
101 }
102
103 pub fn to_base64_modified(&self) -> String {
106 base64_encode(&self.0, MOD_ALPHABET, false)
107 }
108
109 pub fn from_base64_modified(s: &str) -> Result<Checksum> {
111 Ok(Checksum(base64_decode_checksum(s, MOD_ALPHABET, false)?))
112 }
113}
114
115fn hex_val(c: u8) -> Result<u8> {
116 match c {
117 b'0'..=b'9' => Ok(c - b'0'),
118 b'a'..=b'f' => Ok(c - b'a' + 10),
119 b'A'..=b'F' => Ok(c - b'A' + 10),
120 _ => Err(Error::InvalidChecksum(
121 "hex checksum has a non-hex character",
122 )),
123 }
124}
125
126fn base64_encode(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
127 let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
128 for chunk in input.chunks(3) {
129 let b0 = chunk[0];
130 out.push(alphabet[(b0 >> 2) as usize] as char);
131 match chunk.len() {
132 1 => {
133 out.push(alphabet[((b0 & 0x03) << 4) as usize] as char);
134 if pad {
135 out.push_str("==");
136 }
137 }
138 2 => {
139 let b1 = chunk[1];
140 out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
141 out.push(alphabet[((b1 & 0x0f) << 2) as usize] as char);
142 if pad {
143 out.push('=');
144 }
145 }
146 _ => {
147 let (b1, b2) = (chunk[1], chunk[2]);
148 out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
149 out.push(alphabet[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
150 out.push(alphabet[(b2 & 0x3f) as usize] as char);
151 }
152 }
153 }
154 out
155}
156
157fn base64_decode_checksum(s: &str, alphabet: &[u8; 64], padded: bool) -> Result<[u8; 32]> {
167 let bytes = s.as_bytes();
168 let expected = if padded { 44 } else { 43 };
169 if bytes.len() != expected {
170 return Err(Error::InvalidChecksum(
171 "base64 checksum has the wrong length",
172 ));
173 }
174 if padded && bytes[43] != b'=' {
175 return Err(Error::InvalidChecksum("base64 checksum is missing its pad"));
176 }
177 let data = &bytes[..43];
178 let mut out = [0u8; 32];
179 for (group, chunk) in data[..40].chunks_exact(4).enumerate() {
180 let s0 = base64_val(chunk[0], alphabet)?;
181 let s1 = base64_val(chunk[1], alphabet)?;
182 let s2 = base64_val(chunk[2], alphabet)?;
183 let s3 = base64_val(chunk[3], alphabet)?;
184 out[group * 3] = (s0 << 2) | (s1 >> 4);
185 out[group * 3 + 1] = (s1 << 4) | (s2 >> 2);
186 out[group * 3 + 2] = (s2 << 6) | s3;
187 }
188 let s0 = base64_val(data[40], alphabet)?;
189 let s1 = base64_val(data[41], alphabet)?;
190 let s2 = base64_val(data[42], alphabet)?;
191 if s2 & 0x03 != 0 {
192 return Err(Error::InvalidChecksum(
193 "base64 checksum has nonzero trailing bits",
194 ));
195 }
196 out[30] = (s0 << 2) | (s1 >> 4);
197 out[31] = (s1 << 4) | (s2 >> 2);
198 Ok(out)
199}
200
201fn base64_val(c: u8, alphabet: &[u8; 64]) -> Result<u8> {
202 match c {
203 b'A'..=b'Z' => Ok(c - b'A'),
204 b'a'..=b'z' => Ok(c - b'a' + 26),
205 b'0'..=b'9' => Ok(c - b'0' + 52),
206 b'+' => Ok(62),
207 _ if c == alphabet[63] => Ok(63),
210 _ => Err(Error::InvalidChecksum("base64 has an invalid character")),
211 }
212}
213
214impl std::fmt::Display for Checksum {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 f.write_str(&self.to_hex())
217 }
218}
219
220impl std::fmt::Debug for Checksum {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 write!(f, "Checksum({})", self.to_hex())
223 }
224}
225
226impl std::str::FromStr for Checksum {
227 type Err = Error;
228 fn from_str(s: &str) -> Result<Checksum> {
229 Checksum::from_hex(s)
230 }
231}
232
233impl GvType for Checksum {
234 const SIGNATURE: &'static str = "ay";
235 const ALIGNMENT: usize = 1;
236 const FIXED_SIZE: Option<usize> = None;
237}
238
239impl GvEncode for Checksum {
243 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
244 out.extend_from_slice(&self.0);
245 Ok(())
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 const FIXTURE_COMMIT: &str = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
256
257 #[test]
258 fn hex_round_trips_and_is_lowercase() {
259 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
260 assert_eq!(c.to_hex(), FIXTURE_COMMIT);
261 let upper = Checksum::from_hex(&FIXTURE_COMMIT.to_uppercase()).unwrap();
263 assert_eq!(upper, c);
264 }
265
266 #[test]
267 fn hex_rejects_bad_length_and_characters() {
268 assert!(Checksum::from_hex("abcd").is_err());
269 assert!(Checksum::from_hex(&"g".repeat(64)).is_err());
270 }
271
272 #[test]
273 fn lowercase_hex_refuses_an_uppercase_character() {
274 let c = Checksum::from_hex_lower(FIXTURE_COMMIT).unwrap();
275 assert_eq!(c.to_hex(), FIXTURE_COMMIT);
276 assert!(Checksum::from_hex_lower(&FIXTURE_COMMIT.to_uppercase()).is_err());
277 let mixed = format!("B{}", &FIXTURE_COMMIT[1..]);
279 assert!(Checksum::from_hex_lower(&mixed).is_err());
280 assert!(Checksum::from_hex_lower("abcd").is_err());
281 }
282
283 #[test]
284 fn ay_conversion_validates_length() {
285 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
286 assert_eq!(Checksum::from_ay(c.as_bytes()).unwrap(), c);
287 assert!(Checksum::from_ay(&[0u8; 31]).is_err());
288 assert!(Checksum::from_ay(&[0u8; 33]).is_err());
289 }
290
291 #[test]
292 fn base64_reference_vectors() {
293 let zero = Checksum::from_bytes([0u8; 32]);
295 assert_eq!(zero.to_base64_modified(), "A".repeat(43));
296 assert_eq!(zero.to_base64(), format!("{}=", "A".repeat(43)));
297
298 let ones = Checksum::from_bytes([0xffu8; 32]);
302 assert_eq!(ones.to_base64_modified(), format!("{}8", "_".repeat(42)));
303 assert_eq!(ones.to_base64(), format!("{}8=", "/".repeat(42)));
304 assert_eq!(
306 ones.to_base64_modified(),
307 ones.to_base64().trim_end_matches('=').replace('/', "_")
308 );
309 }
310
311 #[test]
312 fn base64_round_trips_both_alphabets() {
313 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
314 assert_eq!(Checksum::from_base64(&c.to_base64()).unwrap(), c);
315 assert_eq!(
316 Checksum::from_base64_modified(&c.to_base64_modified()).unwrap(),
317 c
318 );
319 assert_eq!(c.to_base64_modified().len(), 43);
320 assert_eq!(c.to_base64().len(), 44);
321 }
322
323 fn sample_checksums() -> Vec<Checksum> {
325 let mut v = vec![
326 Checksum::from_bytes([0u8; 32]),
327 Checksum::from_bytes([0xffu8; 32]),
328 Checksum::from_hex(FIXTURE_COMMIT).unwrap(),
329 ];
330 for seed in [1u8, 7, 31, 63, 128, 200, 254] {
332 let mut b = [0u8; 32];
333 for (i, x) in b.iter_mut().enumerate() {
334 *x = seed.wrapping_mul(i as u8).wrapping_add(seed);
335 }
336 v.push(Checksum::from_bytes(b));
337 }
338 v
339 }
340
341 #[test]
342 fn base64_parse_then_render_is_identity_for_accepted_strings() {
343 for c in sample_checksums() {
344 let std = c.to_base64();
345 assert_eq!(Checksum::from_base64(&std).unwrap().to_base64(), std);
346 let modified = c.to_base64_modified();
347 assert_eq!(
348 Checksum::from_base64_modified(&modified)
349 .unwrap()
350 .to_base64_modified(),
351 modified
352 );
353 }
354 }
355
356 #[test]
357 fn base64_rejects_cross_alphabet_glyphs() {
358 let modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
360 assert!(modified.contains('_'));
361 assert!(Checksum::from_base64(&modified).is_err());
362 let std = Checksum::from_bytes([0xffu8; 32]).to_base64();
365 assert!(std.contains('/'));
366 assert!(Checksum::from_base64_modified(std.trim_end_matches('=')).is_err());
367 }
368
369 #[test]
370 fn base64_rejects_nonzero_trailing_bits() {
371 let mut modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
374 modified.pop();
375 modified.push('9');
376 assert!(Checksum::from_base64_modified(&modified).is_err());
377
378 let mut std = Checksum::from_bytes([0u8; 32]).to_base64();
379 std.replace_range(42..43, "9");
381 assert!(Checksum::from_base64(&std).is_err());
382 }
383
384 #[test]
385 fn base64_rejects_wrong_length_and_stray_padding() {
386 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
387 assert!(Checksum::from_base64(c.to_base64().trim_end_matches('=')).is_err());
390 assert!(Checksum::from_base64(&format!("{}=", c.to_base64())).is_err());
391 assert!(Checksum::from_base64_modified(&format!("{}=", c.to_base64_modified())).is_err());
394 assert!(Checksum::from_base64_modified(&c.to_base64()).is_err());
395 }
396
397 #[test]
398 fn sha256_matches_the_empty_input_vector() {
399 assert_eq!(
401 Checksum::sha256(b"").to_hex(),
402 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
403 );
404 }
405
406 #[test]
407 fn ordering_matches_hex_ordering() {
408 let a = Checksum::from_hex(&"00".repeat(32)).unwrap();
409 let b = Checksum::from_hex(&"ff".repeat(32)).unwrap();
410 assert!(a < b);
411 assert!(a.to_hex() < b.to_hex());
412 }
413}