ethers_core/utils/
hash.rs

1//! Various utilities for manipulating Ethereum related data.
2
3use ethabi::ethereum_types::H256;
4use tiny_keccak::{Hasher, Keccak};
5
6/// Hash a message according to [EIP-191] (version `0x01`).
7///
8/// The final message is a UTF-8 string, encoded as follows:
9/// `"\x19Ethereum Signed Message:\n" + message.length + message`
10///
11/// This message is then hashed using [Keccak-256](keccak256).
12///
13/// [EIP-191]: https://eips.ethereum.org/EIPS/eip-191
14pub fn hash_message<T: AsRef<[u8]>>(message: T) -> H256 {
15    const PREFIX: &str = "\x19Ethereum Signed Message:\n";
16
17    let message = message.as_ref();
18    let len = message.len();
19    let len_string = len.to_string();
20
21    let mut eth_message = Vec::with_capacity(PREFIX.len() + len_string.len() + len);
22    eth_message.extend_from_slice(PREFIX.as_bytes());
23    eth_message.extend_from_slice(len_string.as_bytes());
24    eth_message.extend_from_slice(message);
25
26    H256(keccak256(&eth_message))
27}
28
29/// Compute the Keccak-256 hash of input bytes.
30///
31/// Note that strings are interpreted as UTF-8 bytes,
32// TODO: Add Solidity Keccak256 packing support
33pub fn keccak256<T: AsRef<[u8]>>(bytes: T) -> [u8; 32] {
34    let mut output = [0u8; 32];
35
36    let mut hasher = Keccak::v256();
37    hasher.update(bytes.as_ref());
38    hasher.finalize(&mut output);
39
40    output
41}
42
43/// Calculate the function selector as per the contract ABI specification. This
44/// is defined as the first 4 bytes of the Keccak256 hash of the function
45/// signature.
46pub fn id<S: AsRef<str>>(signature: S) -> [u8; 4] {
47    let mut output = [0u8; 4];
48
49    let mut hasher = Keccak::v256();
50    hasher.update(signature.as_ref().as_bytes());
51    hasher.finalize(&mut output);
52
53    output
54}
55
56/// Serialize a type.
57///
58/// # Panics
59///
60/// If the type returns an error during serialization.
61pub fn serialize<T: serde::Serialize>(t: &T) -> serde_json::Value {
62    serde_json::to_value(t).expect("Failed to serialize value")
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    // from https://emn178.github.io/online-tools/keccak_256.html
71    fn test_keccak256() {
72        assert_eq!(
73            hex::encode(keccak256(b"hello")),
74            "1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"
75        );
76    }
77
78    // test vector taken from:
79    // https://web3js.readthedocs.io/en/v1.2.2/web3-eth-accounts.html#hashmessage
80    #[test]
81    fn test_hash_message() {
82        let hash = hash_message("Hello World");
83
84        assert_eq!(
85            hash,
86            "a1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2".parse().unwrap()
87        );
88    }
89
90    #[test]
91    fn simple_function_signature() {
92        // test vector retrieved from
93        // https://web3js.readthedocs.io/en/v1.2.4/web3-eth-abi.html#encodefunctionsignature
94        assert_eq!(id("myMethod(uint256,string)"), [0x24, 0xee, 0x00, 0x97],);
95    }
96
97    #[test]
98    fn revert_function_signature() {
99        assert_eq!(id("Error(string)"), [0x08, 0xc3, 0x79, 0xa0]);
100    }
101}