1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use ethabi::ethereum_types::H256;
use tiny_keccak::{Hasher, Keccak};
const PREFIX: &str = "\x19Ethereum Signed Message:\n";
pub fn hash_message<S>(message: S) -> H256
where
S: AsRef<[u8]>,
{
let message = message.as_ref();
let mut eth_message = format!("{PREFIX}{}", message.len()).into_bytes();
eth_message.extend_from_slice(message);
keccak256(ð_message).into()
}
pub fn keccak256<S>(bytes: S) -> [u8; 32]
where
S: AsRef<[u8]>,
{
let mut output = [0u8; 32];
let mut hasher = Keccak::v256();
hasher.update(bytes.as_ref());
hasher.finalize(&mut output);
output
}
pub fn id<S: AsRef<str>>(signature: S) -> [u8; 4] {
let mut output = [0u8; 4];
let mut hasher = Keccak::v256();
hasher.update(signature.as_ref().as_bytes());
hasher.finalize(&mut output);
output
}
pub fn serialize<T: serde::Serialize>(t: &T) -> serde_json::Value {
serde_json::to_value(t).expect("Types never fail to serialize.")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_keccak256() {
assert_eq!(
hex::encode(keccak256(b"hello")),
"1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"
);
}
#[test]
fn test_hash_message() {
let hash = hash_message("Hello World");
assert_eq!(
hash,
"a1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2".parse().unwrap()
);
}
#[test]
fn simple_function_signature() {
assert_eq!(id("myMethod(uint256,string)"), [0x24, 0xee, 0x00, 0x97],);
}
#[test]
fn revert_function_signature() {
assert_eq!(id("Error(string)"), [0x08, 0xc3, 0x79, 0xa0]);
}
}