Skip to main content

proof_core/
hash.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Hash abstraction: versioned, agile. V0.1 allows SHA-256 and SHA-384 only.
4use crate::error::ErrorCode;
5
6/// Closed set of hash algorithms (V0.1).
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum HashAlgorithm {
9    Sha256,
10    Sha384,
11}
12
13impl HashAlgorithm {
14    /// Engine-local CBOR enum value (NOT the COSE number; mapping is explicit in crypto).
15    pub fn cbor_enum(self) -> u64 {
16        match self {
17            Self::Sha256 => 0,
18            Self::Sha384 => 1,
19        }
20    }
21
22    pub fn from_cbor_enum(v: u64) -> Result<Self, crate::ProofError> {
23        match v {
24            0 => Ok(Self::Sha256),
25            1 => Ok(Self::Sha384),
26            _ => Err(ErrorCode::UnknownAlgorithm.err(format!("unknown hash alg enum {v}"))),
27        }
28    }
29
30    pub fn name(self) -> &'static str {
31        match self {
32            Self::Sha256 => "sha-256",
33            Self::Sha384 => "sha-384",
34        }
35    }
36
37    pub fn from_name(s: &str) -> Result<Self, crate::ProofError> {
38        match s {
39            "sha-256" => Ok(Self::Sha256),
40            "sha-384" => Ok(Self::Sha384),
41            _ => Err(ErrorCode::UnknownAlgorithm.err(format!("unknown hash name {s}"))),
42        }
43    }
44
45    pub fn digest_len(self) -> usize {
46        match self {
47            Self::Sha256 => 32,
48            Self::Sha384 => 48,
49        }
50    }
51}
52
53/// Versioned hash reference. Digest is always over canonical CBOR bytes.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct HashRef {
56    pub v: u8,
57    pub alg: HashAlgorithm,
58    pub digest: Vec<u8>,
59}
60
61impl HashRef {
62    // PE-CRYPTO-008: digest length bound to the algorithm (32/48).
63    pub fn new(alg: HashAlgorithm, digest: Vec<u8>) -> Result<Self, crate::ProofError> {
64        if digest.len() != alg.digest_len() {
65            return Err(ErrorCode::Malformed.err(format!(
66                "digest len {} != {} for {}",
67                digest.len(),
68                alg.digest_len(),
69                alg.name()
70            )));
71        }
72        Ok(Self { v: 1, alg, digest })
73    }
74
75    /// Display form: `hash:v1,<alg>:<lowerhex>`.
76    pub fn display(&self) -> String {
77        format!(
78            "hash:v{},{}:{}",
79            self.v,
80            self.alg.name(),
81            hex::encode(&self.digest)
82        )
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    /// PE-CRYPTO-008: digest length bound to the algorithm (32/48); unknown
91    /// enum names/values rejected (closed agility, no silent downgrade).
92    #[test]
93    fn digest_lengths_enforced() {
94        assert!(HashRef::new(HashAlgorithm::Sha256, vec![0u8; 32]).is_ok());
95        assert!(HashRef::new(HashAlgorithm::Sha384, vec![0u8; 48]).is_ok());
96        assert!(HashRef::new(HashAlgorithm::Sha256, vec![0u8; 48]).is_err());
97        assert!(HashRef::new(HashAlgorithm::Sha384, vec![0u8; 32]).is_err());
98        assert!(HashRef::new(HashAlgorithm::Sha256, vec![]).is_err());
99        assert!(matches!(
100            HashAlgorithm::from_name("sha-256"),
101            Ok(HashAlgorithm::Sha256)
102        ));
103        assert!(HashAlgorithm::from_name("md5").is_err());
104        assert!(matches!(
105            HashAlgorithm::from_cbor_enum(1),
106            Ok(HashAlgorithm::Sha384)
107        ));
108        assert!(HashAlgorithm::from_cbor_enum(7).is_err());
109        let h = HashRef::new(HashAlgorithm::Sha256, vec![0xabu8; 32]).unwrap();
110        assert!(h.display().starts_with("hash:v1,sha-256:"));
111    }
112}