| 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()) | |
| } | |
| mod tests { | |
| use super::*; | |
| 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 | |
| } | |
| } |