From 4dc1d42a935d6855e31fe67cd6959c5a9be21bd8 Mon Sep 17 00:00:00 2001 From: debris Date: Mon, 25 Jul 2016 20:19:33 +0200 Subject: [PATCH 1/8] moving hash.rs to bigint in progress --- Cargo.lock | 1 + util/bigint/Cargo.toml | 1 + util/{ => bigint}/src/hash.rs | 81 +++++++++++++++++++---------------- util/bigint/src/lib.rs | 2 + util/src/common.rs | 4 +- util/src/crypto.rs | 6 ++- util/src/heapsizeof.rs | 1 - util/src/lib.rs | 5 --- util/src/math.rs | 27 ------------ util/src/numbers.rs | 20 --------- 10 files changed, 55 insertions(+), 93 deletions(-) rename util/{ => bigint}/src/hash.rs (88%) delete mode 100644 util/src/math.rs delete mode 100644 util/src/numbers.rs diff --git a/Cargo.lock b/Cargo.lock index 63dabcd43..f837fdd20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,7 @@ name = "bigint" version = "0.1.0" dependencies = [ "heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/util/bigint/Cargo.toml b/util/bigint/Cargo.toml index 357e2956c..68778e18c 100644 --- a/util/bigint/Cargo.toml +++ b/util/bigint/Cargo.toml @@ -13,6 +13,7 @@ rustc_version = "0.1" [dependencies] rustc-serialize = "0.3" heapsize = "0.3" +rand = "0.3.12" [features] x64asm_arithmetic=[] diff --git a/util/src/hash.rs b/util/bigint/src/hash.rs similarity index 88% rename from util/src/hash.rs rename to util/bigint/src/hash.rs index 1b868b87b..9c5081b93 100644 --- a/util/src/hash.rs +++ b/util/bigint/src/hash.rs @@ -16,23 +16,18 @@ //! General hash types, a fixed-size raw-data type used as the output of hash functions. -use rustc_serialize::hex::FromHex; -use std::{ops, fmt, cmp}; +use std::{ops, fmt, cmp, mem}; use std::cmp::*; use std::ops::*; use std::hash::{Hash, Hasher}; use std::str::FromStr; -use math::log2; -use error::UtilError; use rand::Rng; use rand::os::OsRng; -use bytes::{BytesConvertable,Populatable}; -use bigint::uint::{Uint, U256}; +use rustc_serialize::hex::{FromHex, FromHexError}; +use uint::{Uint, U256}; /// Trait for a fixed-size byte array to be used as the output of hash functions. -/// -/// Note: types implementing `FixedHash` must be also `BytesConvertable`. -pub trait FixedHash: Sized + BytesConvertable + Populatable + FromStr + Default { +pub trait FixedHash: Sized + FromStr + Default + DerefMut { /// Create a new, zero-initialised, instance. fn new() -> Self; /// Synonym for `new()`. Prefer to new as it's more readable. @@ -74,6 +69,16 @@ pub fn clean_0x(s: &str) -> &str { } } +/// Returns log2. +pub fn log2(x: usize) -> u32 { + if x <= 1 { + return 0; + } + + let n = x.leading_zeros(); + mem::size_of::() as u32 * 8 - n +} + macro_rules! impl_hash { ($from: ident, $size: expr) => { #[derive(Eq)] @@ -189,7 +194,7 @@ macro_rules! impl_hash { ptr += 1; } index &= mask; - ret.as_slice_mut()[m - 1 - index / 8] |= 1 << (index % 8); + ret[m - 1 - index / 8] |= 1 << (index % 8); } ret @@ -218,15 +223,17 @@ macro_rules! impl_hash { } impl FromStr for $from { - type Err = UtilError; - fn from_str(s: &str) -> Result<$from, UtilError> { + type Err = FromHexError; + + fn from_str(s: &str) -> Result<$from, FromHexError> { let a = try!(s.from_hex()); - if a.len() != $size { return Err(UtilError::BadSize); } - let mut ret = $from([0;$size]); - for i in 0..$size { - ret.0[i] = a[i]; + if a.len() != $size { + return Err(FromHexError::InvalidHexLength); } - Ok(ret) + + let mut ret = [0;$size]; + ret.copy_from_slice(&a); + Ok($from(ret)) } } @@ -460,13 +467,13 @@ impl<'a> From<&'a U256> for H256 { impl From for U256 { fn from(value: H256) -> U256 { - U256::from(value.as_slice()) + U256::from(&value) } } impl<'a> From<&'a H256> for U256 { fn from(value: &'a H256) -> U256 { - U256::from(value.as_slice()) + U256::from(value.as_ref() as &[u8]) } } @@ -505,20 +512,17 @@ impl<'a> From<&'a Address> for H256 { /// Convert string `s` to an `H256`. Will panic if `s` is not 64 characters long or if any of /// those characters are not 0-9, a-z or A-Z. pub fn h256_from_hex(s: &str) -> H256 { - use std::str::FromStr; H256::from_str(s).unwrap() } /// Convert `n` to an `H256`, setting the rightmost 8 bytes. pub fn h256_from_u64(n: u64) -> H256 { - use bigint::uint::U256; H256::from(&U256::from(n)) } /// Convert string `s` to an `Address`. Will panic if `s` is not 40 characters long or if any of /// those characters are not 0-9, a-z or A-Z. pub fn address_from_hex(s: &str) -> Address { - use std::str::FromStr; Address::from_str(s).unwrap() } @@ -539,10 +543,12 @@ impl_hash!(H520, 65); impl_hash!(H1024, 128); impl_hash!(H2048, 256); +known_heap_size!(0, H32, H64, H128, Address, H256, H264, H512, H520, H1024, H2048); + #[cfg(test)] mod tests { use hash::*; - use bigint::uint::*; + use uint::*; use std::str::FromStr; #[test] @@ -572,25 +578,26 @@ mod tests { } #[test] + #[ignore] fn shift_bloomed() { - use sha3::Hashable; + //use sha3::Hashable; - let bloom = H2048::from_str("00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); - let address = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); - let topic = H256::from_str("02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc").unwrap(); + //let bloom = H2048::from_str("00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); + //let address = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); + //let topic = H256::from_str("02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc").unwrap(); - let mut my_bloom = H2048::new(); - assert!(!my_bloom.contains_bloomed(&address.sha3())); - assert!(!my_bloom.contains_bloomed(&topic.sha3())); + //let mut my_bloom = H2048::new(); + //assert!(!my_bloom.contains_bloomed(&address.sha3())); + //assert!(!my_bloom.contains_bloomed(&topic.sha3())); - my_bloom.shift_bloomed(&address.sha3()); - assert!(my_bloom.contains_bloomed(&address.sha3())); - assert!(!my_bloom.contains_bloomed(&topic.sha3())); + //my_bloom.shift_bloomed(&address.sha3()); + //assert!(my_bloom.contains_bloomed(&address.sha3())); + //assert!(!my_bloom.contains_bloomed(&topic.sha3())); - my_bloom.shift_bloomed(&topic.sha3()); - assert_eq!(my_bloom, bloom); - assert!(my_bloom.contains_bloomed(&address.sha3())); - assert!(my_bloom.contains_bloomed(&topic.sha3())); + //my_bloom.shift_bloomed(&topic.sha3()); + //assert_eq!(my_bloom, bloom); + //assert!(my_bloom.contains_bloomed(&address.sha3())); + //assert!(my_bloom.contains_bloomed(&topic.sha3())); } #[test] diff --git a/util/bigint/src/lib.rs b/util/bigint/src/lib.rs index 1d97871e3..746cc8139 100644 --- a/util/bigint/src/lib.rs +++ b/util/bigint/src/lib.rs @@ -16,7 +16,9 @@ #![cfg_attr(asm_available, feature(asm))] +extern crate rand; extern crate rustc_serialize; #[macro_use] extern crate heapsize; pub mod uint; +pub mod hash; diff --git a/util/src/common.rs b/util/src/common.rs index 0d3466dff..216f89a79 100644 --- a/util/src/common.rs +++ b/util/src/common.rs @@ -21,8 +21,10 @@ pub use from_json::*; pub use error::*; pub use bytes::*; pub use vector::*; -pub use numbers::*; pub use sha3::*; +pub use bigint::hash::*; +pub use bigint::uint::*; +pub use bigint::hash; #[macro_export] macro_rules! vec_into { diff --git a/util/src/crypto.rs b/util/src/crypto.rs index b92bb2bae..c9b05a97f 100644 --- a/util/src/crypto.rs +++ b/util/src/crypto.rs @@ -16,7 +16,8 @@ //! Ethcore crypto. -use numbers::*; +use bigint::uint::*; +use bigint::hash::*; use bytes::*; use secp256k1::{key, Secp256k1}; use rand::os::OsRng; @@ -174,7 +175,8 @@ impl KeyPair { /// EC functions #[cfg_attr(feature="dev", allow(similar_names))] pub mod ec { - use numbers::*; + use bigint::hash::*; + use bigint::uint::*; use standard::*; use crypto::*; use crypto::{self}; diff --git a/util/src/heapsizeof.rs b/util/src/heapsizeof.rs index feb679a0b..0719e0026 100644 --- a/util/src/heapsizeof.rs +++ b/util/src/heapsizeof.rs @@ -18,5 +18,4 @@ use hash::*; -known_heap_size!(0, H32, H64, H128, Address, H256, H264, H512, H520, H1024, H2048); diff --git a/util/src/lib.rs b/util/src/lib.rs index bcd9df971..7bdbb43ff 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -126,9 +126,7 @@ pub mod standard; pub mod from_json; #[macro_use] pub mod common; -pub mod numbers; pub mod error; -pub mod hash; pub mod bytes; pub mod rlp; pub mod misc; @@ -140,7 +138,6 @@ pub mod migration; pub mod overlaydb; pub mod journaldb; pub mod kvdb; -mod math; pub mod crypto; pub mod triehash; pub mod trie; @@ -164,7 +161,6 @@ pub use hashdb::*; pub use memorydb::*; pub use overlaydb::*; pub use journaldb::JournalDB; -pub use math::*; pub use crypto::*; pub use triehash::*; pub use trie::*; @@ -178,7 +174,6 @@ pub use timer::*; #[cfg(test)] mod tests { - use super::numbers::*; use std::str::FromStr; #[test] diff --git a/util/src/math.rs b/util/src/math.rs deleted file mode 100644 index afb7611e7..000000000 --- a/util/src/math.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015, 2016 Ethcore (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -//! Common math functions. - -/// Returns log2. -pub fn log2(x: usize) -> u32 { - if x <= 1 { - return 0; - } - - let n = x.leading_zeros(); - ::std::mem::size_of::() as u32 * 8 - n -} diff --git a/util/src/numbers.rs b/util/src/numbers.rs deleted file mode 100644 index b79338fc1..000000000 --- a/util/src/numbers.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2015, 2016 Ethcore (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -//! Utils number types. - -pub use hash::*; -pub use bigint::uint::*; From 17bfc113c1fe9df6b9252f61af4bdf771316d0c1 Mon Sep 17 00:00:00 2001 From: debris Date: Wed, 3 Aug 2016 16:29:36 +0200 Subject: [PATCH 2/8] removed unused code from util and unnecessary dependency of FixedHash --- util/src/bytes.rs | 289 ------------------------------------------ util/src/rlp/bytes.rs | 54 ++++++-- 2 files changed, 40 insertions(+), 303 deletions(-) diff --git a/util/src/bytes.rs b/util/src/bytes.rs index dfd21fd90..a3a546d7a 100644 --- a/util/src/bytes.rs +++ b/util/src/bytes.rs @@ -35,47 +35,6 @@ use std::fmt; use std::slice; use std::ops::{Deref, DerefMut}; -use hash::FixedHash; -use elastic_array::*; -use std::mem; -use std::cmp::Ordering; - -/// Vector like object -pub trait VecLike { - /// Add an element to the collection - fn vec_push(&mut self, value: T); - - /// Add a slice to the collection - fn vec_extend(&mut self, slice: &[T]); -} - -impl VecLike for Vec where T: Copy { - fn vec_push(&mut self, value: T) { - Vec::::push(self, value) - } - - fn vec_extend(&mut self, slice: &[T]) { - Vec::::extend_from_slice(self, slice) - } -} - -macro_rules! impl_veclike_for_elastic_array { - ($from: ident) => { - impl VecLike for $from where T: Copy { - fn vec_push(&mut self, value: T) { - $from::::push(self, value) - } - fn vec_extend(&mut self, slice: &[T]) { - $from::::append_slice(self, slice) - - } - } - } -} - -impl_veclike_for_elastic_array!(ElasticArray16); -impl_veclike_for_elastic_array!(ElasticArray32); -impl_veclike_for_elastic_array!(ElasticArray1024); /// Slie pretty print helper pub struct PrettySlice<'a> (&'a [u8]); @@ -230,213 +189,6 @@ impl Populatable for [T] where T: Sized { } } -#[derive(Debug)] -/// Bytes array deserialization error -pub enum FromBytesError { - /// Not enough bytes for the requested type - NotLongEnough, - /// Too many bytes for the requested type - TooLong, - /// Invalid marker for (enums) - UnknownMarker, -} - -/// Value that can be serialized from bytes array -pub trait FromRawBytes: Sized { - /// function that will instantiate and initialize object from slice - fn from_bytes(d: &[u8]) -> Result; -} - -impl FromRawBytes for T where T: FixedHash { - fn from_bytes(bytes: &[u8]) -> Result { - match bytes.len().cmp(&mem::size_of::()) { - Ordering::Less => return Err(FromBytesError::NotLongEnough), - Ordering::Greater => return Err(FromBytesError::TooLong), - Ordering::Equal => () - }; - - let mut res = T::zero(); - res.copy_raw(bytes); - Ok(res) - } -} - -#[macro_export] -macro_rules! sized_binary_map { - ($target_ty: ident) => { - impl FromRawBytes for $target_ty { - fn from_bytes(bytes: &[u8]) -> Result { - match bytes.len().cmp(&::std::mem::size_of::<$target_ty>()) { - ::std::cmp::Ordering::Less => return Err(FromBytesError::NotLongEnough), - ::std::cmp::Ordering::Greater => return Err(FromBytesError::TooLong), - ::std::cmp::Ordering::Equal => () - }; - let mut res: Self = 0; - res.copy_raw(bytes); - Ok(res) - } - } - impl ToBytesWithMap for $target_ty { - fn to_bytes_map(&self) -> Vec { - let sz = ::std::mem::size_of::<$target_ty>(); - let mut res = Vec::::with_capacity(sz); - - let ip: *const $target_ty = self; - let ptr: *const u8 = ip as *const _; - unsafe { - res.set_len(sz); - ::std::ptr::copy(ptr, res.as_mut_ptr(), sz); - } - res - } - } - } -} - -sized_binary_map!(u16); -sized_binary_map!(u32); -sized_binary_map!(u64); - -/// Value that can be serialized from variable-length byte array -pub trait FromRawBytesVariable: Sized { - /// Create value from slice - fn from_bytes_variable(bytes: &[u8]) -> Result; -} - -impl FromRawBytesVariable for T where T: FromRawBytes { - fn from_bytes_variable(bytes: &[u8]) -> Result { - match bytes.len().cmp(&mem::size_of::()) { - Ordering::Less => return Err(FromBytesError::NotLongEnough), - Ordering::Greater => return Err(FromBytesError::TooLong), - Ordering::Equal => () - }; - - T::from_bytes(bytes) - } -} - -impl FromRawBytesVariable for String { - fn from_bytes_variable(bytes: &[u8]) -> Result { - Ok(::std::str::from_utf8(bytes).unwrap().to_owned()) - } -} - -impl FromRawBytesVariable for Vec where T: FromRawBytes { - fn from_bytes_variable(bytes: &[u8]) -> Result { - let size_of_t = mem::size_of::(); - let length_in_chunks = bytes.len() / size_of_t; - - let mut result = Vec::with_capacity(length_in_chunks); - unsafe { result.set_len(length_in_chunks) }; - for i in 0..length_in_chunks { - *result.get_mut(i).unwrap() = try!(T::from_bytes( - &bytes[size_of_t * i..size_of_t * (i+1)])) - } - Ok(result) - } -} - -impl FromRawBytes for (V1, T2) where V1: FromRawBytesVariable, T2: FromRawBytes { - fn from_bytes(bytes: &[u8]) -> Result { - let header = 8usize; - let mut map: (u64, ) = (0,); - - if bytes.len() < header { return Err(FromBytesError::NotLongEnough); } - map.copy_raw(&bytes[0..header]); - - Ok(( - try!(V1::from_bytes_variable(&bytes[header..header + (map.0 as usize)])), - try!(T2::from_bytes(&bytes[header + (map.0 as usize)..bytes.len()])), - )) - } -} - -impl FromRawBytes for (V1, V2, T3) - where V1: FromRawBytesVariable, - V2: FromRawBytesVariable, - T3: FromRawBytes -{ - fn from_bytes(bytes: &[u8]) -> Result { - let header = 16usize; - let mut map: (u64, u64, ) = (0, 0,); - - if bytes.len() < header { return Err(FromBytesError::NotLongEnough); } - map.copy_raw(&bytes[0..header]); - - let map_1 = (header, header + map.0 as usize); - let map_2 = (map_1.1 as usize, map_1.1 as usize + map.1 as usize); - Ok(( - try!(V1::from_bytes_variable(&bytes[map_1.0..map_1.1])), - try!(V2::from_bytes_variable(&bytes[map_2.0..map_2.1])), - try!(T3::from_bytes(&bytes[map_2.1..bytes.len()])), - )) - } -} - -impl<'a, V1, X1, T2> ToBytesWithMap for (X1, &'a T2) where V1: ToBytesWithMap, X1: Deref, T2: ToBytesWithMap { - fn to_bytes_map(&self) -> Vec { - let header = 8usize; - let v1_size = mem::size_of::(); - let mut result = Vec::with_capacity(header + self.0.len() * v1_size + mem::size_of::()); - result.extend(((self.0.len() * v1_size) as u64).to_bytes_map()); - - for i in 0..self.0.len() { - result.extend(self.0[i].to_bytes_map()); - } - result.extend(self.1.to_bytes_map()); - - result - } - -} - -impl<'a, V1, X1, V2, X2, T3> ToBytesWithMap for (X1, X2, &'a T3) - where V1: ToBytesWithMap, X1: Deref, - V2: ToBytesWithMap, X2: Deref, - T3: ToBytesWithMap -{ - fn to_bytes_map(&self) -> Vec { - let header = 16usize; - let v1_size = mem::size_of::(); - let v2_size = mem::size_of::(); - let mut result = Vec::with_capacity( - header + - self.0.len() * v1_size + - self.1.len() * v2_size + - mem::size_of::() - ); - result.extend(((self.0.len() * v1_size) as u64).to_bytes_map()); - result.extend(((self.1.len() * v2_size) as u64).to_bytes_map()); - for i in 0..self.0.len() { - result.extend(self.0[i].to_bytes_map()); - } - for i in 0..self.1.len() { - result.extend(self.1[i].to_bytes_map()); - } - result.extend(self.2.to_bytes_map()); - - result - } -} - -impl FromRawBytesVariable for Vec { - fn from_bytes_variable(bytes: &[u8]) -> Result, FromBytesError> { - Ok(bytes.to_vec()) - } -} - -/// Value that serializes directly to variable-sized byte array and stores map -pub trait ToBytesWithMap { - /// serialize to variable-sized byte array and store map - fn to_bytes_map(&self) -> Vec; -} - -impl ToBytesWithMap for T where T: FixedHash { - fn to_bytes_map(&self) -> Vec { - self.as_slice().to_owned() - } -} - #[test] fn fax_raw() { let mut x = [255u8; 4]; @@ -488,44 +240,3 @@ fn populate_big_types() { h.copy_raw_from(&a); assert_eq!(h, h256_from_hex("ffffffffffffffffffffffffffffffffffffffff000000000000000000000069")); } - -#[test] -fn raw_bytes_from_tuple() { - type Tup = (Vec, u16); - - let tup: (&[u16], u16) = (&[1; 4], 10); - let bytes = vec![ - // map - 8u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, - // four 1u16 - 1u8, 0u8, - 1u8, 0u8, - 1u8, 0u8, - 1u8, 0u8, - // 10u16 - 10u8, 0u8]; - - let (v, x) = Tup::from_bytes(&bytes).unwrap(); - assert_eq!(tup, (&v[..], x)); - let tup_from = (v, x); - - let tup_to = (tup_from.0, &tup_from.1); - let bytes_to = tup_to.to_bytes_map(); - assert_eq!(bytes_to, bytes); -} - -#[test] -fn bytes_map_from_triple() { - let data: (&[u16], &[u32], u64) = (&[2; 6], &[6; 3], 12u64); - let bytes_map = (data.0, data.1, &data.2).to_bytes_map(); - assert_eq!(bytes_map, vec![ - // data map 2 x u64 - 12, 0, 0, 0, 0, 0, 0, 0, - 12, 0, 0, 0, 0, 0, 0, 0, - // vec![2u16; 6] - 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, - // vec![6u32; 3] - 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, - // 12u64 - 12, 0, 0, 0, 0, 0, 0, 0]); -} diff --git a/util/src/rlp/bytes.rs b/util/src/rlp/bytes.rs index 479fc7261..8d33f390d 100644 --- a/util/src/rlp/bytes.rs +++ b/util/src/rlp/bytes.rs @@ -22,7 +22,7 @@ use std::fmt; use std::cmp::Ordering; use std::error::Error as StdError; use bigint::uint::{Uint, U128, U256}; -use hash::FixedHash; +use hash::{H64, H128, Address, H256, H512, H520, H2048}; use elastic_array::*; /// Vector like object @@ -146,13 +146,25 @@ macro_rules! impl_uint_to_bytes { impl_uint_to_bytes!(U256); impl_uint_to_bytes!(U128); -impl ToBytes for T where T: FixedHash { - fn to_bytes>(&self, out: &mut V) { - out.vec_extend(self.as_slice()); +macro_rules! impl_hash_to_bytes { + ($name: ident) => { + impl ToBytes for $name { + fn to_bytes>(&self, out: &mut V) { + out.vec_extend(&self); + } + fn to_bytes_len(&self) -> usize { self.len() } + } } - fn to_bytes_len(&self) -> usize { self.as_slice().len() } } +impl_hash_to_bytes!(H64); +impl_hash_to_bytes!(H128); +impl_hash_to_bytes!(Address); +impl_hash_to_bytes!(H256); +impl_hash_to_bytes!(H512); +impl_hash_to_bytes!(H520); +impl_hash_to_bytes!(H2048); + /// Error returned when `FromBytes` conversation goes wrong #[derive(Debug, PartialEq, Eq)] pub enum FromBytesError { @@ -250,15 +262,29 @@ macro_rules! impl_uint_from_bytes { impl_uint_from_bytes!(U256, 32); impl_uint_from_bytes!(U128, 16); -impl FromBytes for T where T: FixedHash { - fn from_bytes(bytes: &[u8]) -> FromBytesResult { - match bytes.len().cmp(&T::len()) { - Ordering::Less => return Err(FromBytesError::DataIsTooShort), - Ordering::Greater => return Err(FromBytesError::DataIsTooLong), - Ordering::Equal => () - }; - - Ok(T::from_slice(bytes)) +macro_rules! impl_hash_from_bytes { + ($name: ident, $size: expr) => { + impl FromBytes for $name { + fn from_bytes(bytes: &[u8]) -> FromBytesResult<$name> { + match bytes.len().cmp(&$size) { + Ordering::Less => Err(FromBytesError::DataIsTooShort), + Ordering::Greater => Err(FromBytesError::DataIsTooLong), + Ordering::Equal => { + let mut t = [0u8; $size]; + t.copy_from_slice(bytes); + Ok($name(t)) + } + } + } + } } } +impl_hash_from_bytes!(H64, 8); +impl_hash_from_bytes!(H128, 16); +impl_hash_from_bytes!(Address, 20); +impl_hash_from_bytes!(H256, 32); +impl_hash_from_bytes!(H512, 64); +impl_hash_from_bytes!(H520, 65); +impl_hash_from_bytes!(H2048, 256); + From e8c451ac828b099cf6a6162068fe2e4950251112 Mon Sep 17 00:00:00 2001 From: debris Date: Wed, 3 Aug 2016 18:05:17 +0200 Subject: [PATCH 3/8] cleaning up hash reexports --- ethcore/src/blockchain/best_block.rs | 3 +- ethcore/src/blockchain/block_info.rs | 2 +- ethcore/src/blockchain/generator/generator.rs | 4 +-- ethcore/src/blockchain/import_route.rs | 5 ++-- ethcore/src/blockchain/update.rs | 2 +- ethcore/src/builtin.rs | 2 +- ethcore/src/client/chain_notify.rs | 4 +-- ethcore/src/client/client.rs | 8 +++--- ethcore/src/client/traits.rs | 5 +--- ethcore/src/env_info.rs | 12 ++++---- ethcore/src/ethereum/ethash.rs | 2 +- ethcore/src/ethereum/mod.rs | 12 ++++---- ethcore/src/miner/transaction_queue.rs | 6 ++-- ethcore/src/snapshot/account.rs | 7 ++--- ethcore/src/snapshot/block.rs | 5 ++-- ethcore/src/spec/genesis.rs | 3 +- ethcore/src/types/account_diff.rs | 8 ++---- ethcore/src/types/blockchain_info.rs | 6 ++-- ethcore/src/types/executed.rs | 3 +- ethcore/src/types/log_entry.rs | 11 +++----- ethcore/src/types/receipt.rs | 8 +++--- ethcore/src/types/state_diff.rs | 9 +++--- ethcore/src/types/trace_types/filter.rs | 9 +++--- ethcore/src/types/transaction.rs | 23 +++++++-------- ethcore/src/types/tree_route.rs | 4 +-- ipc/rpc/src/binary.rs | 2 +- json/src/spec/account.rs | 2 +- json/src/uint.rs | 4 +-- json/src/vm/call.rs | 2 +- rpc/src/v1/impls/eth.rs | 2 +- rpc/src/v1/impls/mod.rs | 6 ++-- rpc/src/v1/tests/mocked/eth.rs | 2 +- rpc/src/v1/tests/mocked/eth_signing.rs | 3 +- rpc/src/v1/tests/mocked/ethcore_set.rs | 2 +- rpc/src/v1/tests/mocked/net.rs | 3 +- rpc/src/v1/tests/mocked/personal.rs | 2 +- rpc/src/v1/tests/mocked/personal_signer.rs | 2 +- util/benches/bigint.rs | 2 +- util/benches/rlp.rs | 2 +- util/src/crypto.rs | 28 +++++++++---------- util/src/heapsizeof.rs | 21 -------------- util/src/lib.rs | 2 +- 42 files changed, 102 insertions(+), 148 deletions(-) delete mode 100644 util/src/heapsizeof.rs diff --git a/ethcore/src/blockchain/best_block.rs b/ethcore/src/blockchain/best_block.rs index aa1e1854e..0cea6190c 100644 --- a/ethcore/src/blockchain/best_block.rs +++ b/ethcore/src/blockchain/best_block.rs @@ -14,8 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::bytes::Bytes; -use util::numbers::{U256,H256}; +use util::{Bytes, U256, H256}; use header::BlockNumber; /// Best block info. diff --git a/ethcore/src/blockchain/block_info.rs b/ethcore/src/blockchain/block_info.rs index a7827b043..31f93232b 100644 --- a/ethcore/src/blockchain/block_info.rs +++ b/ethcore/src/blockchain/block_info.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::numbers::{U256,H256}; +use util::{U256,H256}; use header::BlockNumber; /// Brief info about inserted block. diff --git a/ethcore/src/blockchain/generator/generator.rs b/ethcore/src/blockchain/generator/generator.rs index 88c9577e2..07ce7242b 100644 --- a/ethcore/src/blockchain/generator/generator.rs +++ b/ethcore/src/blockchain/generator/generator.rs @@ -14,9 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::hash::H2048; -use util::numbers::U256; -use util::bytes::Bytes; +use util::{U256, H2048, Bytes}; use header::BlockNumber; use super::fork::Fork; use super::bloom::Bloom; diff --git a/ethcore/src/blockchain/import_route.rs b/ethcore/src/blockchain/import_route.rs index 17cbd8caf..02469bb90 100644 --- a/ethcore/src/blockchain/import_route.rs +++ b/ethcore/src/blockchain/import_route.rs @@ -16,7 +16,7 @@ //! Import route. -use util::hash::H256; +use util::H256; use blockchain::block_info::{BlockInfo, BlockLocation}; /// Import route for newly inserted block. @@ -67,8 +67,7 @@ impl From for ImportRoute { #[cfg(test)] mod tests { - use util::hash::H256; - use util::numbers::U256; + use util::{U256, H256}; use blockchain::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData}; use blockchain::ImportRoute; diff --git a/ethcore/src/blockchain/update.rs b/ethcore/src/blockchain/update.rs index 962365338..24d0644e8 100644 --- a/ethcore/src/blockchain/update.rs +++ b/ethcore/src/blockchain/update.rs @@ -1,5 +1,5 @@ use std::collections::HashMap; -use util::numbers::H256; +use util::H256; use header::BlockNumber; use blockchain::block_info::BlockInfo; use blooms::BloomGroup; diff --git a/ethcore/src/builtin.rs b/ethcore/src/builtin.rs index 3c15dd1c2..891f321a1 100644 --- a/ethcore/src/builtin.rs +++ b/ethcore/src/builtin.rs @@ -102,7 +102,7 @@ pub fn new_builtin_exec(name: &str) -> Box { let mut it: InType = InType { hash: H256::new(), v: H256::new(), r: H256::new(), s: H256::new() }; it.copy_raw(input); if it.v == H256::from(&U256::from(27)) || it.v == H256::from(&U256::from(28)) { - let s = Signature::from_rsv(&it.r, &it.s, it.v[31] - 27); + let s = signature_from_rsv(&it.r, &it.s, it.v[31] - 27); if ec::is_valid(&s) { if let Ok(p) = ec::recover(&s, &it.hash) { let r = p.as_slice().sha3(); diff --git a/ethcore/src/client/chain_notify.rs b/ethcore/src/client/chain_notify.rs index 1d6b51803..3269d40b8 100644 --- a/ethcore/src/client/chain_notify.rs +++ b/ethcore/src/client/chain_notify.rs @@ -14,10 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::numbers::*; -use ipc::{IpcConfig, BinaryConvertError}; use std::collections::VecDeque; use std::mem; +use ipc::{IpcConfig, BinaryConvertError}; +use util::H256; /// Represents what has to be handled by actor listening to chain events #[derive(Ipc)] diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 7c66cc5d3..5408d8213 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -27,7 +27,7 @@ use time::precise_time_ns; use util::{journaldb, rlp, Bytes, View, PerfTimer, Itertools, Mutex, RwLock}; use util::journaldb::JournalDB; use util::rlp::{UntrustedRlp}; -use util::numbers::*; +use util::{U256, H256, Address, H2048, Uint}; use util::panics::*; use util::io::*; use util::sha3::*; @@ -256,7 +256,7 @@ impl Client { } } let mut last_hashes = LastHashes::new(); - last_hashes.resize(256, H256::new()); + last_hashes.resize(256, Default::default()); last_hashes[0] = parent_hash; for i in 0..255 { match self.chain.block_details(&last_hashes[i]) { @@ -648,7 +648,7 @@ impl BlockChainClient for Client { timestamp: view.timestamp(), difficulty: view.difficulty(), last_hashes: last_hashes, - gas_used: U256::zero(), + gas_used: Default::default(), gas_limit: U256::max_value(), }; // that's just a copy of the state. @@ -923,7 +923,7 @@ impl BlockChainClient for Client { entry: log, block_hash: hash.clone(), block_number: number, - transaction_hash: hashes.get(index).cloned().unwrap_or_else(H256::new), + transaction_hash: hashes.get(index).cloned().unwrap_or_else(Default::default), transaction_index: index, log_index: log_index + i }) diff --git a/ethcore/src/client/traits.rs b/ethcore/src/client/traits.rs index 348b90c90..859a584a7 100644 --- a/ethcore/src/client/traits.rs +++ b/ethcore/src/client/traits.rs @@ -14,10 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::bytes::Bytes; -use util::hash::{Address, H256, H2048}; -use util::numbers::U256; -use util::Itertools; +use util::{U256, Address, H256, H2048, Bytes, Itertools}; use blockchain::TreeRoute; use block_queue::BlockQueueInfo; use block::{OpenBlock, SealedBlock}; diff --git a/ethcore/src/env_info.rs b/ethcore/src/env_info.rs index e6d15cee6..0a6a19005 100644 --- a/ethcore/src/env_info.rs +++ b/ethcore/src/env_info.rs @@ -14,7 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::*; +use std::cmp; +use util::{U256, Address, H256, Hashable}; use header::BlockNumber; use ethjson; @@ -45,7 +46,7 @@ impl Default for EnvInfo { fn default() -> Self { EnvInfo { number: 0, - author: Address::new(), + author: Default::default(), timestamp: 0, difficulty: 0.into(), gas_limit: 0.into(), @@ -65,7 +66,7 @@ impl From for EnvInfo { gas_limit: e.gas_limit.into(), timestamp: e.timestamp.into(), last_hashes: (1..cmp::min(number + 1, 257)).map(|i| format!("{}", number - i).as_bytes().sha3()).collect(), - gas_used: U256::zero(), + gas_used: Default::default(), } } } @@ -74,10 +75,9 @@ impl From for EnvInfo { mod tests { extern crate rustc_serialize; - use super::*; - use util::hash::*; - use util::numbers::U256; use std::str::FromStr; + use super::*; + use util::{U256, Address}; use ethjson; #[test] diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 2a0f84c23..20dffbd79 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -372,7 +372,7 @@ mod tests { let vm_factory = Default::default(); let mut b = OpenBlock::new(engine.deref(), &vm_factory, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![]).unwrap(); let mut uncle = Header::new(); - let uncle_author = address_from_hex("ef2d6d194084c2de36e0dabfce45d046b37d1106"); + let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".parse().unwrap(); uncle.author = uncle_author.clone(); b.push_uncle(uncle).unwrap(); diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index f48a433d7..f157cb04e 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -69,12 +69,12 @@ mod tests { let mut db = db_result.take(); spec.ensure_db_good(db.as_hashdb_mut()); let s = State::from_existing(db, genesis_header.state_root.clone(), engine.account_start_nonce(), Default::default()).unwrap(); - assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64)); - assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000002")), U256::from(1u64)); - assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000003")), U256::from(1u64)); - assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000004")), U256::from(1u64)); - assert_eq!(s.balance(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")), U256::from(1u64) << 200); - assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000000")), U256::from(0u64)); + assert_eq!(s.balance(&"0000000000000000000000000000000000000001".parse().unwrap()), U256::from(1u64)); + assert_eq!(s.balance(&"0000000000000000000000000000000000000002".parse().unwrap()), U256::from(1u64)); + assert_eq!(s.balance(&"0000000000000000000000000000000000000003".parse().unwrap()), U256::from(1u64)); + assert_eq!(s.balance(&"0000000000000000000000000000000000000004".parse().unwrap()), U256::from(1u64)); + assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".parse().unwrap()), U256::from(1u64) << 200); + assert_eq!(s.balance(&"0000000000000000000000000000000000000000".parse().unwrap()), U256::from(0u64)); } #[test] diff --git a/ethcore/src/miner/transaction_queue.rs b/ethcore/src/miner/transaction_queue.rs index a1b56aaca..eb3587705 100644 --- a/ethcore/src/miner/transaction_queue.rs +++ b/ethcore/src/miner/transaction_queue.rs @@ -29,8 +29,7 @@ //! extern crate rustc_serialize; //! //! use util::crypto::KeyPair; -//! use util::hash::Address; -//! use util::numbers::{Uint, U256}; +//! use util::{Uint, U256, Address}; //! use ethcore::miner::{TransactionQueue, AccountDetails, TransactionOrigin}; //! use ethcore::transaction::*; //! use rustc_serialize::hex::FromHex; @@ -85,8 +84,7 @@ use std::default::Default; use std::cmp::{Ordering}; use std::cmp; use std::collections::{HashMap, BTreeSet}; -use util::numbers::{Uint, U256}; -use util::hash::{Address, H256}; +use util::{Address, H256, Uint, U256}; use util::table::Table; use transaction::*; use error::{Error, TransactionError}; diff --git a/ethcore/src/snapshot/account.rs b/ethcore/src/snapshot/account.rs index 2329b0e34..039de7877 100644 --- a/ethcore/src/snapshot/account.rs +++ b/ethcore/src/snapshot/account.rs @@ -18,10 +18,7 @@ use account_db::{AccountDB, AccountDBMut}; use error::Error; - -use util::{Bytes, HashDB, SHA3_EMPTY, TrieDB}; -use util::hash::{FixedHash, H256}; -use util::numbers::U256; +use util::{U256, FixedHash, H256, Bytes, HashDB, SHA3_EMPTY, TrieDB}; use util::rlp::{DecoderError, Rlp, RlpStream, Stream, UntrustedRlp, View}; // An alternate account structure from ::account::Account. @@ -208,4 +205,4 @@ mod tests { let fat_rlp = UntrustedRlp::new(&fat_rlp); assert_eq!(Account::from_fat_rlp(&mut AccountDBMut::new(db.as_hashdb_mut(), &addr), fat_rlp).unwrap(), account); } -} \ No newline at end of file +} diff --git a/ethcore/src/snapshot/block.rs b/ethcore/src/snapshot/block.rs index fd034d97b..c213c8e03 100644 --- a/ethcore/src/snapshot/block.rs +++ b/ethcore/src/snapshot/block.rs @@ -145,8 +145,7 @@ mod tests { use super::AbridgedBlock; use types::transaction::{Action, Transaction}; - use util::numbers::U256; - use util::hash::{Address, H256, FixedHash}; + use util::{Address, H256, FixedHash, U256}; use util::{Bytes, RlpStream, Stream}; fn encode_block(b: &Block) -> Bytes { @@ -208,4 +207,4 @@ mod tests { let abridged = AbridgedBlock::from_block_view(&BlockView::new(&encoded[..])); assert_eq!(abridged.to_block(H256::new(), 0).unwrap(), b); } -} \ No newline at end of file +} diff --git a/ethcore/src/spec/genesis.rs b/ethcore/src/spec/genesis.rs index b6c214fd6..8f472e996 100644 --- a/ethcore/src/spec/genesis.rs +++ b/ethcore/src/spec/genesis.rs @@ -15,8 +15,7 @@ // along with Parity. If not, see . use util::rlp::*; -use util::numbers::{Uint, U256}; -use util::hash::{Address, H256}; +use util::{Address, H256, Uint, U256}; use ethjson; use super::seal::Seal; diff --git a/ethcore/src/types/account_diff.rs b/ethcore/src/types/account_diff.rs index 5071c2f7e..f6b368dae 100644 --- a/ethcore/src/types/account_diff.rs +++ b/ethcore/src/types/account_diff.rs @@ -16,13 +16,11 @@ //! Diff between two accounts. -use util::numbers::*; use std::cmp::*; -use std::fmt; -use ipc::binary::{BinaryConvertError, BinaryConvertable}; -use util::Bytes; +use std::{fmt, mem}; use std::collections::{VecDeque, BTreeMap}; -use std::mem; +use util::{U256, H256, Uint, Bytes}; +use ipc::binary::{BinaryConvertError, BinaryConvertable}; #[derive(Debug, PartialEq, Eq, Clone, Binary)] /// Diff type for specifying a change (or not). diff --git a/ethcore/src/types/blockchain_info.rs b/ethcore/src/types/blockchain_info.rs index 4e8634dba..713a55843 100644 --- a/ethcore/src/types/blockchain_info.rs +++ b/ethcore/src/types/blockchain_info.rs @@ -16,11 +16,11 @@ //! Blockhain info type definition -use util::numbers::*; -use header::BlockNumber; -use ipc::binary::BinaryConvertError; use std::mem; use std::collections::VecDeque; +use util::{U256, H256}; +use ipc::binary::BinaryConvertError; +use header::BlockNumber; /// Information about the blockchain gathered together. #[derive(Debug, Binary)] diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index efc4da9e2..6d7db6763 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -16,8 +16,7 @@ //! Transaction execution format module. -use util::numbers::*; -use util::Bytes; +use util::{Bytes, U256, Address, U512}; use util::rlp::*; use trace::{VMTrace, FlatTrace}; use types::log_entry::LogEntry; diff --git a/ethcore/src/types/log_entry.rs b/ethcore/src/types/log_entry.rs index 7d8dccc6c..3edbb5d0b 100644 --- a/ethcore/src/types/log_entry.rs +++ b/ethcore/src/types/log_entry.rs @@ -16,18 +16,15 @@ //! Log entry type definition. -use util::numbers::*; +use std::mem; use std::ops::Deref; +use std::collections::VecDeque; +use util::{H256, Address, Bytes, HeapSizeOf, FixedHash, Hashable}; use util::rlp::*; -use util::Bytes; -use util::HeapSizeOf; -use util::sha3::*; +use ipc::binary::BinaryConvertError; use basic_types::LogBloom; use header::BlockNumber; use ethjson; -use ipc::binary::BinaryConvertError; -use std::mem; -use std::collections::VecDeque; /// A record of execution for a `LOG` operation. #[derive(Default, Debug, Clone, PartialEq, Eq, Binary)] diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index 78216eb16..2550b532e 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -16,15 +16,15 @@ //! Receipt -use util::numbers::*; +use std::mem; +use std::collections::VecDeque; +use util::{H256, U256, Address}; use util::rlp::*; use util::HeapSizeOf; use basic_types::LogBloom; use header::BlockNumber; use log_entry::{LogEntry, LocalizedLogEntry}; use ipc::binary::BinaryConvertError; -use std::mem; -use std::collections::VecDeque; /// Information describing execution of a transaction. #[derive(Default, Debug, Clone, Binary)] @@ -45,7 +45,7 @@ impl Receipt { Receipt { state_root: state_root, gas_used: gas_used, - log_bloom: logs.iter().fold(LogBloom::new(), |mut b, l| { b = &b | &l.bloom(); b }), //TODO: use |= operator + log_bloom: logs.iter().fold(Default::default(), |mut b, l| { b = &b | &l.bloom(); b }), //TODO: use |= operator logs: logs, } } diff --git a/ethcore/src/types/state_diff.rs b/ethcore/src/types/state_diff.rs index e341b8436..1f3563804 100644 --- a/ethcore/src/types/state_diff.rs +++ b/ethcore/src/types/state_diff.rs @@ -16,13 +16,12 @@ //! State diff module. -use util::numbers::*; -use account_diff::*; -use ipc::binary::BinaryConvertError; -use std::mem; -use std::fmt; +use std::{mem, fmt}; use std::ops::*; use std::collections::{VecDeque, BTreeMap}; +use util::Address; +use account_diff::*; +use ipc::binary::BinaryConvertError; #[derive(Debug, PartialEq, Eq, Clone, Binary)] /// Expression for the delta between two system states. Encoded the diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index 8b9357cac..3f7e727be 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -17,6 +17,8 @@ //! Trace filters type definitions use std::ops::Range; +use std::mem; +use std::collections::VecDeque; use bloomchain::{Filter as BloomFilter, Bloom, Number}; use util::{Address, FixedHash}; use util::sha3::Hashable; @@ -24,8 +26,6 @@ use basic_types::LogBloom; use trace::flat::FlatTrace; use types::trace_types::trace::{Action, Res}; use ipc::binary::BinaryConvertError; -use std::mem; -use std::collections::VecDeque; /// Addresses filter. /// @@ -55,7 +55,7 @@ impl AddressesFilter { /// Returns blooms of this addresses filter. pub fn blooms(&self) -> Vec { match self.list.is_empty() { - true => vec![LogBloom::new()], + true => vec![Default::default()], false => self.list.iter() .map(|address| LogBloom::from_bloomed(&address.sha3())) .collect(), @@ -142,7 +142,6 @@ mod tests { use trace::trace::{Action, Call, Res, Create, CreateResult, Suicide}; use trace::flat::FlatTrace; use trace::{Filter, AddressesFilter}; - use basic_types::LogBloom; use types::executed::CallType; #[test] @@ -154,7 +153,7 @@ mod tests { }; let blooms = filter.bloom_possibilities(); - assert_eq!(blooms, vec![LogBloom::new()]); + assert_eq!(blooms, vec![Default::default()]); } #[test] diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index ebb82c528..3aa24380f 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -16,19 +16,20 @@ //! Transaction data structure. -use util::numbers::*; +use std::mem; +use std::collections::VecDeque; +use util::{H256, Address, U256, H520}; use std::ops::Deref; use util::rlp::*; use util::sha3::*; use util::{UtilError, CryptoError, Bytes, Signature, Secret, ec}; +use util::crypto::{signature_from_rsv, signature_to_rsv}; use std::cell::*; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; use ipc::binary::BinaryConvertError; -use std::mem; -use std::collections::VecDeque; #[derive(Debug, Clone, PartialEq, Eq, Binary)] /// Transaction action type. @@ -146,7 +147,7 @@ impl Transaction { /// Signs the transaction with signature. pub fn with_signature(self, sig: H520) -> SignedTransaction { - let (r, s, v) = sig.to_rsv(); + let (r, s, v) = signature_to_rsv(&sig); SignedTransaction { unsigned: self, r: r, @@ -162,8 +163,8 @@ impl Transaction { pub fn invalid_sign(self) -> SignedTransaction { SignedTransaction { unsigned: self, - r: U256::zero(), - s: U256::zero(), + r: Default::default(), + s: Default::default(), v: 0, hash: Cell::new(None), sender: Cell::new(None), @@ -174,8 +175,8 @@ impl Transaction { pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { unsigned: self, - r: U256::zero(), - s: U256::zero(), + r: Default::default(), + s: Default::default(), v: 0, hash: Cell::new(None), sender: Cell::new(Some(from)), @@ -290,7 +291,7 @@ impl SignedTransaction { pub fn standard_v(&self) -> u8 { match self.v { 27 => 0, 28 => 1, _ => 4 } } /// Construct a signature object from the sig. - pub fn signature(&self) -> Signature { Signature::from_rsv(&From::from(&self.r), &From::from(&self.s), self.standard_v()) } + pub fn signature(&self) -> Signature { signature_from_rsv(&From::from(&self.r), &From::from(&self.s), self.standard_v()) } /// Checks whether the signature has a low 's' value. pub fn check_low_s(&self) -> Result<(), Error> { @@ -360,10 +361,10 @@ fn sender_test() { assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { - assert_eq!(*to, address_from_hex("095e7baea6a6c7c4c2dfeb977efac326af552d87")); + assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".parse().unwrap()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); - assert_eq!(t.sender().unwrap(), address_from_hex("0f65fe9276bc9a24ae7083ae28e2660ef72df99e")); + assert_eq!(t.sender().unwrap(), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".parse().unwrap()); } #[test] diff --git a/ethcore/src/types/tree_route.rs b/ethcore/src/types/tree_route.rs index 37413be57..7d2da78b8 100644 --- a/ethcore/src/types/tree_route.rs +++ b/ethcore/src/types/tree_route.rs @@ -16,10 +16,10 @@ //! Tree route info type definition -use util::numbers::H256; -use ipc::BinaryConvertError; use std::collections::VecDeque; use std::mem; +use ipc::BinaryConvertError; +use util::H256; /// Represents a tree route between `from` block and `to` block: #[derive(Debug, Binary)] diff --git a/ipc/rpc/src/binary.rs b/ipc/rpc/src/binary.rs index 81cd8cf7f..3ef2785d6 100644 --- a/ipc/rpc/src/binary.rs +++ b/ipc/rpc/src/binary.rs @@ -17,7 +17,7 @@ //! Binary representation of types use util::bytes::Populatable; -use util::numbers::{U256, U512, H256, H2048, Address}; +use util::{U256, U512, H256, H2048, Address}; use std::mem; use std::collections::{VecDeque, BTreeMap}; use std::ops::Range; diff --git a/json/src/spec/account.rs b/json/src/spec/account.rs index 3487906ae..eafb60931 100644 --- a/json/src/spec/account.rs +++ b/json/src/spec/account.rs @@ -44,7 +44,7 @@ impl Account { mod tests { use serde_json; use spec::account::Account; - use util::numbers::U256; + use util::U256; use uint::Uint; use bytes::Bytes; diff --git a/json/src/uint.rs b/json/src/uint.rs index e77001461..e086f98c0 100644 --- a/json/src/uint.rs +++ b/json/src/uint.rs @@ -19,7 +19,7 @@ use std::str::FromStr; use serde::{Deserialize, Deserializer, Error}; use serde::de::Visitor; -use util::numbers::{U256, Uint as U}; +use util::{U256, Uint as U}; /// Lenient uint json deserialization for test json files. #[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] @@ -88,7 +88,7 @@ impl Visitor for UintVisitor { #[cfg(test)] mod test { use serde_json; - use util::numbers::U256; + use util::U256; use uint::Uint; #[test] diff --git a/json/src/vm/call.rs b/json/src/vm/call.rs index 1947fd25c..855853c40 100644 --- a/json/src/vm/call.rs +++ b/json/src/vm/call.rs @@ -39,7 +39,7 @@ pub struct Call { mod tests { use serde_json; use vm::Call; - use util::numbers::U256; + use util::U256; use uint::Uint; use util::hash::Address as Hash160; use hash::Address; diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index c704650a3..37de40900 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -27,7 +27,7 @@ use std::ops::Deref; use ethsync::{SyncProvider, SyncState}; use ethcore::miner::{MinerService, ExternalMinerService}; use jsonrpc_core::*; -use util::numbers::*; +use util::{H256, Address, FixedHash, U256, H64, Uint}; use util::sha3::*; use util::rlp::{encode, decode, UntrustedRlp, View}; use util::{FromHex, Mutex}; diff --git a/rpc/src/v1/impls/mod.rs b/rpc/src/v1/impls/mod.rs index a9dddf843..94aba32e5 100644 --- a/rpc/src/v1/impls/mod.rs +++ b/rpc/src/v1/impls/mod.rs @@ -60,7 +60,7 @@ use ethcore::miner::MinerService; use ethcore::client::MiningBlockChainClient; use ethcore::transaction::{Action, SignedTransaction, Transaction}; use ethcore::account_provider::{AccountProvider, Error as AccountError}; -use util::numbers::*; +use util::{U256, H256, Address}; use util::rlp::encode; use util::bytes::ToPretty; use jsonrpc_core::{Error, ErrorCode, Value, to_value}; @@ -100,13 +100,13 @@ fn prepare_transaction(client: &C, miner: &M, request: TransactionRequest) nonce: request.nonce .or_else(|| miner .last_nonce(&request.from) - .map(|nonce| nonce + U256::one())) + .map(|nonce| nonce + 1.into())) .unwrap_or_else(|| client.latest_nonce(&request.from)), action: request.to.map_or(Action::Create, Action::Call), gas: request.gas.unwrap_or_else(|| miner.sensible_gas_limit()), gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(client, miner)), - value: request.value.unwrap_or_else(U256::zero), + value: request.value.unwrap_or_else(Default::default), data: request.data.map_or_else(Vec::new, |b| b.to_vec()), } } diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index 9e819c1b0..dc95c078e 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use std::time::{Instant, Duration}; use jsonrpc_core::IoHandler; use util::hash::{Address, H256, FixedHash}; -use util::numbers::{Uint, U256}; +use util::{Uint, U256}; use util::Mutex; use ethcore::account_provider::AccountProvider; use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionID}; diff --git a/rpc/src/v1/tests/mocked/eth_signing.rs b/rpc/src/v1/tests/mocked/eth_signing.rs index 69a21cab5..767646576 100644 --- a/rpc/src/v1/tests/mocked/eth_signing.rs +++ b/rpc/src/v1/tests/mocked/eth_signing.rs @@ -22,8 +22,7 @@ use v1::impls::EthSigningQueueClient; use v1::traits::EthSigning; use v1::helpers::{ConfirmationsQueue, SigningQueue}; use v1::tests::helpers::TestMinerService; -use util::{Address, FixedHash}; -use util::numbers::{Uint, U256, H256}; +use util::{Address, FixedHash, Uint, U256, H256}; use ethcore::account_provider::AccountProvider; use ethcore::client::TestBlockChainClient; use ethcore::transaction::{Transaction, Action}; diff --git a/rpc/src/v1/tests/mocked/ethcore_set.rs b/rpc/src/v1/tests/mocked/ethcore_set.rs index 853b7de30..2582b85b7 100644 --- a/rpc/src/v1/tests/mocked/ethcore_set.rs +++ b/rpc/src/v1/tests/mocked/ethcore_set.rs @@ -21,7 +21,7 @@ use v1::{EthcoreSet, EthcoreSetClient}; use ethcore::miner::MinerService; use ethcore::client::TestBlockChainClient; use v1::tests::helpers::TestMinerService; -use util::numbers::*; +use util::{U256, Address}; use rustc_serialize::hex::FromHex; use super::manage_network::TestManageNetwork; use ethsync::ManageNetwork; diff --git a/rpc/src/v1/tests/mocked/net.rs b/rpc/src/v1/tests/mocked/net.rs index 036ced168..836246686 100644 --- a/rpc/src/v1/tests/mocked/net.rs +++ b/rpc/src/v1/tests/mocked/net.rs @@ -18,11 +18,10 @@ use std::sync::Arc; use jsonrpc_core::IoHandler; use v1::{Net, NetClient}; use v1::tests::helpers::{Config, TestSyncProvider}; -use util::numbers::*; fn sync_provider() -> Arc { Arc::new(TestSyncProvider::new(Config { - network_id: U256::from(3), + network_id: 3.into(), num_peers: 120, })) } diff --git a/rpc/src/v1/tests/mocked/personal.rs b/rpc/src/v1/tests/mocked/personal.rs index 290a63c63..4c911d857 100644 --- a/rpc/src/v1/tests/mocked/personal.rs +++ b/rpc/src/v1/tests/mocked/personal.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use std::str::FromStr; use jsonrpc_core::IoHandler; -use util::numbers::*; +use util::{U256, Uint, Address}; use ethcore::account_provider::AccountProvider; use v1::{PersonalClient, Personal}; use v1::tests::helpers::TestMinerService; diff --git a/rpc/src/v1/tests/mocked/personal_signer.rs b/rpc/src/v1/tests/mocked/personal_signer.rs index b0d3ec735..9410ab84e 100644 --- a/rpc/src/v1/tests/mocked/personal_signer.rs +++ b/rpc/src/v1/tests/mocked/personal_signer.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use std::str::FromStr; use jsonrpc_core::IoHandler; -use util::numbers::*; +use util::{U256, Uint, Address}; use ethcore::account_provider::AccountProvider; use ethcore::client::TestBlockChainClient; use ethcore::transaction::{Transaction, Action}; diff --git a/util/benches/bigint.rs b/util/benches/bigint.rs index 3f4164d18..deba13bb4 100644 --- a/util/benches/bigint.rs +++ b/util/benches/bigint.rs @@ -28,7 +28,7 @@ extern crate ethcore_util; extern crate rand; use test::{Bencher, black_box}; -use ethcore_util::numbers::*; +use ethcore_util::U256; #[bench] fn u256_add(b: &mut Bencher) { diff --git a/util/benches/rlp.rs b/util/benches/rlp.rs index 4a983f369..c489afff7 100644 --- a/util/benches/rlp.rs +++ b/util/benches/rlp.rs @@ -28,7 +28,7 @@ extern crate ethcore_util; use test::Bencher; use std::str::FromStr; use ethcore_util::rlp::*; -use ethcore_util::numbers::U256; +use ethcore_util::U256; #[bench] fn bench_stream_u64_value(b: &mut Bencher) { diff --git a/util/src/crypto.rs b/util/src/crypto.rs index 9943f872f..67f370ba6 100644 --- a/util/src/crypto.rs +++ b/util/src/crypto.rs @@ -36,21 +36,19 @@ lazy_static! { static ref SECP256K1: Secp256k1 = Secp256k1::new(); } -impl Signature { - /// Create a new signature from the R, S and V componenets. - pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Signature { - let mut ret: Signature = Signature::new(); - (&mut ret[0..32]).copy_from_slice(r); - (&mut ret[32..64]).copy_from_slice(s); +/// Create a new signature from the R, S and V componenets. +pub fn signature_from_rsv(r: &H256, s: &H256, v: u8) -> Signature { + let mut ret: Signature = Signature::new(); + (&mut ret[0..32]).copy_from_slice(r); + (&mut ret[32..64]).copy_from_slice(s); - ret[64] = v; - ret - } + ret[64] = v; + ret +} - /// Convert transaction to R, S and V components. - pub fn to_rsv(&self) -> (U256, U256, u8) { - (U256::from(&self.as_slice()[0..32]), U256::from(&self.as_slice()[32..64]), self[64]) - } +/// Convert transaction to R, S and V components. +pub fn signature_to_rsv(s: &Signature) -> (U256, U256, u8) { + (U256::from(&s.as_slice()[0..32]), U256::from(&s.as_slice()[32..64]), s[64]) } #[derive(Debug)] @@ -206,10 +204,10 @@ pub mod ec { signature.clone_from_slice(&data); signature[64] = rec_id.to_i32() as u8; - let (_, s, v) = signature.to_rsv(); + let (_, s, v) = signature_to_rsv(&signature); let secp256k1n = U256::from_str("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141").unwrap(); if !is_low_s(&s) { - signature = super::Signature::from_rsv(&H256::from_slice(&signature[0..32]), &H256::from(secp256k1n - s), v ^ 1); + signature = super::signature_from_rsv(&H256::from_slice(&signature[0..32]), &H256::from(secp256k1n - s), v ^ 1); } Ok(signature) } diff --git a/util/src/heapsizeof.rs b/util/src/heapsizeof.rs deleted file mode 100644 index 0719e0026..000000000 --- a/util/src/heapsizeof.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2015, 2016 Ethcore (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -//! Calculates heapsize of util types. - -use hash::*; - - diff --git a/util/src/lib.rs b/util/src/lib.rs index e56f3fe92..80817d721 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -139,7 +139,6 @@ pub mod triehash; pub mod trie; pub mod nibbleslice; pub mod nibblevec; -mod heapsizeof; pub mod semantic_version; pub mod io; pub mod network; @@ -171,6 +170,7 @@ pub use timer::*; #[cfg(test)] mod tests { use std::str::FromStr; + use {U256, H256, Uint}; #[test] fn u256_multi_muls() { From 40515244622d1e2060a58f28db02a269e2651be0 Mon Sep 17 00:00:00 2001 From: debris Date: Thu, 4 Aug 2016 08:52:31 +0200 Subject: [PATCH 4/8] improved naming --- ethcore/src/client/client.rs | 8 ++++---- ethcore/src/env_info.rs | 2 +- ethcore/src/miner/transaction_queue.rs | 3 +-- ethcore/src/types/receipt.rs | 2 +- ethcore/src/types/trace_types/filter.rs | 2 +- ethcore/src/types/transaction.rs | 8 ++++---- rpc/src/v1/impls/mod.rs | 2 +- 7 files changed, 13 insertions(+), 14 deletions(-) diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 7673bb850..be96c8916 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -256,7 +256,7 @@ impl Client { } } let mut last_hashes = LastHashes::new(); - last_hashes.resize(256, Default::default()); + last_hashes.resize(256, H256::default()); last_hashes[0] = parent_hash; for i in 0..255 { match self.chain.block_details(&last_hashes[i]) { @@ -649,7 +649,7 @@ impl BlockChainClient for Client { timestamp: view.timestamp(), difficulty: view.difficulty(), last_hashes: last_hashes, - gas_used: Default::default(), + gas_used: U256::zero(), gas_limit: U256::max_value(), }; // that's just a copy of the state. @@ -696,7 +696,7 @@ impl BlockChainClient for Client { timestamp: view.timestamp(), difficulty: view.difficulty(), last_hashes: last_hashes, - gas_used: U256::zero(), + gas_used: U256::default(), gas_limit: view.gas_limit(), }; for t in txs.iter().take(address.index) { @@ -924,7 +924,7 @@ impl BlockChainClient for Client { entry: log, block_hash: hash.clone(), block_number: number, - transaction_hash: hashes.get(index).cloned().unwrap_or_else(Default::default), + transaction_hash: hashes.get(index).cloned().unwrap_or_else(H256::default), transaction_index: index, log_index: log_index + i }) diff --git a/ethcore/src/env_info.rs b/ethcore/src/env_info.rs index 02a551d3a..ddef71608 100644 --- a/ethcore/src/env_info.rs +++ b/ethcore/src/env_info.rs @@ -47,7 +47,7 @@ impl Default for EnvInfo { fn default() -> Self { EnvInfo { number: 0, - author: Default::default(), + author: Address::default(), timestamp: 0, difficulty: 0.into(), gas_limit: 0.into(), diff --git a/ethcore/src/miner/transaction_queue.rs b/ethcore/src/miner/transaction_queue.rs index eb3587705..6a88b4388 100644 --- a/ethcore/src/miner/transaction_queue.rs +++ b/ethcore/src/miner/transaction_queue.rs @@ -80,8 +80,7 @@ //! - It removes all transactions (either from `current` or `future`) with nonce < client nonce //! - It moves matching `future` transactions to `current` -use std::default::Default; -use std::cmp::{Ordering}; +use std::cmp::Ordering; use std::cmp; use std::collections::{HashMap, BTreeSet}; use util::{Address, H256, Uint, U256}; diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index 2550b532e..07847d1cb 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -45,7 +45,7 @@ impl Receipt { Receipt { state_root: state_root, gas_used: gas_used, - log_bloom: logs.iter().fold(Default::default(), |mut b, l| { b = &b | &l.bloom(); b }), //TODO: use |= operator + log_bloom: logs.iter().fold(LogBloom::default(), |mut b, l| { b = &b | &l.bloom(); b }), //TODO: use |= operator logs: logs, } } diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index 3f7e727be..27ef38e08 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -55,7 +55,7 @@ impl AddressesFilter { /// Returns blooms of this addresses filter. pub fn blooms(&self) -> Vec { match self.list.is_empty() { - true => vec![Default::default()], + true => vec![LogBloom::default()], false => self.list.iter() .map(|address| LogBloom::from_bloomed(&address.sha3())) .collect(), diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 3aa24380f..8c26293d3 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -163,8 +163,8 @@ impl Transaction { pub fn invalid_sign(self) -> SignedTransaction { SignedTransaction { unsigned: self, - r: Default::default(), - s: Default::default(), + r: U256::default(), + s: U256::default(), v: 0, hash: Cell::new(None), sender: Cell::new(None), @@ -175,8 +175,8 @@ impl Transaction { pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { unsigned: self, - r: Default::default(), - s: Default::default(), + r: U256::default(), + s: U256::default(), v: 0, hash: Cell::new(None), sender: Cell::new(Some(from)), diff --git a/rpc/src/v1/impls/mod.rs b/rpc/src/v1/impls/mod.rs index 94aba32e5..86d796f63 100644 --- a/rpc/src/v1/impls/mod.rs +++ b/rpc/src/v1/impls/mod.rs @@ -106,7 +106,7 @@ fn prepare_transaction(client: &C, miner: &M, request: TransactionRequest) action: request.to.map_or(Action::Create, Action::Call), gas: request.gas.unwrap_or_else(|| miner.sensible_gas_limit()), gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(client, miner)), - value: request.value.unwrap_or_else(Default::default), + value: request.value.unwrap_or_else(U256::default), data: request.data.map_or_else(Vec::new, |b| b.to_vec()), } } From 24c73925001ce8b3d58fb686991da27c9d4c0285 Mon Sep 17 00:00:00 2001 From: debris Date: Thu, 4 Aug 2016 14:48:09 +0200 Subject: [PATCH 5/8] removed redundant helper methods --- ethcore/src/state.rs | 2 +- util/bigint/src/hash.rs | 23 ----------------------- util/src/bytes.rs | 11 ++++++----- util/src/crypto.rs | 18 +++++++++--------- util/src/network/host.rs | 2 +- 5 files changed, 17 insertions(+), 39 deletions(-) diff --git a/ethcore/src/state.rs b/ethcore/src/state.rs index e08b0d8f4..e62e0cba2 100644 --- a/ethcore/src/state.rs +++ b/ethcore/src/state.rs @@ -1393,7 +1393,7 @@ fn alter_balance() { let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); let a = Address::zero(); - let b = address_from_u64(1u64); + let b = 1u64.into(); state.add_balance(&a, &U256::from(69u64)); assert_eq!(state.balance(&a), U256::from(69u64)); state.commit().unwrap(); diff --git a/util/bigint/src/hash.rs b/util/bigint/src/hash.rs index 7ef3dcae5..49c51dcdf 100644 --- a/util/bigint/src/hash.rs +++ b/util/bigint/src/hash.rs @@ -510,29 +510,6 @@ impl<'a> From<&'a Address> for H256 { } } -/// Convert string `s` to an `H256`. Will panic if `s` is not 64 characters long or if any of -/// those characters are not 0-9, a-z or A-Z. -pub fn h256_from_hex(s: &str) -> H256 { - H256::from_str(s).unwrap() -} - -/// Convert `n` to an `H256`, setting the rightmost 8 bytes. -pub fn h256_from_u64(n: u64) -> H256 { - H256::from(&U256::from(n)) -} - -/// Convert string `s` to an `Address`. Will panic if `s` is not 40 characters long or if any of -/// those characters are not 0-9, a-z or A-Z. -pub fn address_from_hex(s: &str) -> Address { - Address::from_str(s).unwrap() -} - -/// Convert `n` to an `Address`, setting the rightmost 8 bytes. -pub fn address_from_u64(n: u64) -> Address { - let h256 = h256_from_u64(n); - From::from(h256) -} - impl_hash!(H32, 4); impl_hash!(H64, 8); impl_hash!(H128, 16); diff --git a/util/src/bytes.rs b/util/src/bytes.rs index 3c022e8bf..fd953fe3e 100644 --- a/util/src/bytes.rs +++ b/util/src/bytes.rs @@ -232,11 +232,12 @@ fn fax_raw_dyn() { #[test] fn populate_big_types() { use hash::*; - let a = address_from_hex("ffffffffffffffffffffffffffffffffffffffff"); - let mut h = h256_from_u64(0x69); + let a: Address = "ffffffffffffffffffffffffffffffffffffffff".into(); + let mut h: H256 = 0x69.into(); h.populate_raw_from(&a); - assert_eq!(h, h256_from_hex("ffffffffffffffffffffffffffffffffffffffff000000000000000000000000")); - let mut h = h256_from_u64(0x69); + assert_eq!(h, "ffffffffffffffffffffffffffffffffffffffff000000000000000000000000".into()); + + let mut h: H256 = 0x69.into(); h.copy_raw_from(&a); - assert_eq!(h, h256_from_hex("ffffffffffffffffffffffffffffffffffffffff000000000000000000000069")); + assert_eq!(h, "ffffffffffffffffffffffffffffffffffffffff000000000000000000000069".into()); } diff --git a/util/src/crypto.rs b/util/src/crypto.rs index 67f370ba6..0c05d804d 100644 --- a/util/src/crypto.rs +++ b/util/src/crypto.rs @@ -235,7 +235,7 @@ pub mod ec { /// Check if this is a "low" signature. pub fn is_low(sig: &Signature) -> bool { - H256::from_slice(&sig[32..64]) <= h256_from_hex("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0") + H256::from_slice(&sig[32..64]) <= "7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0".into() } /// Check if this is a "low" signature. @@ -246,10 +246,10 @@ pub mod ec { /// Check if each component of the signature is in range. pub fn is_valid(sig: &Signature) -> bool { sig[64] <= 1 && - H256::from_slice(&sig[0..32]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && - H256::from_slice(&sig[32..64]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && - H256::from_slice(&sig[32..64]) >= h256_from_u64(1) && - H256::from_slice(&sig[0..32]) >= h256_from_u64(1) + H256::from_slice(&sig[0..32]) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() && + H256::from_slice(&sig[32..64]) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() && + H256::from_slice(&sig[32..64]) >= 1.into() && + H256::from_slice(&sig[0..32]) >= 1.into() } } @@ -432,14 +432,14 @@ mod tests { #[test] fn test_invalid_key() { - assert!(KeyPair::from_secret(h256_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")).is_err()); - assert!(KeyPair::from_secret(h256_from_hex("0000000000000000000000000000000000000000000000000000000000000000")).is_err()); - assert!(KeyPair::from_secret(h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")).is_err()); + assert!(KeyPair::from_secret("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".into()).is_err()); + assert!(KeyPair::from_secret("0000000000000000000000000000000000000000000000000000000000000000".into()).is_err()); + assert!(KeyPair::from_secret("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into()).is_err()); } #[test] fn test_key() { - let pair = KeyPair::from_secret(h256_from_hex("6f7b0d801bc7b5ce7bbd930b84fd0369b3eb25d09be58d64ba811091046f3aa2")).unwrap(); + let pair = KeyPair::from_secret("6f7b0d801bc7b5ce7bbd930b84fd0369b3eb25d09be58d64ba811091046f3aa2".into()).unwrap(); assert_eq!(pair.public().hex(), "101b3ef5a4ea7a1c7928e24c4c75fd053c235d7b80c22ae5c03d145d0ac7396e2a4ffff9adee3133a7b05044a5cee08115fd65145e5165d646bde371010d803c"); } diff --git a/util/src/network/host.rs b/util/src/network/host.rs index 7b1baf97a..356953a9d 100644 --- a/util/src/network/host.rs +++ b/util/src/network/host.rs @@ -1151,7 +1151,7 @@ fn key_save_load() { #[test] fn host_client_url() { let mut config = NetworkConfiguration::new(); - let key = h256_from_hex("6f7b0d801bc7b5ce7bbd930b84fd0369b3eb25d09be58d64ba811091046f3aa2"); + let key = "6f7b0d801bc7b5ce7bbd930b84fd0369b3eb25d09be58d64ba811091046f3aa2".into(); config.use_secret = Some(key); let host: Host = Host::new(config, Arc::new(NetworkStats::new())).unwrap(); assert!(host.local_url().starts_with("enode://101b3ef5a4ea7a1c7928e24c4c75fd053c235d7b80c22ae5c03d145d0ac7396e2a4ffff9adee3133a7b05044a5cee08115fd65145e5165d646bde371010d803c@")); From a1867a7ba64e022692b294feb276d069f8f55181 Mon Sep 17 00:00:00 2001 From: debris Date: Thu, 4 Aug 2016 15:38:16 +0200 Subject: [PATCH 6/8] bloomable trait --- ethcore/src/types/filter.rs | 1 + ethcore/src/types/log_entry.rs | 3 +- ethcore/src/types/trace_types/filter.rs | 6 +- ethcore/src/types/trace_types/trace.rs | 3 +- util/bigint/src/hash.rs | 96 +--------------- util/src/bloom.rs | 145 ++++++++++++++++++++++++ util/src/lib.rs | 1 + 7 files changed, 157 insertions(+), 98 deletions(-) create mode 100644 util/src/bloom.rs diff --git a/ethcore/src/types/filter.rs b/ethcore/src/types/filter.rs index d8d5d03bd..a5aed6ac6 100644 --- a/ethcore/src/types/filter.rs +++ b/ethcore/src/types/filter.rs @@ -18,6 +18,7 @@ use util::hash::*; use util::sha3::*; +use util::bloom::Bloomable; use client::BlockID; use log_entry::LogEntry; use ipc::binary::BinaryConvertError; diff --git a/ethcore/src/types/log_entry.rs b/ethcore/src/types/log_entry.rs index 3edbb5d0b..47600fdbb 100644 --- a/ethcore/src/types/log_entry.rs +++ b/ethcore/src/types/log_entry.rs @@ -19,8 +19,9 @@ use std::mem; use std::ops::Deref; use std::collections::VecDeque; -use util::{H256, Address, Bytes, HeapSizeOf, FixedHash, Hashable}; +use util::{H256, Address, Bytes, HeapSizeOf, Hashable}; use util::rlp::*; +use util::bloom::Bloomable; use ipc::binary::BinaryConvertError; use basic_types::LogBloom; use header::BlockNumber; diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index 27ef38e08..03100f411 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -20,8 +20,9 @@ use std::ops::Range; use std::mem; use std::collections::VecDeque; use bloomchain::{Filter as BloomFilter, Bloom, Number}; -use util::{Address, FixedHash}; +use util::Address; use util::sha3::Hashable; +use util::bloom::Bloomable; use basic_types::LogBloom; use trace::flat::FlatTrace; use types::trace_types::trace::{Action, Res}; @@ -137,8 +138,9 @@ impl Filter { #[cfg(test)] mod tests { - use util::{FixedHash, Address}; + use util::Address; use util::sha3::Hashable; + use util::bloom::Bloomable; use trace::trace::{Action, Call, Res, Create, CreateResult, Suicide}; use trace::flat::FlatTrace; use trace::{Filter, AddressesFilter}; diff --git a/ethcore/src/types/trace_types/trace.rs b/ethcore/src/types/trace_types/trace.rs index 8d251032c..4e339d4bd 100644 --- a/ethcore/src/types/trace_types/trace.rs +++ b/ethcore/src/types/trace_types/trace.rs @@ -16,9 +16,10 @@ //! Tracing datatypes. -use util::{U256, Bytes, Address, FixedHash}; +use util::{U256, Bytes, Address}; use util::rlp::*; use util::sha3::Hashable; +use util::bloom::Bloomable; use action_params::ActionParams; use basic_types::LogBloom; use types::executed::CallType; diff --git a/util/bigint/src/hash.rs b/util/bigint/src/hash.rs index 7ef3dcae5..403fb232b 100644 --- a/util/bigint/src/hash.rs +++ b/util/bigint/src/hash.rs @@ -16,7 +16,7 @@ //! General hash types, a fixed-size raw-data type used as the output of hash functions. -use std::{ops, fmt, cmp, mem}; +use std::{ops, fmt, cmp}; use std::cmp::*; use std::ops::*; use std::hash::{Hash, Hasher, BuildHasherDefault}; @@ -28,7 +28,7 @@ use rustc_serialize::hex::{FromHex, FromHexError}; use uint::{Uint, U256}; /// Trait for a fixed-size byte array to be used as the output of hash functions. -pub trait FixedHash: Sized + FromStr + Default + DerefMut { +pub trait FixedHash: Sized { /// Create a new, zero-initialised, instance. fn new() -> Self; /// Synonym for `new()`. Prefer to new as it's more readable. @@ -45,14 +45,6 @@ pub trait FixedHash: Sized + FromStr + Default + DerefMut { fn clone_from_slice(&mut self, src: &[u8]) -> usize; /// Copy the data of this object into some mutable slice of length `len()`. fn copy_to(&self, dest: &mut [u8]); - /// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`. - fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: FixedHash; - /// Same as `shift_bloomed` except that `self` is consumed and a new value returned. - fn with_bloomed(mut self, b: &T) -> Self where T: FixedHash { self.shift_bloomed(b); self } - /// Bloom the current value using the bloom parameter `m`. - fn bloom_part(&self, m: usize) -> T where T: FixedHash; - /// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed. - fn contains_bloomed(&self, b: &T) -> bool where T: FixedHash; /// Returns `true` if all bits set in `b` are also set in `self`. fn contains<'a>(&'a self, b: &'a Self) -> bool; /// Returns `true` if no bits are set. @@ -70,16 +62,6 @@ pub fn clean_0x(s: &str) -> &str { } } -/// Returns log2. -pub fn log2(x: usize) -> u32 { - if x <= 1 { - return 0; - } - - let n = x.leading_zeros(); - mem::size_of::() as u32 * 8 - n -} - macro_rules! impl_hash { ($from: ident, $size: expr) => { #[derive(Eq)] @@ -158,54 +140,6 @@ macro_rules! impl_hash { dest[..min].copy_from_slice(&self.0[..min]); } - fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: FixedHash { - let bp: Self = b.bloom_part($size); - let new_self = &bp | self; - - self.0 = new_self.0; - self - } - - fn bloom_part(&self, m: usize) -> T where T: FixedHash { - // numbers of bits - // TODO: move it to some constant - let p = 3; - - let bloom_bits = m * 8; - let mask = bloom_bits - 1; - let bloom_bytes = (log2(bloom_bits) + 7) / 8; - - // must be a power of 2 - assert_eq!(m & (m - 1), 0); - // out of range - assert!(p * bloom_bytes <= $size); - - // return type - let mut ret = T::new(); - - // 'ptr' to out slice - let mut ptr = 0; - - // set p number of bits, - // p is equal 3 according to yellowpaper - for _ in 0..p { - let mut index = 0 as usize; - for _ in 0..bloom_bytes { - index = (index << 8) | self.0[ptr] as usize; - ptr += 1; - } - index &= mask; - ret[m - 1 - index / 8] |= 1 << (index % 8); - } - - ret - } - - fn contains_bloomed(&self, b: &T) -> bool where T: FixedHash { - let bp: Self = b.bloom_part($size); - self.contains(&bp) - } - fn contains<'a>(&'a self, b: &'a Self) -> bool { &(b & self) == b } @@ -415,9 +349,6 @@ macro_rules! impl_hash { pub fn hex(&self) -> String { format!("{:?}", self) } - - /// Construct new instance equal to the bloomed value of `b`. - pub fn from_bloomed(b: &T) -> Self where T: FixedHash { b.bloom_part($size) } } impl Default for $from { @@ -609,29 +540,6 @@ mod tests { assert_eq!(a | b, c); } - #[test] - #[ignore] - fn shift_bloomed() { - //use sha3::Hashable; - - //let bloom = H2048::from_str("00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); - //let address = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); - //let topic = H256::from_str("02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc").unwrap(); - - //let mut my_bloom = H2048::new(); - //assert!(!my_bloom.contains_bloomed(&address.sha3())); - //assert!(!my_bloom.contains_bloomed(&topic.sha3())); - - //my_bloom.shift_bloomed(&address.sha3()); - //assert!(my_bloom.contains_bloomed(&address.sha3())); - //assert!(!my_bloom.contains_bloomed(&topic.sha3())); - - //my_bloom.shift_bloomed(&topic.sha3()); - //assert_eq!(my_bloom, bloom); - //assert!(my_bloom.contains_bloomed(&address.sha3())); - //assert!(my_bloom.contains_bloomed(&topic.sha3())); - } - #[test] fn from_and_to_address() { let address = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); diff --git a/util/src/bloom.rs b/util/src/bloom.rs new file mode 100644 index 000000000..a67f8d482 --- /dev/null +++ b/util/src/bloom.rs @@ -0,0 +1,145 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Bloom operations. + +use std::mem; +use std::ops::DerefMut; +use {H64, Address, H256, H512, H520, H2048, FixedHash}; + +/// Returns log2. +pub fn log2(x: usize) -> u32 { + if x <= 1 { + return 0; + } + + let n = x.leading_zeros(); + mem::size_of::() as u32 * 8 - n +} + +/// Bloom operations. +pub trait Bloomable: Sized + Default + DerefMut { + /// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`. + fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable; + + /// Same as `shift_bloomed` except that `self` is consumed and a new value returned. + fn with_bloomed(mut self, b: &T) -> Self where T: Bloomable { + self.shift_bloomed(b); + self + } + + /// Construct new instance equal to the bloomed value of `b`. + fn from_bloomed(b: &T) -> Self where T: Bloomable; + + /// Bloom the current value using the bloom parameter `m`. + fn bloom_part(&self, m: usize) -> T where T: Bloomable; + + /// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed. + fn contains_bloomed(&self, b: &T) -> bool where T: Bloomable; +} + +macro_rules! impl_bloomable_for_hash { + ($name: ident, $size: expr) => { + impl Bloomable for $name { + fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable { + let bp: Self = b.bloom_part($size); + let new_self = &bp | self; + + self.0 = new_self.0; + self + } + + fn bloom_part(&self, m: usize) -> T where T: Bloomable + Default { + // numbers of bits + // TODO: move it to some constant + let p = 3; + + let bloom_bits = m * 8; + let mask = bloom_bits - 1; + let bloom_bytes = (log2(bloom_bits) + 7) / 8; + + // must be a power of 2 + assert_eq!(m & (m - 1), 0); + // out of range + assert!(p * bloom_bytes <= $size); + + // return type + let mut ret = T::default(); + + // 'ptr' to out slice + let mut ptr = 0; + + // set p number of bits, + // p is equal 3 according to yellowpaper + for _ in 0..p { + let mut index = 0 as usize; + for _ in 0..bloom_bytes { + index = (index << 8) | self.0[ptr] as usize; + ptr += 1; + } + index &= mask; + ret[m - 1 - index / 8] |= 1 << (index % 8); + } + + ret + } + + fn contains_bloomed(&self, b: &T) -> bool where T: Bloomable { + let bp: Self = b.bloom_part($size); + self.contains(&bp) + } + + fn from_bloomed(b: &T) -> Self where T: Bloomable { + b.bloom_part($size) + } + } + } +} + +impl_bloomable_for_hash!(H64, 8); +impl_bloomable_for_hash!(Address, 20); +impl_bloomable_for_hash!(H256, 32); +impl_bloomable_for_hash!(H512, 64); +impl_bloomable_for_hash!(H520, 65); +impl_bloomable_for_hash!(H2048, 256); + +#[cfg(test)] +mod tests { + use {Address, H256, H2048}; + use sha3::Hashable; + use super::Bloomable; + + #[test] + fn shift_bloomed() { + let bloom: H2048 = "00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".parse().unwrap(); + let address: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".parse().unwrap(); + let topic: H256 = "02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc".parse().unwrap(); + + let mut my_bloom = H2048::default(); + assert!(!my_bloom.contains_bloomed(&address.sha3())); + assert!(!my_bloom.contains_bloomed(&topic.sha3())); + + my_bloom.shift_bloomed(&address.sha3()); + assert!(my_bloom.contains_bloomed(&address.sha3())); + assert!(!my_bloom.contains_bloomed(&topic.sha3())); + + my_bloom.shift_bloomed(&topic.sha3()); + assert_eq!(my_bloom, bloom); + assert!(my_bloom.contains_bloomed(&address.sha3())); + assert!(my_bloom.contains_bloomed(&topic.sha3())); + } +} + diff --git a/util/src/lib.rs b/util/src/lib.rs index 2a35fe8fb..57ff2e6a5 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -117,6 +117,7 @@ pub extern crate using_queue; pub extern crate table; extern crate ansi_term; +pub mod bloom; pub mod standard; #[macro_use] pub mod from_json; From 74c9ecbfd6f3dced2fb2ac0a16d10c495f00d4a9 Mon Sep 17 00:00:00 2001 From: debris Date: Fri, 5 Aug 2016 14:09:21 +0200 Subject: [PATCH 7/8] fixed compiling --- util/network/src/node_table.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/util/network/src/node_table.rs b/util/network/src/node_table.rs index 31045171e..26f6d9f8c 100644 --- a/util/network/src/node_table.rs +++ b/util/network/src/node_table.rs @@ -27,6 +27,7 @@ use std::fs; use std::io::{Read, Write}; use util::hash::*; use util::rlp::*; +use util::UtilError; use time::Tm; use error::NetworkError; use discovery::{TableUpdates, NodeEntry}; @@ -164,7 +165,7 @@ impl FromStr for Node { type Err = NetworkError; fn from_str(s: &str) -> Result { let (id, endpoint) = if s.len() > 136 && &s[0..8] == "enode://" && &s[136..137] == "@" { - (try!(NodeId::from_str(&s[8..136])), try!(NodeEndpoint::from_str(&s[137..]))) + (try!(s[8..136].parse().map_err(UtilError::from)), try!(NodeEndpoint::from_str(&s[137..]))) } else { (NodeId::new(), try!(NodeEndpoint::from_str(s))) From 826988794978d6d49a9a85cc4240f59a4d6dd74b Mon Sep 17 00:00:00 2001 From: debris Date: Mon, 8 Aug 2016 11:18:48 +0200 Subject: [PATCH 8/8] parse().unwrap() -> into() --- ethcore/src/ethereum/ethash.rs | 6 +++--- ethcore/src/ethereum/mod.rs | 20 ++++++++++---------- ethcore/src/types/transaction.rs | 4 ++-- util/bigint/src/uint.rs | 6 ++++++ util/src/bloom.rs | 6 +++--- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index f58e47036..764a74bfe 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -374,13 +374,13 @@ mod tests { let vm_factory = Default::default(); let mut b = OpenBlock::new(engine.deref(), &vm_factory, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![]).unwrap(); let mut uncle = Header::new(); - let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".parse().unwrap(); + let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into(); uncle.author = uncle_author.clone(); b.push_uncle(uncle).unwrap(); let b = b.close(); - assert_eq!(b.state().balance(&Address::zero()), U256::from_str("478eae0e571ba000").unwrap()); - assert_eq!(b.state().balance(&uncle_author), U256::from_str("3cb71f51fc558000").unwrap()); + assert_eq!(b.state().balance(&Address::zero()), "478eae0e571ba000".into()); + assert_eq!(b.state().balance(&uncle_author), "3cb71f51fc558000".into()); } #[test] diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index b0f8ed26f..40e85d619 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -69,21 +69,21 @@ mod tests { let mut db = db_result.take(); spec.ensure_db_good(db.as_hashdb_mut()).unwrap(); let s = State::from_existing(db, genesis_header.state_root.clone(), engine.account_start_nonce(), Default::default()).unwrap(); - assert_eq!(s.balance(&"0000000000000000000000000000000000000001".parse().unwrap()), U256::from(1u64)); - assert_eq!(s.balance(&"0000000000000000000000000000000000000002".parse().unwrap()), U256::from(1u64)); - assert_eq!(s.balance(&"0000000000000000000000000000000000000003".parse().unwrap()), U256::from(1u64)); - assert_eq!(s.balance(&"0000000000000000000000000000000000000004".parse().unwrap()), U256::from(1u64)); - assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".parse().unwrap()), U256::from(1u64) << 200); - assert_eq!(s.balance(&"0000000000000000000000000000000000000000".parse().unwrap()), U256::from(0u64)); + assert_eq!(s.balance(&"0000000000000000000000000000000000000001".into()), 1u64.into()); + assert_eq!(s.balance(&"0000000000000000000000000000000000000002".into()), 1u64.into()); + assert_eq!(s.balance(&"0000000000000000000000000000000000000003".into()), 1u64.into()); + assert_eq!(s.balance(&"0000000000000000000000000000000000000004".into()), 1u64.into()); + assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()), U256::from(1u64) << 200); + assert_eq!(s.balance(&"0000000000000000000000000000000000000000".into()), 0u64.into()); } #[test] fn morden() { let morden = new_morden(); - assert_eq!(morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()); + assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into()); let genesis = morden.genesis_block(); - assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()); + assert_eq!(BlockView::new(&genesis).header_view().sha3(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into()); let _ = morden.engine; } @@ -92,9 +92,9 @@ mod tests { fn frontier() { let frontier = new_frontier(); - assert_eq!(frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap()); + assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into()); let genesis = frontier.genesis_block(); - assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap()); + assert_eq!(BlockView::new(&genesis).header_view().sha3(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into()); let _ = frontier.engine; } diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 8c26293d3..e9cc2211c 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -361,10 +361,10 @@ fn sender_test() { assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { - assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".parse().unwrap()); + assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); - assert_eq!(t.sender().unwrap(), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".parse().unwrap()); + assert_eq!(t.sender().unwrap(), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); } #[test] diff --git a/util/bigint/src/uint.rs b/util/bigint/src/uint.rs index 172e09c70..d66caf3c1 100644 --- a/util/bigint/src/uint.rs +++ b/util/bigint/src/uint.rs @@ -1129,6 +1129,12 @@ macro_rules! construct_uint { Ok(()) } } + + impl From<&'static str> for $name { + fn from(s: &'static str) -> Self { + s.parse().unwrap() + } + } ); } diff --git a/util/src/bloom.rs b/util/src/bloom.rs index a67f8d482..779419d44 100644 --- a/util/src/bloom.rs +++ b/util/src/bloom.rs @@ -124,9 +124,9 @@ mod tests { #[test] fn shift_bloomed() { - let bloom: H2048 = "00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".parse().unwrap(); - let address: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".parse().unwrap(); - let topic: H256 = "02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc".parse().unwrap(); + let bloom: H2048 = "00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let address: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into(); + let topic: H256 = "02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc".into(); let mut my_bloom = H2048::default(); assert!(!my_bloom.contains_bloomed(&address.sha3()));