2015-12-04 13:12:11 +01:00
|
|
|
//! Wrapper around tiny-keccak crate.
|
|
|
|
|
2015-11-27 17:54:33 +01:00
|
|
|
use std::mem::uninitialized;
|
2015-12-01 01:35:32 +01:00
|
|
|
use tiny_keccak::Keccak;
|
2016-01-08 11:52:46 +01:00
|
|
|
use bytes::{BytesConvertable,Populatable};
|
2016-01-09 10:22:03 +01:00
|
|
|
use hash::{H256, FixedHash};
|
2015-11-27 17:54:33 +01:00
|
|
|
|
2015-12-04 13:12:11 +01:00
|
|
|
/// Types implementing this trait are sha3able.
|
2015-12-26 15:48:41 +01:00
|
|
|
///
|
2015-12-04 13:12:11 +01:00
|
|
|
/// ```
|
|
|
|
/// extern crate ethcore_util as util;
|
|
|
|
/// use std::str::FromStr;
|
|
|
|
/// use util::sha3::*;
|
|
|
|
/// use util::hash::*;
|
2015-12-26 15:48:41 +01:00
|
|
|
///
|
2015-12-04 13:12:11 +01:00
|
|
|
/// fn main() {
|
|
|
|
/// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
|
|
|
|
/// }
|
|
|
|
/// ```
|
2015-11-28 00:14:40 +01:00
|
|
|
pub trait Hashable {
|
2015-11-27 17:54:33 +01:00
|
|
|
fn sha3(&self) -> H256;
|
2015-12-26 15:48:41 +01:00
|
|
|
fn sha3_into(&self, dest: &mut [u8]) {
|
|
|
|
self.sha3().copy_to(dest);
|
|
|
|
}
|
2015-11-27 17:54:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Hashable for T where T: BytesConvertable {
|
|
|
|
fn sha3(&self) -> H256 {
|
|
|
|
unsafe {
|
2015-12-01 01:35:32 +01:00
|
|
|
let mut keccak = Keccak::new_keccak256();
|
|
|
|
keccak.update(self.bytes());
|
2015-11-27 17:54:33 +01:00
|
|
|
let mut ret: H256 = uninitialized();
|
2016-01-07 23:59:50 +01:00
|
|
|
keccak.finalize(ret.as_slice_mut());
|
2015-11-27 17:54:33 +01:00
|
|
|
ret
|
|
|
|
}
|
|
|
|
}
|
2015-11-30 16:38:55 +01:00
|
|
|
fn sha3_into(&self, dest: &mut [u8]) {
|
2015-12-02 12:07:46 +01:00
|
|
|
let mut keccak = Keccak::new_keccak256();
|
|
|
|
keccak.update(self.bytes());
|
|
|
|
keccak.finalize(dest);
|
2015-11-30 16:38:55 +01:00
|
|
|
}
|
2015-11-27 17:54:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn sha3_empty() {
|
|
|
|
use std::str::FromStr;
|
2015-11-27 18:15:44 +01:00
|
|
|
assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
|
2015-11-27 17:54:33 +01:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn sha3_as() {
|
|
|
|
use std::str::FromStr;
|
2015-11-27 18:15:44 +01:00
|
|
|
assert_eq!([0x41u8; 32].sha3(), H256::from_str("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8").unwrap());
|
2015-11-27 17:54:33 +01:00
|
|
|
}
|
2015-11-27 18:15:44 +01:00
|
|
|
|