use sha2::{Digest, Sha256};
use crate::http::{get_bytes, HttpError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pinned {
pub size: u64,
pub sha256: String,
}
#[derive(Debug, thiserror::Error)]
pub enum PinError {
#[error(transparent)]
Transport(#[from] HttpError),
#[error("{url} returned HTTP {status}")]
Status { url: String, status: u16 },
}
pub fn sha256_hex(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
pub fn pin_url(url: &str, headers: &[(&str, &str)]) -> Result<Pinned, PinError> {
let response = get_bytes(url, headers)?;
if !response.ok() {
return Err(PinError::Status {
url: url.to_owned(),
status: response.status,
});
}
Ok(Pinned {
size: response.body.len() as u64,
sha256: sha256_hex(&response.body),
})
}