File size: 1,140 Bytes
99f62cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use anyhow::Result;
use cid::Cid;
use sha2::{Digest, Sha256};

/// Generate a Filecoin-compatible CIDv1 (raw codec, sha2-256)
pub fn generate_cid(data: &str) -> Result<String> {
    // Compute SHA-256 hash
    let mut hasher = Sha256::new();
    hasher.update(data.as_bytes());
    let hash_bytes = hasher.finalize();

    // Build multihash (code 0x12 = sha2-256, size 32)
    let mh = cid::multihash::Multihash::wrap(0x12, &hash_bytes)
        .map_err(|e| anyhow::anyhow!("Invalid multihash: {:?}", e))?;

    // CIDv1, raw multicodec (0x55)
    let cid = Cid::new_v1(0x55, mh);
    Ok(cid.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cid_format() {
        let cid = generate_cid("hello world").unwrap();
        // CIDv1 in base32 always starts with 'b'
        assert!(cid.starts_with('b'), "CID should start with 'b': {}", cid);
        // Must be non-empty and decodable
        let decoded = Cid::try_from(cid.as_str()).unwrap();
        assert_eq!(decoded.version(), cid::Version::V1);
        println!("CID: {}", cid); // e.g., bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi
    }
}