summaryrefslogtreecommitdiffstats
path: root/src/hash.rs
blob: 0321437a9f87b5df75cffec3b6adc047259513cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Hashing helpers. `sha256` hex strings are the currency of identity and
//! provenance throughout the system (DESIGN.md §3, §5.3).

use sha2::{Digest, Sha256};
use std::io::{self, Read, Write};

pub const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

pub fn hex(bytes: &[u8]) -> String {
    let mut h = Sha256::new();
    h.update(bytes);
    hex::encode(h.finalize())
}

pub fn hex_str(s: &str) -> String {
    hex(s.as_bytes())
}

/// First `n` hex chars — enough for display, not for identity.
pub fn short(bytes: &[u8], n: usize) -> String {
    let h = hex(bytes);
    h[..n.min(h.len())].to_string()
}

/// Stream-hash a reader, optionally teeing every byte into `sink`.
///
/// Used to hash a download while writing it into the source cache, so the
/// bandwidth is paid for once (§5.3 "stream-hash, don't buffer").
pub fn digest_reader<R: Read>(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> {
    let mut h = Sha256::new();
    let mut buf = vec![0u8; 64 * 1024];
    let mut total = 0u64;
    loop {
        let n = r.read(&mut buf)?;
        if n == 0 {
            break;
        }
        h.update(&buf[..n]);
        if let Some(s) = sink.as_mut() {
            s.write_all(&buf[..n])?;
        }
        total += n as u64;
    }
    Ok((hex::encode(h.finalize()), total))
}

pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> {
    let f = std::fs::File::open(path)?;
    let mut br = io::BufReader::new(f);
    digest_reader(&mut br, None)
}

/// Hash of a canonical, sorted list of `(path, blob_hash)` pairs.
///
/// This is `recipe_hash` (DESIGN.md §3): a digest over *every* file in the AUR
/// snapshot tree — PKGBUILD, .SRCINFO, *.install and any shipped patches or
/// assets — because a patch file shipped in the AUR repo is part of the recipe
/// and is a classic silent-change vector.
pub fn recipe_hash(entries: &[(String, String)]) -> String {
    let mut sorted: Vec<&(String, String)> = entries.iter().collect();
    sorted.sort_unstable_by(|a, b| a.0.cmp(&b.0));
    let mut h = Sha256::new();
    for (path, blob) in &sorted {
        h.update(path.as_bytes());
        h.update([0u8]);
        h.update(blob.as_bytes());
        h.update([0u8]);
    }
    hex::encode(h.finalize())
}

/// Serialize a value to canonical JSON: compact, with every object's keys in
/// sorted order, so equal values always produce equal bytes.
///
/// The ordering is not free in `serde_json` — a struct serializes in field
/// declaration order and a map in whatever order it happens to hold — so the
/// value is routed through `serde_json::Value`, whose map is a `BTreeMap`.
/// That makes the name true rather than aspirational.
///
/// A serialization failure is an error. It used to be `"{}"`, which meant every
/// value that failed to serialize hashed to the same digest — and this is the
/// function behind `Identity::hash`, the value an approval echoes (§6 M-2).
pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> {
    serde_json::to_string(&serde_json::to_value(v)?)
}