Add SHA3
This commit is contained in:
parent
c08292663f
commit
006fe20287
@ -13,5 +13,5 @@ rustc-serialize = "0.3"
|
||||
arrayvec = "0.3"
|
||||
mio = "0.*"
|
||||
rand = "0.*"
|
||||
tiny-keccak = "0.2"
|
||||
tiny-keccak = "0.3"
|
||||
rocksdb = "0.2.1"
|
||||
|
17
src/bytes.rs
17
src/bytes.rs
@ -10,6 +10,23 @@ use std::fmt;
|
||||
use std::error::Error as StdError;
|
||||
use uint::{U128, U256};
|
||||
|
||||
pub trait BytesConvertable {
|
||||
fn bytes(&self) -> &[u8];
|
||||
}
|
||||
|
||||
impl<'a> BytesConvertable for &'a [u8] {
|
||||
fn bytes(&self) -> &[u8] { self }
|
||||
}
|
||||
|
||||
impl BytesConvertable for Vec<u8> {
|
||||
fn bytes(&self) -> &[u8] { self }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_convertable() {
|
||||
assert_eq!(vec![0x12u8, 0x34].bytes(), &[0x12u8, 0x34]);
|
||||
}
|
||||
|
||||
/// TODO: optimise some conversations
|
||||
pub trait ToBytes {
|
||||
fn to_bytes(&self) -> Vec<u8>;
|
||||
|
11
src/hash.rs
11
src/hash.rs
@ -6,6 +6,7 @@ use rustc_serialize::hex::*;
|
||||
use error::EthcoreError;
|
||||
use rand::Rng;
|
||||
use rand::os::OsRng;
|
||||
use bytes::BytesConvertable;
|
||||
|
||||
macro_rules! impl_hash {
|
||||
($from: ident, $size: expr) => {
|
||||
@ -25,6 +26,16 @@ macro_rules! impl_hash {
|
||||
let mut rng = OsRng::new().unwrap();
|
||||
rng.fill_bytes(&mut self.0);
|
||||
}
|
||||
|
||||
pub fn mut_bytes(&mut self) -> &mut [u8; $size] {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl BytesConvertable for $from {
|
||||
fn bytes(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for $from {
|
||||
|
@ -15,6 +15,7 @@ pub mod bytes;
|
||||
pub mod rlp;
|
||||
pub mod vector;
|
||||
pub mod db;
|
||||
pub mod sha3;
|
||||
|
||||
//pub mod network;
|
||||
|
||||
|
29
src/sha3.rs
Normal file
29
src/sha3.rs
Normal file
@ -0,0 +1,29 @@
|
||||
use std::mem::uninitialized;
|
||||
use tiny_keccak::keccak_256;
|
||||
use bytes::BytesConvertable;
|
||||
use hash::H256;
|
||||
|
||||
trait Hashable {
|
||||
fn sha3(&self) -> H256;
|
||||
}
|
||||
|
||||
impl<T> Hashable for T where T: BytesConvertable {
|
||||
fn sha3(&self) -> H256 {
|
||||
unsafe {
|
||||
let mut ret: H256 = uninitialized();
|
||||
keccak_256(self.bytes(), ret.mut_bytes());
|
||||
ret
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha3_empty() {
|
||||
use std::str::FromStr;
|
||||
assert_eq!((&[0u8; 0][..]).sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
|
||||
}
|
||||
#[test]
|
||||
fn sha3_as() {
|
||||
use std::str::FromStr;
|
||||
assert_eq!((&[0x41u8; 32][..]).sha3(), H256::from_str("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8").unwrap());
|
||||
}
|
Loading…
Reference in New Issue
Block a user