openvm_keccak256/
host_impl.rs

1use openvm_keccak256_guest::KECCAK_OUTPUT_SIZE;
2use tiny_keccak::Hasher as _;
3
4/// Keccak-256 hasher state for incremental hashing.
5///
6/// This struct wraps tiny-keccak's Keccak hasher for Keccak-256.
7#[derive(Clone)]
8pub struct Keccak256 {
9    inner: tiny_keccak::Keccak,
10}
11
12impl Keccak256 {
13    /// Creates a new Keccak-256 hasher.
14    pub fn new() -> Self {
15        Self {
16            inner: tiny_keccak::Keccak::v256(),
17        }
18    }
19
20    /// Absorbs input data into the sponge state.
21    pub fn update(&mut self, input: &[u8]) {
22        self.inner.update(input);
23    }
24
25    /// Finalizes the hash computation and writes the result to the output buffer.
26    ///
27    /// # Panics
28    ///
29    /// Panics if `output` is not exactly `KECCAK_OUTPUT_SIZE` (32) bytes long.
30    pub fn finalize(self, output: &mut [u8]) {
31        assert_eq!(
32            output.len(),
33            KECCAK_OUTPUT_SIZE,
34            "output must be exactly 32 bytes"
35        );
36        self.inner.finalize(output);
37    }
38}
39
40impl Default for Keccak256 {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46/// Sets `output` to the keccak256 hash of `input`.
47#[inline(always)]
48pub fn set_keccak256(input: &[u8], output: &mut [u8; KECCAK_OUTPUT_SIZE]) {
49    let mut hasher = Keccak256::new();
50    hasher.update(input);
51    hasher.finalize(output);
52}