Skip to main content

cbcl_core/
multihash.rs

1//! Canonical SHA2-256 multihashes, in multibase base16 (lowercase) text.
2//! Binary layout: unsigned-varint code 0x12, unsigned-varint length 0x20,
3//! then the 32 digest bytes. Text is `f1220` followed by 64 lowercase hex digits.
4//! Hash input and Merkle construction are independent of this wire encoding.
5use alloc::string::String;
6
7pub const SHA2_256_CODE: u8 = 0x12;
8pub const DIGEST_SIZE: usize = 32;
9pub const TEXT_PREFIX: &str = "f1220";
10pub const TEXT_LEN: usize = 69;
11
12pub fn encode(digest: &[u8; DIGEST_SIZE]) -> String {
13    const HEX: &[u8; 16] = b"0123456789abcdef";
14    let mut text = String::with_capacity(TEXT_LEN);
15    text.push_str(TEXT_PREFIX);
16    for b in digest {
17        text.push(HEX[(b >> 4) as usize] as char);
18        text.push(HEX[(b & 15) as usize] as char);
19    }
20    text
21}
22
23/// Decode only the canonical SHA2-256 multibase representation. Unknown
24/// algorithms, noncanonical bases/case, truncation and trailing bytes fail closed.
25pub fn decode(text: &str) -> Option<[u8; DIGEST_SIZE]> {
26    let hex = text.strip_prefix(TEXT_PREFIX)?;
27    if hex.len() != DIGEST_SIZE * 2 {
28        return None;
29    }
30    let nibble = |b: u8| match b {
31        b'0'..=b'9' => Some(b - b'0'),
32        b'a'..=b'f' => Some(b - b'a' + 10),
33        _ => None,
34    };
35    let mut digest = [0; DIGEST_SIZE];
36    for (out, pair) in digest.iter_mut().zip(hex.as_bytes().chunks_exact(2)) {
37        *out = nibble(pair[0])? * 16 + nibble(pair[1])?;
38    }
39    Some(digest)
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use sha2::{Digest, Sha256};
46    #[test]
47    fn multiformats_sha2_256_golden_vector() {
48        // https://github.com/multiformats/multihash#example
49        let digest: [u8; 32] = Sha256::digest(b"multihash").into();
50        let text = "f12209cbc07c3f991725836a3aa2a581ca2029198aa420b9d99bc0e131d9f3e2cbe47";
51        assert_eq!(encode(&digest), text);
52        assert_eq!(decode(text), Some(digest));
53    }
54    #[test]
55    fn rejects_noncanonical_and_unsupported_addresses() {
56        let valid = encode(&[0xab; 32]);
57        for bad in [
58            valid.to_uppercase(),
59            valid.replace("f1220", "f1320"),
60            valid.replace("f1220", "f121f"),
61            valid[1..].into(),
62            valid[..68].into(),
63            alloc::format!("{valid}00"),
64            alloc::format!("sha256:{}", "ab".repeat(32)),
65        ] {
66            assert_eq!(decode(&bad), None, "{bad}");
67        }
68    }
69}