keccak_hasher/
lib.rs

1// Copyright 2017, 2018 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Hasher implementation for the Keccak-256 hash
16
17use hash256_std_hasher::Hash256StdHasher;
18use hash_db::Hasher;
19use tiny_keccak::{Hasher as _, Keccak};
20
21/// The `Keccak` hash output type.
22pub type KeccakHash = [u8; 32];
23
24/// Concrete `Hasher` impl for the Keccak-256 hash
25#[derive(Default, Debug, Clone, PartialEq)]
26pub struct KeccakHasher;
27impl Hasher for KeccakHasher {
28	type Out = KeccakHash;
29
30	type StdHasher = Hash256StdHasher;
31
32	const LENGTH: usize = 32;
33
34	fn hash(x: &[u8]) -> Self::Out {
35		let mut keccak = Keccak::v256();
36		keccak.update(x);
37		let mut out = [0u8; 32];
38		keccak.finalize(&mut out);
39		out
40	}
41}
42
43#[cfg(test)]
44mod tests {
45	use super::*;
46	use std::collections::HashMap;
47
48	#[test]
49	fn hash256_std_hasher_works() {
50		let hello_bytes = b"Hello world!";
51		let hello_key = KeccakHasher::hash(hello_bytes);
52
53		let mut h: HashMap<<KeccakHasher as Hasher>::Out, Vec<u8>> = Default::default();
54		h.insert(hello_key, hello_bytes.to_vec());
55		h.remove(&hello_key);
56
57		let mut h: HashMap<
58			<KeccakHasher as Hasher>::Out,
59			Vec<u8>,
60			std::hash::BuildHasherDefault<Hash256StdHasher>,
61		> = Default::default();
62		h.insert(hello_key, hello_bytes.to_vec());
63		h.remove(&hello_key);
64	}
65}