1use ostrya_gvariant::{GvEncode, GvType};
7
8use crate::error::{Error, Result};
9
10#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct Checksum([u8; 32]);
34
35const STD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
36const MOD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
37
38impl Checksum {
39 pub fn from_bytes(b: [u8; 32]) -> Checksum {
41 Checksum(b)
42 }
43
44 pub fn sha256(data: &[u8]) -> Checksum {
49 use sha2::{Digest, Sha256};
50 Checksum(Sha256::digest(data).into())
51 }
52
53 pub fn as_bytes(&self) -> &[u8; 32] {
55 &self.0
56 }
57
58 pub fn from_hex_lower(s: &str) -> Result<Checksum> {
79 if s.bytes().any(|b| b.is_ascii_uppercase()) {
80 return Err(Error::InvalidChecksum("hex checksum is not lowercase"));
81 }
82 Checksum::from_hex(s)
83 }
84
85 pub fn from_hex(s: &str) -> Result<Checksum> {
98 let bytes = s.as_bytes();
99 if bytes.len() != 64 {
100 return Err(Error::InvalidChecksum("hex checksum is not 64 characters"));
101 }
102 let mut out = [0u8; 32];
103 for (i, pair) in bytes.chunks_exact(2).enumerate() {
104 let hi = hex_val(pair[0])?;
105 let lo = hex_val(pair[1])?;
106 out[i] = (hi << 4) | lo;
107 }
108 Ok(Checksum(out))
109 }
110
111 pub fn to_hex(&self) -> String {
113 const HEX: &[u8; 16] = b"0123456789abcdef";
114 let mut s = String::with_capacity(64);
115 for &b in &self.0 {
116 s.push(HEX[(b >> 4) as usize] as char);
117 s.push(HEX[(b & 0x0f) as usize] as char);
118 }
119 s
120 }
121
122 pub fn from_ay(b: &[u8]) -> Result<Checksum> {
129 let arr: [u8; 32] = b
130 .try_into()
131 .map_err(|_| Error::InvalidChecksum("ay checksum is not 32 bytes"))?;
132 Ok(Checksum(arr))
133 }
134
135 pub fn to_base64(&self) -> String {
139 base64_encode(&self.0, STD_ALPHABET, true)
140 }
141
142 pub fn from_base64(s: &str) -> Result<Checksum> {
161 Ok(Checksum(base64_decode_checksum(s, STD_ALPHABET, true)?))
162 }
163
164 pub fn to_base64_modified(&self) -> String {
169 base64_encode(&self.0, MOD_ALPHABET, false)
170 }
171
172 pub fn from_base64_modified(s: &str) -> Result<Checksum> {
189 Ok(Checksum(base64_decode_checksum(s, MOD_ALPHABET, false)?))
190 }
191}
192
193fn hex_val(c: u8) -> Result<u8> {
194 match c {
195 b'0'..=b'9' => Ok(c - b'0'),
196 b'a'..=b'f' => Ok(c - b'a' + 10),
197 b'A'..=b'F' => Ok(c - b'A' + 10),
198 _ => Err(Error::InvalidChecksum(
199 "hex checksum has a non-hex character",
200 )),
201 }
202}
203
204fn base64_encode(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
205 let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
206 for chunk in input.chunks(3) {
207 let b0 = chunk[0];
208 out.push(alphabet[(b0 >> 2) as usize] as char);
209 match chunk.len() {
210 1 => {
211 out.push(alphabet[((b0 & 0x03) << 4) as usize] as char);
212 if pad {
213 out.push_str("==");
214 }
215 }
216 2 => {
217 let b1 = chunk[1];
218 out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
219 out.push(alphabet[((b1 & 0x0f) << 2) as usize] as char);
220 if pad {
221 out.push('=');
222 }
223 }
224 _ => {
225 let (b1, b2) = (chunk[1], chunk[2]);
226 out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
227 out.push(alphabet[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
228 out.push(alphabet[(b2 & 0x3f) as usize] as char);
229 }
230 }
231 }
232 out
233}
234
235fn base64_decode_checksum(s: &str, alphabet: &[u8; 64], padded: bool) -> Result<[u8; 32]> {
249 let bytes = s.as_bytes();
250 let expected = if padded { 44 } else { 43 };
251 if bytes.len() != expected {
252 return Err(Error::InvalidChecksum(
253 "base64 checksum has the wrong length",
254 ));
255 }
256 if padded && bytes[43] != b'=' {
257 return Err(Error::InvalidChecksum("base64 checksum is missing its pad"));
258 }
259 let data = &bytes[..43];
260 let mut out = [0u8; 32];
261 for (group, chunk) in data[..40].chunks_exact(4).enumerate() {
262 let s0 = base64_val(chunk[0], alphabet)?;
263 let s1 = base64_val(chunk[1], alphabet)?;
264 let s2 = base64_val(chunk[2], alphabet)?;
265 let s3 = base64_val(chunk[3], alphabet)?;
266 out[group * 3] = (s0 << 2) | (s1 >> 4);
267 out[group * 3 + 1] = (s1 << 4) | (s2 >> 2);
268 out[group * 3 + 2] = (s2 << 6) | s3;
269 }
270 let s0 = base64_val(data[40], alphabet)?;
271 let s1 = base64_val(data[41], alphabet)?;
272 let s2 = base64_val(data[42], alphabet)?;
273 if s2 & 0x03 != 0 {
274 return Err(Error::InvalidChecksum(
275 "base64 checksum has nonzero trailing bits",
276 ));
277 }
278 out[30] = (s0 << 2) | (s1 >> 4);
279 out[31] = (s1 << 4) | (s2 >> 2);
280 Ok(out)
281}
282
283fn base64_val(c: u8, alphabet: &[u8; 64]) -> Result<u8> {
284 match c {
285 b'A'..=b'Z' => Ok(c - b'A'),
286 b'a'..=b'z' => Ok(c - b'a' + 26),
287 b'0'..=b'9' => Ok(c - b'0' + 52),
288 b'+' => Ok(62),
289 _ if c == alphabet[63] => Ok(63),
293 _ => Err(Error::InvalidChecksum("base64 has an invalid character")),
294 }
295}
296
297impl std::fmt::Display for Checksum {
298 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299 f.write_str(&self.to_hex())
300 }
301}
302
303impl std::fmt::Debug for Checksum {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 write!(f, "Checksum({})", self.to_hex())
306 }
307}
308
309impl std::str::FromStr for Checksum {
310 type Err = Error;
311 fn from_str(s: &str) -> Result<Checksum> {
312 Checksum::from_hex(s)
313 }
314}
315
316impl GvType for Checksum {
317 const SIGNATURE: &'static str = "ay";
318 const ALIGNMENT: usize = 1;
319 const FIXED_SIZE: Option<usize> = None;
320}
321
322impl GvEncode for Checksum {
328 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
329 out.extend_from_slice(&self.0);
330 Ok(())
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337
338 const FIXTURE_COMMIT: &str = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
341
342 #[test]
343 fn hex_round_trips_and_is_lowercase() {
344 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
345 assert_eq!(c.to_hex(), FIXTURE_COMMIT);
346 let upper = Checksum::from_hex(&FIXTURE_COMMIT.to_uppercase()).unwrap();
348 assert_eq!(upper, c);
349 }
350
351 #[test]
352 fn hex_rejects_bad_length_and_characters() {
353 assert!(Checksum::from_hex("abcd").is_err());
354 assert!(Checksum::from_hex(&"g".repeat(64)).is_err());
355 }
356
357 #[test]
358 fn lowercase_hex_refuses_an_uppercase_character() {
359 let c = Checksum::from_hex_lower(FIXTURE_COMMIT).unwrap();
360 assert_eq!(c.to_hex(), FIXTURE_COMMIT);
361 assert!(Checksum::from_hex_lower(&FIXTURE_COMMIT.to_uppercase()).is_err());
362 let mixed = format!("B{}", &FIXTURE_COMMIT[1..]);
364 assert!(Checksum::from_hex_lower(&mixed).is_err());
365 assert!(Checksum::from_hex_lower("abcd").is_err());
366 }
367
368 #[test]
369 fn ay_conversion_validates_length() {
370 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
371 assert_eq!(Checksum::from_ay(c.as_bytes()).unwrap(), c);
372 assert!(Checksum::from_ay(&[0u8; 31]).is_err());
373 assert!(Checksum::from_ay(&[0u8; 33]).is_err());
374 }
375
376 #[test]
377 fn base64_reference_vectors() {
378 let zero = Checksum::from_bytes([0u8; 32]);
380 assert_eq!(zero.to_base64_modified(), "A".repeat(43));
381 assert_eq!(zero.to_base64(), format!("{}=", "A".repeat(43)));
382
383 let ones = Checksum::from_bytes([0xffu8; 32]);
387 assert_eq!(ones.to_base64_modified(), format!("{}8", "_".repeat(42)));
388 assert_eq!(ones.to_base64(), format!("{}8=", "/".repeat(42)));
389 assert_eq!(
391 ones.to_base64_modified(),
392 ones.to_base64().trim_end_matches('=').replace('/', "_")
393 );
394 }
395
396 #[test]
397 fn base64_round_trips_both_alphabets() {
398 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
399 assert_eq!(Checksum::from_base64(&c.to_base64()).unwrap(), c);
400 assert_eq!(
401 Checksum::from_base64_modified(&c.to_base64_modified()).unwrap(),
402 c
403 );
404 assert_eq!(c.to_base64_modified().len(), 43);
405 assert_eq!(c.to_base64().len(), 44);
406 }
407
408 fn sample_checksums() -> Vec<Checksum> {
410 let mut v = vec![
411 Checksum::from_bytes([0u8; 32]),
412 Checksum::from_bytes([0xffu8; 32]),
413 Checksum::from_hex(FIXTURE_COMMIT).unwrap(),
414 ];
415 for seed in [1u8, 7, 31, 63, 128, 200, 254] {
417 let mut b = [0u8; 32];
418 for (i, x) in b.iter_mut().enumerate() {
419 *x = seed.wrapping_mul(i as u8).wrapping_add(seed);
420 }
421 v.push(Checksum::from_bytes(b));
422 }
423 v
424 }
425
426 #[test]
427 fn base64_parse_then_render_is_identity_for_accepted_strings() {
428 for c in sample_checksums() {
429 let std = c.to_base64();
430 assert_eq!(Checksum::from_base64(&std).unwrap().to_base64(), std);
431 let modified = c.to_base64_modified();
432 assert_eq!(
433 Checksum::from_base64_modified(&modified)
434 .unwrap()
435 .to_base64_modified(),
436 modified
437 );
438 }
439 }
440
441 #[test]
442 fn base64_rejects_cross_alphabet_glyphs() {
443 let modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
445 assert!(modified.contains('_'));
446 assert!(Checksum::from_base64(&modified).is_err());
447 let std = Checksum::from_bytes([0xffu8; 32]).to_base64();
450 assert!(std.contains('/'));
451 assert!(Checksum::from_base64_modified(std.trim_end_matches('=')).is_err());
452 }
453
454 #[test]
455 fn base64_rejects_nonzero_trailing_bits() {
456 let mut modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
460 modified.pop();
461 modified.push('9');
462 assert!(Checksum::from_base64_modified(&modified).is_err());
463
464 let mut std = Checksum::from_bytes([0u8; 32]).to_base64();
465 std.replace_range(42..43, "9");
467 assert!(Checksum::from_base64(&std).is_err());
468 }
469
470 #[test]
471 fn base64_rejects_wrong_length_and_stray_padding() {
472 let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
473 assert!(Checksum::from_base64(c.to_base64().trim_end_matches('=')).is_err());
476 assert!(Checksum::from_base64(&format!("{}=", c.to_base64())).is_err());
477 assert!(Checksum::from_base64_modified(&format!("{}=", c.to_base64_modified())).is_err());
480 assert!(Checksum::from_base64_modified(&c.to_base64()).is_err());
481 }
482
483 #[test]
484 fn sha256_matches_the_empty_input_vector() {
485 assert_eq!(
487 Checksum::sha256(b"").to_hex(),
488 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
489 );
490 }
491
492 #[test]
493 fn ordering_matches_hex_ordering() {
494 let a = Checksum::from_hex(&"00".repeat(32)).unwrap();
495 let b = Checksum::from_hex(&"ff".repeat(32)).unwrap();
496 assert!(a < b);
497 assert!(a.to_hex() < b.to_hex());
498 }
499}