Skip to main content

oxabl_cache_format/
bech32.rs

1//! Bech32 (BIP 173 checksum) without the 90-character limit, lowercase only.
2
3use crate::error::{FormatError, Result};
4use crate::limits::BECH32_CHARS;
5
6/// HRP of a member identity string. Its payload is secret and is handled by the crypto crate.
7pub const IDENTITY_HRP: &str = "oxabl-cache-identity-";
8
9const CHARSET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
10const GENERATOR: [u32; 5] = [
11    0x3b6a_57b2,
12    0x2650_8e6d,
13    0x1ea1_19fa,
14    0x3d42_33dd,
15    0x2a14_62b3,
16];
17
18fn polymod(values: impl IntoIterator<Item = u8>) -> u32 {
19    let mut chk = 1u32;
20    for v in values {
21        let top = chk >> 25;
22        chk = (chk & 0x01ff_ffff) << 5 ^ u32::from(v);
23        for (i, g) in GENERATOR.iter().enumerate() {
24            if (top >> i) & 1 == 1 {
25                chk ^= g;
26            }
27        }
28    }
29    chk
30}
31
32fn hrp_expand(hrp: &str) -> impl Iterator<Item = u8> + '_ {
33    hrp.bytes()
34        .map(|c| c >> 5)
35        .chain(std::iter::once(0))
36        .chain(hrp.bytes().map(|c| c & 31))
37}
38
39fn to_groups(data: &[u8]) -> Vec<u8> {
40    let mut out = Vec::with_capacity((data.len() * 8).div_ceil(5));
41    let (mut acc, mut bits) = (0u32, 0u32);
42    for &b in data {
43        acc = acc << 8 | u32::from(b);
44        bits += 8;
45        while bits >= 5 {
46            bits -= 5;
47            out.push((acc >> bits & 31) as u8);
48        }
49        acc &= (1 << bits) - 1;
50    }
51    if bits > 0 {
52        out.push((acc << (5 - bits) & 31) as u8);
53    }
54    out
55}
56
57fn from_groups(groups: &[u8]) -> Result<Vec<u8>> {
58    let mut out = Vec::with_capacity(groups.len() * 5 / 8);
59    let (mut acc, mut bits) = (0u32, 0u32);
60    for &g in groups {
61        acc = acc << 5 | u32::from(g);
62        bits += 5;
63        if bits >= 8 {
64            bits -= 8;
65            out.push((acc >> bits & 0xff) as u8);
66        }
67        acc &= (1 << bits) - 1;
68    }
69    if bits >= 5 || acc != 0 {
70        return Err(FormatError::Invalid("bech32 padding"));
71    }
72    Ok(out)
73}
74
75fn check_hrp(hrp: &str) -> Result<()> {
76    if hrp.is_empty()
77        || !hrp
78            .bytes()
79            .all(|c| (33..=126).contains(&c) && !c.is_ascii_uppercase())
80    {
81        return Err(FormatError::Invalid("bech32 hrp"));
82    }
83    Ok(())
84}
85
86/// Encodes `data` under `hrp`, which must be printable ASCII without uppercase letters.
87pub fn encode(hrp: &str, data: &[u8]) -> Result<String> {
88    check_hrp(hrp)?;
89    let groups = to_groups(data);
90    if hrp.len() + 1 + groups.len() + 6 > BECH32_CHARS {
91        return Err(FormatError::LimitExceeded("bech32 length"));
92    }
93    let chk = polymod(
94        hrp_expand(hrp)
95            .chain(groups.iter().copied())
96            .chain([0u8; 6]),
97    ) ^ 1;
98    let mut out = String::with_capacity(hrp.len() + 1 + groups.len() + 6);
99    out.push_str(hrp);
100    out.push('1');
101    for g in groups {
102        out.push(char::from(CHARSET[usize::from(g)]));
103    }
104    for i in 0..6 {
105        out.push(char::from(CHARSET[(chk >> (5 * (5 - i)) & 31) as usize]));
106    }
107    Ok(out)
108}
109
110/// Decodes a lowercase Bech32 string that must carry `expected_hrp`.
111pub fn decode(s: &str, expected_hrp: &str) -> Result<Vec<u8>> {
112    if s.len() > BECH32_CHARS {
113        return Err(FormatError::LimitExceeded("bech32 length"));
114    }
115    check_hrp(expected_hrp)?;
116    let rest = s
117        .strip_prefix(expected_hrp)
118        .and_then(|r| r.strip_prefix('1'))
119        .ok_or(FormatError::Invalid("bech32 hrp"))?;
120    if rest.len() < 6 {
121        return Err(FormatError::Invalid("bech32 checksum"));
122    }
123    let mut groups = Vec::with_capacity(rest.len());
124    for c in rest.bytes() {
125        let g = CHARSET
126            .iter()
127            .position(|&x| x == c)
128            .ok_or(FormatError::Invalid("bech32 character"))?;
129        groups.push(g as u8);
130    }
131    if polymod(hrp_expand(expected_hrp).chain(groups.iter().copied())) != 1 {
132        return Err(FormatError::Invalid("bech32 checksum"));
133    }
134    groups.truncate(groups.len() - 6);
135    from_groups(&groups)
136}