Skip to main content

qualia_core_db/net/qdnf/contracts/compile/
verify.rs

1//! Exact-byte digest checks. A matching digest without the bytes is not a signature.
2
3use crate::crypto::network::digest::sha384;
4use crate::net::qdnf::errors::QdnfError;
5use crate::net::qdnf::types::StrongDigest;
6
7/// Verify that `original_bytes` are present and hash to `digest`.
8///
9/// Empty input is [`QdnfError::Malformed`] (an attacker cannot pass a digest
10/// without the bytes). A zero digest is malformed. A live hash mismatch is
11/// [`QdnfError::Conflict`] (forged digest).
12pub fn verify_exact_bytes(digest: StrongDigest, original_bytes: &[u8]) -> Result<(), QdnfError> {
13    if original_bytes.is_empty() {
14        return Err(QdnfError::Malformed);
15    }
16    if digest.is_zero() {
17        return Err(QdnfError::Malformed);
18    }
19    let got = sha384(original_bytes);
20    if got != digest {
21        return Err(QdnfError::Conflict);
22    }
23    Ok(())
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29    use crate::crypto::network::digest::sha384;
30
31    #[test]
32    fn empty_bytes_are_malformed_even_with_matching_digest() {
33        let digest = sha384(b"contract-bytes");
34        assert_eq!(verify_exact_bytes(digest, b""), Err(QdnfError::Malformed));
35    }
36
37    #[test]
38    fn zero_digest_is_malformed() {
39        assert_eq!(
40            verify_exact_bytes(StrongDigest::ZERO, b"present"),
41            Err(QdnfError::Malformed)
42        );
43    }
44
45    #[test]
46    fn hash_mismatch_is_conflict() {
47        let digest = sha384(b"original");
48        assert_eq!(
49            verify_exact_bytes(digest, b"tampered"),
50            Err(QdnfError::Conflict)
51        );
52    }
53
54    #[test]
55    fn matching_bytes_verify() {
56        let bytes = b"pinned-artifact";
57        assert!(verify_exact_bytes(sha384(bytes), bytes).is_ok());
58    }
59}