use sha2::{Sha256, Digest};
pub fn hash256(data: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(data);
hasher.finalize().into()
}
pub fn hex_to_bytes(hex: &str) -> Result<[u8; 32], &'static str> {
if hex.len() != 64 {
return Err("Expected 64 hex characters for 32 bytes");
}
let mut result = [0u8; 32];
for i in 0..32 {
result[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16)
.map_err(|_| "Invalid hex character")?;
}
Ok(result)
}
pub fn bytes_to_hex(bytes: &[u8; 32]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
pub fn receipt_hash_from_json_bytes(bytes: &[u8]) -> [u8; 32] {
hash256(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hash256() {
let result = hash256(b"test");
assert_eq!(result.len(), 32);
}
#[test]
fn test_hex_roundtrip() {
let original = hash256(b"test");
let hex = bytes_to_hex(&original);
let recovered = hex_to_bytes(&hex).unwrap();
assert_eq!(original, recovered);
}
}