Skip to main content

miden_crypto/hash/blake/
mod.rs

1use core::mem::size_of;
2
3use super::{
4    HasherExt,
5    digest::{Digest, Digest192, Digest256},
6};
7use crate::{Felt, field::BasedVectorSpace};
8
9#[cfg(test)]
10mod tests;
11
12// RE-EXPORTS
13// ================================================================================================
14
15/// Re-export of the Blake3 hasher from Plonky3 for use in the prover config downstream.
16pub use p3_blake3::Blake3 as Blake3Hasher;
17
18// TYPE ALIASES
19// ================================================================================================
20
21/// Alias for the generic `Digest` type, for consistency with other hash modules.
22pub type Blake3Digest<const N: usize> = Digest<N>;
23
24// BLAKE3 256-BIT OUTPUT
25// ================================================================================================
26
27/// 256-bit output blake3 hasher.
28#[derive(Debug, Copy, Clone, Eq, PartialEq)]
29pub struct Blake3_256;
30
31impl HasherExt for Blake3_256 {
32    type Digest = Digest256;
33
34    fn hash_iter<'a>(slices: impl Iterator<Item = &'a [u8]>) -> Self::Digest {
35        let mut hasher = blake3::Hasher::new();
36        for slice in slices {
37            hasher.update(slice);
38        }
39        Digest::new(hasher.finalize().into())
40    }
41}
42
43impl Blake3_256 {
44    /// Blake3 collision resistance is 128-bits for 32-bytes output.
45    pub const COLLISION_RESISTANCE: u32 = 128;
46
47    pub fn hash(bytes: &[u8]) -> Digest256 {
48        Digest::new(blake3::hash(bytes).into())
49    }
50
51    pub fn merge(values: &[Digest256; 2]) -> Digest256 {
52        Self::hash(Digest::digests_as_bytes(values))
53    }
54
55    pub fn merge_many(values: &[Digest256]) -> Digest256 {
56        Digest::new(blake3::hash(Digest::digests_as_bytes(values)).into())
57    }
58
59    /// Returns a hash of the provided field elements.
60    #[inline(always)]
61    pub fn hash_elements<E: BasedVectorSpace<Felt>>(elements: &[E]) -> Digest256 {
62        Digest::new(hash_elements(elements))
63    }
64
65    /// Hashes an iterator of byte slices.
66    #[inline(always)]
67    pub fn hash_iter<'a>(slices: impl Iterator<Item = &'a [u8]>) -> Digest256 {
68        <Self as HasherExt>::hash_iter(slices)
69    }
70}
71
72// BLAKE3 192-BIT OUTPUT
73// ================================================================================================
74
75/// 192-bit output blake3 hasher.
76#[derive(Debug, Copy, Clone, Eq, PartialEq)]
77pub struct Blake3_192;
78
79impl HasherExt for Blake3_192 {
80    type Digest = Digest192;
81
82    fn hash_iter<'a>(slices: impl Iterator<Item = &'a [u8]>) -> Self::Digest {
83        let mut hasher = blake3::Hasher::new();
84        for slice in slices {
85            hasher.update(slice);
86        }
87        Digest::new(shrink_array(hasher.finalize().into()))
88    }
89}
90
91impl Blake3_192 {
92    /// Blake3 collision resistance is 96-bits for 24-bytes output.
93    pub const COLLISION_RESISTANCE: u32 = 96;
94
95    pub fn hash(bytes: &[u8]) -> Digest192 {
96        Digest::new(shrink_array(blake3::hash(bytes).into()))
97    }
98
99    // Note: Same as Blake3_256 - these methods replaced trait delegations to remove Winterfell.
100    pub fn merge_many(values: &[Digest192]) -> Digest192 {
101        let bytes = Digest::digests_as_bytes(values);
102        Digest::new(shrink_array(blake3::hash(bytes).into()))
103    }
104
105    pub fn merge(values: &[Digest192; 2]) -> Digest192 {
106        Self::hash(Digest::digests_as_bytes(values))
107    }
108
109    /// Returns a hash of the provided field elements.
110    #[inline(always)]
111    pub fn hash_elements<E: BasedVectorSpace<Felt>>(elements: &[E]) -> Digest192 {
112        Digest::new(hash_elements(elements))
113    }
114
115    /// Hashes an iterator of byte slices.
116    #[inline(always)]
117    pub fn hash_iter<'a>(slices: impl Iterator<Item = &'a [u8]>) -> Digest192 {
118        <Self as HasherExt>::hash_iter(slices)
119    }
120}
121
122// HELPER FUNCTIONS
123// ================================================================================================
124
125/// Hash the elements into bytes and shrink the output.
126fn hash_elements<const N: usize, E>(elements: &[E]) -> [u8; N]
127where
128    E: BasedVectorSpace<Felt>,
129{
130    let digest = {
131        const FELT_BYTES: usize = size_of::<u64>();
132        const { assert!(FELT_BYTES == 8, "buffer arithmetic assumes 8-byte field elements") };
133
134        let mut hasher = blake3::Hasher::new();
135        // BLAKE3 block size: 64 bytes
136        let mut buf = [0_u8; 64];
137        let mut buf_offset = 0;
138
139        for elem in elements.iter() {
140            for &felt in E::as_basis_coefficients_slice(elem) {
141                buf[buf_offset..buf_offset + FELT_BYTES]
142                    .copy_from_slice(&felt.as_canonical_u64().to_le_bytes());
143                buf_offset += FELT_BYTES;
144
145                if buf_offset == 64 {
146                    hasher.update(&buf);
147                    buf_offset = 0;
148                }
149            }
150        }
151
152        if buf_offset > 0 {
153            hasher.update(&buf[..buf_offset]);
154        }
155
156        hasher.finalize()
157    };
158
159    shrink_array(digest.into())
160}
161
162/// Shrinks an array.
163///
164/// Due to compiler optimizations, this function is zero-copy.
165fn shrink_array<const M: usize, const N: usize>(source: [u8; M]) -> [u8; N] {
166    const {
167        assert!(M >= N, "size of destination should be smaller or equal than source");
168    }
169    core::array::from_fn(|i| source[i])
170}