web3_hash_utils/
lib.rs

1//! Utility functions for computing hashes.
2use ethereum_types::H256;
3use sha3::{Digest, Keccak256};
4
5const PREFIX: &str = "\x19Ethereum Signed Message:\n";
6
7/// Hash a message according to EIP-191.
8///
9/// The data is a UTF-8 encoded string and will enveloped as follows:
10/// `"\x19Ethereum Signed Message:\n" + message.length + message` and hashed
11/// using keccak256.
12pub fn hash_message<S>(message: S) -> H256
13where
14    S: AsRef<[u8]>,
15{
16    let message = message.as_ref();
17    let mut eth_message = format!("{}{}", PREFIX, message.len()).into_bytes();
18    eth_message.extend_from_slice(message);
19    keccak256(&eth_message).into()
20}
21
22/// Compute the Keccak-256 hash of input bytes.
23///
24/// Panics if the computed hash is not the expected length (32 bytes).
25pub fn keccak256<S>(bytes: S) -> [u8; 32]
26where
27    S: AsRef<[u8]>,
28{
29    let hash = Keccak256::digest(bytes.as_ref());
30    let hash: [u8; 32] = hash
31        .as_slice()
32        .try_into()
33        .expect("hash is not the correct length");
34    hash
35}