Skip to main content

revive_common/
keccak256.rs

1//! Keccak-256 hash utilities.
2
3use serde::{Deserialize, Serialize};
4use sha3::digest::FixedOutput;
5use sha3::Digest;
6
7pub const DIGEST_BYTES: usize = 32;
8
9/// Keccak-256 hash utilities.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct Keccak256 {
12    /// Binary representation.
13    bytes: [u8; DIGEST_BYTES],
14    /// Hexadecimal string representation.
15    string: String,
16}
17
18impl Keccak256 {
19    /// Computes the `keccak256` hash for `preimage`.
20    pub fn from_slice(preimage: &[u8]) -> Self {
21        let bytes = sha3::Keccak256::digest(preimage).into();
22        let string = format!("0x{}", hex::encode(bytes));
23        Self { bytes, string }
24    }
25
26    /// Computes the `keccak256` hash for an array of `preimages`.
27    pub fn from_slices<R: AsRef<[u8]>>(preimages: &[R]) -> Self {
28        let mut hasher = sha3::Keccak256::new();
29        for preimage in preimages.iter() {
30            hasher.update(preimage);
31        }
32        let bytes: [u8; DIGEST_BYTES] = hasher.finalize_fixed().into();
33        let string = format!("0x{}", hex::encode(bytes));
34        Self { bytes, string }
35    }
36
37    /// Returns a reference to the 32-byte SHA-3 hash.
38    pub fn as_bytes(&self) -> &[u8] {
39        self.bytes.as_slice()
40    }
41
42    /// Returns a reference to the hexadecimal string representation.
43    pub fn as_str(&self) -> &str {
44        self.string.as_str()
45    }
46
47    /// Extracts the binary representation.
48    pub fn to_vec(&self) -> Vec<u8> {
49        self.bytes.to_vec()
50    }
51}
52
53impl std::fmt::Display for Keccak256 {
54    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
55        write!(f, "{}", self.as_str())
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    #[test]
62    fn hash_and_stringify_works() {
63        assert_eq!(
64            super::Keccak256::from_slices(&["foo".as_bytes(), "bar".as_bytes(),]).as_str(),
65            "0x38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed98873e"
66        );
67    }
68}