Skip to main content

ostrya_core/
checksum.rs

1//! The 32-byte SHA-256 object checksum and its forms.
2//!
3//! The hex, standard base64, and modified base64 codecs are hand-written to
4//! the RFC 4648 alphabet. The `sha2` crate computes the digest.
5
6use ostrya_gvariant::{GvEncode, GvType};
7
8use crate::error::{Error, Result};
9
10/// A 32-byte SHA-256 checksum that names an object.
11///
12/// # Forms
13///
14/// A checksum has these forms:
15///
16/// - 64 lowercase hex characters, in refs, loose paths, and object names. See
17///   [`to_hex`](Checksum::to_hex) and [`from_hex`](Checksum::from_hex).
18/// - The raw 32-byte `ay`, inside commit and dirtree objects. See
19///   [`as_bytes`](Checksum::as_bytes) and [`from_ay`](Checksum::from_ay).
20/// - Modified base64, in static-delta directory names. See
21///   [`to_base64_modified`](Checksum::to_base64_modified) and
22///   [`from_base64_modified`](Checksum::from_base64_modified).
23/// - Standard padded base64. See [`to_base64`](Checksum::to_base64) and
24///   [`from_base64`](Checksum::from_base64).
25///
26/// # Order
27///
28/// `Checksum` values compare byte-wise. The byte order equals the order of
29/// the lowercase hex strings. A sort of `Checksum` values gives the ASCII
30/// checksum order of the on-disk format, for example the order of the
31/// `ostree.sizes` entries.
32#[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    /// Creates a checksum from the raw digest bytes.
40    pub fn from_bytes(b: [u8; 32]) -> Checksum {
41        Checksum(b)
42    }
43
44    /// Returns the SHA-256 digest of `data`.
45    ///
46    /// This digest is the checksum of a metadata object, where `data` is the
47    /// serialized GVariant form of the object.
48    pub fn sha256(data: &[u8]) -> Checksum {
49        use sha2::{Digest, Sha256};
50        Checksum(Sha256::digest(data).into())
51    }
52
53    /// Returns the raw digest bytes.
54    pub fn as_bytes(&self) -> &[u8; 32] {
55        &self.0
56    }
57
58    /// Parses 64 lowercase hex characters.
59    ///
60    /// This is the form that [`to_hex`](Checksum::to_hex) writes. The rule
61    /// applies to a revision: a name of 64 characters is a checksum only if
62    /// it is lowercase hex. An uppercase or mixed-case name of that length is
63    /// a ref name.
64    ///
65    /// For a checksum from stored bytes, [`from_hex`](Checksum::from_hex) is
66    /// the parser. It accepts both cases.
67    ///
68    /// # Errors
69    ///
70    /// The function returns [`Error::InvalidChecksum`] with one of these
71    /// messages:
72    ///
73    /// - `hex checksum is not lowercase` if `s` holds an uppercase character.
74    ///   This check comes first.
75    /// - `hex checksum is not 64 characters` if `s` is not 64 bytes long.
76    /// - `hex checksum has a non-hex character` if a character is not in
77    ///   `0-9` or `a-f`.
78    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    /// Parses 64 hex characters in uppercase, lowercase, or mixed case.
86    ///
87    /// [`to_hex`](Checksum::to_hex) writes the result in lowercase.
88    ///
89    /// # Errors
90    ///
91    /// The function returns [`Error::InvalidChecksum`] with one of these
92    /// messages:
93    ///
94    /// - `hex checksum is not 64 characters` if `s` is not 64 bytes long.
95    /// - `hex checksum has a non-hex character` if a character is not in
96    ///   `0-9`, `a-f`, or `A-F`.
97    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    /// Returns the checksum as 64 lowercase hex characters.
112    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    /// Creates a checksum from the payload of a GVariant `ay` value.
123    ///
124    /// # Errors
125    ///
126    /// The function returns [`Error::InvalidChecksum`] with the message
127    /// `ay checksum is not 32 bytes` if `b` is not exactly 32 bytes long.
128    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    /// Returns the checksum as standard padded base64 of 44 characters.
136    ///
137    /// The string holds 43 data characters and one `=` pad.
138    pub fn to_base64(&self) -> String {
139        base64_encode(&self.0, STD_ALPHABET, true)
140    }
141
142    /// Parses standard padded base64 of exactly 44 characters.
143    ///
144    /// The string must hold 43 data characters and one `=` pad. Each checksum
145    /// has exactly one accepted spelling.
146    ///
147    /// # Errors
148    ///
149    /// The function returns [`Error::InvalidChecksum`] with one of these
150    /// messages:
151    ///
152    /// - `base64 checksum has the wrong length` if `s` is not 44 bytes long.
153    /// - `base64 checksum is missing its pad` if the last character is not
154    ///   `=`.
155    /// - `base64 has an invalid character` if a data character is not in the
156    ///   standard alphabet. The modified character `_` is not in this
157    ///   alphabet.
158    /// - `base64 checksum has nonzero trailing bits` if the two unused low
159    ///   bits of the last data character are not zero.
160    pub fn from_base64(s: &str) -> Result<Checksum> {
161        Ok(Checksum(base64_decode_checksum(s, STD_ALPHABET, true)?))
162    }
163
164    /// Returns the checksum as modified base64 of 43 characters.
165    ///
166    /// Modified base64 is standard base64 with `_` in the place of `/` and
167    /// with no trailing `=`.
168    pub fn to_base64_modified(&self) -> String {
169        base64_encode(&self.0, MOD_ALPHABET, false)
170    }
171
172    /// Parses modified base64 of exactly 43 characters with no pad.
173    ///
174    /// Each checksum has exactly one accepted spelling.
175    ///
176    /// # Errors
177    ///
178    /// The function returns [`Error::InvalidChecksum`] with one of these
179    /// messages:
180    ///
181    /// - `base64 checksum has the wrong length` if `s` is not 43 bytes long.
182    ///   A stray trailing `=` makes the string 44 bytes long.
183    /// - `base64 has an invalid character` if a character is not in the
184    ///   modified alphabet. The standard character `/` and the pad `=` are
185    ///   not in this alphabet.
186    /// - `base64 checksum has nonzero trailing bits` if the two unused low
187    ///   bits of the last character are not zero.
188    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
235/// Decodes exactly one 32-byte checksum, with the sextets read from `alphabet`.
236///
237/// A 32-byte digest is 43 significant base64 characters: ten groups of 4
238/// characters (30 bytes) and then one group of 3 characters (2 bytes). The
239/// standard form adds one `=` pad, for a total of 44 characters. The modified
240/// form is the 43 characters alone.
241///
242/// The decoder is strict, so each checksum has exactly one accepted spelling:
243///
244/// - The length must be exact.
245/// - Each character must be in `alphabet`, so the standard `/` and the
246///   modified `_` do not alias.
247/// - The two unused low bits of the last significant sextet must be zero.
248fn 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        // Index 63 is the only character that differs between the alphabets:
290        // `/` in the standard alphabet, `_` in the modified alphabet. Accept
291        // the character of `alphabet` and refuse the other one.
292        _ 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
322/// Encodes the checksum as its raw 32 bytes, the GVariant `ay` form.
323///
324/// [`Checksum::from_ay`] decodes this form.
325// There is no `GvDecode` impl. `from_ay` returns `Error::InvalidChecksum` if
326// the width is wrong, and the decoder path goes through it.
327impl 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    // The commit checksum that the fixture generator recorded in
339    // tests/fixtures/generated/MANIFEST.
340    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        // Uppercase input parses to the same value.
347        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        // One uppercase character is enough, and the length rule still holds.
363        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        // 32 zero bytes: 43 'A' sextets, one '=' pad under standard base64.
379        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        // 32 0xff bytes test the high sextets and the '_' for '/' swap.
384        // Ten full 0xffffff groups give index-63 sextets ('_' modified, '/'
385        // standard). The last two bytes give '_' '_' '8'.
386        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        // The two alphabets differ only in the index-63 glyph.
390        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    // A spread of checksums for the strict-decoding round-trip checks.
409    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        // A few deterministic byte patterns exercise varied final sextets.
416        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        // The modified rendering of all-ones carries '_', invalid in standard.
444        let modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
445        assert!(modified.contains('_'));
446        assert!(Checksum::from_base64(&modified).is_err());
447        // The standard form holds '/', which is not in the modified alphabet.
448        // Trim its pad first, so that the test covers only the alphabet.
449        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        // The last significant sextet of a 32-byte checksum has two unused low
457        // bits. The parsers must refuse a character that sets them ('9' is
458        // sextet 61).
459        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        // Replace the last data character (index 42), before the '=' pad.
466        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        // The standard form requires one trailing pad. The parser refuses the
474        // unpadded form of 43 characters and a double-padded form of 45.
475        assert!(Checksum::from_base64(c.to_base64().trim_end_matches('=')).is_err());
476        assert!(Checksum::from_base64(&format!("{}=", c.to_base64())).is_err());
477        // The modified form takes exactly 43 characters with no pad. The
478        // parser refuses a stray pad and a padded string of standard length.
479        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        // The well-known SHA-256 digest of the empty input.
486        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}