Skip to main content

qualia_core_db/q42/volume/
cid.rs

1//! CID parse and block verification for IPFS-published Q42 segments.
2//!
3//! A gateway is only a transport. The CID's multihash is the authority: a
4//! decoded block is accepted only when `sha2-256(block) == CID digest`.
5//! CIDv0 (`Qm…`) and CIDv1 sha2-256 (`bafy…` / `bafk…` / raw hex) are supported.
6
7use std::io;
8
9use sha2::{Digest, Sha256};
10
11fn invalid(message: impl Into<String>) -> io::Error {
12    io::Error::new(io::ErrorKind::InvalidData, message.into())
13}
14
15/// A verified content identifier. Only sha2-256 (32-byte) digests are accepted.
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17pub struct CidSha256 {
18    pub version: u8,
19    pub codec: u64,
20    pub digest: [u8; 32],
21}
22
23impl CidSha256 {
24    pub const RAW: u64 = 0x55;
25    pub const DAG_PB: u64 = 0x70;
26
27    /// Parses a CID text form; `io` error on malformed input.
28    pub fn parse(text: &str) -> io::Result<Self> {
29        let text = text.trim();
30        if text.is_empty() {
31            return Err(invalid("empty CID"));
32        }
33        if text.starts_with("Qm") {
34            return parse_cidv0(text);
35        }
36        if let Some(hex) = text.strip_prefix("f") {
37            return parse_cidv1(&decode_hex(hex)?);
38        }
39        if let Some(b32) = text.strip_prefix("b") {
40            return parse_cidv1(&decode_base32(b32)?);
41        }
42        Err(invalid(
43            "CID must be CIDv0 (Qm…) or CIDv1 base32 (b…) / hex (f…)",
44        ))
45    }
46
47    /// Computes the CID for a raw block.
48    pub fn for_raw_block(block: &[u8]) -> Self {
49        Self {
50            version: 1,
51            codec: Self::RAW,
52            digest: sha256(block),
53        }
54    }
55
56    /// Verifies `block` matches this CID; error on mismatch.
57    pub fn verify_block(&self, block: &[u8]) -> io::Result<()> {
58        let actual = sha256(block);
59        if actual != self.digest {
60            return Err(invalid("block bytes do not match CID sha2-256 digest"));
61        }
62        Ok(())
63    }
64
65    /// Base32 CID string.
66    pub fn encode_base32(&self) -> String {
67        let mut raw = Vec::new();
68        raw.push(self.version);
69        encode_varint(&mut raw, self.codec);
70        raw.push(0x12);
71        raw.push(32);
72        raw.extend_from_slice(&self.digest);
73        let mut out = String::from("b");
74        out.push_str(&encode_base32(&raw));
75        out
76    }
77}
78
79fn parse_cidv0(text: &str) -> io::Result<CidSha256> {
80    let bytes = decode_base58btc(text)?;
81    if bytes.len() != 34 || bytes[0] != 0x12 || bytes[1] != 32 {
82        return Err(invalid("CIDv0 must be sha2-256 (34 bytes)"));
83    }
84    let mut digest = [0u8; 32];
85    digest.copy_from_slice(&bytes[2..]);
86    Ok(CidSha256 {
87        version: 0,
88        codec: CidSha256::DAG_PB,
89        digest,
90    })
91}
92
93fn parse_cidv1(bytes: &[u8]) -> io::Result<CidSha256> {
94    if bytes.first() != Some(&0x01) {
95        return Err(invalid("CIDv1 version byte must be 0x01"));
96    }
97    let (codec, used) = decode_varint(&bytes[1..])?;
98    let rest = &bytes[1 + used..];
99    if rest.len() != 34 || rest[0] != 0x12 || rest[1] != 32 {
100        return Err(invalid("only sha2-256 CIDv1 is accepted"));
101    }
102    let mut digest = [0u8; 32];
103    digest.copy_from_slice(&rest[2..]);
104    Ok(CidSha256 {
105        version: 1,
106        codec,
107        digest,
108    })
109}
110
111/// Raw SHA-256 of `bytes`.
112pub fn sha256(bytes: &[u8]) -> [u8; 32] {
113    Sha256::digest(bytes).into()
114}
115
116fn encode_varint(out: &mut Vec<u8>, mut value: u64) {
117    loop {
118        let mut byte = (value & 0x7f) as u8;
119        value >>= 7;
120        if value != 0 {
121            byte |= 0x80;
122        }
123        out.push(byte);
124        if value == 0 {
125            return;
126        }
127    }
128}
129
130fn decode_varint(bytes: &[u8]) -> io::Result<(u64, usize)> {
131    let mut value = 0u64;
132    let mut shift = 0u32;
133    for (index, byte) in bytes.iter().copied().enumerate() {
134        value |= u64::from(byte & 0x7f) << shift;
135        if byte & 0x80 == 0 {
136            return Ok((value, index + 1));
137        }
138        shift += 7;
139        if shift >= 64 {
140            return Err(invalid("CID varint overflow"));
141        }
142    }
143    Err(invalid("truncated CID varint"))
144}
145
146fn decode_hex(text: &str) -> io::Result<Vec<u8>> {
147    if text.len() % 2 != 0 {
148        return Err(invalid("odd-length hex CID"));
149    }
150    let mut out = Vec::with_capacity(text.len() / 2);
151    let bytes = text.as_bytes();
152    for pair in bytes.chunks(2) {
153        let hi = hex_nibble(pair[0])?;
154        let lo = hex_nibble(pair[1])?;
155        out.push((hi << 4) | lo);
156    }
157    Ok(out)
158}
159
160fn hex_nibble(byte: u8) -> io::Result<u8> {
161    match byte {
162        b'0'..=b'9' => Ok(byte - b'0'),
163        b'a'..=b'f' => Ok(byte - b'a' + 10),
164        b'A'..=b'F' => Ok(byte - b'A' + 10),
165        _ => Err(invalid("invalid hex digit in CID")),
166    }
167}
168
169fn decode_base32(text: &str) -> io::Result<Vec<u8>> {
170    let mut bits: u32 = 0;
171    let mut nbits = 0u32;
172    let mut out = Vec::new();
173    for byte in text.bytes() {
174        if byte == b'=' {
175            continue;
176        }
177        let value = match byte {
178            b'a'..=b'z' => byte - b'a',
179            b'A'..=b'Z' => byte - b'A',
180            b'2'..=b'7' => byte - b'2' + 26,
181            _ => return Err(invalid("invalid base32 digit in CID")),
182        };
183        bits = (bits << 5) | u32::from(value);
184        nbits += 5;
185        if nbits >= 8 {
186            nbits -= 8;
187            out.push((bits >> nbits) as u8);
188            bits &= (1 << nbits) - 1;
189        }
190    }
191    Ok(out)
192}
193
194fn encode_base32(bytes: &[u8]) -> String {
195    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
196    let mut bits: u32 = 0;
197    let mut nbits = 0u32;
198    let mut out = String::new();
199    for byte in bytes {
200        bits = (bits << 8) | u32::from(*byte);
201        nbits += 8;
202        while nbits >= 5 {
203            nbits -= 5;
204            out.push(ALPHABET[((bits >> nbits) & 0x1f) as usize] as char);
205            bits &= (1 << nbits) - 1;
206        }
207    }
208    if nbits > 0 {
209        out.push(ALPHABET[((bits << (5 - nbits)) & 0x1f) as usize] as char);
210    }
211    out
212}
213
214fn decode_base58btc(text: &str) -> io::Result<Vec<u8>> {
215    const ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
216    let mut acc = vec![0u8; 1];
217    for byte in text.bytes() {
218        let digit = ALPHABET
219            .iter()
220            .position(|candidate| *candidate == byte)
221            .ok_or_else(|| invalid("invalid base58 digit in CID"))?;
222        let mut carry = digit;
223        for slot in acc.iter_mut().rev() {
224            let value = *slot as usize * 58 + carry;
225            *slot = (value & 0xff) as u8;
226            carry = value >> 8;
227        }
228        while carry > 0 {
229            acc.insert(0, (carry & 0xff) as u8);
230            carry >>= 8;
231        }
232    }
233    let leading = text.bytes().take_while(|b| *b == b'1').count();
234    let mut out = vec![0u8; leading];
235    let skip = acc.iter().position(|b| *b != 0).unwrap_or(acc.len());
236    out.extend_from_slice(&acc[skip..]);
237    Ok(out)
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn raw_block_round_trip_and_tamper_is_detected() {
246        let block = b"q42-superblock-bytes";
247        let cid = CidSha256::for_raw_block(block);
248        let encoded = cid.encode_base32();
249        assert!(encoded.starts_with('b'));
250        let parsed = CidSha256::parse(&encoded).unwrap();
251        parsed.verify_block(block).unwrap();
252        assert!(parsed.verify_block(b"tampered").is_err());
253    }
254
255    #[test]
256    fn hex_cidv1_parses() {
257        let block = b"hello-q42";
258        let digest = sha256(block);
259        let mut raw = vec![0x01, 0x55, 0x12, 32];
260        raw.extend_from_slice(&digest);
261        let mut hex = String::from("f");
262        for byte in &raw {
263            hex.push_str(&format!("{byte:02x}"));
264        }
265        let cid = CidSha256::parse(&hex).unwrap();
266        assert_eq!(cid.codec, CidSha256::RAW);
267        cid.verify_block(block).unwrap();
268    }
269}