From f0e8abb07bca9c6a9f646f71f5cefa8243dd1493 Mon Sep 17 00:00:00 2001 From: debris Date: Wed, 30 Aug 2017 19:18:28 +0200 Subject: [PATCH] Hashable::sha3 -> fn keccak for ethcore --- Cargo.lock | 5 ++ ethash/src/compute.rs | 42 +++++++------- ethash/src/lib.rs | 2 +- ethcore/Cargo.toml | 1 + ethcore/evm/Cargo.toml | 1 + ethcore/evm/src/interpreter/mod.rs | 9 +-- ethcore/evm/src/interpreter/shared_cache.rs | 4 +- ethcore/evm/src/lib.rs | 1 + ethcore/src/account_db.rs | 35 ++++++------ ethcore/src/block.rs | 15 ++--- ethcore/src/blockchain/blockchain.rs | 56 +++++++++---------- ethcore/src/blockchain/generator/complete.rs | 3 +- ethcore/src/blockchain/generator/generator.rs | 9 ++- ethcore/src/builtin.rs | 13 +---- ethcore/src/client/client.rs | 15 ++--- ethcore/src/client/test_client.rs | 3 +- ethcore/src/encoded.rs | 13 ++--- ethcore/src/engines/authority_round/mod.rs | 11 ++-- ethcore/src/engines/basic_authority.rs | 5 +- ethcore/src/engines/tendermint/message.rs | 12 ++-- ethcore/src/engines/tendermint/mod.rs | 25 +++++---- ethcore/src/engines/validator_set/contract.rs | 3 +- ethcore/src/engines/validator_set/multi.rs | 5 +- .../engines/validator_set/safe_contract.rs | 8 ++- ethcore/src/engines/vote_collector.rs | 43 +++++++------- ethcore/src/ethereum/ethash.rs | 3 +- ethcore/src/ethereum/mod.rs | 4 +- ethcore/src/executive.rs | 15 ++--- ethcore/src/header.rs | 21 +++---- ethcore/src/lib.rs | 1 + ethcore/src/migrations/state/v7.rs | 6 +- ethcore/src/miner/banning_queue.rs | 12 ++-- ethcore/src/miner/miner.rs | 5 +- ethcore/src/pod_account.rs | 5 +- ethcore/src/snapshot/account.rs | 43 +++++++------- ethcore/src/snapshot/block.rs | 5 +- ethcore/src/snapshot/io.rs | 22 ++++---- ethcore/src/snapshot/mod.rs | 14 ++--- ethcore/src/snapshot/tests/helpers.rs | 6 +- .../src/snapshot/tests/proof_of_authority.rs | 8 +-- ethcore/src/snapshot/tests/proof_of_work.rs | 4 +- ethcore/src/snapshot/tests/state.rs | 9 ++- ethcore/src/spec/genesis.rs | 6 +- ethcore/src/spec/spec.rs | 25 +++++---- ethcore/src/state/account.rs | 39 ++++++------- ethcore/src/state/mod.rs | 21 +++---- ethcore/src/state_db.rs | 7 ++- ethcore/src/tests/client.rs | 5 +- ethcore/src/tests/evm.rs | 5 +- ethcore/src/tests/helpers.rs | 3 +- ethcore/src/trace/types/filter.rs | 54 +++++++++--------- ethcore/src/trace/types/trace.rs | 14 ++--- ethcore/src/transaction.rs | 17 +++--- ethcore/src/verification/verification.rs | 8 ++- ethcore/src/views/block.rs | 17 ++---- ethcore/src/views/body.rs | 5 +- ethcore/src/views/header.rs | 13 ++--- ethcore/src/views/transaction.rs | 14 ++--- ethcore/types/Cargo.toml | 1 + ethcore/types/src/filter.rs | 7 ++- ethcore/types/src/lib.rs | 1 + ethcore/types/src/log_entry.rs | 5 +- ethcore/vm/Cargo.toml | 3 +- ethcore/vm/src/action_params.rs | 6 +- ethcore/vm/src/env_info.rs | 5 +- ethcore/vm/src/lib.rs | 3 +- stratum/Cargo.toml | 1 + stratum/src/lib.rs | 6 +- util/benches/trie.rs | 14 ++--- 69 files changed, 429 insertions(+), 398 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bd3469589..439ba8936 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -301,6 +301,7 @@ dependencies = [ "bloomable 0.1.0", "ethcore-util 1.8.0", "ethjson 0.1.0", + "hash 0.1.0", "rlp 0.2.0", "rlp_derive 0.1.0", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -516,6 +517,7 @@ dependencies = [ "evm 0.1.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "hardware-wallet 1.8.0", + "hash 0.1.0", "hyper 0.10.0-a.0 (git+https://github.com/paritytech/hyper)", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -756,6 +758,7 @@ dependencies = [ "ethcore-logger 1.8.0", "ethcore-util 1.8.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "jsonrpc-macros 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "jsonrpc-tcp-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", @@ -921,6 +924,7 @@ dependencies = [ "ethcore-util 1.8.0", "ethjson 0.1.0", "evmjit 1.8.0", + "hash 0.1.0", "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "parity-wasm 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3185,6 +3189,7 @@ dependencies = [ "ethcore-util 1.8.0", "ethjson 0.1.0", "evmjit 1.8.0", + "hash 0.1.0", "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.2.0", diff --git a/ethash/src/compute.rs b/ethash/src/compute.rs index ab2c758df..ae680b686 100644 --- a/ethash/src/compute.rs +++ b/ethash/src/compute.rs @@ -23,7 +23,7 @@ use primal::is_prime; use std::cell::Cell; use std::mem; use std::ptr; -use sha3; +use hash; use std::slice; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; @@ -200,7 +200,7 @@ impl SeedHashCompute { #[inline] pub fn resume_compute_seedhash(mut hash: H256, start_epoch: u64, end_epoch: u64) -> H256 { for _ in start_epoch..end_epoch { - unsafe { sha3::sha3_256(hash[..].as_mut_ptr(), 32, hash[..].as_ptr(), 32) }; + unsafe { hash::keccak_256(hash[..].as_mut_ptr(), 32, hash[..].as_ptr(), 32) }; } hash } @@ -214,14 +214,14 @@ fn fnv_hash(x: u32, y: u32) -> u32 { return x.wrapping_mul(FNV_PRIME) ^ y; } -fn sha3_512(input: &[u8], output: &mut [u8]) { - unsafe { sha3::sha3_512(output.as_mut_ptr(), output.len(), input.as_ptr(), input.len()) }; +fn keccak_512(input: &[u8], output: &mut [u8]) { + unsafe { hash::keccak_512(output.as_mut_ptr(), output.len(), input.as_ptr(), input.len()) }; } -fn sha3_512_inplace(input: &mut [u8]) { +fn keccak_512_inplace(input: &mut [u8]) { // This is safe since `sha3_*` uses an internal buffer and copies the result to the output. This // means that we can reuse the input buffer for both input and output. - unsafe { sha3::sha3_512(input.as_mut_ptr(), input.len(), input.as_ptr(), input.len()) }; + unsafe { hash::keccak_512(input.as_mut_ptr(), input.len(), input.as_ptr(), input.len()) }; } fn get_cache_size(block_number: u64) -> usize { @@ -250,23 +250,23 @@ fn get_data_size(block_number: u64) -> usize { /// Boundary recovered from mix hash pub fn quick_get_difficulty(header_hash: &H256, nonce: u64, mix_hash: &H256) -> H256 { unsafe { - // This is safe - the `sha3_512` call below reads the first 40 bytes (which we explicitly set + // This is safe - the `keccak_512` call below reads the first 40 bytes (which we explicitly set // with two `copy_nonoverlapping` calls) but writes the first 64, and then we explicitly write - // the next 32 bytes before we read the whole thing with `sha3_256`. + // the next 32 bytes before we read the whole thing with `keccak_256`. // // This cannot be elided by the compiler as it doesn't know the implementation of - // `sha3_512`. + // `keccak_512`. let mut buf: [u8; 64 + 32] = mem::uninitialized(); ptr::copy_nonoverlapping(header_hash.as_ptr(), buf.as_mut_ptr(), 32); ptr::copy_nonoverlapping(mem::transmute(&nonce), buf[32..].as_mut_ptr(), 8); - sha3::sha3_512(buf.as_mut_ptr(), 64, buf.as_ptr(), 40); + hash::keccak_512(buf.as_mut_ptr(), 64, buf.as_ptr(), 40); ptr::copy_nonoverlapping(mix_hash.as_ptr(), buf[64..].as_mut_ptr(), 32); - // This is initialized in `sha3_256` + // This is initialized in `keccak_256` let mut hash: [u8; 32] = mem::uninitialized(); - sha3::sha3_256(hash.as_mut_ptr(), hash.len(), buf.as_ptr(), buf.len()); + hash::keccak_256(hash.as_mut_ptr(), hash.len(), buf.as_ptr(), buf.len()); hash } @@ -320,7 +320,7 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) half_mix: unsafe { // Pack `header_hash` and `nonce` together // We explicitly write the first 40 bytes, leaving the last 24 as uninitialized. Then - // `sha3_512` reads the first 40 bytes (4th parameter) and overwrites the entire array, + // `keccak_512` reads the first 40 bytes (4th parameter) and overwrites the entire array, // leaving it fully initialized. let mut out: [u8; NODE_BYTES] = mem::uninitialized(); @@ -336,7 +336,7 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) ); // compute sha3-512 hash and replicate across mix - sha3::sha3_512( + hash::keccak_512( out.as_mut_ptr(), NODE_BYTES, out.as_ptr(), @@ -427,10 +427,10 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) let value: H256 = unsafe { // We can interpret the buffer as an array of `u8`s, since it's `repr(C)`. let read_ptr: *const u8 = mem::transmute(&buf); - // We overwrite the second half since `sha3_256` has an internal buffer and so allows + // We overwrite the second half since `keccak_256` has an internal buffer and so allows // overlapping arrays as input. let write_ptr: *mut u8 = mem::transmute(&mut buf.compress_bytes); - sha3::sha3_256( + hash::keccak_256( write_ptr, buf.compress_bytes.len(), read_ptr, @@ -450,7 +450,7 @@ fn calculate_dag_item(node_index: u32, cache: &[Node]) -> Node { let mut ret = cache[node_index as usize % num_parent_nodes].clone(); ret.as_words_mut()[0] ^= node_index; - sha3_512_inplace(&mut ret.bytes); + keccak_512_inplace(&mut ret.bytes); debug_assert_eq!(NODE_WORDS, 16); for i in 0..ETHASH_DATASET_PARENTS as u32 { @@ -467,7 +467,7 @@ fn calculate_dag_item(node_index: u32, cache: &[Node]) -> Node { } } - sha3_512_inplace(&mut ret.bytes); + keccak_512_inplace(&mut ret.bytes); ret } @@ -485,9 +485,9 @@ fn light_new>(cache_dir: T, block_number: u64) -> Light { // Use uninit instead of unnecessarily writing `size_of::() * num_nodes` 0s nodes.set_len(num_nodes); - sha3_512(&seedhash[0..32], &mut nodes.get_unchecked_mut(0).bytes); + keccak_512(&seedhash[0..32], &mut nodes.get_unchecked_mut(0).bytes); for i in 1..num_nodes { - sha3::sha3_512(nodes.get_unchecked_mut(i).bytes.as_mut_ptr(), NODE_BYTES, nodes.get_unchecked(i - 1).bytes.as_ptr(), NODE_BYTES); + hash::keccak_512(nodes.get_unchecked_mut(i).bytes.as_mut_ptr(), NODE_BYTES, nodes.get_unchecked(i - 1).bytes.as_ptr(), NODE_BYTES); } debug_assert_eq!(NODE_WORDS, 16); @@ -504,7 +504,7 @@ fn light_new>(cache_dir: T, block_number: u64) -> Light { } } - sha3_512(&data.bytes, &mut nodes.get_unchecked_mut(i).bytes); + keccak_512(&data.bytes, &mut nodes.get_unchecked_mut(i).bytes); } } } diff --git a/ethash/src/lib.rs b/ethash/src/lib.rs index 9112546c4..f88e8a3f5 100644 --- a/ethash/src/lib.rs +++ b/ethash/src/lib.rs @@ -20,7 +20,7 @@ #![cfg_attr(feature = "benches", feature(test))] extern crate primal; -extern crate sha3; +extern crate hash; extern crate parking_lot; #[macro_use] diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index c49e31898..4af0f315d 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -59,6 +59,7 @@ table = { path = "../util/table" } bloomable = { path = "../util/bloomable" } vm = { path = "vm" } wasm = { path = "wasm" } +hash = { path = "../util/hash" } [dev-dependencies] native-contracts = { path = "native_contracts", features = ["test_contracts"] } diff --git a/ethcore/evm/Cargo.toml b/ethcore/evm/Cargo.toml index 2780703da..4dc239e19 100644 --- a/ethcore/evm/Cargo.toml +++ b/ethcore/evm/Cargo.toml @@ -17,6 +17,7 @@ vm = { path = "../vm" } parity-wasm = "0.12" ethcore-logger = { path = "../../logger" } wasm-utils = { git = "https://github.com/paritytech/wasm-utils" } +hash = { path = "../../util/hash" } [dev-dependencies] rustc-hex = "1.0" diff --git a/ethcore/evm/src/interpreter/mod.rs b/ethcore/evm/src/interpreter/mod.rs index cb8fe3a52..edf8bc3f5 100644 --- a/ethcore/evm/src/interpreter/mod.rs +++ b/ethcore/evm/src/interpreter/mod.rs @@ -26,6 +26,7 @@ mod shared_cache; use std::marker::PhantomData; use std::{cmp, mem}; use std::sync::Arc; +use hash::keccak; use vm::{ self, ActionParams, ActionValue, CallType, MessageCallResult, @@ -180,7 +181,7 @@ impl vm::Vm for Interpreter { match result { InstructionResult::JumpToPosition(position) => { if valid_jump_destinations.is_none() { - let code_hash = params.code_hash.clone().unwrap_or_else(|| code.sha3()); + let code_hash = params.code_hash.clone().unwrap_or_else(|| keccak(code.as_ref())); valid_jump_destinations = Some(self.cache.jump_destinations(&code_hash, code)); } let jump_destinations = valid_jump_destinations.as_ref().expect("jump_destinations are initialized on first jump; qed"); @@ -464,8 +465,8 @@ impl Interpreter { instructions::SHA3 => { let offset = stack.pop_back(); let size = stack.pop_back(); - let sha3 = self.mem.read_slice(offset, size).sha3(); - stack.push(U256::from(&*sha3)); + let k = keccak(self.mem.read_slice(offset, size)); + stack.push(U256::from(&*k)); }, instructions::SLOAD => { let key = H256::from(&stack.pop_back()); @@ -880,7 +881,7 @@ mod tests { use rustc_hex::FromHex; use vmtype::VMType; use factory::Factory; - use vm::{self, ActionParams, ActionValue}; + use vm::{ActionParams, ActionValue}; use vm::tests::{FakeExt, test_finalize}; #[test] diff --git a/ethcore/evm/src/interpreter/shared_cache.rs b/ethcore/evm/src/interpreter/shared_cache.rs index a93afa79a..6f6620a3b 100644 --- a/ethcore/evm/src/interpreter/shared_cache.rs +++ b/ethcore/evm/src/interpreter/shared_cache.rs @@ -15,8 +15,8 @@ // along with Parity. If not, see . use std::sync::Arc; +use hash::KECCAK_EMPTY; use util::{H256, HeapSizeOf, Mutex}; -use util::sha3::*; use util::cache::MemoryLruCache; use bit_set::BitSet; use super::super::instructions; @@ -49,7 +49,7 @@ impl SharedCache { /// Get jump destinations bitmap for a contract. pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Arc { - if code_hash == &SHA3_EMPTY { + if code_hash == &KECCAK_EMPTY { return Self::find_jump_destinations(code); } diff --git a/ethcore/evm/src/lib.rs b/ethcore/evm/src/lib.rs index 833b26664..5cde3a131 100644 --- a/ethcore/evm/src/lib.rs +++ b/ethcore/evm/src/lib.rs @@ -26,6 +26,7 @@ extern crate parity_wasm; extern crate wasm_utils; extern crate ethcore_logger; extern crate vm; +extern crate hash; #[macro_use] extern crate lazy_static; diff --git a/ethcore/src/account_db.rs b/ethcore/src/account_db.rs index 5ce555aef..48bb448dd 100644 --- a/ethcore/src/account_db.rs +++ b/ethcore/src/account_db.rs @@ -16,6 +16,7 @@ //! DB backend wrapper for Account trie use std::collections::HashMap; +use hash::{KECCAK_NULL_RLP, keccak}; use util::*; use rlp::NULL_RLP; @@ -79,7 +80,7 @@ impl<'db> AccountDB<'db> { /// Create a new AccountDB from an address. #[cfg(test)] pub fn new(db: &'db HashDB, address: &Address) -> Self { - Self::from_hash(db, address.sha3()) + Self::from_hash(db, keccak(address)) } /// Create a new AcountDB from an address' hash. @@ -97,14 +98,14 @@ impl<'db> HashDB for AccountDB<'db>{ } fn get(&self, key: &H256) -> Option { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP)); } self.db.get(&combine_key(&self.address_hash, key)) } fn contains(&self, key: &H256) -> bool { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return true; } self.db.contains(&combine_key(&self.address_hash, key)) @@ -133,7 +134,7 @@ impl<'db> AccountDBMut<'db> { /// Create a new AccountDB from an address. #[cfg(test)] pub fn new(db: &'db mut HashDB, address: &Address) -> Self { - Self::from_hash(db, address.sha3()) + Self::from_hash(db, keccak(address)) } /// Create a new AcountDB from an address' hash. @@ -156,14 +157,14 @@ impl<'db> HashDB for AccountDBMut<'db>{ } fn get(&self, key: &H256) -> Option { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP)); } self.db.get(&combine_key(&self.address_hash, key)) } fn contains(&self, key: &H256) -> bool { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return true; } self.db.contains(&combine_key(&self.address_hash, key)) @@ -171,16 +172,16 @@ impl<'db> HashDB for AccountDBMut<'db>{ fn insert(&mut self, value: &[u8]) -> H256 { if value == &NULL_RLP { - return SHA3_NULL_RLP.clone(); + return KECCAK_NULL_RLP.clone(); } - let k = value.sha3(); + let k = keccak(value); let ak = combine_key(&self.address_hash, &k); self.db.emplace(ak, DBValue::from_slice(value)); k } fn emplace(&mut self, key: H256, value: DBValue) { - if key == SHA3_NULL_RLP { + if key == KECCAK_NULL_RLP { return; } let key = combine_key(&self.address_hash, &key); @@ -188,7 +189,7 @@ impl<'db> HashDB for AccountDBMut<'db>{ } fn remove(&mut self, key: &H256) { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return; } let key = combine_key(&self.address_hash, key); @@ -204,14 +205,14 @@ impl<'db> HashDB for Wrapping<'db> { } fn get(&self, key: &H256) -> Option { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP)); } self.0.get(key) } fn contains(&self, key: &H256) -> bool { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return true; } self.0.contains(key) @@ -238,14 +239,14 @@ impl<'db> HashDB for WrappingMut<'db>{ } fn get(&self, key: &H256) -> Option { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP)); } self.0.get(key) } fn contains(&self, key: &H256) -> bool { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return true; } self.0.contains(key) @@ -253,20 +254,20 @@ impl<'db> HashDB for WrappingMut<'db>{ fn insert(&mut self, value: &[u8]) -> H256 { if value == &NULL_RLP { - return SHA3_NULL_RLP.clone(); + return KECCAK_NULL_RLP.clone(); } self.0.insert(value) } fn emplace(&mut self, key: H256, value: DBValue) { - if key == SHA3_NULL_RLP { + if key == KECCAK_NULL_RLP { return; } self.0.emplace(key, value) } fn remove(&mut self, key: &H256) { - if key == &SHA3_NULL_RLP { + if key == &KECCAK_NULL_RLP { return; } self.0.remove(key) diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index 64958700e..35eb41a83 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -19,9 +19,10 @@ use std::cmp; use std::sync::Arc; use std::collections::HashSet; +use hash::{keccak, KECCAK_NULL_RLP}; use rlp::{UntrustedRlp, RlpStream, Encodable, Decodable, DecoderError}; -use util::{Bytes, Address, Hashable, U256, H256, ordered_trie_root, SHA3_NULL_RLP}; +use util::{Bytes, Address, U256, H256, ordered_trie_root}; use util::error::{Mismatch, OutOfBounds}; use basic_types::{LogBloom, Seal}; @@ -400,7 +401,7 @@ impl<'x> OpenBlock<'x> { } s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().into_vec()))); let uncle_bytes = s.block.uncles.iter().fold(RlpStream::new_list(s.block.uncles.len()), |mut s, u| {s.append_raw(&u.rlp(Seal::With), 1); s} ).out(); - s.block.header.set_uncles_hash(uncle_bytes.sha3()); + s.block.header.set_uncles_hash(keccak(&uncle_bytes)); s.block.header.set_state_root(s.block.state.root().clone()); s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().into_vec()))); s.block.header.set_log_bloom(s.block.receipts.iter().fold(LogBloom::zero(), |mut b, r| {b = &b | &r.log_bloom; b})); //TODO: use |= operator @@ -425,14 +426,14 @@ impl<'x> OpenBlock<'x> { if let Err(e) = s.block.state.commit() { warn!("Encountered error on state commit: {}", e); } - if s.block.header.transactions_root().is_zero() || s.block.header.transactions_root() == &SHA3_NULL_RLP { + if s.block.header.transactions_root().is_zero() || s.block.header.transactions_root() == &KECCAK_NULL_RLP { s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().into_vec()))); } let uncle_bytes = s.block.uncles.iter().fold(RlpStream::new_list(s.block.uncles.len()), |mut s, u| {s.append_raw(&u.rlp(Seal::With), 1); s} ).out(); if s.block.header.uncles_hash().is_zero() { - s.block.header.set_uncles_hash(uncle_bytes.sha3()); + s.block.header.set_uncles_hash(keccak(&uncle_bytes)); } - if s.block.header.receipts_root().is_zero() || s.block.header.receipts_root() == &SHA3_NULL_RLP { + if s.block.header.receipts_root().is_zero() || s.block.header.receipts_root() == &KECCAK_NULL_RLP { s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().into_vec()))); } @@ -465,7 +466,7 @@ impl<'x> IsBlock for LockedBlock { impl ClosedBlock { /// Get the hash of the header without seal arguments. - pub fn hash(&self) -> H256 { self.header().rlp_sha3(Seal::Without) } + pub fn hash(&self) -> H256 { self.header().rlp_keccak(Seal::Without) } /// Turn this into a `LockedBlock`, unable to be reopened again. pub fn lock(self) -> LockedBlock { @@ -490,7 +491,7 @@ impl ClosedBlock { impl LockedBlock { /// Get the hash of the header without seal arguments. - pub fn hash(&self) -> H256 { self.header().rlp_sha3(Seal::Without) } + pub fn hash(&self) -> H256 { self.header().rlp_keccak(Seal::Without) } /// Provide a valid seal in order to turn this into a `SealedBlock`. /// diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index 001df861c..a39417321 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -511,7 +511,7 @@ impl BlockChain { // we need to insert genesis into the cache let block = BlockView::new(genesis); let header = block.header_view(); - let hash = block.sha3(); + let hash = block.hash(); let details = BlockDetails { number: header.number(), @@ -763,7 +763,7 @@ impl BlockChain { pub fn insert_unordered_block(&self, batch: &mut DBTransaction, bytes: &[u8], receipts: Vec, parent_td: Option, is_best: bool, is_ancient: bool) -> bool { let block = BlockView::new(bytes); let header = block.header_view(); - let hash = header.sha3(); + let hash = header.hash(); if self.is_known(&hash) { return false; @@ -965,7 +965,7 @@ impl BlockChain { // create views onto rlp let block = BlockView::new(bytes); let header = block.header_view(); - let hash = header.sha3(); + let hash = header.hash(); if self.is_known_child(&header.parent_hash(), &hash) { return ImportRoute::none(); @@ -1004,7 +1004,7 @@ impl BlockChain { /// Get inserted block info which is critical to prepare extras updates. fn block_info(&self, header: &HeaderView) -> BlockInfo { - let hash = header.sha3(); + let hash = header.hash(); let number = header.number(); let parent_hash = header.parent_hash(); let parent_details = self.block_details(&parent_hash).unwrap_or_else(|| panic!("Invalid parent hash: {:?}", parent_hash)); @@ -1465,9 +1465,9 @@ mod tests { #![cfg_attr(feature="dev", allow(similar_names))] use std::sync::Arc; use rustc_hex::FromHex; + use hash::keccak; use util::kvdb::KeyValueDB; use util::hash::*; - use util::sha3::Hashable; use receipt::Receipt; use blockchain::{BlockProvider, BlockChain, Config, ImportRoute}; use tests::helpers::*; @@ -1517,8 +1517,8 @@ mod tests { let mut finalizer = BlockFinalizer::default(); let genesis = canon_chain.generate(&mut finalizer).unwrap(); let first = canon_chain.generate(&mut finalizer).unwrap(); - let genesis_hash = BlockView::new(&genesis).header_view().sha3(); - let first_hash = BlockView::new(&first).header_view().sha3(); + let genesis_hash = BlockView::new(&genesis).header_view().hash(); + let first_hash = BlockView::new(&first).header_view().hash(); let db = new_db(); let bc = new_chain(&genesis, db.clone()); @@ -1548,7 +1548,7 @@ mod tests { let mut canon_chain = ChainGenerator::default(); let mut finalizer = BlockFinalizer::default(); let genesis = canon_chain.generate(&mut finalizer).unwrap(); - let genesis_hash = BlockView::new(&genesis).header_view().sha3(); + let genesis_hash = BlockView::new(&genesis).header_view().hash(); let db = new_db(); let bc = new_chain(&genesis, db.clone()); @@ -1557,7 +1557,7 @@ mod tests { let mut batch = db.transaction(); for _ in 0..10 { let block = canon_chain.generate(&mut finalizer).unwrap(); - block_hashes.push(BlockView::new(&block).header_view().sha3()); + block_hashes.push(BlockView::new(&block).header_view().hash()); bc.insert_block(&mut batch, &block, vec![]); bc.commit(); } @@ -1606,14 +1606,14 @@ mod tests { assert_eq!( [&b4b, &b3b, &b2b].iter().map(|b| BlockView::new(b).header()).collect::>(), - bc.find_uncle_headers(&BlockView::new(&b4a).header_view().sha3(), 3).unwrap() + bc.find_uncle_headers(&BlockView::new(&b4a).header_view().hash(), 3).unwrap() ); // TODO: insert block that already includes one of them as an uncle to check it's not allowed. } fn secret() -> Secret { - "".sha3().into() + keccak("").into() } #[test] @@ -1645,8 +1645,8 @@ mod tests { let b2 = fork_chain .generate(&mut fork_finalizer).unwrap(); - let b1a_hash = BlockView::new(&b1a).header_view().sha3(); - let b2_hash = BlockView::new(&b2).header_view().sha3(); + let b1a_hash = BlockView::new(&b1a).header_view().hash(); + let b2_hash = BlockView::new(&b2).header_view().hash(); let t1_hash = t1.hash(); @@ -1729,9 +1729,9 @@ mod tests { .with_transaction(t3.clone()) .generate(&mut fork_finalizer).unwrap(); - let b1a_hash = BlockView::new(&b1a).header_view().sha3(); - let b1b_hash = BlockView::new(&b1b).header_view().sha3(); - let b2_hash = BlockView::new(&b2).header_view().sha3(); + let b1a_hash = BlockView::new(&b1a).header_view().hash(); + let b1b_hash = BlockView::new(&b1b).header_view().hash(); + let b2_hash = BlockView::new(&b2).header_view().hash(); let t1_hash = t1.hash(); let t2_hash = t2.hash(); @@ -1789,11 +1789,11 @@ mod tests { let b3b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap(); let b3a = canon_chain.generate(&mut finalizer).unwrap(); - let genesis_hash = BlockView::new(&genesis).header_view().sha3(); - let b1_hash= BlockView::new(&b1).header_view().sha3(); - let b2_hash= BlockView::new(&b2).header_view().sha3(); - let b3a_hash= BlockView::new(&b3a).header_view().sha3(); - let b3b_hash= BlockView::new(&b3b).header_view().sha3(); + let genesis_hash = BlockView::new(&genesis).header_view().hash(); + let b1_hash= BlockView::new(&b1).header_view().hash(); + let b2_hash= BlockView::new(&b2).header_view().hash(); + let b3a_hash= BlockView::new(&b3a).header_view().hash(); + let b3b_hash= BlockView::new(&b3b).header_view().hash(); // b3a is a part of canon chain, whereas b3b is part of sidechain let best_block_hash = b3a_hash.clone(); @@ -1909,8 +1909,8 @@ mod tests { let mut finalizer = BlockFinalizer::default(); let genesis = canon_chain.generate(&mut finalizer).unwrap(); let first = canon_chain.generate(&mut finalizer).unwrap(); - let genesis_hash = BlockView::new(&genesis).header_view().sha3(); - let first_hash = BlockView::new(&first).header_view().sha3(); + let genesis_hash = BlockView::new(&genesis).header_view().hash(); + let first_hash = BlockView::new(&first).header_view().hash(); let db = new_db(); { @@ -2225,9 +2225,9 @@ mod tests { let genesis = canon_chain.generate(&mut finalizer).unwrap(); let first = canon_chain.generate(&mut finalizer).unwrap(); let second = canon_chain.generate(&mut finalizer).unwrap(); - let genesis_hash = BlockView::new(&genesis).header_view().sha3(); - let first_hash = BlockView::new(&first).header_view().sha3(); - let second_hash = BlockView::new(&second).header_view().sha3(); + let genesis_hash = BlockView::new(&genesis).header_view().hash(); + let first_hash = BlockView::new(&first).header_view().hash(); + let second_hash = BlockView::new(&second).header_view().hash(); let db = new_db(); let bc = new_chain(&genesis, db.clone()); @@ -2265,7 +2265,7 @@ mod tests { // create a longer fork for i in 0..5 { let canon_block = canon_chain.generate(&mut finalizer).unwrap(); - let hash = BlockView::new(&canon_block).header_view().sha3(); + let hash = BlockView::new(&canon_block).header_view().hash(); bc.insert_block(&mut batch, &canon_block, vec![]); bc.insert_epoch_transition(&mut batch, i, EpochTransition { @@ -2278,7 +2278,7 @@ mod tests { assert_eq!(bc.best_block_number(), 5); - let hash = BlockView::new(&uncle).header_view().sha3(); + let hash = BlockView::new(&uncle).header_view().hash(); bc.insert_block(&mut batch, &uncle, vec![]); bc.insert_epoch_transition(&mut batch, 999, EpochTransition { block_hash: hash, diff --git a/ethcore/src/blockchain/generator/complete.rs b/ethcore/src/blockchain/generator/complete.rs index 0c22d4dfc..4cdda3f47 100644 --- a/ethcore/src/blockchain/generator/complete.rs +++ b/ethcore/src/blockchain/generator/complete.rs @@ -16,7 +16,6 @@ use util::hash::H256; use util::bytes::Bytes; -use util::sha3::Hashable; use views::BlockView; #[derive(Default, Clone)] @@ -46,7 +45,7 @@ impl<'a, I> Iterator for Complete<'a, I> where I: Iterator, ::Ite fn next(&mut self) -> Option { self.iter.next().map(|item| { let rlp = item.complete(self.finalizer.parent_hash.clone()); - self.finalizer.parent_hash = BlockView::new(&rlp).header_view().sha3(); + self.finalizer.parent_hash = BlockView::new(&rlp).header_view().hash(); rlp }) } diff --git a/ethcore/src/blockchain/generator/generator.rs b/ethcore/src/blockchain/generator/generator.rs index a2c2c441a..be9378268 100644 --- a/ethcore/src/blockchain/generator/generator.rs +++ b/ethcore/src/blockchain/generator/generator.rs @@ -111,7 +111,6 @@ impl Iterator for ChainGenerator { mod tests { use util::hash::{H256, H2048}; - use util::sha3::Hashable; use views::BlockView; use blockchain::generator::{ChainIterator, ChainGenerator, BlockFinalizer}; @@ -129,7 +128,7 @@ mod tests { let b1_rlp = canon_chain.generate(&mut finalizer).unwrap(); let b1 = BlockView::new(&b1_rlp); - assert_eq!(b1.header_view().parent_hash(), genesis.header_view().sha3()); + assert_eq!(b1.header_view().parent_hash(), genesis.header_view().hash()); assert_eq!(b1.header_view().number(), 1); let mut fork_chain = canon_chain.fork(1); @@ -137,13 +136,13 @@ mod tests { let b2_rlp_fork = fork_chain.generate(&mut finalizer.fork()).unwrap(); let b2_fork = BlockView::new(&b2_rlp_fork); - assert_eq!(b2_fork.header_view().parent_hash(), b1.header_view().sha3()); + assert_eq!(b2_fork.header_view().parent_hash(), b1.header_view().hash()); assert_eq!(b2_fork.header_view().number(), 2); let b2_rlp = canon_chain.generate(&mut finalizer).unwrap(); let b2 = BlockView::new(&b2_rlp); - assert_eq!(b2.header_view().parent_hash(), b1.header_view().sha3()); + assert_eq!(b2.header_view().parent_hash(), b1.header_view().hash()); assert_eq!(b2.header_view().number(), 2); assert!(b2.header_view().difficulty() > b2_fork.header_view().difficulty()); } @@ -163,7 +162,7 @@ mod tests { assert_eq!(block0.header_view().parent_hash(), H256::default()); assert_eq!(block1.header_view().number(), 1); - assert_eq!(block1.header_view().parent_hash(), block0.header_view().sha3()); + assert_eq!(block1.header_view().parent_hash(), block0.header_view().hash()); } diff --git a/ethcore/src/builtin.rs b/ethcore/src/builtin.rs index 9e49e610c..b6d7064eb 100644 --- a/ethcore/src/builtin.rs +++ b/ethcore/src/builtin.rs @@ -23,7 +23,8 @@ use crypto::ripemd160::Ripemd160 as Ripemd160Digest; use crypto::digest::Digest; use num::{BigUint, Zero, One}; -use util::{U256, H256, Hashable, BytesRef}; +use hash::keccak; +use util::{U256, H256, BytesRef}; use ethkey::{Signature, recover as ec_recover}; use ethjson; @@ -228,7 +229,7 @@ impl Impl for EcRecover { let s = Signature::from_rsv(&r, &s, bit); if s.is_valid() { if let Ok(p) = ec_recover(&s, &hash) { - let r = p.sha3(); + let r = keccak(p); output.write(0, &[0; 12]); output.write(12, &r[12..r.len()]); } @@ -572,14 +573,6 @@ mod tests { #[test] fn ecrecover() { - /*let k = KeyPair::from_secret(b"test".sha3()).unwrap(); - let a: Address = From::from(k.public().sha3()); - println!("Address: {}", a); - let m = b"hello world".sha3(); - println!("Message: {}", m); - let s = k.sign(&m).unwrap(); - println!("Signed: {}", s);*/ - let f = ethereum_builtin("ecrecover"); let i = FromHex::from_hex("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad000000000000000000000000000000000000000000000000000000000000001b650acf9d3f5f0a2c799776a1254355d5f4061762a237396a99a0e0e3fc2bcd6729514a0dacb2e623ac4abd157cb18163ff942280db4d5caad66ddf941ba12e03").unwrap(); diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index ac8a0aea9..9d5465593 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -23,7 +23,8 @@ use time::precise_time_ns; use itertools::Itertools; // util -use util::{Bytes, PerfTimer, Mutex, RwLock, MutexGuard, Hashable}; +use hash::keccak; +use util::{Bytes, PerfTimer, Mutex, RwLock, MutexGuard}; use util::{journaldb, DBValue, TrieFactory, Trie}; use util::{U256, H256, Address, H2048}; use util::trie::TrieSpec; @@ -652,7 +653,7 @@ impl Client { .map(Into::into) .collect(); - assert_eq!(header.hash(), BlockView::new(block_data).header_view().sha3()); + assert_eq!(header.hash(), BlockView::new(block_data).header_view().hash()); //let traces = From::from(block.traces().clone().unwrap_or_else(Vec::new)); @@ -1503,7 +1504,7 @@ impl BlockChainClient for Client { }; let (_, db) = state.drop(); - let account_db = self.factories.accountdb.readonly(db.as_hashdb(), account.sha3()); + let account_db = self.factories.accountdb.readonly(db.as_hashdb(), keccak(account)); let trie = match self.factories.trie.readonly(account_db.as_hashdb(), &root) { Ok(trie) => trie, _ => { @@ -1591,7 +1592,7 @@ impl BlockChainClient for Client { use verification::queue::kind::BlockLike; use verification::queue::kind::blocks::Unverified; - // create unverified block here so the `sha3` calculation can be cached. + // create unverified block here so the `keccak` calculation can be cached. let unverified = Unverified::new(bytes); { @@ -1792,7 +1793,7 @@ impl BlockChainClient for Client { let dispatch = move |reg_addr, data| { future::done(self.call_contract(BlockId::Latest, reg_addr, data)) }; - r.get_address(dispatch, name.as_bytes().sha3(), "A".to_string()).wait().ok() + r.get_address(dispatch, keccak(name.as_bytes()), "A".to_string()).wait().ok() }) .and_then(|a| if a.is_zero() { None } else { Some(a) }) } @@ -2067,16 +2068,16 @@ mod tests { #[test] fn should_return_correct_log_index() { + use hash::keccak; use super::transaction_receipt; use ethkey::KeyPair; use log_entry::{LogEntry, LocalizedLogEntry}; use receipt::{Receipt, LocalizedReceipt}; use transaction::{Transaction, LocalizedTransaction, Action}; - use util::Hashable; use tests::helpers::TestEngine; // given - let key = KeyPair::from_secret_slice(&"test".sha3()).unwrap(); + let key = KeyPair::from_secret_slice(&keccak("test")).unwrap(); let secret = key.secret(); let engine = TestEngine::new(0); diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 0e7e53e43..256d7953d 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -22,6 +22,7 @@ use std::collections::{HashMap, BTreeMap}; use std::mem; use itertools::Itertools; use rustc_hex::FromHex; +use hash::keccak; use util::*; use rlp::*; use ethkey::{Generator, Random}; @@ -241,7 +242,7 @@ impl TestBlockChainClient { uncle_header.set_parent_hash(self.last_hash.read().clone()); uncle_header.set_number(n as BlockNumber); uncles.append(&uncle_header); - header.set_uncles_hash(uncles.as_raw().sha3()); + header.set_uncles_hash(keccak(uncles.as_raw())); uncles }, _ => RlpStream::new_list(0) diff --git a/ethcore/src/encoded.rs b/ethcore/src/encoded.rs index 125a00fd0..e6eb025e9 100644 --- a/ethcore/src/encoded.rs +++ b/ethcore/src/encoded.rs @@ -28,7 +28,8 @@ use header::{BlockNumber, Header as FullHeader}; use transaction::UnverifiedTransaction; use views; -use util::{Address, Hashable, H256, H2048, U256, HeapSizeOf}; +use util::{Address, H256, H2048, U256, HeapSizeOf}; +use hash::keccak; use rlp::Rlp; /// Owning header view. @@ -64,7 +65,7 @@ impl Header { // forwarders to borrowed view. impl Header { /// Returns the header hash. - pub fn hash(&self) -> H256 { self.sha3() } + pub fn hash(&self) -> H256 { keccak(&self.0) } /// Returns the parent hash. pub fn parent_hash(&self) -> H256 { self.view().parent_hash() } @@ -109,12 +110,6 @@ impl Header { pub fn seal(&self) -> Vec> { self.view().seal() } } -impl Hashable for Header { - fn sha3(&self) -> H256 { - self.0.sha3() - } -} - /// Owning block body view. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] @@ -218,7 +213,7 @@ impl Block { // forwarders to borrowed header view. impl Block { /// Returns the header hash. - pub fn hash(&self) -> H256 { self.header_view().sha3() } + pub fn hash(&self) -> H256 { self.header_view().hash() } /// Returns the parent hash. pub fn parent_hash(&self) -> H256 { self.header_view().parent_hash() } diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index 508cd3e25..acc1a3834 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -841,6 +841,7 @@ impl Engine for AuthorityRound { mod tests { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use hash::keccak; use util::*; use header::Header; use error::{Error, BlockError}; @@ -895,8 +896,8 @@ mod tests { #[test] fn generates_seal_and_does_not_double_propose() { let tap = Arc::new(AccountProvider::transient_provider()); - let addr1 = tap.insert_account("1".sha3().into(), "1").unwrap(); - let addr2 = tap.insert_account("2".sha3().into(), "2").unwrap(); + let addr1 = tap.insert_account(keccak("1").into(), "1").unwrap(); + let addr2 = tap.insert_account(keccak("2").into(), "2").unwrap(); let spec = Spec::new_test_round(); let engine = &*spec.engine; @@ -927,7 +928,7 @@ mod tests { #[test] fn proposer_switching() { let tap = AccountProvider::transient_provider(); - let addr = tap.insert_account("0".sha3().into(), "0").unwrap(); + let addr = tap.insert_account(keccak("0").into(), "0").unwrap(); let mut parent_header: Header = Header::default(); parent_header.set_seal(vec![encode(&0usize).into_vec()]); parent_header.set_gas_limit("222222".parse::().unwrap()); @@ -952,7 +953,7 @@ mod tests { #[test] fn rejects_future_block() { let tap = AccountProvider::transient_provider(); - let addr = tap.insert_account("0".sha3().into(), "0").unwrap(); + let addr = tap.insert_account(keccak("0").into(), "0").unwrap(); let mut parent_header: Header = Header::default(); parent_header.set_seal(vec![encode(&0usize).into_vec()]); @@ -978,7 +979,7 @@ mod tests { #[test] fn rejects_step_backwards() { let tap = AccountProvider::transient_provider(); - let addr = tap.insert_account("0".sha3().into(), "0").unwrap(); + let addr = tap.insert_account(keccak("0").into(), "0").unwrap(); let mut parent_header: Header = Header::default(); parent_header.set_seal(vec![encode(&4usize).into_vec()]); diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index 5d6a44fc5..c22e66dfd 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -252,6 +252,7 @@ impl Engine for BasicAuthority { #[cfg(test)] mod tests { use std::sync::Arc; + use hash::keccak; use util::*; use block::*; use error::{BlockError, Error}; @@ -308,7 +309,7 @@ mod tests { #[test] fn can_generate_seal() { let tap = AccountProvider::transient_provider(); - let addr = tap.insert_account("".sha3().into(), "").unwrap(); + let addr = tap.insert_account(keccak("").into(), "").unwrap(); let spec = new_test_authority(); let engine = &*spec.engine; @@ -326,7 +327,7 @@ mod tests { #[test] fn seals_internally() { let tap = AccountProvider::transient_provider(); - let authority = tap.insert_account("".sha3().into(), "").unwrap(); + let authority = tap.insert_account(keccak("").into(), "").unwrap(); let engine = new_test_authority().engine; assert!(!engine.seals_internally().unwrap()); diff --git a/ethcore/src/engines/tendermint/message.rs b/ethcore/src/engines/tendermint/message.rs index 68bdcb0f7..ae0050bbb 100644 --- a/ethcore/src/engines/tendermint/message.rs +++ b/ethcore/src/engines/tendermint/message.rs @@ -17,6 +17,7 @@ //! Tendermint message handling. use std::cmp; +use hash::keccak; use util::*; use super::{Height, View, BlockHash, Step}; use error::Error; @@ -99,7 +100,7 @@ impl ConsensusMessage { pub fn verify(&self) -> Result { let full_rlp = ::rlp::encode(self); let block_info = Rlp::new(&full_rlp).at(1); - let public_key = recover(&self.signature.into(), &block_info.as_raw().sha3())?; + let public_key = recover(&self.signature.into(), &keccak(block_info.as_raw()))?; Ok(public_to_address(&public_key)) } } @@ -194,12 +195,13 @@ pub fn message_full_rlp(signature: &H520, vote_info: &Bytes) -> Bytes { } pub fn message_hash(vote_step: VoteStep, block_hash: H256) -> H256 { - message_info_rlp(&vote_step, Some(block_hash)).sha3() + keccak(message_info_rlp(&vote_step, Some(block_hash))) } #[cfg(test)] mod tests { use std::sync::Arc; + use hash::keccak; use util::*; use rlp::*; use account_provider::AccountProvider; @@ -228,7 +230,7 @@ mod tests { view: 123, step: Step::Precommit, }, - block_hash: Some("1".sha3()) + block_hash: Some(keccak("1")), }; let raw_rlp = ::rlp::encode(&message).into_vec(); let rlp = Rlp::new(&raw_rlp); @@ -251,12 +253,12 @@ mod tests { #[test] fn generate_and_verify() { let tap = Arc::new(AccountProvider::transient_provider()); - let addr = tap.insert_account("0".sha3().into(), "0").unwrap(); + let addr = tap.insert_account(keccak("0").into(), "0").unwrap(); tap.unlock_account_permanently(addr, "0".into()).unwrap(); let mi = message_info_rlp(&VoteStep::new(123, 2, Step::Precommit), Some(H256::default())); - let raw_rlp = message_full_rlp(&tap.sign(addr, None, mi.sha3()).unwrap().into(), &mi); + let raw_rlp = message_full_rlp(&tap.sign(addr, None, keccak(&mi)).unwrap().into(), &mi); let rlp = UntrustedRlp::new(&raw_rlp); let message: ConsensusMessage = rlp.as_val().unwrap(); diff --git a/ethcore/src/engines/tendermint/mod.rs b/ethcore/src/engines/tendermint/mod.rs index cc75e99c3..0f63bac17 100644 --- a/ethcore/src/engines/tendermint/mod.rs +++ b/ethcore/src/engines/tendermint/mod.rs @@ -28,6 +28,7 @@ mod params; use std::sync::{Weak, Arc}; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::collections::{HashSet, BTreeMap, HashMap}; +use hash::keccak; use std::cmp; use util::*; use client::{Client, EngineClient}; @@ -214,7 +215,7 @@ impl Tendermint { let r = self.view.load(AtomicOrdering::SeqCst); let s = *self.step.read(); let vote_info = message_info_rlp(&VoteStep::new(h, r, s), block_hash); - match (self.signer.read().address(), self.sign(vote_info.sha3()).map(Into::into)) { + match (self.signer.read().address(), self.sign(keccak(&vote_info)).map(Into::into)) { (Some(validator), Ok(signature)) => { let message_rlp = message_full_rlp(&signature, &vote_info); let message = ConsensusMessage::new(signature, h, r, s, block_hash); @@ -499,7 +500,7 @@ impl Engine for Tendermint { let view = self.view.load(AtomicOrdering::SeqCst); let bh = Some(header.bare_hash()); let vote_info = message_info_rlp(&VoteStep::new(height, view, Step::Propose), bh.clone()); - if let Ok(signature) = self.sign(vote_info.sha3()).map(Into::into) { + if let Ok(signature) = self.sign(keccak(&vote_info)).map(Into::into) { // Insert Propose vote. debug!(target: "engine", "Submitting proposal {} at height {} view {}.", header.bare_hash(), height, view); self.votes.vote(ConsensusMessage::new(signature, height, view, Step::Propose, bh), author); @@ -523,7 +524,7 @@ impl Engine for Tendermint { let rlp = UntrustedRlp::new(rlp); let message: ConsensusMessage = rlp.as_val()?; if !self.votes.is_old_or_known(&message) { - let sender = public_to_address(&recover(&message.signature.into(), &rlp.at(1)?.as_raw().sha3())?); + let sender = public_to_address(&recover(&message.signature.into(), &keccak(rlp.at(1)?.as_raw()))?); if !self.is_authority(&sender) { return Err(EngineError::NotAuthorized(sender).into()); } @@ -809,7 +810,7 @@ mod tests { fn vote(engine: &Engine, signer: F, height: usize, view: usize, step: Step, block_hash: Option) -> Bytes where F: FnOnce(H256) -> Result { let mi = message_info_rlp(&VoteStep::new(height, view, step), block_hash); - let m = message_full_rlp(&signer(mi.sha3()).unwrap().into(), &mi); + let m = message_full_rlp(&signer(keccak(&mi)).unwrap().into(), &mi); engine.handle_message(&m).unwrap(); m } @@ -817,7 +818,7 @@ mod tests { fn proposal_seal(tap: &Arc, header: &Header, view: View) -> Vec { let author = header.author(); let vote_info = message_info_rlp(&VoteStep::new(header.number() as Height, view, Step::Propose), Some(header.bare_hash())); - let signature = tap.sign(*author, None, vote_info.sha3()).unwrap(); + let signature = tap.sign(*author, None, keccak(vote_info)).unwrap(); vec![ ::rlp::encode(&view).into_vec(), ::rlp::encode(&H520::from(signature)).into_vec(), @@ -826,7 +827,7 @@ mod tests { } fn insert_and_unlock(tap: &Arc, acc: &str) -> Address { - let addr = tap.insert_account(acc.sha3().into(), acc).unwrap(); + let addr = tap.insert_account(keccak(acc).into(), acc).unwrap(); tap.unlock_account_permanently(addr, acc.into()).unwrap(); addr } @@ -933,7 +934,7 @@ mod tests { let mut seal = proposal_seal(&tap, &header, 0); let vote_info = message_info_rlp(&VoteStep::new(2, 0, Step::Precommit), Some(header.bare_hash())); - let signature1 = tap.sign(proposer, None, vote_info.sha3()).unwrap(); + let signature1 = tap.sign(proposer, None, keccak(&vote_info)).unwrap(); seal[1] = ::rlp::NULL_RLP.to_vec(); seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone())]).into_vec(); @@ -946,7 +947,7 @@ mod tests { } let voter = insert_and_unlock(&tap, "0"); - let signature0 = tap.sign(voter, None, vote_info.sha3()).unwrap(); + let signature0 = tap.sign(voter, None, keccak(&vote_info)).unwrap(); seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone()), H520::from(signature0.clone())]).into_vec(); header.set_seal(seal.clone()); @@ -954,7 +955,7 @@ mod tests { assert!(engine.verify_block_family(&header, &parent_header, None).is_ok()); let bad_voter = insert_and_unlock(&tap, "101"); - let bad_signature = tap.sign(bad_voter, None, vote_info.sha3()).unwrap(); + let bad_signature = tap.sign(bad_voter, None, keccak(vote_info)).unwrap(); seal[2] = ::rlp::encode_list(&vec![H520::from(signature1), H520::from(bad_signature)]).into_vec(); header.set_seal(seal); @@ -1087,10 +1088,10 @@ mod tests { let mut seal = proposal_seal(&tap, &header, 0); let vote_info = message_info_rlp(&VoteStep::new(2, 0, Step::Precommit), Some(header.bare_hash())); - let signature1 = tap.sign(proposer, None, vote_info.sha3()).unwrap(); + let signature1 = tap.sign(proposer, None, keccak(&vote_info)).unwrap(); let voter = insert_and_unlock(&tap, "0"); - let signature0 = tap.sign(voter, None, vote_info.sha3()).unwrap(); + let signature0 = tap.sign(voter, None, keccak(&vote_info)).unwrap(); seal[1] = ::rlp::NULL_RLP.to_vec(); seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone())]).into_vec(); @@ -1127,7 +1128,7 @@ mod tests { assert!(epoch_verifier.verify_light(&header).is_ok()); let bad_voter = insert_and_unlock(&tap, "101"); - let bad_signature = tap.sign(bad_voter, None, vote_info.sha3()).unwrap(); + let bad_signature = tap.sign(bad_voter, None, keccak(&vote_info)).unwrap(); seal[2] = ::rlp::encode_list(&vec![H520::from(signature1), H520::from(bad_signature)]).into_vec(); header.set_seal(seal); diff --git a/ethcore/src/engines/validator_set/contract.rs b/ethcore/src/engines/validator_set/contract.rs index 7c1890379..ff16eb1d2 100644 --- a/ethcore/src/engines/validator_set/contract.rs +++ b/ethcore/src/engines/validator_set/contract.rs @@ -128,6 +128,7 @@ impl ValidatorSet for ValidatorContract { mod tests { use std::sync::Arc; use rustc_hex::FromHex; + use hash::keccak; use util::*; use rlp::encode; use spec::Spec; @@ -153,7 +154,7 @@ mod tests { #[test] fn reports_validators() { let tap = Arc::new(AccountProvider::transient_provider()); - let v1 = tap.insert_account("1".sha3().into(), "").unwrap(); + let v1 = tap.insert_account(keccak("1").into(), "").unwrap(); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, Some(tap.clone())); client.engine().register_client(Arc::downgrade(&client)); let validator_contract = "0000000000000000000000000000000000000005".parse::
().unwrap(); diff --git a/ethcore/src/engines/validator_set/multi.rs b/ethcore/src/engines/validator_set/multi.rs index 9acf6050b..477a453b2 100644 --- a/ethcore/src/engines/validator_set/multi.rs +++ b/ethcore/src/engines/validator_set/multi.rs @@ -144,6 +144,7 @@ impl ValidatorSet for Multi { mod tests { use std::sync::Arc; use std::collections::BTreeMap; + use hash::keccak; use account_provider::AccountProvider; use client::{BlockChainClient, EngineClient}; use engines::EpochChange; @@ -163,9 +164,9 @@ mod tests { let _ = ::env_logger::init(); let tap = Arc::new(AccountProvider::transient_provider()); - let s0: Secret = "0".sha3().into(); + let s0: Secret = keccak("0").into(); let v0 = tap.insert_account(s0.clone(), "").unwrap(); - let v1 = tap.insert_account("1".sha3().into(), "").unwrap(); + let v1 = tap.insert_account(keccak("1").into(), "").unwrap(); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_multi, Some(tap)); client.engine().register_client(Arc::downgrade(&client)); diff --git a/ethcore/src/engines/validator_set/safe_contract.rs b/ethcore/src/engines/validator_set/safe_contract.rs index 1abcf2c8f..6480a298e 100644 --- a/ethcore/src/engines/validator_set/safe_contract.rs +++ b/ethcore/src/engines/validator_set/safe_contract.rs @@ -19,6 +19,7 @@ use std::sync::{Weak, Arc}; use futures::Future; use native_contracts::ValidatorSet as Provider; +use hash::keccak; use util::*; use util::cache::MemoryLruCache; @@ -41,7 +42,7 @@ const MEMOIZE_CAPACITY: usize = 500; const EVENT_NAME: &'static [u8] = &*b"InitiateChange(bytes32,address[])"; lazy_static! { - static ref EVENT_NAME_HASH: H256 = EVENT_NAME.sha3(); + static ref EVENT_NAME_HASH: H256 = keccak(EVENT_NAME); } /// The validator contract should have the following interface: @@ -424,6 +425,7 @@ impl ValidatorSet for ValidatorSafeContract { mod tests { use std::sync::Arc; use rustc_hex::FromHex; + use hash::keccak; use util::*; use types::ids::BlockId; use spec::Spec; @@ -449,9 +451,9 @@ mod tests { #[test] fn knows_validators() { let tap = Arc::new(AccountProvider::transient_provider()); - let s0: Secret = "1".sha3().into(); + let s0: Secret = keccak("1").into(); let v0 = tap.insert_account(s0.clone(), "").unwrap(); - let v1 = tap.insert_account("0".sha3().into(), "").unwrap(); + let v1 = tap.insert_account(keccak("0").into(), "").unwrap(); let chain_id = Spec::new_validator_safe_contract().chain_id(); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap)); client.engine().register_client(Arc::downgrade(&client)); diff --git a/ethcore/src/engines/vote_collector.rs b/ethcore/src/engines/vote_collector.rs index b934fdb2e..387715a03 100644 --- a/ethcore/src/engines/vote_collector.rs +++ b/ethcore/src/engines/vote_collector.rs @@ -206,6 +206,7 @@ impl VoteCollector { #[cfg(test)] mod tests { + use hash::keccak; use util::*; use rlp::*; use super::*; @@ -251,7 +252,7 @@ mod tests { #[test] fn seal_retrieval() { let collector = VoteCollector::default(); - let bh = Some("1".sha3()); + let bh = Some(keccak("1")); let mut signatures = Vec::new(); for _ in 0..5 { signatures.push(H520::random()); @@ -263,9 +264,9 @@ mod tests { // Good proposal random_vote(&collector, signatures[0].clone(), propose_round.clone(), bh.clone()); // Wrong block proposal. - random_vote(&collector, signatures[0].clone(), propose_round.clone(), Some("0".sha3())); + random_vote(&collector, signatures[0].clone(), propose_round.clone(), Some(keccak("0"))); // Wrong block commit. - random_vote(&collector, signatures[3].clone(), commit_round.clone(), Some("0".sha3())); + random_vote(&collector, signatures[3].clone(), commit_round.clone(), Some(keccak("0"))); // Wrong round. random_vote(&collector, signatures[0].clone(), 6, bh.clone()); // Wrong round. @@ -291,22 +292,22 @@ mod tests { let round1 = 1; let round3 = 3; // good 1 - random_vote(&collector, H520::random(), round1, Some("0".sha3())); - random_vote(&collector, H520::random(), 0, Some("0".sha3())); + random_vote(&collector, H520::random(), round1, Some(keccak("0"))); + random_vote(&collector, H520::random(), 0, Some(keccak("0"))); // good 3 - random_vote(&collector, H520::random(), round3, Some("0".sha3())); - random_vote(&collector, H520::random(), 2, Some("0".sha3())); + random_vote(&collector, H520::random(), round3, Some(keccak("0"))); + random_vote(&collector, H520::random(), 2, Some(keccak("0"))); // good prevote - random_vote(&collector, H520::random(), round1, Some("1".sha3())); + random_vote(&collector, H520::random(), round1, Some(keccak("1"))); // good prevote let same_sig = H520::random(); - random_vote(&collector, same_sig.clone(), round1, Some("1".sha3())); - random_vote(&collector, same_sig, round1, Some("1".sha3())); + random_vote(&collector, same_sig.clone(), round1, Some(keccak("1"))); + random_vote(&collector, same_sig, round1, Some(keccak("1"))); // good precommit - random_vote(&collector, H520::random(), round3, Some("1".sha3())); + random_vote(&collector, H520::random(), round3, Some(keccak("1"))); // good prevote - random_vote(&collector, H520::random(), round1, Some("0".sha3())); - random_vote(&collector, H520::random(), 4, Some("2".sha3())); + random_vote(&collector, H520::random(), round1, Some(keccak("0"))); + random_vote(&collector, H520::random(), 4, Some(keccak("2"))); assert_eq!(collector.count_round_votes(&round1), 4); assert_eq!(collector.count_round_votes(&round3), 2); @@ -314,7 +315,7 @@ mod tests { let message = TestMessage { signature: H520::default(), step: round1, - block_hash: Some("1".sha3()) + block_hash: Some(keccak("1")) }; assert_eq!(collector.count_aligned_votes(&message), 2); } @@ -325,11 +326,11 @@ mod tests { let vote = |round, hash| { random_vote(&collector, H520::random(), round, hash); }; - vote(6, Some("0".sha3())); - vote(3, Some("0".sha3())); - vote(7, Some("0".sha3())); - vote(8, Some("1".sha3())); - vote(1, Some("1".sha3())); + vote(6, Some(keccak("0"))); + vote(3, Some(keccak("0"))); + vote(7, Some(keccak("0"))); + vote(8, Some(keccak("1"))); + vote(1, Some(keccak("1"))); collector.throw_out_old(&7); assert_eq!(collector.len(), 2); @@ -340,9 +341,9 @@ mod tests { let collector = VoteCollector::default(); let round = 3; // Vote is inserted fine. - assert!(full_vote(&collector, H520::random(), round, Some("0".sha3()), &Address::default())); + assert!(full_vote(&collector, H520::random(), round, Some(keccak("0")), &Address::default())); // Returns the double voting address. - assert!(!full_vote(&collector, H520::random(), round, Some("1".sha3()), &Address::default())); + assert!(!full_vote(&collector, H520::random(), round, Some(keccak("1")), &Address::default())); assert_eq!(collector.count_round_votes(&round), 1); } } diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index fc7b27403..cab05b9ca 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -18,6 +18,7 @@ use std::path::Path; use std::cmp; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; +use hash::{KECCAK_EMPTY_LIST_RLP}; use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager}; use util::*; use block::*; @@ -458,7 +459,7 @@ impl Ethash { panic!("Can't calculate genesis block difficulty"); } - let parent_has_uncles = parent.uncles_hash() != &sha3::SHA3_EMPTY_LIST_RLP; + let parent_has_uncles = parent.uncles_hash() != &KECCAK_EMPTY_LIST_RLP; let min_difficulty = self.ethash_params.minimum_difficulty; diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index dee86883b..0b2b1ec3e 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -119,7 +119,7 @@ mod tests { assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into()); let genesis = morden.genesis_block(); - assert_eq!(BlockView::new(&genesis).header_view().sha3(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into()); + assert_eq!(BlockView::new(&genesis).header_view().hash(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into()); let _ = morden.engine; } @@ -130,7 +130,7 @@ mod tests { assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into()); let genesis = frontier.genesis_block(); - assert_eq!(BlockView::new(&genesis).header_view().sha3(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into()); + assert_eq!(BlockView::new(&genesis).header_view().hash(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into()); let _ = frontier.engine; } diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index 66a770243..7ac35945b 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -17,6 +17,7 @@ //! Transaction Execution environment. use std::cmp; use std::sync::Arc; +use hash::keccak; use util::*; use state::{Backend as StateBackend, State, Substate, CleanupMode}; use engines::Engine; @@ -47,20 +48,20 @@ pub fn contract_address(address_scheme: CreateContractAddress, sender: &Address, let mut stream = RlpStream::new_list(2); stream.append(sender); stream.append(nonce); - (From::from(stream.as_raw().sha3()), None) + (From::from(keccak(stream.as_raw())), None) }, CreateContractAddress::FromCodeHash => { - let code_hash = code.sha3(); + let code_hash = keccak(code); let mut buffer = [0xffu8; 20 + 32]; &mut buffer[20..].copy_from_slice(&code_hash[..]); - (From::from((&buffer[..]).sha3()), Some(code_hash)) + (From::from(keccak(&buffer[..])), Some(code_hash)) }, CreateContractAddress::FromSenderAndCodeHash => { - let code_hash = code.sha3(); + let code_hash = keccak(code); let mut buffer = [0u8; 20 + 32]; &mut buffer[..20].copy_from_slice(&sender[..]); &mut buffer[20..].copy_from_slice(&code_hash[..]); - (From::from((&buffer[..]).sha3()), Some(code_hash)) + (From::from(keccak(&buffer[..])), Some(code_hash)) }, } } @@ -1307,8 +1308,8 @@ mod tests { } } - evm_test!{test_sha3: test_sha3_jit, test_sha3_int} - fn test_sha3(factory: Factory) { + evm_test!{test_keccak: test_keccak_jit, test_keccak_int} + fn test_keccak(factory: Factory) { let code = "6064640fffffffff20600055".from_hex().unwrap(); let sender = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); diff --git a/ethcore/src/header.rs b/ethcore/src/header.rs index a9a4f948d..14bbe5d85 100644 --- a/ethcore/src/header.rs +++ b/ethcore/src/header.rs @@ -18,6 +18,7 @@ use std::cmp; use std::cell::RefCell; +use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP, keccak}; use util::*; use basic_types::{LogBloom, ZERO_LOGBLOOM}; use time::get_time; @@ -100,12 +101,12 @@ impl Default for Header { number: 0, author: Address::default(), - transactions_root: SHA3_NULL_RLP, - uncles_hash: SHA3_EMPTY_LIST_RLP, + transactions_root: KECCAK_NULL_RLP, + uncles_hash: KECCAK_EMPTY_LIST_RLP, extra_data: vec![], - state_root: SHA3_NULL_RLP, - receipts_root: SHA3_NULL_RLP, + state_root: KECCAK_NULL_RLP, + receipts_root: KECCAK_NULL_RLP, log_bloom: ZERO_LOGBLOOM.clone(), gas_used: U256::default(), gas_limit: U256::default(), @@ -194,13 +195,13 @@ impl Header { /// Set the seal field of the header. pub fn set_seal(&mut self, a: Vec) { self.seal = a; self.note_dirty(); } - /// Get the hash of this header (sha3 of the RLP). + /// Get the hash of this header (keccak of the RLP). pub fn hash(&self) -> H256 { let mut hash = self.hash.borrow_mut(); match &mut *hash { &mut Some(ref h) => h.clone(), hash @ &mut None => { - let h = self.rlp_sha3(Seal::With); + let h = self.rlp_keccak(Seal::With); *hash = Some(h.clone()); h } @@ -213,7 +214,7 @@ impl Header { match &mut *hash { &mut Some(ref h) => h.clone(), hash @ &mut None => { - let h = self.rlp_sha3(Seal::Without); + let h = self.rlp_keccak(Seal::Without); *hash = Some(h.clone()); h } @@ -257,8 +258,8 @@ impl Header { s.out() } - /// Get the SHA3 (Keccak) of this header, optionally `with_seal`. - pub fn rlp_sha3(&self, with_seal: Seal) -> H256 { self.rlp(with_seal).sha3() } + /// Get the KECCAK (Keccak) of this header, optionally `with_seal`. + pub fn rlp_keccak(&self, with_seal: Seal) -> H256 { keccak(self.rlp(with_seal)) } } impl Decodable for Header { @@ -278,7 +279,7 @@ impl Decodable for Header { timestamp: cmp::min(r.val_at::(11)?, u64::max_value().into()).as_u64(), extra_data: r.val_at(12)?, seal: vec![], - hash: RefCell::new(Some(r.as_raw().sha3())), + hash: RefCell::new(Some(keccak(r.as_raw()))), bare_hash: RefCell::new(None), }; diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 15d44626b..5b5c0e5f6 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -101,6 +101,7 @@ extern crate num; extern crate price_info; extern crate rand; extern crate rlp; +extern crate hash; #[macro_use] extern crate rlp_derive; diff --git a/ethcore/src/migrations/state/v7.rs b/ethcore/src/migrations/state/v7.rs index 9a9a65d7b..5a5a92764 100644 --- a/ethcore/src/migrations/state/v7.rs +++ b/ethcore/src/migrations/state/v7.rs @@ -23,14 +23,14 @@ use util::Bytes; use util::{Address, H256}; use util::kvdb::Database; use util::migration::{Batch, Config, Error, Migration, SimpleMigration, Progress}; -use util::sha3::Hashable; +use hash::keccak; use std::sync::Arc; use rlp::{decode, Rlp, RlpStream}; // attempt to migrate a key, value pair. None if migration not possible. fn attempt_migrate(mut key_h: H256, val: &[u8]) -> Option { - let val_hash = val.sha3(); + let val_hash = keccak(val); if key_h != val_hash { // this is a key which has been xor'd with an address. @@ -43,7 +43,7 @@ fn attempt_migrate(mut key_h: H256, val: &[u8]) -> Option { return None; } - let address_hash = Address::from(address).sha3(); + let address_hash = keccak(Address::from(address)); // create the xor'd key in place. key_h.copy_from_slice(&*val_hash); diff --git a/ethcore/src/miner/banning_queue.rs b/ethcore/src/miner/banning_queue.rs index 46d7e7cf8..82de8a747 100644 --- a/ethcore/src/miner/banning_queue.rs +++ b/ethcore/src/miner/banning_queue.rs @@ -24,7 +24,8 @@ use transient_hashmap::TransientHashMap; use miner::{TransactionQueue, TransactionQueueDetailsProvider, TransactionImportResult, TransactionOrigin}; use miner::transaction_queue::QueuingInstant; use error::{Error, TransactionError}; -use util::{U256, H256, Address, Hashable}; +use util::{U256, H256, Address}; +use hash::keccak; type Count = u16; @@ -103,7 +104,7 @@ impl BanningTransactionQueue { // Check code if let Action::Create = transaction.action { - let code_hash = transaction.data.sha3(); + let code_hash = keccak(&transaction.data); let count = self.codes_bans.direct().get(&code_hash).cloned().unwrap_or(0); if count > threshold { debug!(target: "txqueue", "Ignoring transaction {:?} because code is banned.", transaction.hash()); @@ -131,7 +132,7 @@ impl BanningTransactionQueue { self.ban_recipient(recipient) }, Action::Create => { - self.ban_codehash(transaction.data.sha3()) + self.ban_codehash(keccak(&transaction.data)) }, }; sender_banned || recipient_or_code_banned @@ -210,13 +211,14 @@ impl DerefMut for BanningTransactionQueue { mod tests { use std::time::Duration; use rustc_hex::FromHex; + use hash::keccak; use super::{BanningTransactionQueue, Threshold}; use ethkey::{Random, Generator}; use transaction::{Transaction, SignedTransaction, Action}; use error::{Error, TransactionError}; use client::TransactionImportResult; use miner::{TransactionQueue, TransactionOrigin}; - use util::{U256, Address, Hashable}; + use util::{U256, Address}; use miner::transaction_queue::test::DummyTransactionDetailsProvider; fn queue() -> BanningTransactionQueue { @@ -310,7 +312,7 @@ mod tests { fn should_not_accept_transactions_with_banned_code() { // given let tx = transaction(Action::Create); - let codehash = tx.data.sha3(); + let codehash = keccak(&tx.data); let mut txq = queue(); // Banlist once (threshold not reached) let banlist1 = txq.ban_codehash(codehash); diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index 0639c645f..2fa4a76e2 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -1235,6 +1235,7 @@ mod tests { use std::sync::Arc; use std::time::Duration; use rustc_hex::FromHex; + use hash::keccak; use super::super::{MinerService, PrioritizationStrategy}; use super::*; use block::IsBlock; @@ -1418,7 +1419,7 @@ mod tests { fn should_fail_setting_engine_signer_on_pow() { let spec = Spec::new_pow_test_spec; let tap = Arc::new(AccountProvider::transient_provider()); - let addr = tap.insert_account("1".sha3().into(), "").unwrap(); + let addr = tap.insert_account(keccak("1").into(), "").unwrap(); let client = generate_dummy_client_with_spec_and_accounts(spec, Some(tap.clone())); assert!(match client.miner().set_engine_signer(addr, "".into()) { Err(AccountError::InappropriateChain) => true, _ => false }) } @@ -1427,7 +1428,7 @@ mod tests { fn should_fail_setting_engine_signer_without_account_provider() { let spec = Spec::new_instant; let tap = Arc::new(AccountProvider::transient_provider()); - let addr = tap.insert_account("1".sha3().into(), "").unwrap(); + let addr = tap.insert_account(keccak("1").into(), "").unwrap(); let client = generate_dummy_client_with_spec_and_accounts(spec, None); assert!(match client.miner().set_engine_signer(addr, "".into()) { Err(AccountError::NotFound) => true, _ => false }); } diff --git a/ethcore/src/pod_account.rs b/ethcore/src/pod_account.rs index 4204b591d..b8606008c 100644 --- a/ethcore/src/pod_account.rs +++ b/ethcore/src/pod_account.rs @@ -17,6 +17,7 @@ use std::fmt; use std::collections::BTreeMap; use itertools::Itertools; +use hash::{keccak}; use util::*; use state::Account; use ethjson; @@ -61,7 +62,7 @@ impl PodAccount { stream.append(&self.nonce); stream.append(&self.balance); stream.append(&sec_trie_root(self.storage.iter().map(|(k, v)| (k.to_vec(), rlp::encode(&U256::from(&**v)).to_vec())).collect())); - stream.append(&self.code.as_ref().unwrap_or(&vec![]).sha3()); + stream.append(&keccak(&self.code.as_ref().unwrap_or(&vec![]))); stream.out() } @@ -117,7 +118,7 @@ impl fmt::Display for PodAccount { self.balance, self.nonce, self.code.as_ref().map_or(0, |c| c.len()), - self.code.as_ref().map_or_else(H256::new, |c| c.sha3()), + self.code.as_ref().map_or_else(H256::new, |c| keccak(c)), self.storage.len(), ) } diff --git a/ethcore/src/snapshot/account.rs b/ethcore/src/snapshot/account.rs index a9f2ba593..2df29989b 100644 --- a/ethcore/src/snapshot/account.rs +++ b/ethcore/src/snapshot/account.rs @@ -19,8 +19,9 @@ use account_db::{AccountDB, AccountDBMut}; use basic_account::BasicAccount; use snapshot::Error; +use hash::{KECCAK_EMPTY, KECCAK_NULL_RLP}; -use util::{U256, H256, Bytes, HashDB, SHA3_EMPTY, SHA3_NULL_RLP}; +use util::{U256, H256, Bytes, HashDB}; use util::trie::{TrieDB, Trie}; use rlp::{RlpStream, UntrustedRlp}; @@ -30,8 +31,8 @@ use std::collections::HashSet; const ACC_EMPTY: BasicAccount = BasicAccount { nonce: U256([0, 0, 0, 0]), balance: U256([0, 0, 0, 0]), - storage_root: SHA3_NULL_RLP, - code_hash: SHA3_EMPTY, + storage_root: KECCAK_NULL_RLP, + code_hash: KECCAK_EMPTY, }; // whether an encoded account has code and how it is referred to. @@ -78,7 +79,7 @@ pub fn to_fat_rlps(account_hash: &H256, acc: &BasicAccount, acct_db: &AccountDB, .append(&acc.balance); // [has_code, code_hash]. - if acc.code_hash == SHA3_EMPTY { + if acc.code_hash == KECCAK_EMPTY { account_stream.append(&CodeState::Empty.raw()).append_empty_data(); } else if used_code.contains(&acc.code_hash) { account_stream.append(&CodeState::Hash.raw()).append(&acc.code_hash); @@ -164,7 +165,7 @@ pub fn from_fat_rlp( // load the code if it exists. let (code_hash, new_code) = match code_state { - CodeState::Empty => (SHA3_EMPTY, None), + CodeState::Empty => (KECCAK_EMPTY, None), CodeState::Inline => { let code: Bytes = rlp.val_at(3)?; let code_hash = acct_db.insert(&code); @@ -210,8 +211,8 @@ mod tests { use tests::helpers::get_temp_state_db; use snapshot::tests::helpers::fill_storage; - use util::sha3::{SHA3_EMPTY, SHA3_NULL_RLP}; - use util::{Address, H256, HashDB, DBValue, Hashable}; + use hash::{KECCAK_EMPTY, KECCAK_NULL_RLP, keccak}; + use util::{Address, H256, HashDB, DBValue}; use rlp::UntrustedRlp; use std::collections::HashSet; @@ -226,14 +227,14 @@ mod tests { let account = BasicAccount { nonce: 50.into(), balance: 123456789.into(), - storage_root: SHA3_NULL_RLP, - code_hash: SHA3_EMPTY, + storage_root: KECCAK_NULL_RLP, + code_hash: KECCAK_EMPTY, }; let thin_rlp = ::rlp::encode(&account); assert_eq!(::rlp::decode::(&thin_rlp), account); - let fat_rlps = to_fat_rlps(&addr.sha3(), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), usize::max_value(), usize::max_value()).unwrap(); + let fat_rlps = to_fat_rlps(&keccak(&addr), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), usize::max_value(), usize::max_value()).unwrap(); let fat_rlp = UntrustedRlp::new(&fat_rlps[0]).at(1).unwrap(); assert_eq!(from_fat_rlp(&mut AccountDBMut::new(db.as_hashdb_mut(), &addr), fat_rlp, H256::zero()).unwrap().0, account); } @@ -245,20 +246,20 @@ mod tests { let account = { let acct_db = AccountDBMut::new(db.as_hashdb_mut(), &addr); - let mut root = SHA3_NULL_RLP; + let mut root = KECCAK_NULL_RLP; fill_storage(acct_db, &mut root, &mut H256::zero()); BasicAccount { nonce: 25.into(), balance: 987654321.into(), storage_root: root, - code_hash: SHA3_EMPTY, + code_hash: KECCAK_EMPTY, } }; let thin_rlp = ::rlp::encode(&account); assert_eq!(::rlp::decode::(&thin_rlp), account); - let fat_rlp = to_fat_rlps(&addr.sha3(), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), usize::max_value(), usize::max_value()).unwrap(); + let fat_rlp = to_fat_rlps(&keccak(&addr), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), usize::max_value(), usize::max_value()).unwrap(); let fat_rlp = UntrustedRlp::new(&fat_rlp[0]).at(1).unwrap(); assert_eq!(from_fat_rlp(&mut AccountDBMut::new(db.as_hashdb_mut(), &addr), fat_rlp, H256::zero()).unwrap().0, account); } @@ -270,21 +271,21 @@ mod tests { let account = { let acct_db = AccountDBMut::new(db.as_hashdb_mut(), &addr); - let mut root = SHA3_NULL_RLP; + let mut root = KECCAK_NULL_RLP; fill_storage(acct_db, &mut root, &mut H256::zero()); BasicAccount { nonce: 25.into(), balance: 987654321.into(), storage_root: root, - code_hash: SHA3_EMPTY, + code_hash: KECCAK_EMPTY, } }; let thin_rlp = ::rlp::encode(&account); assert_eq!(::rlp::decode::(&thin_rlp), account); - let fat_rlps = to_fat_rlps(&addr.sha3(), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), 500, 1000).unwrap(); - let mut root = SHA3_NULL_RLP; + let fat_rlps = to_fat_rlps(&keccak(addr), &account, &AccountDB::new(db.as_hashdb(), &addr), &mut Default::default(), 500, 1000).unwrap(); + let mut root = KECCAK_NULL_RLP; let mut restored_account = None; for rlp in fat_rlps { let fat_rlp = UntrustedRlp::new(&rlp).at(1).unwrap(); @@ -314,21 +315,21 @@ mod tests { let account1 = BasicAccount { nonce: 50.into(), balance: 123456789.into(), - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, code_hash: code_hash, }; let account2 = BasicAccount { nonce: 400.into(), balance: 98765432123456789usize.into(), - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, code_hash: code_hash, }; let mut used_code = HashSet::new(); - let fat_rlp1 = to_fat_rlps(&addr1.sha3(), &account1, &AccountDB::new(db.as_hashdb(), &addr1), &mut used_code, usize::max_value(), usize::max_value()).unwrap(); - let fat_rlp2 = to_fat_rlps(&addr2.sha3(), &account2, &AccountDB::new(db.as_hashdb(), &addr2), &mut used_code, usize::max_value(), usize::max_value()).unwrap(); + let fat_rlp1 = to_fat_rlps(&keccak(&addr1), &account1, &AccountDB::new(db.as_hashdb(), &addr1), &mut used_code, usize::max_value(), usize::max_value()).unwrap(); + let fat_rlp2 = to_fat_rlps(&keccak(&addr2), &account2, &AccountDB::new(db.as_hashdb(), &addr2), &mut used_code, usize::max_value(), usize::max_value()).unwrap(); assert_eq!(used_code.len(), 1); let fat_rlp1 = UntrustedRlp::new(&fat_rlp1[0]).at(1).unwrap(); diff --git a/ethcore/src/snapshot/block.rs b/ethcore/src/snapshot/block.rs index e7b100f69..fa4b3c19f 100644 --- a/ethcore/src/snapshot/block.rs +++ b/ethcore/src/snapshot/block.rs @@ -18,10 +18,11 @@ use block::Block; use header::Header; +use hash::keccak; use views::BlockView; use rlp::{DecoderError, RlpStream, UntrustedRlp}; -use util::{Bytes, Hashable, H256}; +use util::{Bytes, H256}; use util::triehash::ordered_trie_root; const HEADER_FIELDS: usize = 8; @@ -111,7 +112,7 @@ impl AbridgedBlock { let mut uncles_rlp = RlpStream::new(); uncles_rlp.append_list(&uncles); - header.set_uncles_hash(uncles_rlp.as_raw().sha3()); + header.set_uncles_hash(keccak(uncles_rlp.as_raw())); let mut seal_fields = Vec::new(); for i in (HEADER_FIELDS + BLOCK_FIELDS)..rlp.item_count()? { diff --git a/ethcore/src/snapshot/io.rs b/ethcore/src/snapshot/io.rs index f28adcf7f..fc3962e73 100644 --- a/ethcore/src/snapshot/io.rs +++ b/ethcore/src/snapshot/io.rs @@ -342,7 +342,7 @@ impl SnapshotReader for LooseReader { #[cfg(test)] mod tests { use devtools::RandomTempPath; - use util::sha3::Hashable; + use hash::keccak; use snapshot::ManifestData; use super::{SnapshotWriter, SnapshotReader, PackedWriter, PackedReader, LooseWriter, LooseReader, SNAPSHOT_VERSION}; @@ -359,24 +359,24 @@ mod tests { let mut block_hashes = Vec::new(); for chunk in STATE_CHUNKS { - let hash = chunk.sha3(); + let hash = keccak(&chunk); state_hashes.push(hash.clone()); writer.write_state_chunk(hash, chunk).unwrap(); } for chunk in BLOCK_CHUNKS { - let hash = chunk.sha3(); + let hash = keccak(&chunk); block_hashes.push(hash.clone()); - writer.write_block_chunk(chunk.sha3(), chunk).unwrap(); + writer.write_block_chunk(keccak(&chunk), chunk).unwrap(); } let manifest = ManifestData { version: SNAPSHOT_VERSION, state_hashes: state_hashes, block_hashes: block_hashes, - state_root: b"notarealroot".sha3(), + state_root: keccak(b"notarealroot"), block_number: 12345678987654321, - block_hash: b"notarealblock".sha3(), + block_hash: keccak(b"notarealblock"), }; writer.finish(manifest.clone()).unwrap(); @@ -398,24 +398,24 @@ mod tests { let mut block_hashes = Vec::new(); for chunk in STATE_CHUNKS { - let hash = chunk.sha3(); + let hash = keccak(&chunk); state_hashes.push(hash.clone()); writer.write_state_chunk(hash, chunk).unwrap(); } for chunk in BLOCK_CHUNKS { - let hash = chunk.sha3(); + let hash = keccak(&chunk); block_hashes.push(hash.clone()); - writer.write_block_chunk(chunk.sha3(), chunk).unwrap(); + writer.write_block_chunk(keccak(&chunk), chunk).unwrap(); } let manifest = ManifestData { version: SNAPSHOT_VERSION, state_hashes: state_hashes, block_hashes: block_hashes, - state_root: b"notarealroot".sha3(), + state_root: keccak(b"notarealroot"), block_number: 12345678987654321, - block_hash: b"notarealblock".sha3(), + block_hash: keccak(b"notarealblock)"), }; writer.finish(manifest.clone()).unwrap(); diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index a15c15566..974b074cf 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -22,6 +22,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use hash::{keccak, KECCAK_NULL_RLP, KECCAK_EMPTY}; use account_db::{AccountDB, AccountDBMut}; use blockchain::{BlockChain, BlockProvider}; @@ -29,13 +30,12 @@ use engines::Engine; use header::Header; use ids::BlockId; -use util::{Bytes, Hashable, HashDB, DBValue, snappy, U256}; +use util::{Bytes, HashDB, DBValue, snappy, U256}; use util::Mutex; use util::hash::{H256}; use util::journaldb::{self, Algorithm, JournalDB}; use util::kvdb::KeyValueDB; use util::trie::{TrieDB, TrieDBMut, Trie, TrieMut}; -use util::sha3::SHA3_NULL_RLP; use rlp::{RlpStream, UntrustedRlp}; use bloom_journal::Bloom; @@ -183,7 +183,7 @@ pub fn chunk_secondary<'a>(mut chunker: Box, chain: &'a Bloc let mut chunk_sink = |raw_data: &[u8]| { let compressed_size = snappy::compress_into(raw_data, &mut snappy_buffer); let compressed = &snappy_buffer[..compressed_size]; - let hash = compressed.sha3(); + let hash = keccak(&compressed); let size = compressed.len(); writer.lock().write_block_chunk(hash, compressed)?; @@ -240,7 +240,7 @@ impl<'a> StateChunker<'a> { let compressed_size = snappy::compress_into(&raw_data, &mut self.snappy_buffer); let compressed = &self.snappy_buffer[..compressed_size]; - let hash = compressed.sha3(); + let hash = keccak(&compressed); self.writer.lock().write_state_chunk(hash, compressed)?; trace!(target: "snapshot", "wrote state chunk. size: {}, uncompressed size: {}", compressed_size, raw_data.len()); @@ -318,7 +318,7 @@ impl StateRebuilder { pub fn new(db: Arc, pruning: Algorithm) -> Self { StateRebuilder { db: journaldb::new(db.clone(), pruning, ::db::COL_STATE), - state_root: SHA3_NULL_RLP, + state_root: KECCAK_NULL_RLP, known_code: HashMap::new(), missing_code: HashMap::new(), bloom: StateDB::load_bloom(&*db), @@ -362,7 +362,7 @@ impl StateRebuilder { // batch trie writes { - let mut account_trie = if self.state_root != SHA3_NULL_RLP { + let mut account_trie = if self.state_root != KECCAK_NULL_RLP { TrieDBMut::from_existing(self.db.as_hashdb_mut(), &mut self.state_root)? } else { TrieDBMut::new(self.db.as_hashdb_mut(), &mut self.state_root) @@ -443,7 +443,7 @@ fn rebuild_accounts( // new inline code Some(code) => status.new_code.push((code_hash, code, hash)), None => { - if code_hash != ::util::SHA3_EMPTY { + if code_hash != KECCAK_EMPTY { // see if this code has already been included inline match known_code.get(&code_hash) { Some(&first_with) => { diff --git a/ethcore/src/snapshot/tests/helpers.rs b/ethcore/src/snapshot/tests/helpers.rs index 6429667f5..bfc9db92a 100644 --- a/ethcore/src/snapshot/tests/helpers.rs +++ b/ethcore/src/snapshot/tests/helpers.rs @@ -18,6 +18,7 @@ //! which can be queried before and after a full snapshot/restore cycle. use std::sync::Arc; +use hash::{KECCAK_NULL_RLP}; use account_db::AccountDBMut; use basic_account::BasicAccount; @@ -36,7 +37,6 @@ use util::hashdb::HashDB; use util::journaldb; use util::trie::{Alphabet, StandardMap, SecTrieDBMut, TrieMut, ValueMode}; use util::trie::{TrieDB, TrieDBMut, Trie}; -use util::sha3::SHA3_NULL_RLP; // the proportion of accounts we will alter each tick. const ACCOUNT_CHURN: f32 = 0.01; @@ -51,7 +51,7 @@ impl StateProducer { /// Create a new `StateProducer`. pub fn new() -> Self { StateProducer { - state_root: SHA3_NULL_RLP, + state_root: KECCAK_NULL_RLP, storage_seed: H256::zero(), } } @@ -115,7 +115,7 @@ pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { count: 100, }; { - let mut trie = if *root == SHA3_NULL_RLP { + let mut trie = if *root == KECCAK_NULL_RLP { SecTrieDBMut::new(&mut db, root) } else { SecTrieDBMut::from_existing(&mut db, root).unwrap() diff --git a/ethcore/src/snapshot/tests/proof_of_authority.rs b/ethcore/src/snapshot/tests/proof_of_authority.rs index 7c44ec20a..509ccb8fd 100644 --- a/ethcore/src/snapshot/tests/proof_of_authority.rs +++ b/ethcore/src/snapshot/tests/proof_of_authority.rs @@ -30,7 +30,7 @@ use spec::Spec; use tests::helpers; use transaction::{Transaction, Action, SignedTransaction}; -use util::{Address, Hashable}; +use util::Address; use util::kvdb; const PASS: &'static str = ""; @@ -38,14 +38,14 @@ const TRANSITION_BLOCK_1: usize = 2; // block at which the contract becomes acti const TRANSITION_BLOCK_2: usize = 10; // block at which the second contract activates. macro_rules! secret { - ($e: expr) => { Secret::from_slice(&$e.sha3()) } + ($e: expr) => { Secret::from_slice(&$crate::hash::keccak($e)) } } lazy_static! { // contract addresses. static ref CONTRACT_ADDR_1: Address = Address::from_str("0000000000000000000000000000000000000005").unwrap(); static ref CONTRACT_ADDR_2: Address = Address::from_str("0000000000000000000000000000000000000006").unwrap(); - // secret: `sha3(1)`, and initial validator. + // secret: `keccak(1)`, and initial validator. static ref RICH_ADDR: Address = Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap(); // rich address' secret. static ref RICH_SECRET: Secret = secret!("1"); @@ -53,7 +53,7 @@ lazy_static! { /// Contract code used here: https://gist.github.com/anonymous/2a43783647e0f0dfcc359bd6fd81d6d9 -/// Account with secrets "1".sha3() is initially the validator. +/// Account with secrets keccak("1") is initially the validator. /// Transitions to the contract at block 2, initially same validator set. /// Create a new Spec with AuthorityRound which uses a contract at address 5 to determine the current validators using `getValidators`. /// `native_contracts::test_contracts::ValidatorSet` provides a native wrapper for the ABi. diff --git a/ethcore/src/snapshot/tests/proof_of_work.rs b/ethcore/src/snapshot/tests/proof_of_work.rs index a6c0166f5..907fcead8 100644 --- a/ethcore/src/snapshot/tests/proof_of_work.rs +++ b/ethcore/src/snapshot/tests/proof_of_work.rs @@ -71,7 +71,7 @@ fn chunk_and_restore(amount: u64) { version: 2, state_hashes: Vec::new(), block_hashes: block_hashes, - state_root: ::util::sha3::SHA3_NULL_RLP, + state_root: ::hash::KECCAK_NULL_RLP, block_number: amount, block_hash: best_hash, }; @@ -134,7 +134,7 @@ fn checks_flag() { version: 2, state_hashes: Vec::new(), block_hashes: Vec::new(), - state_root: ::util::sha3::SHA3_NULL_RLP, + state_root: ::hash::KECCAK_NULL_RLP, block_number: 102, block_hash: H256::default(), }; diff --git a/ethcore/src/snapshot/tests/state.rs b/ethcore/src/snapshot/tests/state.rs index 744b86577..9a98af5ff 100644 --- a/ethcore/src/snapshot/tests/state.rs +++ b/ethcore/src/snapshot/tests/state.rs @@ -32,10 +32,9 @@ use util::memorydb::MemoryDB; use util::Mutex; use devtools::RandomTempPath; -use util::sha3::SHA3_NULL_RLP; - use std::sync::Arc; use std::sync::atomic::AtomicBool; +use hash::{KECCAK_NULL_RLP, keccak}; #[test] fn snap_and_restore() { @@ -98,7 +97,7 @@ fn snap_and_restore() { fn get_code_from_prev_chunk() { use std::collections::HashSet; use rlp::RlpStream; - use util::{HashDB, H256, U256, Hashable}; + use util::{HashDB, H256, U256}; use account_db::{AccountDBMut, AccountDB}; @@ -107,8 +106,8 @@ fn get_code_from_prev_chunk() { let mut acc_stream = RlpStream::new_list(4); acc_stream.append(&U256::default()) .append(&U256::default()) - .append(&SHA3_NULL_RLP) - .append(&code.sha3()); + .append(&KECCAK_NULL_RLP) + .append(&keccak(code)); let (h1, h2) = (H256::random(), H256::random()); diff --git a/ethcore/src/spec/genesis.rs b/ethcore/src/spec/genesis.rs index b7db9aa90..159320291 100644 --- a/ethcore/src/spec/genesis.rs +++ b/ethcore/src/spec/genesis.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . use util::{Address, H256, U256}; -use util::sha3::SHA3_NULL_RLP; +use hash::KECCAK_NULL_RLP; use ethjson; use super::seal::Seal; @@ -54,8 +54,8 @@ impl From for Genesis { timestamp: g.timestamp.map_or(0, Into::into), parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into), gas_limit: g.gas_limit.into(), - transactions_root: g.transactions_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into), - receipts_root: g.receipts_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into), + transactions_root: g.transactions_root.map_or_else(|| KECCAK_NULL_RLP.clone(), Into::into), + receipts_root: g.receipts_root.map_or_else(|| KECCAK_NULL_RLP.clone(), Into::into), state_root: g.state_root.map(Into::into), gas_used: g.gas_used.map_or_else(U256::zero, Into::into), extra_data: g.extra_data.map_or_else(Vec::new, Into::into), diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 7d82a470c..02f16b0fa 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -21,6 +21,7 @@ use std::collections::BTreeMap; use std::path::Path; use std::sync::Arc; use rustc_hex::FromHex; +use hash::{KECCAK_NULL_RLP, keccak}; use super::genesis::Genesis; use super::seal::Generic as GenericSeal; @@ -203,9 +204,9 @@ pub struct Spec { pub gas_used: U256, /// The genesis block's timestamp field. pub timestamp: u64, - /// Transactions root of the genesis block. Should be SHA3_NULL_RLP. + /// Transactions root of the genesis block. Should be KECCAK_NULL_RLP. pub transactions_root: H256, - /// Receipts root of the genesis block. Should be SHA3_NULL_RLP. + /// Receipts root of the genesis block. Should be KECCAK_NULL_RLP. pub receipts_root: H256, /// The genesis block's extra data field. pub extra_data: Bytes, @@ -287,7 +288,7 @@ impl Spec { // given a pre-constructor state, run all the given constructors and produce a new state and state root. fn run_constructors(&self, factories: &Factories, mut db: T) -> Result { - let mut root = SHA3_NULL_RLP; + let mut root = KECCAK_NULL_RLP; // basic accounts in spec. { @@ -301,7 +302,7 @@ impl Spec { for (address, account) in self.genesis_state.get().iter() { db.note_non_null_account(address); account.insert_additional( - &mut *factories.accountdb.create(db.as_hashdb_mut(), address.sha3()), + &mut *factories.accountdb.create(db.as_hashdb_mut(), keccak(address)), &factories.trie ); } @@ -333,7 +334,7 @@ impl Spec { trace!(target: "spec", " .. root before = {}", state.root()); let params = ActionParams { code_address: address.clone(), - code_hash: Some(constructor.sha3()), + code_hash: Some(keccak(constructor)), address: address.clone(), sender: from.clone(), origin: from.clone(), @@ -399,7 +400,7 @@ impl Spec { header.set_number(0); header.set_author(self.author.clone()); header.set_transactions_root(self.transactions_root.clone()); - header.set_uncles_hash(RlpStream::new_list(0).out().sha3()); + header.set_uncles_hash(keccak(RlpStream::new_list(0).out())); header.set_extra_data(self.extra_data.clone()); header.set_state_root(self.state_root()); header.set_receipts_root(self.receipts_root.clone()); @@ -483,7 +484,7 @@ impl Spec { /// Create a new Spec which conforms to the Frontier-era Morden chain except that it's a NullEngine consensus. pub fn new_test() -> Spec { load_bundled!("null_morden") } - /// Create a new Spec which is a NullEngine consensus with a premine of address whose secret is sha3(''). + /// Create a new Spec which is a NullEngine consensus with a premine of address whose secret is keccak(''). pub fn new_null() -> Spec { load_bundled!("null") } /// Create a new Spec which constructs a contract at address 5 with storage at 0 equal to 1. @@ -493,15 +494,15 @@ impl Spec { pub fn new_instant() -> Spec { load_bundled!("instant_seal") } /// Create a new Spec with AuthorityRound consensus which does internal sealing (not requiring work). - /// Accounts with secrets "0".sha3() and "1".sha3() are the validators. + /// Accounts with secrets keccak("0") and keccak("1") are the validators. pub fn new_test_round() -> Self { load_bundled!("authority_round") } /// Create a new Spec with Tendermint consensus which does internal sealing (not requiring work). - /// Account "0".sha3() and "1".sha3() are a authorities. + /// Account keccak("0") and keccak("1") are a authorities. pub fn new_test_tendermint() -> Self { load_bundled!("tendermint") } /// TestList.sol used in both specs: https://github.com/paritytech/contracts/pull/30/files - /// Accounts with secrets "0".sha3() and "1".sha3() are initially the validators. + /// Accounts with secrets keccak("0") and keccak("1") are initially the validators. /// Create a new Spec with BasicAuthority which uses a contract at address 5 to determine the current validators using `getValidators`. /// Second validator can be removed with "0xbfc708a000000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1" and added back in using "0x4d238c8e00000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1". pub fn new_validator_safe_contract() -> Self { load_bundled!("validator_safe_contract") } @@ -512,7 +513,7 @@ impl Spec { pub fn new_validator_contract() -> Self { load_bundled!("validator_contract") } /// Create a new Spec with BasicAuthority which uses multiple validator sets changing with height. - /// Account with secrets "0".sha3() is the validator for block 1 and with "1".sha3() onwards. + /// Account with secrets keccak("0") is the validator for block 1 and with keccak("1") onwards. pub fn new_validator_multi() -> Self { load_bundled!("validator_multi") } /// Create a new spec for a PoW chain @@ -540,7 +541,7 @@ mod tests { assert_eq!(test_spec.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()); let genesis = test_spec.genesis_block(); - assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()); + assert_eq!(BlockView::new(&genesis).header_view().hash(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()); } #[test] diff --git a/ethcore/src/state/account.rs b/ethcore/src/state/account.rs index 1235fd289..e5d8b3814 100644 --- a/ethcore/src/state/account.rs +++ b/ethcore/src/state/account.rs @@ -19,6 +19,7 @@ use std::fmt; use std::sync::Arc; use std::collections::HashMap; +use hash::{KECCAK_EMPTY, KECCAK_NULL_RLP, keccak}; use util::*; use pod_account::*; use rlp::*; @@ -81,10 +82,10 @@ impl Account { Account { balance: balance, nonce: nonce, - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, storage_cache: Self::empty_storage_cache(), storage_changes: storage, - code_hash: code.sha3(), + code_hash: keccak(&code), code_size: Some(code.len()), code_cache: Arc::new(code), code_filth: Filth::Dirty, @@ -101,10 +102,10 @@ impl Account { Account { balance: pod.balance, nonce: pod.nonce, - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, storage_cache: Self::empty_storage_cache(), storage_changes: pod.storage.into_iter().collect(), - code_hash: pod.code.as_ref().map_or(SHA3_EMPTY, |c| c.sha3()), + code_hash: pod.code.as_ref().map_or(KECCAK_EMPTY, |c| keccak(c)), code_filth: Filth::Dirty, code_size: Some(pod.code.as_ref().map_or(0, |c| c.len())), code_cache: Arc::new(pod.code.map_or_else(|| { warn!("POD account with unknown code is being created! Assuming no code."); vec![] }, |c| c)), @@ -117,10 +118,10 @@ impl Account { Account { balance: balance, nonce: nonce, - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, storage_cache: Self::empty_storage_cache(), storage_changes: HashMap::new(), - code_hash: SHA3_EMPTY, + code_hash: KECCAK_EMPTY, code_cache: Arc::new(vec![]), code_size: Some(0), code_filth: Filth::Clean, @@ -140,10 +141,10 @@ impl Account { Account { balance: balance, nonce: nonce, - storage_root: SHA3_NULL_RLP, + storage_root: KECCAK_NULL_RLP, storage_cache: Self::empty_storage_cache(), storage_changes: HashMap::new(), - code_hash: SHA3_EMPTY, + code_hash: KECCAK_EMPTY, code_cache: Arc::new(vec![]), code_size: None, code_filth: Filth::Clean, @@ -154,7 +155,7 @@ impl Account { /// Set this account's code to the given code. /// NOTE: Account should have been created with `new_contract()` pub fn init_code(&mut self, code: Bytes) { - self.code_hash = code.sha3(); + self.code_hash = keccak(&code); self.code_cache = Arc::new(code); self.code_size = Some(self.code_cache.len()); self.code_filth = Filth::Dirty; @@ -211,7 +212,7 @@ impl Account { pub fn address_hash(&self, address: &Address) -> H256 { let hash = self.address_hash.get(); hash.unwrap_or_else(|| { - let hash = address.sha3(); + let hash = keccak(address); self.address_hash.set(Some(hash.clone())); hash }) @@ -220,7 +221,7 @@ impl Account { /// returns the account's code. If `None` then the code cache isn't available - /// get someone who knows to call `note_code`. pub fn code(&self) -> Option> { - if self.code_hash != SHA3_EMPTY && self.code_cache.is_empty() { + if self.code_hash != KECCAK_EMPTY && self.code_cache.is_empty() { return None; } Some(self.code_cache.clone()) @@ -235,7 +236,7 @@ impl Account { #[cfg(test)] /// Provide a byte array which hashes to the `code_hash`. returns the hash as a result. pub fn note_code(&mut self, code: Bytes) -> Result<(), H256> { - let h = code.sha3(); + let h = keccak(&code); if self.code_hash == h { self.code_cache = Arc::new(code); self.code_size = Some(self.code_cache.len()); @@ -247,7 +248,7 @@ impl Account { /// Is `code_cache` valid; such that code is going to return Some? pub fn is_cached(&self) -> bool { - !self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == SHA3_EMPTY) + !self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == KECCAK_EMPTY) } /// Provide a database to get `code_hash`. Should not be called if it is a contract without code. @@ -284,7 +285,7 @@ impl Account { // TODO: fill out self.code_cache; trace!("Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty()); self.code_size.is_some() || - if self.code_hash != SHA3_EMPTY { + if self.code_hash != KECCAK_EMPTY { match db.get(&self.code_hash) { Some(x) => { self.code_size = Some(x.len()); @@ -308,19 +309,19 @@ impl Account { /// NOTE: Will panic if `!self.storage_is_clean()` pub fn is_empty(&self) -> bool { assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean."); - self.is_null() && self.storage_root == SHA3_NULL_RLP + self.is_null() && self.storage_root == KECCAK_NULL_RLP } /// Check if account has zero nonce, balance, no code. pub fn is_null(&self) -> bool { self.balance.is_zero() && self.nonce.is_zero() && - self.code_hash == SHA3_EMPTY + self.code_hash == KECCAK_EMPTY } /// Check if account is basic (Has no code). pub fn is_basic(&self) -> bool { - self.code_hash == SHA3_EMPTY + self.code_hash == KECCAK_EMPTY } /// Return the storage root associated with this account or None if it has been altered via the overlay. @@ -592,8 +593,8 @@ mod tests { assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"); assert_eq!(a.balance(), &U256::from(69u8)); assert_eq!(a.nonce(), &U256::from(0u8)); - assert_eq!(a.code_hash(), SHA3_EMPTY); - assert_eq!(a.storage_root().unwrap(), &SHA3_NULL_RLP); + assert_eq!(a.code_hash(), KECCAK_EMPTY); + assert_eq!(a.storage_root().unwrap(), &KECCAK_NULL_RLP); } #[test] diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index 1b36c91ec..e7b0cb228 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -24,6 +24,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, BTreeMap, HashSet}; use std::fmt; use std::sync::Arc; +use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY}; use receipt::Receipt; use engines::Engine; @@ -552,7 +553,7 @@ impl State { /// Get an account's code hash. pub fn code_hash(&self, a: &Address) -> trie::Result { self.ensure_cached(a, RequireCache::None, true, - |a| a.as_ref().map_or(SHA3_EMPTY, |a| a.code_hash())) + |a| a.as_ref().map_or(KECCAK_EMPTY, |a| a.code_hash())) } /// Get accounts' code size. @@ -938,7 +939,7 @@ impl State { /// Returns a merkle proof of the account's trie node omitted or an encountered trie error. /// If the account doesn't exist in the trie, prove that and return defaults. /// Requires a secure trie to be used for accurate results. - /// `account_key` == sha3(address) + /// `account_key` == keccak(address) pub fn prove_account(&self, account_key: H256) -> trie::Result<(Vec, BasicAccount)> { let mut recorder = Recorder::new(); let trie = TrieDB::new(self.db.as_hashdb(), &self.root)?; @@ -949,8 +950,8 @@ impl State { let account = maybe_account.unwrap_or_else(|| BasicAccount { balance: 0.into(), nonce: self.account_start_nonce, - code_hash: SHA3_EMPTY, - storage_root: ::util::sha3::SHA3_NULL_RLP, + code_hash: KECCAK_EMPTY, + storage_root: KECCAK_NULL_RLP, }); Ok((recorder.drain().into_iter().map(|r| r.data).collect(), account)) @@ -959,11 +960,11 @@ impl State { /// Prove an account's storage key's existence or nonexistence in the state. /// Returns a merkle proof of the account's storage trie. /// Requires a secure trie to be used for correctness. - /// `account_key` == sha3(address) - /// `storage_key` == sha3(key) + /// `account_key` == keccak(address) + /// `storage_key` == keccak(key) pub fn prove_storage(&self, account_key: H256, storage_key: H256) -> trie::Result<(Vec, H256)> { // TODO: probably could look into cache somehow but it's keyed by - // address, not sha3(address). + // address, not keccak(address). let trie = TrieDB::new(self.db.as_hashdb(), &self.root)?; let acc = match trie.get_with(&account_key, Account::from_rlp)? { Some(acc) => acc, @@ -1008,13 +1009,13 @@ impl Clone for State { #[cfg(test)] mod tests { - use std::sync::Arc; use std::str::FromStr; use rustc_hex::FromHex; + use hash::keccak; use super::*; use ethkey::Secret; - use util::{U256, H256, Address, Hashable}; + use util::{U256, H256, Address}; use tests::helpers::*; use vm::EnvInfo; use spec::*; @@ -1024,7 +1025,7 @@ mod tests { use evm::CallType; fn secret() -> Secret { - "".sha3().into() + keccak("").into() } #[test] diff --git a/ethcore/src/state_db.rs b/ethcore/src/state_db.rs index e2f6fdaf0..ce96dc4fc 100644 --- a/ethcore/src/state_db.rs +++ b/ethcore/src/state_db.rs @@ -24,7 +24,8 @@ use util::hash::{H256}; use util::hashdb::HashDB; use state::{self, Account}; use header::BlockNumber; -use util::{Address, DBTransaction, UtilError, Mutex, Hashable}; +use hash::keccak; +use util::{Address, DBTransaction, UtilError, Mutex}; use bloom_journal::{Bloom, BloomJournal}; use db::COL_ACCOUNT_BLOOM; use byteorder::{LittleEndian, ByteOrder}; @@ -443,13 +444,13 @@ impl state::Backend for StateDB { fn note_non_null_account(&self, address: &Address) { trace!(target: "account_bloom", "Note account bloom: {:?}", address); let mut bloom = self.account_bloom.lock(); - bloom.set(&*address.sha3()); + bloom.set(&*keccak(address)); } fn is_known_null(&self, address: &Address) -> bool { trace!(target: "account_bloom", "Check account bloom: {:?}", address); let bloom = self.account_bloom.lock(); - let is_null = !bloom.check(&*address.sha3()); + let is_null = !bloom.check(&*keccak(address)); is_null } } diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index ea7dd32f5..6176e53bb 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -16,6 +16,7 @@ use std::str::FromStr; use std::sync::Arc; +use hash::keccak; use io::IoChannel; use client::{BlockChainClient, MiningBlockChainClient, Client, ClientConfig, BlockId}; use state::{self, State, CleanupMode}; @@ -254,7 +255,7 @@ fn can_mine() { let b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]).close(); - assert_eq!(*b.block().header().parent_hash(), BlockView::new(&dummy_blocks[0]).header_view().sha3()); + assert_eq!(*b.block().header().parent_hash(), BlockView::new(&dummy_blocks[0]).header_view().hash()); } #[test] @@ -298,7 +299,7 @@ fn change_history_size() { #[test] fn does_not_propagate_delayed_transactions() { - let key = KeyPair::from_secret("test".sha3().into()).unwrap(); + let key = KeyPair::from_secret(keccak("test").into()).unwrap(); let secret = key.secret(); let tx0 = PendingTransaction::new(Transaction { nonce: 0.into(), diff --git a/ethcore/src/tests/evm.rs b/ethcore/src/tests/evm.rs index 7b0e03d24..69351d587 100644 --- a/ethcore/src/tests/evm.rs +++ b/ethcore/src/tests/evm.rs @@ -1,6 +1,7 @@ //! Tests of EVM integration with transaction execution. use std::sync::Arc; +use hash::keccak; use vm::{EnvInfo, ActionParams, ActionValue, CallType}; use evm::{Factory, VMType}; use executive::Executive; @@ -16,11 +17,11 @@ use util::*; evm_test!{test_blockhash_eip210: test_blockhash_eip210_jit, test_blockhash_eip210_int} fn test_blockhash_eip210(factory: Factory) { let get_prev_hash_code = Arc::new("600143034060205260206020f3".from_hex().unwrap()); // this returns previous block hash - let get_prev_hash_code_hash = get_prev_hash_code.sha3(); + let get_prev_hash_code_hash = keccak(get_prev_hash_code.as_ref()); // This is same as DEFAULT_BLOCKHASH_CONTRACT except for metropolis transition block check removed. let test_blockhash_contract = "73fffffffffffffffffffffffffffffffffffffffe33141561007a57600143036020526000356101006020510755600061010060205107141561005057600035610100610100602051050761010001555b6000620100006020510714156100755760003561010062010000602051050761020001555b61014a565b4360003512151561009057600060405260206040f35b610100600035430312156100b357610100600035075460605260206060f3610149565b62010000600035430312156100d157600061010060003507146100d4565b60005b156100f6576101006101006000350507610100015460805260206080f3610148565b630100000060003543031215610116576000620100006000350714610119565b60005b1561013c57610100620100006000350507610200015460a052602060a0f3610147565b600060c052602060c0f35b5b5b5b5b"; let blockhash_contract_code = Arc::new(test_blockhash_contract.from_hex().unwrap()); - let blockhash_contract_code_hash = blockhash_contract_code.sha3(); + let blockhash_contract_code_hash = keccak(blockhash_contract_code.as_ref()); let engine = TestEngine::new_metropolis(); let mut env_info = EnvInfo::default(); diff --git a/ethcore/src/tests/helpers.rs b/ethcore/src/tests/helpers.rs index d8ba8313e..3d4a4b336 100644 --- a/ethcore/src/tests/helpers.rs +++ b/ethcore/src/tests/helpers.rs @@ -16,6 +16,7 @@ use std::collections::BTreeMap; use std::sync::Arc; +use hash::keccak; use ethkey::KeyPair; use io::*; use client::{BlockChainClient, Client, ClientConfig}; @@ -178,7 +179,7 @@ pub fn generate_dummy_client_with_spec_accounts_and_data(get_test_spec: F, ac let mut last_hashes = vec![]; let mut last_header = genesis_header.clone(); - let kp = KeyPair::from_secret_slice(&"".sha3()).unwrap(); + let kp = KeyPair::from_secret_slice(&keccak("")).unwrap(); let author = kp.address(); let mut n = 0; diff --git a/ethcore/src/trace/types/filter.rs b/ethcore/src/trace/types/filter.rs index 1b2e2077a..5c92dcedc 100644 --- a/ethcore/src/trace/types/filter.rs +++ b/ethcore/src/trace/types/filter.rs @@ -18,8 +18,8 @@ use std::ops::Range; use bloomchain::{Filter as BloomFilter, Bloom, Number}; +use hash::keccak; use util::Address; -use util::sha3::Hashable; use bloomable::Bloomable; use basic_types::LogBloom; use trace::flat::FlatTrace; @@ -55,7 +55,7 @@ impl AddressesFilter { match self.list.is_empty() { true => vec![LogBloom::default()], false => self.list.iter() - .map(|address| LogBloom::from_bloomed(&address.sha3())) + .map(|address| LogBloom::from_bloomed(&keccak(address))) .collect(), } } @@ -67,7 +67,7 @@ impl AddressesFilter { false => blooms .into_iter() .flat_map(|bloom| self.list.iter() - .map(|address| bloom.with_bloomed(&address.sha3())) + .map(|address| bloom.with_bloomed(&keccak(address))) .collect::>()) .collect(), } @@ -136,7 +136,7 @@ impl Filter { #[cfg(test)] mod tests { use util::Address; - use util::sha3::Hashable; + use hash::keccak; use bloomable::Bloomable; use trace::trace::{Action, Call, Res, Create, CreateResult, Suicide}; use trace::flat::FlatTrace; @@ -166,9 +166,9 @@ mod tests { let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_bloomed(&Address::from(1).sha3())); - assert!(blooms[0].contains_bloomed(&Address::from(2).sha3())); - assert!(!blooms[0].contains_bloomed(&Address::from(3).sha3())); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(1)))); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(2)))); + assert!(!blooms[0].contains_bloomed(&keccak(Address::from(3)))); } #[test] @@ -182,8 +182,8 @@ mod tests { let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_bloomed(&Address::from(1).sha3())); - assert!(!blooms[0].contains_bloomed(&Address::from(2).sha3())); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(1)))); + assert!(!blooms[0].contains_bloomed(&keccak(Address::from(2)))); } #[test] @@ -197,8 +197,8 @@ mod tests { let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_bloomed(&Address::from(1).sha3())); - assert!(!blooms[0].contains_bloomed(&Address::from(2).sha3())); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(1)))); + assert!(!blooms[0].contains_bloomed(&keccak(Address::from(2)))); } #[test] @@ -212,25 +212,25 @@ mod tests { let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 4); - assert!(blooms[0].contains_bloomed(&Address::from(1).sha3())); - assert!(blooms[0].contains_bloomed(&Address::from(2).sha3())); - assert!(!blooms[0].contains_bloomed(&Address::from(3).sha3())); - assert!(!blooms[0].contains_bloomed(&Address::from(4).sha3())); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(1)))); + assert!(blooms[0].contains_bloomed(&keccak(Address::from(2)))); + assert!(!blooms[0].contains_bloomed(&keccak(Address::from(3)))); + assert!(!blooms[0].contains_bloomed(&keccak(Address::from(4)))); - assert!(blooms[1].contains_bloomed(&Address::from(1).sha3())); - assert!(blooms[1].contains_bloomed(&Address::from(4).sha3())); - assert!(!blooms[1].contains_bloomed(&Address::from(2).sha3())); - assert!(!blooms[1].contains_bloomed(&Address::from(3).sha3())); + assert!(blooms[1].contains_bloomed(&keccak(Address::from(1)))); + assert!(blooms[1].contains_bloomed(&keccak(Address::from(4)))); + assert!(!blooms[1].contains_bloomed(&keccak(Address::from(2)))); + assert!(!blooms[1].contains_bloomed(&keccak(Address::from(3)))); - assert!(blooms[2].contains_bloomed(&Address::from(2).sha3())); - assert!(blooms[2].contains_bloomed(&Address::from(3).sha3())); - assert!(!blooms[2].contains_bloomed(&Address::from(1).sha3())); - assert!(!blooms[2].contains_bloomed(&Address::from(4).sha3())); + assert!(blooms[2].contains_bloomed(&keccak(Address::from(2)))); + assert!(blooms[2].contains_bloomed(&keccak(Address::from(3)))); + assert!(!blooms[2].contains_bloomed(&keccak(Address::from(1)))); + assert!(!blooms[2].contains_bloomed(&keccak(Address::from(4)))); - assert!(blooms[3].contains_bloomed(&Address::from(3).sha3())); - assert!(blooms[3].contains_bloomed(&Address::from(4).sha3())); - assert!(!blooms[3].contains_bloomed(&Address::from(1).sha3())); - assert!(!blooms[3].contains_bloomed(&Address::from(2).sha3())); + assert!(blooms[3].contains_bloomed(&keccak(Address::from(3)))); + assert!(blooms[3].contains_bloomed(&keccak(Address::from(4)))); + assert!(!blooms[3].contains_bloomed(&keccak(Address::from(1)))); + assert!(!blooms[3].contains_bloomed(&keccak(Address::from(2)))); } #[test] diff --git a/ethcore/src/trace/types/trace.rs b/ethcore/src/trace/types/trace.rs index 5fa0260c6..af0fa5f6e 100644 --- a/ethcore/src/trace/types/trace.rs +++ b/ethcore/src/trace/types/trace.rs @@ -17,7 +17,7 @@ //! Tracing datatypes. use util::{U256, Bytes, Address}; -use util::sha3::Hashable; +use hash::keccak; use bloomable::Bloomable; use rlp::*; @@ -51,7 +51,7 @@ pub struct CreateResult { impl CreateResult { /// Returns bloom. pub fn bloom(&self) -> LogBloom { - LogBloom::from_bloomed(&self.address.sha3()) + LogBloom::from_bloomed(&keccak(&self.address)) } } @@ -90,8 +90,8 @@ impl Call { /// Returns call action bloom. /// The bloom contains from and to addresses. pub fn bloom(&self) -> LogBloom { - LogBloom::from_bloomed(&self.from.sha3()) - .with_bloomed(&self.to.sha3()) + LogBloom::from_bloomed(&keccak(&self.from)) + .with_bloomed(&keccak(&self.to)) } } @@ -124,7 +124,7 @@ impl Create { /// Returns bloom create action bloom. /// The bloom contains only from address. pub fn bloom(&self) -> LogBloom { - LogBloom::from_bloomed(&self.from.sha3()) + LogBloom::from_bloomed(&keccak(&self.from)) } } @@ -143,8 +143,8 @@ pub struct Suicide { impl Suicide { /// Return suicide action bloom. pub fn bloom(&self) -> LogBloom { - LogBloom::from_bloomed(&self.address.sha3()) - .with_bloomed(&self.refund_address.sha3()) + LogBloom::from_bloomed(&keccak(self.address)) + .with_bloomed(&keccak(self.refund_address)) } } diff --git a/ethcore/src/transaction.rs b/ethcore/src/transaction.rs index 0bd61dceb..e68021768 100644 --- a/ethcore/src/transaction.rs +++ b/ethcore/src/transaction.rs @@ -18,7 +18,7 @@ use std::ops::Deref; use rlp::*; -use util::sha3::Hashable; +use hash::keccak; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; @@ -166,7 +166,7 @@ impl Transaction { pub fn hash(&self, chain_id: Option) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, chain_id); - stream.as_raw().sha3() + keccak(stream.as_raw()) } /// Signs the transaction as coming from `sender`. @@ -273,7 +273,7 @@ impl Decodable for UnverifiedTransaction { if d.item_count()? != 9 { return Err(DecoderError::RlpIncorrectListLen); } - let hash = d.as_raw().sha3(); + let hash = keccak(d.as_raw()); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, @@ -298,7 +298,7 @@ impl Encodable for UnverifiedTransaction { impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { - let hash = (&*self.rlp_bytes()).sha3(); + let hash = keccak(&*self.rlp_bytes()); self.hash = hash; self } @@ -356,7 +356,7 @@ impl UnverifiedTransaction { } } - /// Get the hash of this header (sha3 of the RLP). + /// Get the hash of this header (keccak of the RLP). pub fn hash(&self) -> H256 { self.hash } @@ -544,7 +544,8 @@ impl From for PendingTransaction { #[cfg(test)] mod tests { use super::*; - use util::{Hashable, U256}; + use util::{U256}; + use hash::keccak; #[test] fn sender_test() { @@ -574,7 +575,7 @@ mod tests { value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); - assert_eq!(Address::from(key.public().sha3()), t.sender()); + assert_eq!(Address::from(keccak(key.public())), t.sender()); assert_eq!(t.chain_id(), None); } @@ -608,7 +609,7 @@ mod tests { value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); - assert_eq!(Address::from(key.public().sha3()), t.sender()); + assert_eq!(Address::from(keccak(key.public())), t.sender()); assert_eq!(t.chain_id(), Some(69)); } diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 00976dca7..11fd01d7b 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -22,6 +22,7 @@ //! 3. Final verification against the blockchain done before enactment. use std::collections::HashSet; +use hash::keccak; use util::*; use engines::Engine; use error::{BlockError, Error}; @@ -256,7 +257,7 @@ fn verify_block_integrity(block: &[u8], transactions_root: &H256, uncles_hash: & if expected_root != transactions_root { return Err(From::from(BlockError::InvalidTransactionsRoot(Mismatch { expected: expected_root.clone(), found: transactions_root.clone() }))) } - let expected_uncles = &block.at(2)?.as_raw().sha3(); + let expected_uncles = &keccak(block.at(2)?.as_raw()); if expected_uncles != uncles_hash { return Err(From::from(BlockError::InvalidUnclesHash(Mismatch { expected: expected_uncles.clone(), found: uncles_hash.clone() }))) } @@ -266,6 +267,7 @@ fn verify_block_integrity(block: &[u8], transactions_root: &H256, uncles_hash: & #[cfg(test)] mod tests { use std::collections::{BTreeMap, HashMap}; + use hash::keccak; use util::*; use ethkey::{Random, Generator}; use header::*; @@ -324,7 +326,7 @@ mod tests { pub fn insert(&mut self, bytes: Bytes) { let number = BlockView::new(&bytes).header_view().number(); - let hash = BlockView::new(&bytes).header_view().sha3(); + let hash = BlockView::new(&bytes).header_view().hash(); self.blocks.insert(hash.clone(), bytes); self.numbers.insert(number, hash.clone()); } @@ -482,7 +484,7 @@ mod tests { let good_uncles = vec![ good_uncle1.clone(), good_uncle2.clone() ]; let mut uncles_rlp = RlpStream::new(); uncles_rlp.append_list(&good_uncles); - let good_uncles_hash = uncles_rlp.as_raw().sha3(); + let good_uncles_hash = keccak(uncles_rlp.as_raw()); let good_transactions_root = ordered_trie_root(good_transactions.iter().map(|t| ::rlp::encode::(t).into_vec())); let mut parent = good.clone(); diff --git a/ethcore/src/views/block.rs b/ethcore/src/views/block.rs index f00ca548f..723a9f1b8 100644 --- a/ethcore/src/views/block.rs +++ b/ethcore/src/views/block.rs @@ -16,6 +16,7 @@ //! View onto block rlp. +use hash::keccak; use util::*; use header::*; use transaction::*; @@ -44,7 +45,7 @@ impl<'a> BlockView<'a> { /// Block header hash. pub fn hash(&self) -> H256 { - self.sha3() + self.header_view().hash() } /// Return reference to underlaying rlp. @@ -75,7 +76,7 @@ impl<'a> BlockView<'a> { /// Return List of transactions with additional localization info. pub fn localized_transactions(&self) -> Vec { let header = self.header_view(); - let block_hash = header.sha3(); + let block_hash = header.hash(); let block_number = header.number(); self.transactions() .into_iter() @@ -101,7 +102,7 @@ impl<'a> BlockView<'a> { /// Return transaction hashes. pub fn transaction_hashes(&self) -> Vec { - self.rlp.at(1).iter().map(|rlp| rlp.as_raw().sha3()).collect() + self.rlp.at(1).iter().map(|rlp| keccak(rlp.as_raw())).collect() } /// Returns transaction at given index without deserializing unnecessary data. @@ -112,7 +113,7 @@ impl<'a> BlockView<'a> { /// Returns localized transaction at given index. pub fn localized_transaction_at(&self, index: usize) -> Option { let header = self.header_view(); - let block_hash = header.sha3(); + let block_hash = header.hash(); let block_number = header.number(); self.transaction_at(index).map(|t| LocalizedTransaction { signed: t, @@ -140,7 +141,7 @@ impl<'a> BlockView<'a> { /// Return list of uncle hashes of given block. pub fn uncle_hashes(&self) -> Vec { - self.rlp.at(2).iter().map(|rlp| rlp.as_raw().sha3()).collect() + self.rlp.at(2).iter().map(|rlp| keccak(rlp.as_raw())).collect() } /// Return nth uncle. @@ -154,12 +155,6 @@ impl<'a> BlockView<'a> { } } -impl<'a> Hashable for BlockView<'a> { - fn sha3(&self) -> H256 { - self.header_view().sha3() - } -} - #[cfg(test)] mod tests { use std::str::FromStr; diff --git a/ethcore/src/views/body.rs b/ethcore/src/views/body.rs index 038e152b0..d7509af82 100644 --- a/ethcore/src/views/body.rs +++ b/ethcore/src/views/body.rs @@ -16,6 +16,7 @@ //! View onto block body rlp. +use hash::keccak; use util::*; use header::*; use transaction::*; @@ -78,7 +79,7 @@ impl<'a> BodyView<'a> { /// Return transaction hashes. pub fn transaction_hashes(&self) -> Vec { - self.rlp.at(0).iter().map(|rlp| rlp.as_raw().sha3()).collect() + self.rlp.at(0).iter().map(|rlp| keccak(rlp.as_raw())).collect() } /// Returns transaction at given index without deserializing unnecessary data. @@ -114,7 +115,7 @@ impl<'a> BodyView<'a> { /// Return list of uncle hashes of given block. pub fn uncle_hashes(&self) -> Vec { - self.rlp.at(1).iter().map(|rlp| rlp.as_raw().sha3()).collect() + self.rlp.at(1).iter().map(|rlp| keccak(rlp.as_raw())).collect() } /// Return nth uncle. diff --git a/ethcore/src/views/header.rs b/ethcore/src/views/header.rs index 4506d98ec..977aaa9a2 100644 --- a/ethcore/src/views/header.rs +++ b/ethcore/src/views/header.rs @@ -16,7 +16,8 @@ //! View onto block header rlp -use util::{U256, Bytes, Hashable, H256, Address, H2048}; +use hash::keccak; +use util::{U256, Bytes, H256, Address, H2048}; use rlp::Rlp; use header::BlockNumber; @@ -41,7 +42,9 @@ impl<'a> HeaderView<'a> { } /// Returns header hash. - pub fn hash(&self) -> H256 { self.sha3() } + pub fn hash(&self) -> H256 { + keccak(self.rlp.as_raw()) + } /// Returns raw rlp. pub fn rlp(&self) -> &Rlp<'a> { &self.rlp } @@ -95,12 +98,6 @@ impl<'a> HeaderView<'a> { } } -impl<'a> Hashable for HeaderView<'a> { - fn sha3(&self) -> H256 { - self.rlp.as_raw().sha3() - } -} - #[cfg(test)] mod tests { use std::str::FromStr; diff --git a/ethcore/src/views/transaction.rs b/ethcore/src/views/transaction.rs index 11c7fc2f1..e19dfd952 100644 --- a/ethcore/src/views/transaction.rs +++ b/ethcore/src/views/transaction.rs @@ -15,7 +15,8 @@ // along with Parity. If not, see . //! View onto transaction rlp -use util::{U256, Bytes, Hashable, H256}; +use util::{U256, Bytes, H256}; +use hash::keccak; use rlp::Rlp; /// View onto transaction rlp. @@ -43,6 +44,11 @@ impl<'a> TransactionView<'a> { &self.rlp } + /// Returns transaction hash. + pub fn hash(&self) -> H256 { + keccak(self.rlp.as_raw()) + } + /// Get the nonce field of the transaction. pub fn nonce(&self) -> U256 { self.rlp.val_at(0) } @@ -68,12 +74,6 @@ impl<'a> TransactionView<'a> { pub fn s(&self) -> U256 { self.rlp.val_at(8) } } -impl<'a> Hashable for TransactionView<'a> { - fn sha3(&self) -> H256 { - self.rlp.as_raw().sha3() - } -} - #[cfg(test)] mod tests { use std::str::FromStr; diff --git a/ethcore/types/Cargo.toml b/ethcore/types/Cargo.toml index 82963f960..bb43d0d49 100644 --- a/ethcore/types/Cargo.toml +++ b/ethcore/types/Cargo.toml @@ -10,6 +10,7 @@ rlp_derive = { path = "../../util/rlp_derive" } ethcore-util = { path = "../../util" } ethjson = { path = "../../json" } bloomable = { path = "../../util/bloomable" } +hash = { path = "../../util/hash" } [dev-dependencies] rustc-hex= "1.0" diff --git a/ethcore/types/src/filter.rs b/ethcore/types/src/filter.rs index 6e344b4ef..92fc31edd 100644 --- a/ethcore/types/src/filter.rs +++ b/ethcore/types/src/filter.rs @@ -16,10 +16,11 @@ //! Blockchain filter -use util::{Address, H256, Hashable, H2048}; +use util::{Address, H256, H2048}; use bloomable::Bloomable; use ids::BlockId; use log_entry::LogEntry; +use hash::keccak; /// Blockchain Filter. #[derive(Debug, PartialEq)] @@ -78,7 +79,7 @@ impl Filter { Some(ref addresses) if !addresses.is_empty() => addresses.iter().map(|ref address| { let mut bloom = H2048::default(); - bloom.shift_bloomed(&address.sha3()); + bloom.shift_bloomed(&keccak(address)); bloom }).collect(), _ => vec![H2048::default()] @@ -89,7 +90,7 @@ impl Filter { Some(ref topics) => bs.into_iter().flat_map(|bloom| { topics.into_iter().map(|topic| { let mut b = bloom.clone(); - b.shift_bloomed(&topic.sha3()); + b.shift_bloomed(&keccak(topic)); b }).collect::>() }).collect() diff --git a/ethcore/types/src/lib.rs b/ethcore/types/src/lib.rs index 10a4ac71e..4050bf737 100644 --- a/ethcore/types/src/lib.rs +++ b/ethcore/types/src/lib.rs @@ -22,6 +22,7 @@ extern crate rlp; #[macro_use] extern crate rlp_derive; extern crate bloomable; +extern crate hash; #[cfg(test)] extern crate rustc_hex; diff --git a/ethcore/types/src/log_entry.rs b/ethcore/types/src/log_entry.rs index 152b48a0e..40b0f3ea9 100644 --- a/ethcore/types/src/log_entry.rs +++ b/ethcore/types/src/log_entry.rs @@ -17,7 +17,8 @@ //! Log entry type definition. use std::ops::Deref; -use util::{H256, Address, Bytes, HeapSizeOf, Hashable}; +use hash::keccak; +use util::{H256, Address, Bytes, HeapSizeOf}; use bloomable::Bloomable; use {BlockNumber}; @@ -45,7 +46,7 @@ impl HeapSizeOf for LogEntry { impl LogEntry { /// Calculates the bloom of this log entry. pub fn bloom(&self) -> LogBloom { - self.topics.iter().fold(LogBloom::from_bloomed(&self.address.sha3()), |b, t| b.with_bloomed(&t.sha3())) + self.topics.iter().fold(LogBloom::from_bloomed(&keccak(&self.address)), |b, t| b.with_bloomed(&keccak(t))) } } diff --git a/ethcore/vm/Cargo.toml b/ethcore/vm/Cargo.toml index 50efe936c..3f308d8f5 100644 --- a/ethcore/vm/Cargo.toml +++ b/ethcore/vm/Cargo.toml @@ -11,4 +11,5 @@ common-types = { path = "../types" } evmjit = { path = "../../evmjit", optional = true } ethjson = { path = "../../json" } lazy_static = "0.2" -rlp = { path = "../../util/rlp" } \ No newline at end of file +rlp = { path = "../../util/rlp" } +hash = { path = "../../util/hash" } diff --git a/ethcore/vm/src/action_params.rs b/ethcore/vm/src/action_params.rs index 401d7ee57..ab32e8d9f 100644 --- a/ethcore/vm/src/action_params.rs +++ b/ethcore/vm/src/action_params.rs @@ -17,7 +17,7 @@ //! Evm input params. use util::{Address, Bytes, U256}; use util::hash::{H256}; -use util::sha3::{Hashable, SHA3_EMPTY}; +use hash::{keccak, KECCAK_EMPTY}; use ethjson; use call_type::CallType; @@ -87,7 +87,7 @@ impl Default for ActionParams { fn default() -> ActionParams { ActionParams { code_address: Address::new(), - code_hash: Some(SHA3_EMPTY), + code_hash: Some(KECCAK_EMPTY), address: Address::new(), sender: Address::new(), origin: Address::new(), @@ -106,7 +106,7 @@ impl From for ActionParams { let address: Address = t.address.into(); ActionParams { code_address: Address::new(), - code_hash: Some((&*t.code).sha3()), + code_hash: Some(keccak(&*t.code)), address: address, sender: t.sender.into(), origin: t.origin.into(), diff --git a/ethcore/vm/src/env_info.rs b/ethcore/vm/src/env_info.rs index 8634d9c75..12f035183 100644 --- a/ethcore/vm/src/env_info.rs +++ b/ethcore/vm/src/env_info.rs @@ -18,7 +18,8 @@ use std::cmp; use std::sync::Arc; -use util::{U256, Address, H256, Hashable}; +use hash::keccak; +use util::{U256, Address, H256}; use types::BlockNumber; use ethjson; @@ -68,7 +69,7 @@ impl From for EnvInfo { difficulty: e.difficulty.into(), gas_limit: e.gas_limit.into(), timestamp: e.timestamp.into(), - last_hashes: Arc::new((1..cmp::min(number + 1, 257)).map(|i| format!("{}", number - i).as_bytes().sha3()).collect()), + last_hashes: Arc::new((1..cmp::min(number + 1, 257)).map(|i| keccak(format!("{}", number - i).as_bytes())).collect()), gas_used: U256::default(), } } diff --git a/ethcore/vm/src/lib.rs b/ethcore/vm/src/lib.rs index 0c9e32dc6..010e88eba 100644 --- a/ethcore/vm/src/lib.rs +++ b/ethcore/vm/src/lib.rs @@ -20,6 +20,7 @@ extern crate ethcore_util as util; extern crate common_types as types; extern crate ethjson; extern crate rlp; +extern crate hash; mod action_params; mod call_type; @@ -45,4 +46,4 @@ pub trait Vm { /// It returns either an error, a known amount of gas left, or parameters to be used /// to compute the final gas left. fn exec(&mut self, params: ActionParams, ext: &mut Ext) -> Result; -} \ No newline at end of file +} diff --git a/stratum/Cargo.toml b/stratum/Cargo.toml index dcd605bb8..9bf75779f 100644 --- a/stratum/Cargo.toml +++ b/stratum/Cargo.toml @@ -24,3 +24,4 @@ ethcore-ipc-nano = { path = "../ipc/nano" } futures = "0.1" tokio-core = "0.1" ethcore-logger = { path = "../logger" } +hash = { path = "../util/hash" } diff --git a/stratum/src/lib.rs b/stratum/src/lib.rs index 0042ab1e9..0cffd67b6 100644 --- a/stratum/src/lib.rs +++ b/stratum/src/lib.rs @@ -25,6 +25,7 @@ extern crate ethcore_ipc as ipc; extern crate semver; extern crate futures; extern crate ethcore_logger; +extern crate hash; #[cfg(test)] extern crate tokio_core; extern crate ethcore_devtools as devtools; @@ -54,7 +55,8 @@ use std::sync::Arc; use std::net::SocketAddr; use std::collections::{HashSet, HashMap}; -use util::{H256, Hashable, RwLock, RwLockReadGuard}; +use hash::keccak; +use util::{H256, RwLock, RwLockReadGuard}; type RpcResult = BoxFuture; @@ -228,7 +230,7 @@ impl Stratum { fn authorize(&self, params: Params, meta: SocketMetadata) -> RpcResult { future::result(params.parse::<(String, String)>().map(|(worker_id, secret)|{ if let Some(valid_secret) = self.secret { - let hash = secret.sha3(); + let hash = keccak(secret); if hash != valid_secret { return to_value(&false); } diff --git a/util/benches/trie.rs b/util/benches/trie.rs index e02077ad4..2ae10cf39 100644 --- a/util/benches/trie.rs +++ b/util/benches/trie.rs @@ -20,6 +20,7 @@ extern crate test; extern crate ethcore_util; #[macro_use] extern crate log; +extern crate hash; use test::{Bencher, black_box}; use ethcore_util::hash::*; @@ -27,12 +28,11 @@ use ethcore_util::bytes::*; use ethcore_util::trie::*; use ethcore_util::memorydb::*; use ethcore_util::triehash::*; -use ethcore_util::sha3::*; - +use hash::keccak; fn random_word(alphabet: &[u8], min_count: usize, diff_count: usize, seed: &mut H256) -> Vec { assert!(min_count + diff_count <= 32); - *seed = seed.sha3(); + *seed = keccak(&seed); let r = min_count + (seed[31] as usize % (diff_count + 1)); let mut ret: Vec = Vec::with_capacity(r); for i in 0..r { @@ -43,13 +43,13 @@ fn random_word(alphabet: &[u8], min_count: usize, diff_count: usize, seed: &mut fn random_bytes(min_count: usize, diff_count: usize, seed: &mut H256) -> Vec { assert!(min_count + diff_count <= 32); - *seed = seed.sha3(); + *seed = keccak(&seed); let r = min_count + (seed[31] as usize % (diff_count + 1)); seed[0..r].to_vec() } fn random_value(seed: &mut H256) -> Bytes { - *seed = seed.sha3(); + *seed = keccak(&seed); match seed[0] % 2 { 1 => vec![seed[31];1], _ => seed.to_vec(), @@ -306,11 +306,11 @@ fn triehash_insertions_six_low(b: &mut Bencher) { } #[bench] -fn sha3x10000(b: &mut Bencher) { +fn keccakx10000(b: &mut Bencher) { b.iter(||{ let mut seed = H256::new(); for _ in 0..10000 { - seed = seed.sha3() + seed = keccak(&seed); } }) }