mod canonical;
mod hash;
pub use canonical::canonical_encode;
pub use hash::HashAlgorithm;
use crate::error::{MigratromError, Result};
use crate::types::Operation;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParsedChecksum {
pub algo: String,
pub hex: String,
}
pub fn checksum(operations: &[Operation]) -> String {
checksum_with(operations, HashAlgorithm::DEFAULT)
}
pub fn checksum_with(operations: &[Operation], algorithm: HashAlgorithm) -> String {
let digest = algorithm.hash(&canonical_encode(operations));
format!("{}/{}", algorithm.name(), hex::encode(digest))
}
pub fn parse_checksum(stored: &str) -> Result<ParsedChecksum> {
let Some(slash) = stored.find('/') else {
return Err(MigratromError::Config(format!(
"malformed checksum (missing '/'): {stored}"
)));
};
let algo = &stored[..slash];
let hex = &stored[slash + 1..];
let valid_hex = !hex.is_empty()
&& hex.len().is_multiple_of(2)
&& hex.bytes().all(|b| b.is_ascii_hexdigit());
if algo.is_empty() || !valid_hex {
return Err(MigratromError::Config(format!(
"malformed checksum: {stored}"
)));
}
Ok(ParsedChecksum {
algo: algo.to_string(),
hex: hex.to_string(),
})
}
pub fn verify_checksum(stored: &str, operations: &[Operation], migration_id: i64) -> Result<()> {
let parsed = parse_checksum(stored)?;
let Some(algorithm) = HashAlgorithm::from_name(&parsed.algo) else {
return Err(MigratromError::Config(format!(
"unknown checksum algorithm: {}",
parsed.algo
)));
};
let actual = checksum_with(operations, algorithm);
let actual_parsed = parse_checksum(&actual)?;
if parsed.hex.eq_ignore_ascii_case(&actual_parsed.hex) {
Ok(())
} else {
Err(MigratromError::ChecksumMismatch {
id: migration_id,
expected: stored.to_string(),
actual,
})
}
}