diff --git a/Cargo.lock b/Cargo.lock index 439ba8936..38569b271 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -654,6 +654,7 @@ dependencies = [ "ethcore-util 1.8.0", "evm 0.1.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -730,6 +731,7 @@ dependencies = [ "ethkey 0.2.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "hyper 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)", "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)", @@ -902,6 +904,7 @@ dependencies = [ "ethcore-network 1.8.0", "ethcore-util 1.8.0", "ethkey 0.2.0", + "hash 0.1.0", "heapsize 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipnetwork 0.12.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1862,6 +1865,7 @@ dependencies = [ "fdlimit 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "ipnetwork 0.12.6 (registry+https://github.com/rust-lang/crates.io-index)", "isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", @@ -1909,6 +1913,7 @@ dependencies = [ "ethcore-util 1.8.0", "fetch 0.1.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", @@ -1954,6 +1959,7 @@ dependencies = [ "ethcore-util 1.8.0", "fetch 0.1.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2021,6 +2027,7 @@ dependencies = [ "fetch 0.1.0", "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "hash 0.1.0", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", @@ -2057,6 +2064,7 @@ version = "1.4.0" dependencies = [ "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-ws-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index 06abd7b31..9f6dd9ccb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,7 @@ parity-updater = { path = "updater" } parity-whisper = { path = "whisper" } path = { path = "util/path" } panic_hook = { path = "panic_hook" } +hash = { path = "util/hash" } parity-dapps = { path = "dapps", optional = true } clippy = { version = "0.0.103", optional = true} diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index b1751c616..76b026c9a 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -35,6 +35,7 @@ node-health = { path = "./node-health" } parity-hash-fetch = { path = "../hash-fetch" } parity-reactor = { path = "../util/reactor" } parity-ui = { path = "./ui" } +hash = { path = "../util/hash" } clippy = { version = "0.0.103", optional = true} diff --git a/dapps/src/apps/fetcher/installers.rs b/dapps/src/apps/fetcher/installers.rs index 82c91c859..9c220b057 100644 --- a/dapps/src/apps/fetcher/installers.rs +++ b/dapps/src/apps/fetcher/installers.rs @@ -19,9 +19,9 @@ use std::{fs, fmt}; use std::io::{self, Read, Write}; use std::path::PathBuf; use fetch::{self, Mime}; +use hash::keccak_buffer; use util::H256; -use util::sha3::sha3; use page::{LocalPageEndpoint, PageCache}; use handlers::{ContentValidator, ValidatorResponse}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest, serialize_manifest, Manifest}; @@ -57,9 +57,9 @@ fn write_response_and_check_hash( file.flush()?; // Validate hash - // TODO [ToDr] calculate sha3 in-flight while reading the response + // TODO [ToDr] calculate keccak in-flight while reading the response let mut file = io::BufReader::new(fs::File::open(&content_path)?); - let hash = sha3(&mut file)?; + let hash = keccak_buffer(&mut file)?; if id == hash { Ok((file.into_inner(), content_path)) } else { diff --git a/dapps/src/lib.rs b/dapps/src/lib.rs index 073db5121..f5670c959 100644 --- a/dapps/src/lib.rs +++ b/dapps/src/lib.rs @@ -43,6 +43,7 @@ extern crate parity_dapps_glue as parity_dapps; extern crate parity_hash_fetch as hash_fetch; extern crate parity_reactor; extern crate parity_ui; +extern crate hash; #[macro_use] extern crate log; diff --git a/ethcore/light/Cargo.toml b/ethcore/light/Cargo.toml index 9fda78f47..f0c8590e3 100644 --- a/ethcore/light/Cargo.toml +++ b/ethcore/light/Cargo.toml @@ -31,6 +31,7 @@ bincode = "0.8.0" serde = "1.0" serde_derive = "1.0" stats = { path = "../../util/stats" } +hash = { path = "../../util/hash" } [features] default = [] diff --git a/ethcore/light/src/client/header_chain.rs b/ethcore/light/src/client/header_chain.rs index d6ac109c7..e99e89c37 100644 --- a/ethcore/light/src/client/header_chain.rs +++ b/ethcore/light/src/client/header_chain.rs @@ -486,7 +486,7 @@ impl HeaderChain { /// Get the genesis hash. pub fn genesis_hash(&self) -> H256 { - ::util::Hashable::sha3(&self.genesis_header) + self.genesis_header.hash() } /// Get the best block's data. diff --git a/ethcore/light/src/lib.rs b/ethcore/light/src/lib.rs index c2ab483d2..0487d5d23 100644 --- a/ethcore/light/src/lib.rs +++ b/ethcore/light/src/lib.rs @@ -83,6 +83,7 @@ extern crate smallvec; extern crate stats; extern crate time; extern crate vm; +extern crate hash; #[cfg(feature = "ipc")] extern crate ethcore_ipc as ipc; diff --git a/ethcore/light/src/on_demand/request.rs b/ethcore/light/src/on_demand/request.rs index 6a2201349..8ee41437b 100644 --- a/ethcore/light/src/on_demand/request.rs +++ b/ethcore/light/src/on_demand/request.rs @@ -25,13 +25,13 @@ use ethcore::receipt::Receipt; use ethcore::state::{self, ProvedExecution}; use ethcore::transaction::SignedTransaction; use vm::EnvInfo; +use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY, KECCAK_EMPTY_LIST_RLP, keccak}; use request::{self as net_request, IncompleteRequest, CompleteRequest, Output, OutputKind, Field}; use rlp::{RlpStream, UntrustedRlp}; use util::{Address, Bytes, DBValue, HashDB, Mutex, H256, U256}; use util::memorydb::MemoryDB; -use util::sha3::{Hashable, SHA3_NULL_RLP, SHA3_EMPTY, SHA3_EMPTY_LIST_RLP}; use util::trie::{Trie, TrieDB, TrieError}; const SUPPLIED_MATCHES: &'static str = "supplied responses always match produced requests; enforced by `check_response`; qed"; @@ -276,7 +276,7 @@ impl From for CheckedRequest { Request::Account(req) => { let net_req = net_request::IncompleteAccountRequest { block_hash: req.header.field(), - address_hash: ::util::Hashable::sha3(&req.address).into(), + address_hash: ::hash::keccak(&req.address).into(), }; CheckedRequest::Account(req, net_req) } @@ -366,7 +366,7 @@ impl CheckedRequest { } CheckedRequest::Receipts(ref check, ref req) => { // empty transactions -> no receipts - if check.0.as_ref().ok().map_or(false, |hdr| hdr.receipts_root() == SHA3_NULL_RLP) { + if check.0.as_ref().ok().map_or(false, |hdr| hdr.receipts_root() == KECCAK_NULL_RLP) { return Some(Response::Receipts(Vec::new())); } @@ -377,7 +377,7 @@ impl CheckedRequest { CheckedRequest::Body(ref check, ref req) => { // check for empty body. if let Some(hdr) = check.0.as_ref().ok() { - if hdr.transactions_root() == SHA3_NULL_RLP && hdr.uncles_hash() == SHA3_EMPTY_LIST_RLP { + if hdr.transactions_root() == KECCAK_NULL_RLP && hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { let mut stream = RlpStream::new_list(3); stream.append_raw(hdr.rlp().as_raw(), 1); stream.begin_list(0); @@ -422,7 +422,7 @@ impl CheckedRequest { }) } CheckedRequest::Code(_, ref req) => { - if req.code_hash.as_ref().map_or(false, |&h| h == SHA3_EMPTY) { + if req.code_hash.as_ref().map_or(false, |&h| h == KECCAK_EMPTY) { Some(Response::Code(Vec::new())) } else { None @@ -571,8 +571,8 @@ impl net_request::ResponseLike for Response { match *self { Response::HeaderProof((ref hash, _)) => f(0, Output::Hash(*hash)), Response::Account(None) => { - f(0, Output::Hash(SHA3_EMPTY)); // code hash - f(1, Output::Hash(SHA3_NULL_RLP)); // storage root. + f(0, Output::Hash(KECCAK_EMPTY)); // code hash + f(1, Output::Hash(KECCAK_NULL_RLP)); // storage root. } Response::Account(Some(ref acc)) => { f(0, Output::Hash(acc.code_hash)); @@ -688,7 +688,7 @@ impl HeaderByHash { }; let header = headers.get(0).ok_or(Error::Empty)?; - let hash = header.sha3(); + let hash = header.hash(); match hash == expected_hash { true => { cache.lock().insert_block_header(hash, header.clone()); @@ -713,7 +713,7 @@ impl Body { return Err(Error::WrongTrieRoot(header.transactions_root(), tx_root)); } - let uncles_hash = body.rlp().at(1).as_raw().sha3(); + let uncles_hash = keccak(body.rlp().at(1).as_raw()); if uncles_hash != header.uncles_hash() { return Err(Error::WrongHash(header.uncles_hash(), uncles_hash)); } @@ -768,7 +768,7 @@ impl Account { let mut db = MemoryDB::new(); for node in proof { db.insert(&node[..]); } - match TrieDB::new(&db, &state_root).and_then(|t| t.get(&self.address.sha3()))? { + match TrieDB::new(&db, &state_root).and_then(|t| t.get(&keccak(&self.address)))? { Some(val) => { let rlp = UntrustedRlp::new(&val); Ok(Some(BasicAccount { @@ -800,7 +800,7 @@ impl Code { code_hash: &H256, code: &[u8] ) -> Result, Error> { - let found_hash = code.sha3(); + let found_hash = keccak(code); if &found_hash == code_hash { Ok(code.to_vec()) } else { @@ -853,6 +853,7 @@ mod tests { use util::{MemoryDB, Address, Mutex, H256}; use util::trie::{Trie, TrieMut, SecTrieDB, SecTrieDBMut}; use util::trie::recorder::Recorder; + use hash::keccak; use ethcore::client::{BlockChainClient, TestBlockChainClient, EachBlockWith}; use ethcore::header::Header; @@ -998,7 +999,7 @@ mod tests { #[test] fn check_code() { let code = vec![1u8; 256]; - let code_hash = ::util::Hashable::sha3(&code); + let code_hash = keccak(&code); let header = Header::new(); let req = Code { header: encoded::Header::new(::rlp::encode(&header).into_vec()).into(), diff --git a/hash-fetch/Cargo.toml b/hash-fetch/Cargo.toml index 502723bbb..e87ffea1a 100644 --- a/hash-fetch/Cargo.toml +++ b/hash-fetch/Cargo.toml @@ -18,3 +18,4 @@ fetch = { path = "../util/fetch" } ethcore-util = { path = "../util" } parity-reactor = { path = "../util/reactor" } native-contracts = { path = "../ethcore/native_contracts" } +hash = { path = "../util/hash" } diff --git a/hash-fetch/src/client.rs b/hash-fetch/src/client.rs index bd773e9b3..d63df794a 100644 --- a/hash-fetch/src/client.rs +++ b/hash-fetch/src/client.rs @@ -21,11 +21,12 @@ use std::io::Write; use std::sync::Arc; use std::path::PathBuf; +use hash::keccak_buffer; use fetch::{Fetch, Response, Error as FetchError, Client as FetchClient}; use futures::Future; use parity_reactor::Remote; use urlhint::{ContractClient, URLHintContract, URLHint, URLHintResult}; -use util::{H256, sha3}; +use util::H256; /// API for fetching by hash. pub trait HashFetch: Send + Sync + 'static { @@ -101,7 +102,7 @@ fn validate_hash(path: PathBuf, hash: H256, result: Result // And validate the hash let mut file_reader = io::BufReader::new(fs::File::open(&path)?); - let content_hash = sha3(&mut file_reader)?; + let content_hash = keccak_buffer(&mut file_reader)?; if content_hash != hash { Err(Error::HashMismatch{ got: content_hash, expected: hash }) } else { diff --git a/hash-fetch/src/lib.rs b/hash-fetch/src/lib.rs index 4952ecea2..987770252 100644 --- a/hash-fetch/src/lib.rs +++ b/hash-fetch/src/lib.rs @@ -31,6 +31,7 @@ extern crate native_contracts; extern crate parity_reactor; extern crate rand; extern crate rustc_hex; +extern crate hash; pub extern crate fetch; diff --git a/hash-fetch/src/urlhint.rs b/hash-fetch/src/urlhint.rs index bc4b63cf2..3fa32eb15 100644 --- a/hash-fetch/src/urlhint.rs +++ b/hash-fetch/src/urlhint.rs @@ -20,10 +20,11 @@ use std::sync::Arc; use rustc_hex::ToHex; use mime::Mime; use mime_guess; +use hash::keccak; use futures::{future, BoxFuture, Future}; use native_contracts::{Registry, Urlhint}; -use util::{Address, Bytes, Hashable}; +use util::{Address, Bytes}; const COMMIT_LEN: usize = 20; @@ -164,7 +165,7 @@ impl URLHint for URLHintContract { let urlhint = self.urlhint.clone(); let client = self.client.clone(); - self.registrar.get_address(do_call, "githubhint".sha3(), "A".into()) + self.registrar.get_address(do_call, keccak("githubhint"), "A".into()) .map(|addr| if addr == Address::default() { None } else { Some(addr) }) .and_then(move |address| { let mut fixed_id = [0; 32]; diff --git a/parity/blockchain.rs b/parity/blockchain.rs index 426c8d447..a94b387d4 100644 --- a/parity/blockchain.rs +++ b/parity/blockchain.rs @@ -21,7 +21,8 @@ use std::time::{Instant, Duration}; use std::thread::sleep; use std::sync::Arc; use rustc_hex::FromHex; -use util::{ToPretty, U256, H256, Address, Hashable}; +use hash::{keccak, KECCAK_NULL_RLP}; +use util::{ToPretty, U256, H256, Address}; use rlp::PayloadInfo; use ethcore::service::ClientService; use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, BlockImportError, BlockChainClient, BlockId}; @@ -639,13 +640,13 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> { out.write_fmt(format_args!("\n\"0x{}\": {{\"balance\": \"{:x}\", \"nonce\": \"{:x}\"", account.hex(), balance, client.nonce(&account, at).unwrap_or_else(U256::zero))).expect("Write error"); let code = client.code(&account, at).unwrap_or(None).unwrap_or_else(Vec::new); if !code.is_empty() { - out.write_fmt(format_args!(", \"code_hash\": \"0x{}\"", code.sha3().hex())).expect("Write error"); + out.write_fmt(format_args!(", \"code_hash\": \"0x{}\"", keccak(&code).hex())).expect("Write error"); if cmd.code { out.write_fmt(format_args!(", \"code\": \"{}\"", code.to_hex())).expect("Write error"); } } - let storage_root = client.storage_root(&account, at).unwrap_or(::util::SHA3_NULL_RLP); - if storage_root != ::util::SHA3_NULL_RLP { + let storage_root = client.storage_root(&account, at).unwrap_or(KECCAK_NULL_RLP); + if storage_root != KECCAK_NULL_RLP { out.write_fmt(format_args!(", \"storage_root\": \"0x{}\"", storage_root.hex())).expect("Write error"); if cmd.storage { out.write_fmt(format_args!(", \"storage\": {{")).expect("Write error"); diff --git a/parity/configuration.rs b/parity/configuration.rs index 681804346..11360c41b 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -22,7 +22,8 @@ use std::collections::BTreeMap; use std::cmp::max; use std::str::FromStr; use cli::{Args, ArgsError}; -use util::{Hashable, H256, U256, Bytes, version_data, Address}; +use hash::keccak; +use util::{H256, U256, Bytes, version_data, Address}; use util::journaldb::Algorithm; use util::Colour; use ethsync::{NetworkConfiguration, is_valid_node_url}; @@ -506,7 +507,7 @@ impl Configuration { io_path: self.directories().db, listen_addr: self.stratum_interface(), port: self.args.flag_ports_shift + self.args.flag_stratum_port, - secret: self.args.flag_stratum_secret.as_ref().map(|s| s.parse::().unwrap_or_else(|_| s.sha3())), + secret: self.args.flag_stratum_secret.as_ref().map(|s| s.parse::().unwrap_or_else(|_| keccak(s))), })) } else { Ok(None) } } @@ -729,7 +730,7 @@ impl Configuration { ret.listen_address = Some(format!("{}", listen)); ret.public_address = public.map(|p| format!("{}", p)); ret.use_secret = match self.args.flag_node_key.as_ref() - .map(|s| s.parse::().or_else(|_| Secret::from_unsafe_slice(&s.sha3())).map_err(|e| format!("Invalid key: {:?}", e)) + .map(|s| s.parse::().or_else(|_| Secret::from_unsafe_slice(&keccak(s))).map_err(|e| format!("Invalid key: {:?}", e)) ) { None => None, Some(Ok(key)) => Some(key), diff --git a/parity/main.rs b/parity/main.rs index d79fb0064..00c219963 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -70,6 +70,7 @@ extern crate parity_whisper; extern crate path; extern crate rpc_cli; extern crate node_filter; +extern crate hash; #[macro_use] extern crate log as rlog; @@ -130,7 +131,7 @@ use std::collections::HashMap; use std::io::{self as stdio, BufReader, Read, Write}; use std::fs::{remove_file, metadata, File, create_dir_all}; use std::path::PathBuf; -use util::sha3::sha3; +use hash::keccak_buffer; use cli::Args; use configuration::{Cmd, Execute, Configuration}; use deprecated::find_deprecated; @@ -140,7 +141,7 @@ use dir::default_hypervisor_path; fn print_hash_of(maybe_file: Option) -> Result { if let Some(file) = maybe_file { let mut f = BufReader::new(File::open(&file).map_err(|_| "Unable to open file".to_owned())?); - let hash = sha3(&mut f).map_err(|_| "Unable to read from file".to_owned())?; + let hash = keccak_buffer(&mut f).map_err(|_| "Unable to read from file".to_owned())?; Ok(hash.hex()) } else { Err("Streaming from standard input not yet supported. Specify a file.".to_owned()) diff --git a/parity/snapshot.rs b/parity/snapshot.rs index dc786a2ea..34aa3252f 100644 --- a/parity/snapshot.rs +++ b/parity/snapshot.rs @@ -20,6 +20,7 @@ use std::time::Duration; use std::path::{Path, PathBuf}; use std::sync::Arc; +use hash::keccak; use ethcore::snapshot::{Progress, RestorationStatus, SnapshotService as SS}; use ethcore::snapshot::io::{SnapshotReader, PackedReader, PackedWriter}; use ethcore::snapshot::service::Service as SnapshotService; @@ -65,8 +66,6 @@ pub struct SnapshotCommand { // helper for reading chunks from arbitrary reader and feeding them into the // service. fn restore_using(snapshot: Arc, reader: &R, recover: bool) -> Result<(), String> { - use util::sha3::Hashable; - let manifest = reader.manifest(); info!("Restoring to block #{} (0x{:?})", manifest.block_number, manifest.block_hash); @@ -95,7 +94,7 @@ fn restore_using(snapshot: Arc, reader: &R, let chunk = reader.chunk(state_hash) .map_err(|e| format!("Encountered error while reading chunk {:?}: {}", state_hash, e))?; - let hash = chunk.sha3(); + let hash = keccak(&chunk); if hash != state_hash { return Err(format!("Mismatched chunk hash. Expected {:?}, got {:?}", state_hash, hash)); } @@ -112,7 +111,7 @@ fn restore_using(snapshot: Arc, reader: &R, let chunk = reader.chunk(block_hash) .map_err(|e| format!("Encountered error while reading chunk {:?}: {}", block_hash, e))?; - let hash = chunk.sha3(); + let hash = keccak(&chunk); if hash != block_hash { return Err(format!("Mismatched chunk hash. Expected {:?}, got {:?}", block_hash, hash)); } diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index a5a371cdf..382878683 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -54,6 +54,7 @@ parity-updater = { path = "../updater" } rlp = { path = "../util/rlp" } stats = { path = "../util/stats" } vm = { path = "../ethcore/vm" } +hash = { path = "../util/hash" } clippy = { version = "0.0.103", optional = true} pretty_assertions = "0.1" diff --git a/rpc/src/authcodes.rs b/rpc/src/authcodes.rs index 4427eda78..bb44eb506 100644 --- a/rpc/src/authcodes.rs +++ b/rpc/src/authcodes.rs @@ -21,7 +21,8 @@ use std::{fs, time, mem}; use itertools::Itertools; use rand::Rng; use rand::os::OsRng; -use util::{H256, Hashable}; +use hash::keccak; +use util::H256; /// Providing current time in seconds pub trait TimeProvider { @@ -162,7 +163,7 @@ impl AuthCodes { return false; } - let as_token = |code| format!("{}:{}", code, time).sha3(); + let as_token = |code| keccak(format!("{}:{}", code, time)); // Check if it's the initial token. if self.is_empty() { @@ -231,12 +232,13 @@ mod tests { use std::io::{Read, Write}; use std::{time, fs}; use std::cell::Cell; + use hash::keccak; - use util::{H256, Hashable}; + use util::H256; use super::*; fn generate_hash(val: &str, time: u64) -> H256 { - format!("{}:{}", val, time).sha3() + keccak(format!("{}:{}", val, time)) } #[test] diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index c429471f3..7db99ba2c 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -60,6 +60,7 @@ extern crate parity_reactor; extern crate parity_updater as updater; extern crate rlp; extern crate stats; +extern crate hash; #[macro_use] extern crate log; diff --git a/rpc/src/tests/ws.rs b/rpc/src/tests/ws.rs index 77fb1ea2c..6d4874845 100644 --- a/rpc/src/tests/ws.rs +++ b/rpc/src/tests/ws.rs @@ -56,7 +56,7 @@ pub fn request(server: Server, request: &str) -> http_client::Respon #[cfg(test)] mod testing { use std::time; - use util::Hashable; + use hash::keccak; use devtools::http_client; use super::{serve, request}; @@ -125,7 +125,7 @@ mod testing { {{}} ", port, - format!("{}:{}", code, timestamp).sha3(), + keccak(format!("{}:{}", code, timestamp)), timestamp, ) ); @@ -155,7 +155,7 @@ mod testing { {{}} ", port, - format!("{}:{}", code, timestamp).sha3(), + keccak(format!("{}:{}", code, timestamp)), timestamp, ) ); @@ -171,7 +171,7 @@ mod testing { {{}} ", port, - format!("{}:{}", code, timestamp).sha3(), + keccak(format!("{}:{}", code, timestamp)), timestamp, ) ); diff --git a/rpc/src/v1/helpers/dispatch.rs b/rpc/src/v1/helpers/dispatch.rs index ab8dd655a..41fc201cf 100644 --- a/rpc/src/v1/helpers/dispatch.rs +++ b/rpc/src/v1/helpers/dispatch.rs @@ -26,8 +26,8 @@ use light::client::LightChainClient; use light::on_demand::{request, OnDemand}; use light::TransactionQueue as LightTransactionQueue; use rlp; +use hash::keccak; use util::{Address, H520, H256, U256, Bytes, Mutex, RwLock}; -use util::sha3::Hashable; use stats::Corpus; use ethkey::Signature; @@ -226,7 +226,7 @@ pub fn eth_data_hash(mut data: Bytes) -> H256 { format!("\x19Ethereum Signed Message:\n{}", data.len()) .into_bytes(); message_data.append(&mut data); - message_data.sha3() + keccak(message_data) } /// Dispatcher for light clients -- fetches default gas price, next nonce, etc. from network. diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 0cf70bf23..f31d32426 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -24,7 +24,6 @@ use futures::{self, future, BoxFuture, Future}; use rlp::{self, UntrustedRlp}; use time::get_time; use util::{H160, H256, Address, U256, H64}; -use util::sha3::Hashable; use util::Mutex; use ethash::SeedHashCompute; @@ -149,7 +148,7 @@ impl EthClient where let view = block.header_view(); Ok(Some(RichBlock { inner: Block { - hash: Some(view.sha3().into()), + hash: Some(view.hash().into()), size: Some(block.rlp().as_raw().len().into()), parent_hash: view.parent_hash().into(), uncles_hash: view.uncles_hash().into(), diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index d33b5a06f..7e40bf71a 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -38,7 +38,7 @@ use ethcore::filter::Filter as EthcoreFilter; use ethcore::transaction::{Action, SignedTransaction, Transaction as EthTransaction}; use ethsync::LightSync; use rlp::UntrustedRlp; -use util::sha3::{SHA3_NULL_RLP, SHA3_EMPTY_LIST_RLP}; +use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP}; use util::{RwLock, Mutex, U256}; use futures::{future, Future, BoxFuture, IntoFuture}; @@ -295,7 +295,7 @@ impl Eth for EthClient { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { - if hdr.transactions_root() == SHA3_NULL_RLP { + if hdr.transactions_root() == KECCAK_NULL_RLP { future::ok(Some(U256::from(0).into())).boxed() } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) @@ -311,7 +311,7 @@ impl Eth for EthClient { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); self.fetcher().header(num.into()).and_then(move |hdr| { - if hdr.transactions_root() == SHA3_NULL_RLP { + if hdr.transactions_root() == KECCAK_NULL_RLP { future::ok(Some(U256::from(0).into())).boxed() } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) @@ -327,7 +327,7 @@ impl Eth for EthClient { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { - if hdr.uncles_hash() == SHA3_EMPTY_LIST_RLP { + if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { future::ok(Some(U256::from(0).into())).boxed() } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) @@ -343,7 +343,7 @@ impl Eth for EthClient { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); self.fetcher().header(num.into()).and_then(move |hdr| { - if hdr.uncles_hash() == SHA3_EMPTY_LIST_RLP { + if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { future::ok(Some(U256::from(0).into())).boxed() } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index b97327168..bac6556e3 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use ethsync::ManageNetwork; use fetch::Fetch; use futures::{BoxFuture, Future}; -use util::sha3; +use hash::keccak_buffer; use jsonrpc_core::Error; use v1::helpers::dapps::DappsService; @@ -129,7 +129,7 @@ impl ParitySet for ParitySetClient { result .map_err(errors::fetch) .and_then(|response| { - sha3(&mut io::BufReader::new(response)).map_err(errors::fetch) + keccak_buffer(&mut io::BufReader::new(response)).map_err(errors::fetch) }) .map(Into::into) })) diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index 540964e63..38890d6d1 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -24,7 +24,7 @@ use ethcore::mode::Mode; use ethsync::ManageNetwork; use fetch::{self, Fetch}; use futures::{BoxFuture, Future}; -use util::sha3; +use hash::keccak_buffer; use updater::{Service as UpdateService}; use jsonrpc_core::Error; @@ -170,7 +170,7 @@ impl ParitySet for ParitySetClient where result .map_err(errors::fetch) .and_then(|response| { - sha3(&mut io::BufReader::new(response)).map_err(errors::fetch) + keccak_buffer(&mut io::BufReader::new(response)).map_err(errors::fetch) }) .map(Into::into) })) diff --git a/rpc/src/v1/impls/web3.rs b/rpc/src/v1/impls/web3.rs index 859c44567..d0be2db81 100644 --- a/rpc/src/v1/impls/web3.rs +++ b/rpc/src/v1/impls/web3.rs @@ -15,11 +15,11 @@ // along with Parity. If not, see . //! Web3 rpc implementation. +use hash::keccak; use jsonrpc_core::*; use util::version; use v1::traits::Web3; use v1::types::{H256, Bytes}; -use util::sha3::Hashable; /// Web3 rpc implementation. pub struct Web3Client; @@ -35,6 +35,6 @@ impl Web3 for Web3Client { } fn sha3(&self, data: Bytes) -> Result { - Ok(data.0.sha3().into()) + Ok(keccak(&data.0).into()) } } diff --git a/rpc/src/v1/tests/eth.rs b/rpc/src/v1/tests/eth.rs index cbbfa8dc0..c13ee79c8 100644 --- a/rpc/src/v1/tests/eth.rs +++ b/rpc/src/v1/tests/eth.rs @@ -29,7 +29,7 @@ use ethcore::miner::{MinerOptions, Banning, GasPricer, MinerService, ExternalMin use ethcore::account_provider::AccountProvider; use ethjson::blockchain::BlockChain; use io::IoChannel; -use util::{U256, H256, Address, Hashable}; +use util::{U256, H256, Address}; use jsonrpc_core::IoHandler; use v1::impls::{EthClient, SigningUnsafeClient}; @@ -431,7 +431,7 @@ fn verify_transaction_counts(name: String, chain: BlockChain) { for b in chain.blocks_rlp().iter().filter(|b| Block::is_good(b)).map(|b| BlockView::new(b)) { let count = b.transactions_count(); - let hash = b.sha3(); + let hash = b.hash(); let number = b.header_view().number(); let (req, res) = by_hash(hash, count, &mut id); diff --git a/rpc_client/Cargo.toml b/rpc_client/Cargo.toml index 5cc688fb5..1e39d8b1e 100644 --- a/rpc_client/Cargo.toml +++ b/rpc_client/Cargo.toml @@ -19,3 +19,4 @@ jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "pa jsonrpc-ws-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } parity-rpc = { path = "../rpc" } ethcore-util = { path = "../util" } +hash = { path = "../util/hash" } diff --git a/rpc_client/src/client.rs b/rpc_client/src/client.rs index 3f55fbe73..9c6c4ebe8 100644 --- a/rpc_client/src/client.rs +++ b/rpc_client/src/client.rs @@ -9,7 +9,8 @@ use std::thread; use std::time; use std::path::PathBuf; -use util::{Hashable, Mutex}; +use hash::keccak; +use util::Mutex; use url::Url; use std::fs::File; @@ -72,7 +73,7 @@ impl Handler for RpcHandler { WsError::new(WsErrorKind::Internal, format!("{}", err)) })?; let secs = timestamp.as_secs(); - let hashed = format!("{}:{}", self.auth_code, secs).sha3(); + let hashed = keccak(format!("{}:{}", self.auth_code, secs)); let proto = format!("{:?}_{}", hashed, secs); r.add_protocol(&proto); Ok(r) diff --git a/rpc_client/src/lib.rs b/rpc_client/src/lib.rs index d1967ccbd..805754b22 100644 --- a/rpc_client/src/lib.rs +++ b/rpc_client/src/lib.rs @@ -11,6 +11,7 @@ extern crate serde; extern crate serde_json; extern crate tempdir; extern crate url; +extern crate hash; #[macro_use] extern crate log; diff --git a/secret_store/Cargo.toml b/secret_store/Cargo.toml index 19f342aa9..8a8010540 100644 --- a/secret_store/Cargo.toml +++ b/secret_store/Cargo.toml @@ -29,6 +29,7 @@ ethabi = "2.0" ethcore = { path = "../ethcore" } ethcore-devtools = { path = "../devtools" } ethcore-util = { path = "../util" } +hash = { path = "../util/hash" } ethcore-ipc = { path = "../ipc/rpc" } ethcore-ipc-nano = { path = "../ipc/nano" } ethcore-logger = { path = "../logger" } diff --git a/secret_store/src/key_server_cluster/math.rs b/secret_store/src/key_server_cluster/math.rs index 047a4556c..1c81d063e 100644 --- a/secret_store/src/key_server_cluster/math.rs +++ b/secret_store/src/key_server_cluster/math.rs @@ -15,7 +15,8 @@ // along with Parity. If not, see . use ethkey::{Public, Secret, Random, Generator, math}; -use util::{U256, H256, Hashable}; +use util::{U256, H256}; +use hash::keccak; use key_server_cluster::Error; #[derive(Debug)] @@ -306,7 +307,7 @@ pub fn combine_message_hash_with_public(message_hash: &H256, public: &Public) -> buffer[32..64].copy_from_slice(&public[0..32]); // calculate hash of buffer - let hash = (&buffer[..]).sha3(); + let hash = keccak(&buffer[..]); // map hash to EC finite field value let hash: U256 = hash.into(); diff --git a/secret_store/src/key_server_set.rs b/secret_store/src/key_server_set.rs index e17dceed5..02e509c89 100644 --- a/secret_store/src/key_server_set.rs +++ b/secret_store/src/key_server_set.rs @@ -22,7 +22,8 @@ use parking_lot::Mutex; use ethcore::filter::Filter; use ethcore::client::{Client, BlockChainClient, BlockId, ChainNotify}; use native_contracts::KeyServerSet as KeyServerSetContract; -use util::{H256, Address, Bytes, Hashable}; +use hash::keccak; +use util::{H256, Address, Bytes}; use types::all::{Error, Public, NodeAddress}; const KEY_SERVER_SET_CONTRACT_REGISTRY_NAME: &'static str = "secretstore_server_set"; @@ -33,8 +34,8 @@ const ADDED_EVENT_NAME: &'static [u8] = &*b"KeyServerAdded(address)"; const REMOVED_EVENT_NAME: &'static [u8] = &*b"KeyServerRemoved(address)"; lazy_static! { - static ref ADDED_EVENT_NAME_HASH: H256 = ADDED_EVENT_NAME.sha3(); - static ref REMOVED_EVENT_NAME_HASH: H256 = REMOVED_EVENT_NAME.sha3(); + static ref ADDED_EVENT_NAME_HASH: H256 = keccak(ADDED_EVENT_NAME); + static ref REMOVED_EVENT_NAME_HASH: H256 = keccak(REMOVED_EVENT_NAME); } /// Key Server set diff --git a/secret_store/src/lib.rs b/secret_store/src/lib.rs index d7f35a55a..8ba8648f8 100644 --- a/secret_store/src/lib.rs +++ b/secret_store/src/lib.rs @@ -44,6 +44,7 @@ extern crate ethcore_logger as logger; extern crate ethcrypto; extern crate ethkey; extern crate native_contracts; +extern crate hash; mod key_server_cluster; mod types; diff --git a/sync/Cargo.toml b/sync/Cargo.toml index b9a411879..5fb3628df 100644 --- a/sync/Cargo.toml +++ b/sync/Cargo.toml @@ -18,6 +18,7 @@ ethcore-io = { path = "../util/io" } ethcore-light = { path = "../ethcore/light"} ethcore = { path = "../ethcore" } rlp = { path = "../util/rlp" } +hash = { path = "../util/hash" } clippy = { version = "0.0.103", optional = true} log = "0.3" env_logger = "0.4" diff --git a/sync/src/block_sync.rs b/sync/src/block_sync.rs index 92c8df429..2cf8f974c 100644 --- a/sync/src/block_sync.rs +++ b/sync/src/block_sync.rs @@ -478,7 +478,7 @@ impl BlockDownloader { let receipts = block_and_receipts.receipts; let (h, number, parent) = { let header = BlockView::new(&block).header_view(); - (header.sha3(), header.number(), header.parent_hash()) + (header.hash(), header.number(), header.parent_hash()) }; // Perform basic block verification diff --git a/sync/src/blocks.rs b/sync/src/blocks.rs index dbd797007..b953db09a 100644 --- a/sync/src/blocks.rs +++ b/sync/src/blocks.rs @@ -17,6 +17,7 @@ use std::collections::{HashSet, HashMap}; use std::collections::hash_map::Entry; use smallvec::SmallVec; +use hash::{keccak, KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP}; use util::*; use rlp::*; use network::NetworkError; @@ -342,7 +343,7 @@ impl BlockCollection { let body = UntrustedRlp::new(&b); let tx = body.at(0)?; let tx_root = ordered_trie_root(tx.iter().map(|r| r.as_raw().to_vec())); //TODO: get rid of vectors here - let uncles = body.at(1)?.as_raw().sha3(); + let uncles = keccak(body.at(1)?.as_raw()); HeaderId { transactions_root: tx_root, uncles: uncles @@ -425,7 +426,7 @@ impl BlockCollection { transactions_root: info.transactions_root().clone(), uncles: info.uncles_hash().clone(), }; - if header_id.transactions_root == sha3::SHA3_NULL_RLP && header_id.uncles == sha3::SHA3_EMPTY_LIST_RLP { + if header_id.transactions_root == KECCAK_NULL_RLP && header_id.uncles == KECCAK_EMPTY_LIST_RLP { // empty body, just mark as downloaded let mut body_stream = RlpStream::new_list(2); body_stream.append_raw(&::rlp::EMPTY_LIST_RLP, 1); @@ -438,7 +439,7 @@ impl BlockCollection { } if self.need_receipts { let receipt_root = info.receipts_root().clone(); - if receipt_root == sha3::SHA3_NULL_RLP { + if receipt_root == KECCAK_NULL_RLP { let receipts_stream = RlpStream::new_list(0); block.receipts = Some(receipts_stream.out()); } else { @@ -489,7 +490,6 @@ mod test { use ethcore::client::{TestBlockChainClient, EachBlockWith, BlockId, BlockChainClient}; use ethcore::views::HeaderView; use ethcore::header::BlockNumber; - use util::*; use rlp::*; fn is_empty(bc: &BlockCollection) -> bool { @@ -526,7 +526,7 @@ mod test { .map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).unwrap().into_inner()) .collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); - let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); + let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).hash()).collect(); let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect(); bc.reset_to(heads); assert!(!bc.is_empty()); @@ -581,7 +581,7 @@ mod test { .map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).unwrap().into_inner()) .collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); - let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); + let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).hash()).collect(); let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect(); bc.reset_to(heads); @@ -605,7 +605,7 @@ mod test { .map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).unwrap().into_inner()) .collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); - let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); + let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).hash()).collect(); let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect(); bc.reset_to(heads); diff --git a/sync/src/chain.rs b/sync/src/chain.rs index 3a472c88f..9c62a2a61 100644 --- a/sync/src/chain.rs +++ b/sync/src/chain.rs @@ -91,6 +91,7 @@ use std::collections::{HashSet, HashMap}; use std::cmp; +use hash::keccak; use util::*; use rlp::*; use network::*; @@ -682,7 +683,7 @@ impl ChainSync { peer.confirmation = ForkConfirmation::TooShort; } else { let header = r.at(0)?.as_raw(); - if header.sha3() == fork_hash { + if keccak(&header) == fork_hash { trace!(target: "sync", "{}: Confirmed peer", peer_id); peer.confirmation = ForkConfirmation::Confirmed; if !io.chain_overlay().read().contains_key(&fork_number) { @@ -894,7 +895,7 @@ impl ChainSync { } let block_rlp = r.at(0)?; let header_rlp = block_rlp.at(0)?; - let h = header_rlp.as_raw().sha3(); + let h = keccak(&header_rlp.as_raw()); trace!(target: "sync", "{} -> NewBlock ({})", peer_id, h); let header: BlockHeader = header_rlp.as_val()?; if header.number() > self.highest_block.unwrap_or(0) { @@ -1055,7 +1056,7 @@ impl ChainSync { self.continue_sync(io); return Ok(()); } - self.snapshot.reset_to(&manifest, &manifest_rlp.as_raw().sha3()); + self.snapshot.reset_to(&manifest, &keccak(manifest_rlp.as_raw())); io.snapshot_service().begin_restore(manifest); self.state = SyncState::SnapshotData; @@ -1509,7 +1510,7 @@ impl ChainSync { false => io.snapshot_service().manifest(), }; let block_number = manifest.as_ref().map_or(0, |m| m.block_number); - let manifest_hash = manifest.map_or(H256::new(), |m| m.into_rlp().sha3()); + let manifest_hash = manifest.map_or(H256::new(), |m| keccak(m.into_rlp())); packet.append(&manifest_hash); packet.append(&block_number); } @@ -1531,7 +1532,7 @@ impl ChainSync { match io.chain().block_header(BlockId::Hash(hash)) { Some(hdr) => { let number = hdr.number().into(); - debug_assert_eq!(hdr.sha3(), hash); + debug_assert_eq!(hdr.hash(), hash); if max_headers == 1 || io.chain().block_hash(BlockId::Number(number)) != Some(hash) { // Non canonical header or single header requested @@ -2229,7 +2230,6 @@ mod tests { use tests::helpers::*; use tests::snapshot::TestSnapshotService; use util::{U256, Address, RwLock}; - use util::sha3::Hashable; use util::hash::H256; use util::bytes::Bytes; use rlp::{Rlp, RlpStream, UntrustedRlp}; @@ -2394,7 +2394,7 @@ mod tests { let blocks: Vec<_> = (0 .. 100) .map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).map(|b| b.into_inner()).unwrap()).collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); - let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); + let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).hash()).collect(); let queue = RwLock::new(VecDeque::new()); let ss = TestSnapshotService::new(); diff --git a/sync/src/lib.rs b/sync/src/lib.rs index 51947317d..237d6c437 100644 --- a/sync/src/lib.rs +++ b/sync/src/lib.rs @@ -38,6 +38,7 @@ extern crate parking_lot; extern crate smallvec; extern crate rlp; extern crate ipnetwork; +extern crate hash; extern crate ethcore_light as light; diff --git a/sync/src/snapshot.rs b/sync/src/snapshot.rs index cecfbe425..d3cdf274f 100644 --- a/sync/src/snapshot.rs +++ b/sync/src/snapshot.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . - -use util::{H256, Hashable}; +use hash::keccak; +use util::H256; use std::collections::HashSet; use ethcore::snapshot::ManifestData; @@ -71,7 +71,7 @@ impl Snapshot { /// Validate chunk and mark it as downloaded pub fn validate_chunk(&mut self, chunk: &[u8]) -> Result { - let hash = chunk.sha3(); + let hash = keccak(chunk); if self.completed_chunks.contains(&hash) { trace!(target: "sync", "Ignored proccessed chunk: {}", hash.hex()); return Err(()); @@ -136,6 +136,7 @@ impl Snapshot { #[cfg(test)] mod test { + use hash::keccak; use util::*; use super::*; use ethcore::snapshot::ManifestData; @@ -153,13 +154,13 @@ mod test { let block_chunks: Vec = (0..20).map(|_| H256::random().to_vec()).collect(); let manifest = ManifestData { version: 2, - state_hashes: state_chunks.iter().map(|data| data.sha3()).collect(), - block_hashes: block_chunks.iter().map(|data| data.sha3()).collect(), + state_hashes: state_chunks.iter().map(|data| keccak(data)).collect(), + block_hashes: block_chunks.iter().map(|data| keccak(data)).collect(), state_root: H256::new(), block_number: 42, block_hash: H256::new(), }; - let mhash = manifest.clone().into_rlp().sha3(); + let mhash = keccak(manifest.clone().into_rlp()); (manifest, mhash, state_chunks, block_chunks) } @@ -211,7 +212,7 @@ mod test { assert!(snapshot.is_complete()); assert_eq!(snapshot.done_chunks(), 40); assert_eq!(snapshot.done_chunks(), snapshot.total_chunks()); - assert_eq!(snapshot.snapshot_hash(), Some(manifest.into_rlp().sha3())); + assert_eq!(snapshot.snapshot_hash(), Some(keccak(manifest.into_rlp()))); } #[test] diff --git a/sync/src/tests/consensus.rs b/sync/src/tests/consensus.rs index 9b01156b7..a47c4a486 100644 --- a/sync/src/tests/consensus.rs +++ b/sync/src/tests/consensus.rs @@ -15,6 +15,7 @@ // along with Parity. If not, see . use std::sync::Arc; +use hash::keccak; use util::*; use io::{IoHandler, IoContext, IoChannel}; use ethcore::client::{BlockChainClient, Client}; @@ -56,8 +57,8 @@ fn new_tx(secret: &Secret, nonce: U256, chain_id: u64) -> PendingTransaction { #[test] fn authority_round() { - let s0 = KeyPair::from_secret_slice(&"1".sha3()).unwrap(); - let s1 = KeyPair::from_secret_slice(&"0".sha3()).unwrap(); + let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap(); + let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap(); let ap = Arc::new(AccountProvider::transient_provider()); ap.insert_account(s0.secret().clone(), "").unwrap(); ap.insert_account(s1.secret().clone(), "").unwrap(); @@ -143,8 +144,8 @@ fn authority_round() { #[test] fn tendermint() { - let s0 = KeyPair::from_secret_slice(&"1".sha3()).unwrap(); - let s1 = KeyPair::from_secret_slice(&"0".sha3()).unwrap(); + let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap(); + let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap(); let ap = Arc::new(AccountProvider::transient_provider()); ap.insert_account(s0.secret().clone(), "").unwrap(); ap.insert_account(s1.secret().clone(), "").unwrap(); diff --git a/sync/src/tests/snapshot.rs b/sync/src/tests/snapshot.rs index 9303aa9f7..d49bcf440 100644 --- a/sync/src/tests/snapshot.rs +++ b/sync/src/tests/snapshot.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use std::sync::Arc; +use hash::keccak; use util::*; use ethcore::snapshot::{SnapshotService, ManifestData, RestorationStatus}; use ethcore::header::BlockNumber; @@ -50,14 +51,14 @@ impl TestSnapshotService { let block_chunks: Vec = (0..num_block_chunks).map(|_| H256::random().to_vec()).collect(); let manifest = ManifestData { version: 2, - state_hashes: state_chunks.iter().map(|data| data.sha3()).collect(), - block_hashes: block_chunks.iter().map(|data| data.sha3()).collect(), + state_hashes: state_chunks.iter().map(|data| keccak(data)).collect(), + block_hashes: block_chunks.iter().map(|data| keccak(data)).collect(), state_root: H256::new(), block_number: block_number, block_hash: block_hash, }; - let mut chunks: HashMap = state_chunks.into_iter().map(|data| (data.sha3(), data)).collect(); - chunks.extend(block_chunks.into_iter().map(|data| (data.sha3(), data))); + let mut chunks: HashMap = state_chunks.into_iter().map(|data| (keccak(&data), data)).collect(); + chunks.extend(block_chunks.into_iter().map(|data| (keccak(&data), data))); TestSnapshotService { manifest: Some(manifest), chunks: chunks,