Merge pull request #6187 from paritytech/split

removed std reexports from util && fixed broken tests
This commit is contained in:
Marek Kotewicz 2017-08-01 17:19:02 +02:00 committed by GitHub
commit b24053f4df
99 changed files with 375 additions and 284 deletions

15
Cargo.lock generated
View File

@ -190,6 +190,14 @@ name = "blastfig"
version = "0.3.3" version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "bloomable"
version = "0.1.0"
dependencies = [
"ethcore-bigint 0.1.3",
"tiny-keccak 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "bloomchain" name = "bloomchain"
version = "0.1.0" version = "0.1.0"
@ -280,6 +288,7 @@ dependencies = [
name = "common-types" name = "common-types"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"bloomable 0.1.0",
"ethcore-util 1.8.0", "ethcore-util 1.8.0",
"ethjson 0.1.0", "ethjson 0.1.0",
"rlp 0.2.0", "rlp 0.2.0",
@ -471,6 +480,7 @@ name = "ethcore"
version = "1.8.0" version = "1.8.0"
dependencies = [ dependencies = [
"bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"bloomable 0.1.0",
"bloomchain 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "bloomchain 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"bn 0.4.4 (git+https://github.com/paritytech/bn)", "bn 0.4.4 (git+https://github.com/paritytech/bn)",
"byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
@ -511,8 +521,10 @@ dependencies = [
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"semver 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "semver 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
"stats 0.1.0", "stats 0.1.0",
"table 0.1.0",
"time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"transient-hashmap 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "transient-hashmap 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"using_queue 0.1.0",
"vm 0.1.0", "vm 0.1.0",
"wasm 0.1.0", "wasm 0.1.0",
] ]
@ -764,11 +776,9 @@ dependencies = [
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
"sha3 0.1.0", "sha3 0.1.0",
"table 0.1.0",
"target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)",
"tiny-keccak 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "tiny-keccak 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"using_queue 0.1.0",
"vergen 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "vergen 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
@ -917,6 +927,7 @@ dependencies = [
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"vm 0.1.0",
] ]
[[package]] [[package]]

View File

@ -33,13 +33,14 @@
use std::io; use std::io;
use std::{fmt, mem, time}; use std::{fmt, mem, time};
use std::sync::Arc;
use std::collections::VecDeque; use std::collections::VecDeque;
use futures::{self, Future, BoxFuture}; use futures::{self, Future, BoxFuture};
use futures_cpupool::CpuPool; use futures_cpupool::CpuPool;
use ntp; use ntp;
use time::{Duration, Timespec}; use time::{Duration, Timespec};
use util::{Arc, RwLock}; use util::RwLock;
/// Time checker error. /// Time checker error.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]

View File

@ -53,6 +53,9 @@ semver = "0.6"
stats = { path = "../util/stats" } stats = { path = "../util/stats" }
time = "0.1" time = "0.1"
transient-hashmap = "0.4" transient-hashmap = "0.4"
using_queue = { path = "../util/using_queue" }
table = { path = "../util/table" }
bloomable = { path = "../util/bloomable" }
vm = { path = "vm" } vm = { path = "vm" }
wasm = { path = "wasm" } wasm = { path = "wasm" }

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::cmp;
use util::*; use util::*;
use super::u256_to_address; use super::u256_to_address;
@ -82,7 +83,7 @@ impl<Gas: evm::CostType> Gasometer<Gas> {
}; };
if let Some(Ok(r)) = requested { if let Some(Ok(r)) = requested {
Ok(min(r, max_gas_provided)) Ok(cmp::min(r, max_gas_provided))
} else { } else {
Ok(max_gas_provided) Ok(max_gas_provided)
} }

View File

@ -24,6 +24,8 @@ mod memory;
mod shared_cache; mod shared_cache;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::{cmp, mem};
use std::sync::Arc;
use vm::{ use vm::{
self, ActionParams, ActionValue, CallType, MessageCallResult, self, ActionParams, ActionValue, CallType, MessageCallResult,

View File

@ -15,6 +15,10 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::fmt::Debug; use std::fmt::Debug;
use std::str::FromStr;
use std::hash::Hash;
use std::sync::Arc;
use std::collections::{HashMap, HashSet};
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::*; use util::*;
use vm::{self, ActionParams, ActionValue}; use vm::{self, ActionParams, ActionValue};

View File

@ -15,6 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! DB backend wrapper for Account trie //! DB backend wrapper for Account trie
use std::collections::HashMap;
use util::*; use util::*;
use rlp::NULL_RLP; use rlp::NULL_RLP;

View File

@ -16,6 +16,9 @@
//! Blockchain database. //! Blockchain database.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::mem;
use bloomchain as bc; use bloomchain as bc;
use util::*; use util::*;
use rlp::*; use rlp::*;

View File

@ -16,6 +16,8 @@
//! Blockchain DB extras. //! Blockchain DB extras.
use std::ops;
use std::io::Write;
use bloomchain; use bloomchain;
use blooms::{GroupPosition, BloomGroup}; use blooms::{GroupPosition, BloomGroup};
use db::Key; use db::Key;
@ -56,7 +58,7 @@ fn with_index(hash: &H256, i: ExtrasIndex) -> H264 {
pub struct BlockNumberKey([u8; 5]); pub struct BlockNumberKey([u8; 5]);
impl Deref for BlockNumberKey { impl ops::Deref for BlockNumberKey {
type Target = [u8]; type Target = [u8];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@ -88,7 +90,7 @@ impl Key<BlockDetails> for H256 {
pub struct LogGroupKey([u8; 6]); pub struct LogGroupKey([u8; 6]);
impl Deref for LogGroupKey { impl ops::Deref for LogGroupKey {
type Target = [u8]; type Target = [u8];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@ -160,7 +162,8 @@ pub const EPOCH_KEY_PREFIX: &'static [u8; DB_PREFIX_LEN] = &[
]; ];
pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]); pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]);
impl Deref for EpochTransitionsKey {
impl ops::Deref for EpochTransitionsKey {
type Target = [u8]; type Target = [u8];
fn deref(&self) -> &[u8] { &self.0[..] } fn deref(&self) -> &[u8] { &self.0[..] }

View File

@ -17,6 +17,9 @@
//! Test client. //! Test client.
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder};
use std::sync::Arc;
use std::collections::{HashMap, BTreeMap};
use std::mem;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::*; use util::*;
use rlp::*; use rlp::*;

View File

@ -17,8 +17,10 @@
//! A blockchain engine that supports a non-instant BFT proof-of-authority. //! A blockchain engine that supports a non-instant BFT proof-of-authority.
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::sync::Weak; use std::sync::{Weak, Arc};
use std::time::{UNIX_EPOCH, Duration}; use std::time::{UNIX_EPOCH, Duration};
use std::collections::{BTreeMap, HashSet, HashMap};
use std::cmp;
use account_provider::AccountProvider; use account_provider::AccountProvider;
use block::*; use block::*;
@ -445,9 +447,9 @@ impl Engine for AuthorityRound {
let gas_limit = parent.gas_limit().clone(); let gas_limit = parent.gas_limit().clone();
let bound_divisor = self.params().gas_limit_bound_divisor; let bound_divisor = self.params().gas_limit_bound_divisor;
if gas_limit < gas_floor_target { if gas_limit < gas_floor_target {
min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into()) cmp::min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into())
} else { } else {
max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into()) cmp::max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into())
} }
}); });
} }
@ -798,7 +800,7 @@ impl Engine for AuthorityRound {
} }
} }
fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> result::Result<(), Error> { fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> Result<(), Error> {
t.check_low_s()?; t.check_low_s()?;
if let Some(n) = t.network_id() { if let Some(n) = t.network_id() {
@ -834,6 +836,7 @@ impl Engine for AuthorityRound {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use util::*; use util::*;
use header::Header; use header::Header;
@ -924,10 +927,10 @@ mod tests {
let addr = tap.insert_account("0".sha3().into(), "0").unwrap(); let addr = tap.insert_account("0".sha3().into(), "0").unwrap();
let mut parent_header: Header = Header::default(); let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&0usize).into_vec()]); parent_header.set_seal(vec![encode(&0usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap()); parent_header.set_gas_limit("222222".parse::<U256>().unwrap());
let mut header: Header = Header::default(); let mut header: Header = Header::default();
header.set_number(1); header.set_number(1);
header.set_gas_limit(U256::from_str("222222").unwrap()); header.set_gas_limit("222222".parse::<U256>().unwrap());
header.set_author(addr); header.set_author(addr);
let engine = Spec::new_test_round().engine; let engine = Spec::new_test_round().engine;
@ -950,10 +953,10 @@ mod tests {
let mut parent_header: Header = Header::default(); let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&0usize).into_vec()]); parent_header.set_seal(vec![encode(&0usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap()); parent_header.set_gas_limit("222222".parse::<U256>().unwrap());
let mut header: Header = Header::default(); let mut header: Header = Header::default();
header.set_number(1); header.set_number(1);
header.set_gas_limit(U256::from_str("222222").unwrap()); header.set_gas_limit("222222".parse::<U256>().unwrap());
header.set_author(addr); header.set_author(addr);
let engine = Spec::new_test_round().engine; let engine = Spec::new_test_round().engine;
@ -976,10 +979,10 @@ mod tests {
let mut parent_header: Header = Header::default(); let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&4usize).into_vec()]); parent_header.set_seal(vec![encode(&4usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap()); parent_header.set_gas_limit("222222".parse::<U256>().unwrap());
let mut header: Header = Header::default(); let mut header: Header = Header::default();
header.set_number(1); header.set_number(1);
header.set_gas_limit(U256::from_str("222222").unwrap()); header.set_gas_limit("222222".parse::<U256>().unwrap());
header.set_author(addr); header.set_author(addr);
let engine = Spec::new_test_round().engine; let engine = Spec::new_test_round().engine;
@ -1013,10 +1016,10 @@ mod tests {
let mut parent_header: Header = Header::default(); let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&1usize).into_vec()]); parent_header.set_seal(vec![encode(&1usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap()); parent_header.set_gas_limit("222222".parse::<U256>().unwrap());
let mut header: Header = Header::default(); let mut header: Header = Header::default();
header.set_number(1); header.set_number(1);
header.set_gas_limit(U256::from_str("222222").unwrap()); header.set_gas_limit("222222".parse::<U256>().unwrap());
header.set_seal(vec![encode(&3usize).into_vec()]); header.set_seal(vec![encode(&3usize).into_vec()]);
// Do not report when signer not present. // Do not report when signer not present.

View File

@ -16,7 +16,9 @@
//! A blockchain engine that supports a basic, non-BFT proof-of-authority. //! A blockchain engine that supports a basic, non-BFT proof-of-authority.
use std::sync::Weak; use std::sync::{Weak, Arc};
use std::collections::BTreeMap;
use std::cmp;
use util::*; use util::*;
use ethkey::{recover, public_to_address, Signature}; use ethkey::{recover, public_to_address, Signature};
use account_provider::AccountProvider; use account_provider::AccountProvider;
@ -116,9 +118,9 @@ impl Engine for BasicAuthority {
let gas_limit = parent.gas_limit().clone(); let gas_limit = parent.gas_limit().clone();
let bound_divisor = self.params().gas_limit_bound_divisor; let bound_divisor = self.params().gas_limit_bound_divisor;
if gas_limit < gas_floor_target { if gas_limit < gas_floor_target {
min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into()) cmp::min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into())
} else { } else {
max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into()) cmp::max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into())
} }
}); });
} }
@ -142,7 +144,7 @@ impl Engine for BasicAuthority {
Seal::None Seal::None
} }
fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
// check the seal fields. // check the seal fields.
// TODO: pull this out into common code. // TODO: pull this out into common code.
if header.seal().len() != self.seal_fields() { if header.seal().len() != self.seal_fields() {
@ -153,11 +155,11 @@ impl Engine for BasicAuthority {
Ok(()) Ok(())
} }
fn verify_block_unordered(&self, _header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_unordered(&self, _header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
Ok(()) Ok(())
} }
fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
// Do not calculate difficulty for genesis blocks. // Do not calculate difficulty for genesis blocks.
if header.number() == 0 { if header.number() == 0 {
return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() }))); return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() })));
@ -249,6 +251,7 @@ impl Engine for BasicAuthority {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use util::*; use util::*;
use block::*; use block::*;
use error::{BlockError, Error}; use error::{BlockError, Error};

View File

@ -14,8 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::BTreeMap; use std::collections::{BTreeMap, HashMap};
use util::{Address, HashMap}; use util::Address;
use builtin::Builtin; use builtin::Builtin;
use engines::{Engine, Seal}; use engines::{Engine, Seal};
use spec::CommonParams; use spec::CommonParams;
@ -63,6 +63,7 @@ impl Engine for InstantSeal {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use util::*; use util::*;
use tests::helpers::*; use tests::helpers::*;
use spec::Spec; use spec::Spec;

View File

@ -35,7 +35,9 @@ pub use self::instant_seal::InstantSeal;
pub use self::null_engine::NullEngine; pub use self::null_engine::NullEngine;
pub use self::tendermint::Tendermint; pub use self::tendermint::Tendermint;
use std::sync::Weak; use std::sync::{Weak, Arc};
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use self::epoch::PendingTransition; use self::epoch::PendingTransition;
@ -391,6 +393,7 @@ pub trait Engine : Sync + Send {
/// Common engine utilities /// Common engine utilities
pub mod common { pub mod common {
use std::sync::Arc;
use block::ExecutedBlock; use block::ExecutedBlock;
use error::Error; use error::Error;
use transaction::SYSTEM_ADDRESS; use transaction::SYSTEM_ADDRESS;

View File

@ -16,7 +16,8 @@
//! A signer used by Engines which need to sign messages. //! A signer used by Engines which need to sign messages.
use util::{Arc, H256, Address}; use std::sync::Arc;
use util::{H256, Address};
use ethkey::Signature; use ethkey::Signature;
use account_provider::{self, AccountProvider}; use account_provider::{self, AccountProvider};

View File

@ -16,6 +16,7 @@
//! Tendermint message handling. //! Tendermint message handling.
use std::cmp;
use util::*; use util::*;
use super::{Height, View, BlockHash, Step}; use super::{Height, View, BlockHash, Step};
use error::Error; use error::Error;
@ -110,13 +111,13 @@ impl Default for VoteStep {
} }
impl PartialOrd for VoteStep { impl PartialOrd for VoteStep {
fn partial_cmp(&self, m: &VoteStep) -> Option<Ordering> { fn partial_cmp(&self, m: &VoteStep) -> Option<cmp::Ordering> {
Some(self.cmp(m)) Some(self.cmp(m))
} }
} }
impl Ord for VoteStep { impl Ord for VoteStep {
fn cmp(&self, m: &VoteStep) -> Ordering { fn cmp(&self, m: &VoteStep) -> cmp::Ordering {
if self.height != m.height { if self.height != m.height {
self.height.cmp(&m.height) self.height.cmp(&m.height)
} else if self.view != m.view { } else if self.view != m.view {
@ -198,6 +199,7 @@ pub fn message_hash(vote_step: VoteStep, block_hash: H256) -> H256 {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use util::*; use util::*;
use rlp::*; use rlp::*;
use account_provider::AccountProvider; use account_provider::AccountProvider;

View File

@ -25,8 +25,10 @@
mod message; mod message;
mod params; mod params;
use std::sync::Weak; use std::sync::{Weak, Arc};
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::collections::{HashSet, BTreeMap, HashMap};
use std::cmp;
use util::*; use util::*;
use client::{Client, EngineClient}; use client::{Client, EngineClient};
use error::{Error, BlockError}; use error::{Error, BlockError};
@ -469,9 +471,9 @@ impl Engine for Tendermint {
let gas_limit = parent.gas_limit().clone(); let gas_limit = parent.gas_limit().clone();
let bound_divisor = self.params().gas_limit_bound_divisor; let bound_divisor = self.params().gas_limit_bound_divisor;
if gas_limit < gas_floor_target { if gas_limit < gas_floor_target {
min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into()) cmp::min(gas_floor_target, gas_limit + gas_limit / bound_divisor - 1.into())
} else { } else {
max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into()) cmp::max(gas_floor_target, gas_limit - gas_limit / bound_divisor + 1.into())
} }
}); });
} }
@ -768,6 +770,7 @@ impl Engine for Tendermint {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::str::FromStr;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::*; use util::*;
use block::*; use block::*;

View File

@ -126,6 +126,7 @@ impl ValidatorSet for ValidatorContract {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::*; use util::*;
use rlp::encode; use rlp::encode;
@ -142,11 +143,11 @@ mod tests {
#[test] #[test]
fn fetches_validators() { fn fetches_validators() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, None); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, None);
let vc = Arc::new(ValidatorContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap())); let vc = Arc::new(ValidatorContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
vc.register_contract(Arc::downgrade(&client)); vc.register_contract(Arc::downgrade(&client));
let last_hash = client.best_block_header().hash(); let last_hash = client.best_block_header().hash();
assert!(vc.contains(&last_hash, &Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap())); assert!(vc.contains(&last_hash, &"7d577a597b2742b498cb5cf0c26cdcd726d39e6e".parse::<Address>().unwrap()));
assert!(vc.contains(&last_hash, &Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap())); assert!(vc.contains(&last_hash, &"82a978b3f5962a5b0957d9ee9eef472ee55b42f1".parse::<Address>().unwrap()));
} }
#[test] #[test]
@ -155,7 +156,7 @@ mod tests {
let v1 = tap.insert_account("1".sha3().into(), "").unwrap(); let v1 = tap.insert_account("1".sha3().into(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, Some(tap.clone())); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, Some(tap.clone()));
client.engine().register_client(Arc::downgrade(&client)); client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap(); let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
// Make sure reporting can be done. // Make sure reporting can be done.
client.miner().set_gas_floor_target(1_000_000.into()); client.miner().set_gas_floor_target(1_000_000.into());

View File

@ -142,6 +142,8 @@ impl ValidatorSet for Multi {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use std::collections::BTreeMap;
use account_provider::AccountProvider; use account_provider::AccountProvider;
use client::{BlockChainClient, EngineClient}; use client::{BlockChainClient, EngineClient};
use engines::EpochChange; use engines::EpochChange;

View File

@ -16,7 +16,7 @@
/// Validator set maintained in a contract, updated using `getValidators` method. /// Validator set maintained in a contract, updated using `getValidators` method.
use std::sync::Weak; use std::sync::{Weak, Arc};
use futures::Future; use futures::Future;
use native_contracts::ValidatorSet as Provider; use native_contracts::ValidatorSet as Provider;
@ -422,6 +422,7 @@ impl ValidatorSet for ValidatorSafeContract {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::*; use util::*;
use types::ids::BlockId; use types::ids::BlockId;
@ -438,11 +439,11 @@ mod tests {
#[test] #[test]
fn fetches_validators() { fn fetches_validators() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let vc = Arc::new(ValidatorSafeContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap())); let vc = Arc::new(ValidatorSafeContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
vc.register_contract(Arc::downgrade(&client)); vc.register_contract(Arc::downgrade(&client));
let last_hash = client.best_block_header().hash(); let last_hash = client.best_block_header().hash();
assert!(vc.contains(&last_hash, &Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap())); assert!(vc.contains(&last_hash, &"7d577a597b2742b498cb5cf0c26cdcd726d39e6e".parse::<Address>().unwrap()));
assert!(vc.contains(&last_hash, &Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap())); assert!(vc.contains(&last_hash, &"82a978b3f5962a5b0957d9ee9eef472ee55b42f1".parse::<Address>().unwrap()));
} }
#[test] #[test]
@ -454,7 +455,7 @@ mod tests {
let network_id = Spec::new_validator_safe_contract().network_id(); let network_id = Spec::new_validator_safe_contract().network_id();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap)); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
client.engine().register_client(Arc::downgrade(&client)); client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap(); let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
client.miner().set_engine_signer(v1, "".into()).unwrap(); client.miner().set_engine_signer(v1, "".into()).unwrap();
// Remove "1" validator. // Remove "1" validator.
@ -520,7 +521,7 @@ mod tests {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None); let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let engine = client.engine().clone(); let engine = client.engine().clone();
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap(); let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
let last_hash = client.best_block_header().hash(); let last_hash = client.best_block_header().hash();
let mut new_header = Header::default(); let mut new_header = Header::default();

View File

@ -17,8 +17,9 @@
/// Used for Engine testing. /// Used for Engine testing.
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use util::{Arc, Bytes, H256, Address, HeapSizeOf}; use util::{Bytes, H256, Address, HeapSizeOf};
use engines::{Call, Engine}; use engines::{Call, Engine};
use header::{Header, BlockNumber}; use header::{Header, BlockNumber};

View File

@ -17,6 +17,8 @@
//! Collects votes on hashes at each Message::Round. //! Collects votes on hashes at each Message::Round.
use std::fmt::Debug; use std::fmt::Debug;
use std::collections::{BTreeMap, HashSet, HashMap};
use std::hash::Hash;
use util::*; use util::*;
use rlp::{Encodable, RlpStream}; use rlp::{Encodable, RlpStream};

View File

@ -16,6 +16,7 @@
//! General error types for use in ethcore. //! General error types for use in ethcore.
use std::fmt;
use util::*; use util::*;
use io::*; use io::*;
use header::BlockNumber; use header::BlockNumber;

View File

@ -15,6 +15,9 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::path::Path; use std::path::Path;
use std::cmp;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager}; use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager};
use util::*; use util::*;
use block::*; use block::*;
@ -223,15 +226,15 @@ impl Engine for Arc<Ethash> {
let lower_limit = gas_limit - gas_limit / bound_divisor + 1.into(); let lower_limit = gas_limit - gas_limit / bound_divisor + 1.into();
let upper_limit = gas_limit + gas_limit / bound_divisor - 1.into(); let upper_limit = gas_limit + gas_limit / bound_divisor - 1.into();
let gas_limit = if gas_limit < gas_floor_target { let gas_limit = if gas_limit < gas_floor_target {
let gas_limit = min(gas_floor_target, upper_limit); let gas_limit = cmp::min(gas_floor_target, upper_limit);
round_block_gas_limit(gas_limit, lower_limit, upper_limit) round_block_gas_limit(gas_limit, lower_limit, upper_limit)
} else if gas_limit > gas_ceil_target { } else if gas_limit > gas_ceil_target {
let gas_limit = max(gas_ceil_target, lower_limit); let gas_limit = cmp::max(gas_ceil_target, lower_limit);
round_block_gas_limit(gas_limit, lower_limit, upper_limit) round_block_gas_limit(gas_limit, lower_limit, upper_limit)
} else { } else {
let total_lower_limit = max(lower_limit, gas_floor_target); let total_lower_limit = cmp::max(lower_limit, gas_floor_target);
let total_upper_limit = min(upper_limit, gas_ceil_target); let total_upper_limit = cmp::min(upper_limit, gas_ceil_target);
let gas_limit = max(gas_floor_target, min(total_upper_limit, let gas_limit = cmp::max(gas_floor_target, cmp::min(total_upper_limit,
lower_limit + (header.gas_used().clone() * 6.into() / 5.into()) / bound_divisor)); lower_limit + (header.gas_used().clone() * 6.into() / 5.into()) / bound_divisor));
round_block_gas_limit(gas_limit, total_lower_limit, total_upper_limit) round_block_gas_limit(gas_limit, total_lower_limit, total_upper_limit)
}; };
@ -307,7 +310,7 @@ impl Engine for Arc<Ethash> {
Ok(()) Ok(())
} }
fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
// check the seal fields. // check the seal fields.
if header.seal().len() != self.seal_fields() { if header.seal().len() != self.seal_fields() {
return Err(From::from(BlockError::InvalidSealArity( return Err(From::from(BlockError::InvalidSealArity(
@ -345,7 +348,7 @@ impl Engine for Arc<Ethash> {
Ok(()) Ok(())
} }
fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
if header.seal().len() != self.seal_fields() { if header.seal().len() != self.seal_fields() {
return Err(From::from(BlockError::InvalidSealArity( return Err(From::from(BlockError::InvalidSealArity(
Mismatch { expected: self.seal_fields(), found: header.seal().len() } Mismatch { expected: self.seal_fields(), found: header.seal().len() }
@ -364,7 +367,7 @@ impl Engine for Arc<Ethash> {
Ok(()) Ok(())
} }
fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
// we should not calculate difficulty for genesis blocks // we should not calculate difficulty for genesis blocks
if header.number() == 0 { if header.number() == 0 {
return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() }))); return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() })));
@ -388,7 +391,7 @@ impl Engine for Arc<Ethash> {
Ok(()) Ok(())
} }
fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> result::Result<(), Error> { fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> Result<(), Error> {
if header.number() >= self.ethash_params.min_gas_price_transition && t.gas_price < self.ethash_params.min_gas_price { if header.number() >= self.ethash_params.min_gas_price_transition && t.gas_price < self.ethash_params.min_gas_price {
return Err(TransactionError::InsufficientGasPrice { minimal: self.ethash_params.min_gas_price, got: t.gas_price }.into()); return Err(TransactionError::InsufficientGasPrice { minimal: self.ethash_params.min_gas_price, got: t.gas_price }.into());
} }
@ -481,28 +484,28 @@ impl Ethash {
if diff_inc <= threshold { if diff_inc <= threshold {
*parent.difficulty() + *parent.difficulty() / difficulty_bound_divisor * (threshold - diff_inc).into() *parent.difficulty() + *parent.difficulty() / difficulty_bound_divisor * (threshold - diff_inc).into()
} else { } else {
let multiplier = min(diff_inc - threshold, 99).into(); let multiplier = cmp::min(diff_inc - threshold, 99).into();
parent.difficulty().saturating_sub( parent.difficulty().saturating_sub(
*parent.difficulty() / difficulty_bound_divisor * multiplier *parent.difficulty() / difficulty_bound_divisor * multiplier
) )
} }
}; };
target = max(min_difficulty, target); target = cmp::max(min_difficulty, target);
if header.number() < self.ethash_params.bomb_defuse_transition { if header.number() < self.ethash_params.bomb_defuse_transition {
if header.number() < self.ethash_params.ecip1010_pause_transition { if header.number() < self.ethash_params.ecip1010_pause_transition {
let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize;
if period > 1 { if period > 1 {
target = max(min_difficulty, target + (U256::from(1) << (period - 2))); target = cmp::max(min_difficulty, target + (U256::from(1) << (period - 2)));
} }
} }
else if header.number() < self.ethash_params.ecip1010_continue_transition { else if header.number() < self.ethash_params.ecip1010_continue_transition {
let fixed_difficulty = ((self.ethash_params.ecip1010_pause_transition / EXP_DIFF_PERIOD) - 2) as usize; let fixed_difficulty = ((self.ethash_params.ecip1010_pause_transition / EXP_DIFF_PERIOD) - 2) as usize;
target = max(min_difficulty, target + (U256::from(1) << fixed_difficulty)); target = cmp::max(min_difficulty, target + (U256::from(1) << fixed_difficulty));
} }
else { else {
let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize;
let delay = ((self.ethash_params.ecip1010_continue_transition - self.ethash_params.ecip1010_pause_transition) / EXP_DIFF_PERIOD) as usize; let delay = ((self.ethash_params.ecip1010_continue_transition - self.ethash_params.ecip1010_pause_transition) / EXP_DIFF_PERIOD) as usize;
target = max(min_difficulty, target + (U256::from(1) << (period - delay - 2))); target = cmp::max(min_difficulty, target + (U256::from(1) << (period - delay - 2)));
} }
} }
target target
@ -547,6 +550,9 @@ impl Header {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::str::FromStr;
use std::collections::BTreeMap;
use std::sync::Arc;
use util::*; use util::*;
use block::*; use block::*;
use tests::helpers::*; use tests::helpers::*;

View File

@ -15,6 +15,8 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment. //! Transaction Execution environment.
use std::cmp;
use std::sync::Arc;
use util::*; use util::*;
use state::{Backend as StateBackend, State, Substate, CleanupMode}; use state::{Backend as StateBackend, State, Substate, CleanupMode};
use engines::Engine; use engines::Engine;
@ -597,10 +599,11 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> {
#[allow(dead_code)] #[allow(dead_code)]
mod tests { mod tests {
use std::sync::Arc; use std::sync::Arc;
use std::str::FromStr;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use ethkey::{Generator, Random}; use ethkey::{Generator, Random};
use super::*; use super::*;
use util::{H256, U256, U512, Address, FromStr}; use util::{H256, U256, U512, Address};
use util::bytes::BytesRef; use util::bytes::BytesRef;
use vm::{ActionParams, ActionValue, CallType, EnvInfo, CreateContractAddress}; use vm::{ActionParams, ActionValue, CallType, EnvInfo, CreateContractAddress};
use evm::{Factory, VMType}; use evm::{Factory, VMType};

View File

@ -15,6 +15,8 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment. //! Transaction Execution environment.
use std::cmp;
use std::sync::Arc;
use util::*; use util::*;
use state::{Backend as StateBackend, State, Substate, CleanupMode}; use state::{Backend as StateBackend, State, Substate, CleanupMode};
use engines::Engine; use engines::Engine;
@ -469,7 +471,7 @@ mod tests {
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); let hash = ext.blockhash(&"0000000000000000000000000000000000000000000000000000000000120000".parse::<U256>().unwrap());
assert_eq!(hash, H256::zero()); assert_eq!(hash, H256::zero());
} }
@ -493,7 +495,7 @@ mod tests {
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); let hash = ext.blockhash(&"0000000000000000000000000000000000000000000000000000000000120000".parse::<U256>().unwrap());
assert_eq!(test_hash, hash); assert_eq!(test_hash, hash);
} }
@ -512,10 +514,10 @@ mod tests {
// this should panic because we have no balance on any account // this should panic because we have no balance on any account
ext.call( ext.call(
&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap(), &"0000000000000000000000000000000000000000000000000000000000120000".parse::<U256>().unwrap(),
&Address::new(), &Address::new(),
&Address::new(), &Address::new(),
Some(U256::from_str("0000000000000000000000000000000000000000000000000000000000150000").unwrap()), Some("0000000000000000000000000000000000000000000000000000000000150000".parse::<U256>().unwrap()),
&[], &[],
&Address::new(), &Address::new(),
&mut output, &mut output,

View File

@ -16,13 +16,13 @@
//! Block header. //! Block header.
use std::cmp;
use std::cell::RefCell;
use util::*; use util::*;
use basic_types::{LogBloom, ZERO_LOGBLOOM}; use basic_types::{LogBloom, ZERO_LOGBLOOM};
use time::get_time; use time::get_time;
use rlp::*; use rlp::*;
use std::cell::RefCell;
pub use basic_types::Seal; pub use basic_types::Seal;
pub use types::BlockNumber; pub use types::BlockNumber;
@ -175,7 +175,7 @@ impl Header {
/// Set the timestamp field of the header. /// Set the timestamp field of the header.
pub fn set_timestamp(&mut self, a: u64) { self.timestamp = a; self.note_dirty(); } pub fn set_timestamp(&mut self, a: u64) { self.timestamp = a; self.note_dirty(); }
/// Set the timestamp field of the header to the current time. /// Set the timestamp field of the header to the current time.
pub fn set_timestamp_now(&mut self, but_later_than: u64) { self.timestamp = max(get_time().sec as u64, but_later_than + 1); self.note_dirty(); } pub fn set_timestamp_now(&mut self, but_later_than: u64) { self.timestamp = cmp::max(get_time().sec as u64, but_later_than + 1); self.note_dirty(); }
/// Set the number field of the header. /// Set the number field of the header.
pub fn set_number(&mut self, a: BlockNumber) { self.number = a; self.note_dirty(); } pub fn set_number(&mut self, a: BlockNumber) { self.number = a; self.note_dirty(); }
/// Set the author field of the header. /// Set the author field of the header.
@ -275,7 +275,7 @@ impl Decodable for Header {
number: r.val_at(8)?, number: r.val_at(8)?,
gas_limit: r.val_at(9)?, gas_limit: r.val_at(9)?,
gas_used: r.val_at(10)?, gas_used: r.val_at(10)?,
timestamp: min(r.val_at::<U256>(11)?, u64::max_value().into()).as_u64(), timestamp: cmp::min(r.val_at::<U256>(11)?, u64::max_value().into()).as_u64(),
extra_data: r.val_at(12)?, extra_data: r.val_at(12)?,
seal: vec![], seal: vec![],
hash: RefCell::new(Some(r.as_raw().sha3())), hash: RefCell::new(Some(r.as_raw().sha3())),

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use super::test_common::*; use std::sync::Arc;
use client::{BlockChainClient, Client, ClientConfig}; use client::{BlockChainClient, Client, ClientConfig};
use block::Block; use block::Block;
use ethereum; use ethereum;

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use super::test_common::*; use super::test_common::*;
use state::{Backend as StateBackend, State, Substate}; use state::{Backend as StateBackend, State, Substate};
use executive::*; use executive::*;

View File

@ -15,6 +15,8 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
pub use util::*; pub use util::*;
use std::collections::HashSet;
use std::io::Read;
use std::fs::{File, read_dir}; use std::fs::{File, read_dir};
use std::path::Path; use std::path::Path;
use std::ffi::OsString; use std::ffi::OsString;

View File

@ -106,6 +106,9 @@ extern crate semver;
extern crate stats; extern crate stats;
extern crate time; extern crate time;
extern crate transient_hashmap; extern crate transient_hashmap;
extern crate using_queue;
extern crate table;
extern crate bloomable;
extern crate vm; extern crate vm;
extern crate wasm; extern crate wasm;

View File

@ -15,9 +15,11 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::time::{Instant, Duration}; use std::time::{Instant, Duration};
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use util::*; use util::*;
use util::using_queue::{UsingQueue, GetAction}; use using_queue::{UsingQueue, GetAction};
use account_provider::{AccountProvider, SignError as AccountError}; use account_provider::{AccountProvider, SignError as AccountError};
use state::{State, CleanupMode}; use state::{State, CleanupMode};
use client::{MiningBlockChainClient, Executive, Executed, EnvInfo, TransactOptions, BlockId, CallAnalytics, TransactionId}; use client::{MiningBlockChainClient, Executive, Executed, EnvInfo, TransactOptions, BlockId, CallAnalytics, TransactionId};

View File

@ -106,7 +106,7 @@ use std::cmp;
use std::collections::{HashSet, HashMap, BTreeSet, BTreeMap}; use std::collections::{HashSet, HashMap, BTreeSet, BTreeMap};
use linked_hash_map::LinkedHashMap; use linked_hash_map::LinkedHashMap;
use util::{Address, H256, U256, HeapSizeOf}; use util::{Address, H256, U256, HeapSizeOf};
use util::table::Table; use table::Table;
use transaction::*; use transaction::*;
use error::{Error, TransactionError}; use error::{Error, TransactionError};
use client::TransactionImportResult; use client::TransactionImportResult;
@ -1447,7 +1447,7 @@ fn check_if_removed(sender: &Address, nonce: &U256, dropped: Option<HashMap<Addr
#[cfg(test)] #[cfg(test)]
pub mod test { pub mod test {
use rustc_hex::FromHex; use rustc_hex::FromHex;
use util::table::*; use table::Table;
use util::*; use util::*;
use ethkey::{Random, Generator}; use ethkey::{Random, Generator};
use error::{Error, TransactionError}; use error::{Error, TransactionError};

View File

@ -16,6 +16,7 @@
extern crate hyper; extern crate hyper;
use std::io::Write;
use hyper::header::ContentType; use hyper::header::ContentType;
use hyper::method::Method; use hyper::method::Method;
use hyper::client::{Request, Response, Client}; use hyper::client::{Request, Response, Client};

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::fmt;
use std::collections::BTreeMap;
use util::*; use util::*;
use state::Account; use state::Account;
use ethjson; use ethjson;
@ -166,7 +168,7 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option<A
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use util::*; use std::collections::BTreeMap;
use types::account_diff::*; use types::account_diff::*;
use super::{PodAccount, diff_pod}; use super::{PodAccount, diff_pod};

View File

@ -16,6 +16,8 @@
//! State of all accounts in the system expressed in Plain Old Data. //! State of all accounts in the system expressed in Plain Old Data.
use std::fmt;
use std::collections::BTreeMap;
use util::*; use util::*;
use pod_account::{self, PodAccount}; use pod_account::{self, PodAccount};
use types::state_diff::StateDiff; use types::state_diff::StateDiff;
@ -77,7 +79,7 @@ pub fn diff_pod(pre: &PodState, post: &PodState) -> StateDiff {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use util::*; use std::collections::BTreeMap;
use types::state_diff::*; use types::state_diff::*;
use types::account_diff::*; use types::account_diff::*;
use pod_account::PodAccount; use pod_account::PodAccount;

View File

@ -16,6 +16,8 @@
//! Creates and registers client and network services. //! Creates and registers client and network services.
use std::sync::Arc;
use std::path::Path;
use util::*; use util::*;
use io::*; use io::*;
use spec::Spec; use spec::Spec;

View File

@ -16,6 +16,10 @@
//! Parameters for a block chain. //! Parameters for a block chain.
use std::io::Read;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use super::genesis::Genesis; use super::genesis::Genesis;
use super::seal::Generic as GenericSeal; use super::seal::Generic as GenericSeal;
@ -512,6 +516,7 @@ impl Spec {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::str::FromStr;
use util::*; use util::*;
use views::*; use views::*;
use tests::helpers::get_temp_state_db; use tests::helpers::get_temp_state_db;

View File

@ -16,6 +16,9 @@
//! Single account in the system. //! Single account in the system.
use std::fmt;
use std::sync::Arc;
use std::collections::HashMap;
use util::*; use util::*;
use pod_account::*; use pod_account::*;
use rlp::*; use rlp::*;

View File

@ -21,6 +21,9 @@
use std::cell::{RefCell, RefMut}; use std::cell::{RefCell, RefMut};
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use std::collections::{HashMap, BTreeMap, HashSet};
use std::fmt;
use std::sync::Arc;
use receipt::Receipt; use receipt::Receipt;
use engines::Engine; use engines::Engine;

View File

@ -15,6 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{VecDeque, HashSet}; use std::collections::{VecDeque, HashSet};
use std::sync::Arc;
use lru_cache::LruCache; use lru_cache::LruCache;
use util::cache::MemoryLruCache; use util::cache::MemoryLruCache;
use util::journaldb::JournalDB; use util::journaldb::JournalDB;
@ -23,7 +24,7 @@ use util::hash::{H256};
use util::hashdb::HashDB; use util::hashdb::HashDB;
use state::{self, Account}; use state::{self, Account};
use header::BlockNumber; use header::BlockNumber;
use util::{Arc, Address, DBTransaction, UtilError, Mutex, Hashable}; use util::{Address, DBTransaction, UtilError, Mutex, Hashable};
use bloom_journal::{Bloom, BloomJournal}; use bloom_journal::{Bloom, BloomJournal};
use db::COL_ACCOUNT_BLOOM; use db::COL_ACCOUNT_BLOOM;
use byteorder::{LittleEndian, ByteOrder}; use byteorder::{LittleEndian, ByteOrder};

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::str::FromStr;
use std::sync::Arc;
use io::IoChannel; use io::IoChannel;
use client::{BlockChainClient, MiningBlockChainClient, Client, ClientConfig, BlockId}; use client::{BlockChainClient, MiningBlockChainClient, Client, ClientConfig, BlockId};
use state::{self, State, CleanupMode}; use state::{self, State, CleanupMode};

View File

@ -1,5 +1,6 @@
//! Tests of EVM integration with transaction execution. //! Tests of EVM integration with transaction execution.
use std::sync::Arc;
use vm::{EnvInfo, ActionParams, ActionValue, CallType}; use vm::{EnvInfo, ActionParams, ActionValue, CallType};
use evm::{Factory, VMType}; use evm::{Factory, VMType};
use executive::Executive; use executive::Executive;

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::BTreeMap;
use std::sync::Arc;
use ethkey::KeyPair; use ethkey::KeyPair;
use io::*; use io::*;
use client::{BlockChainClient, Client, ClientConfig}; use client::{BlockChainClient, Client, ClientConfig};
@ -347,7 +349,7 @@ pub fn get_good_dummy_block_fork_seq(start_number: usize, count: usize, parent_h
for i in start_number .. start_number + count + 1 { for i in start_number .. start_number + count + 1 {
let mut block_header = Header::new(); let mut block_header = Header::new();
block_header.set_gas_limit(test_engine.params().min_gas_limit); block_header.set_gas_limit(test_engine.params().min_gas_limit);
block_header.set_difficulty(U256::from(i).mul(U256([0, 1, 0, 0]))); block_header.set_difficulty(U256::from(i) * U256([0, 1, 0, 0]));
block_header.set_timestamp(rolling_timestamp); block_header.set_timestamp(rolling_timestamp);
block_header.set_number(i as u64); block_header.set_number(i as u64);
block_header.set_parent_hash(parent); block_header.set_parent_hash(parent);

View File

@ -20,7 +20,7 @@ use std::ops::Range;
use bloomchain::{Filter as BloomFilter, Bloom, Number}; use bloomchain::{Filter as BloomFilter, Bloom, Number};
use util::Address; use util::Address;
use util::sha3::Hashable; use util::sha3::Hashable;
use util::bloom::Bloomable; use bloomable::Bloomable;
use basic_types::LogBloom; use basic_types::LogBloom;
use trace::flat::FlatTrace; use trace::flat::FlatTrace;
use super::trace::{Action, Res}; use super::trace::{Action, Res};
@ -137,7 +137,7 @@ impl Filter {
mod tests { mod tests {
use util::Address; use util::Address;
use util::sha3::Hashable; use util::sha3::Hashable;
use util::bloom::Bloomable; use bloomable::Bloomable;
use trace::trace::{Action, Call, Res, Create, CreateResult, Suicide}; use trace::trace::{Action, Call, Res, Create, CreateResult, Suicide};
use trace::flat::FlatTrace; use trace::flat::FlatTrace;
use trace::{Filter, AddressesFilter, TraceError}; use trace::{Filter, AddressesFilter, TraceError};

View File

@ -18,7 +18,7 @@
use util::{U256, Bytes, Address}; use util::{U256, Bytes, Address};
use util::sha3::Hashable; use util::sha3::Hashable;
use util::bloom::Bloomable; use bloomable::Bloomable;
use rlp::*; use rlp::*;
use vm::ActionParams; use vm::ActionParams;

View File

@ -19,7 +19,9 @@
use std::thread::{self, JoinHandle}; use std::thread::{self, JoinHandle};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
use std::sync::{Condvar as SCondvar, Mutex as SMutex}; use std::sync::{Condvar as SCondvar, Mutex as SMutex, Arc};
use std::cmp;
use std::collections::{VecDeque, HashSet, HashMap};
use util::*; use util::*;
use io::*; use io::*;
use error::*; use error::*;
@ -234,8 +236,8 @@ impl<K: Kind> VerificationQueue<K> {
let scale_verifiers = config.verifier_settings.scale_verifiers; let scale_verifiers = config.verifier_settings.scale_verifiers;
let num_cpus = ::num_cpus::get(); let num_cpus = ::num_cpus::get();
let max_verifiers = min(num_cpus, MAX_VERIFIERS); let max_verifiers = cmp::min(num_cpus, MAX_VERIFIERS);
let default_amount = max(1, min(max_verifiers, config.verifier_settings.num_verifiers)); let default_amount = cmp::max(1, cmp::min(max_verifiers, config.verifier_settings.num_verifiers));
let state = Arc::new((Mutex::new(State::Work(default_amount)), Condvar::new())); let state = Arc::new((Mutex::new(State::Work(default_amount)), Condvar::new()));
let mut verifier_handles = Vec::with_capacity(max_verifiers); let mut verifier_handles = Vec::with_capacity(max_verifiers);
@ -278,8 +280,8 @@ impl<K: Kind> VerificationQueue<K> {
processing: RwLock::new(HashMap::new()), processing: RwLock::new(HashMap::new()),
empty: empty, empty: empty,
ticks_since_adjustment: AtomicUsize::new(0), ticks_since_adjustment: AtomicUsize::new(0),
max_queue_size: max(config.max_queue_size, MIN_QUEUE_LIMIT), max_queue_size: cmp::max(config.max_queue_size, MIN_QUEUE_LIMIT),
max_mem_use: max(config.max_mem_use, MIN_MEM_LIMIT), max_mem_use: cmp::max(config.max_mem_use, MIN_MEM_LIMIT),
scale_verifiers: scale_verifiers, scale_verifiers: scale_verifiers,
verifier_handles: verifier_handles, verifier_handles: verifier_handles,
state: state, state: state,
@ -567,7 +569,7 @@ impl<K: Kind> VerificationQueue<K> {
/// Removes up to `max` verified items from the queue /// Removes up to `max` verified items from the queue
pub fn drain(&self, max: usize) -> Vec<K::Verified> { pub fn drain(&self, max: usize) -> Vec<K::Verified> {
let mut verified = self.verification.verified.lock(); let mut verified = self.verification.verified.lock();
let count = min(max, verified.len()); let count = cmp::min(max, verified.len());
let result = verified.drain(..count).collect::<Vec<_>>(); let result = verified.drain(..count).collect::<Vec<_>>();
let drained_size = result.iter().map(HeapSizeOf::heap_size_of_children).fold(0, |a, c| a + c); let drained_size = result.iter().map(HeapSizeOf::heap_size_of_children).fold(0, |a, c| a + c);
@ -687,8 +689,8 @@ impl<K: Kind> VerificationQueue<K> {
// or below 1. // or below 1.
fn scale_verifiers(&self, target: usize) { fn scale_verifiers(&self, target: usize) {
let current = self.num_verifiers(); let current = self.num_verifiers();
let target = min(self.verifier_handles.len(), target); let target = cmp::min(self.verifier_handles.len(), target);
let target = max(1, target); let target = cmp::max(1, target);
debug!(target: "verification", "Scaling from {} to {} verifiers", current, target); debug!(target: "verification", "Scaling from {} to {} verifiers", current, target);
@ -725,7 +727,6 @@ impl<K: Kind> Drop for VerificationQueue<K> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use util::*;
use io::*; use io::*;
use spec::*; use spec::*;
use super::{BlockQueue, Config, State}; use super::{BlockQueue, Config, State};

View File

@ -21,6 +21,7 @@
//! 2. Signatures verification done in the queue. //! 2. Signatures verification done in the queue.
//! 3. Final verification against the blockchain done before enactment. //! 3. Final verification against the blockchain done before enactment.
use std::collections::HashSet;
use util::*; use util::*;
use engines::Engine; use engines::Engine;
use error::{BlockError, Error}; use error::{BlockError, Error};
@ -264,6 +265,7 @@ fn verify_block_integrity(block: &[u8], transactions_root: &H256, uncles_hash: &
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::collections::{BTreeMap, HashMap};
use util::*; use util::*;
use ethkey::{Random, Generator}; use ethkey::{Random, Generator};
use header::*; use header::*;

View File

@ -8,6 +8,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
rlp = { path = "../../util/rlp" } rlp = { path = "../../util/rlp" }
ethcore-util = { path = "../../util" } ethcore-util = { path = "../../util" }
ethjson = { path = "../../json" } ethjson = { path = "../../json" }
bloomable = { path = "../../util/bloomable" }
[dev-dependencies] [dev-dependencies]
rustc-hex= "1.0" rustc-hex= "1.0"

View File

@ -17,7 +17,7 @@
//! Blockchain filter //! Blockchain filter
use util::{Address, H256, Hashable, H2048}; use util::{Address, H256, Hashable, H2048};
use util::bloom::Bloomable; use bloomable::Bloomable;
use ids::BlockId; use ids::BlockId;
use log_entry::LogEntry; use log_entry::LogEntry;

View File

@ -19,6 +19,7 @@
extern crate ethcore_util as util; extern crate ethcore_util as util;
extern crate ethjson; extern crate ethjson;
extern crate rlp; extern crate rlp;
extern crate bloomable;
#[cfg(test)] #[cfg(test)]
extern crate rustc_hex; extern crate rustc_hex;

View File

@ -18,7 +18,7 @@
use std::ops::Deref; use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable}; use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable; use bloomable::Bloomable;
use rlp::*; use rlp::*;
use {BlockNumber}; use {BlockNumber};
@ -114,8 +114,8 @@ mod tests {
#[test] #[test]
fn test_empty_log_bloom() { fn test_empty_log_bloom() {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); let bloom = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".parse::<H2048>().unwrap();
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); let address = "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6".parse::<Address>().unwrap();
let log = LogEntry { let log = LogEntry {
address: address, address: address,
topics: vec![], topics: vec![],

View File

@ -16,6 +16,7 @@
//! Interface for Evm externalities. //! Interface for Evm externalities.
use std::sync::Arc;
use util::*; use util::*;
use call_type::CallType; use call_type::CallType;
use env_info::EnvInfo; use env_info::EnvInfo;

View File

@ -25,7 +25,7 @@ extern crate panic_hook;
use std::{env, fmt, process}; use std::{env, fmt, process};
use std::num::ParseIntError; use std::num::ParseIntError;
use docopt::Docopt; use docopt::Docopt;
use rustc_hex::{FromHex, FromHexError}; use rustc_hex::{ToHex, FromHex, FromHexError};
use ethkey::{KeyPair, Random, Brain, Prefix, Error as EthkeyError, Generator, sign, verify_public, verify_address}; use ethkey::{KeyPair, Random, Brain, Prefix, Error as EthkeyError, Generator, sign, verify_public, verify_address};
use std::io; use std::io;
@ -170,7 +170,7 @@ fn main() {
fn display(keypair: KeyPair, mode: DisplayMode) -> String { fn display(keypair: KeyPair, mode: DisplayMode) -> String {
match mode { match mode {
DisplayMode::KeyPair => format!("{}", keypair), DisplayMode::KeyPair => format!("{}", keypair),
DisplayMode::Secret => format!("{:?}", keypair.secret()), DisplayMode::Secret => format!("{}", keypair.secret().to_hex()),
DisplayMode::Public => format!("{:?}", keypair.public()), DisplayMode::Public => format!("{:?}", keypair.public()),
DisplayMode::Address => format!("{:?}", keypair.address()), DisplayMode::Address => format!("{:?}", keypair.address()),
} }
@ -248,9 +248,9 @@ address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned();
.collect::<Vec<String>>(); .collect::<Vec<String>>();
let expected = let expected =
"secret: 17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55 "secret: aa22b54c0cb43ee30a014afe5ef3664b1cde299feabca46cd3167a85a57c39f2
public: 689268c0ff57a20cd299fa60d3fb374862aff565b20b5f1767906a99e6e09f3ff04ca2b2a5cd22f62941db103c0356df1a8ed20ce322cab2483db67685afd124 public: c4c5398da6843632c123f543d714d2d2277716c11ff612b2a2f23c6bda4d6f0327c31cd58c55a9572c3cc141dade0c32747a13b7ef34c241b26c84adbb28fcf4
address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned(); address: 006e27b6a72e1f34c626762f3c4761547aff1421".to_owned();
assert_eq!(execute(command).unwrap(), expected); assert_eq!(execute(command).unwrap(), expected);
} }
@ -261,7 +261,7 @@ address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned();
.map(Into::into) .map(Into::into)
.collect::<Vec<String>>(); .collect::<Vec<String>>();
let expected = "17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55".to_owned(); let expected = "aa22b54c0cb43ee30a014afe5ef3664b1cde299feabca46cd3167a85a57c39f2".to_owned();
assert_eq!(execute(command).unwrap(), expected); assert_eq!(execute(command).unwrap(), expected);
} }
@ -272,7 +272,7 @@ address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned();
.map(Into::into) .map(Into::into)
.collect::<Vec<String>>(); .collect::<Vec<String>>();
let expected = "689268c0ff57a20cd299fa60d3fb374862aff565b20b5f1767906a99e6e09f3ff04ca2b2a5cd22f62941db103c0356df1a8ed20ce322cab2483db67685afd124".to_owned(); let expected = "c4c5398da6843632c123f543d714d2d2277716c11ff612b2a2f23c6bda4d6f0327c31cd58c55a9572c3cc141dade0c32747a13b7ef34c241b26c84adbb28fcf4".to_owned();
assert_eq!(execute(command).unwrap(), expected); assert_eq!(execute(command).unwrap(), expected);
} }
@ -283,7 +283,7 @@ address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned();
.map(Into::into) .map(Into::into)
.collect::<Vec<String>>(); .collect::<Vec<String>>();
let expected = "26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned(); let expected = "006e27b6a72e1f34c626762f3c4761547aff1421".to_owned();
assert_eq!(execute(command).unwrap(), expected); assert_eq!(execute(command).unwrap(), expected);
} }

View File

@ -17,6 +17,7 @@
use std::fmt; use std::fmt;
use std::ops::Deref; use std::ops::Deref;
use std::str::FromStr; use std::str::FromStr;
use rustc_hex::ToHex;
use secp256k1::key; use secp256k1::key;
use bigint::hash::H256; use bigint::hash::H256;
use {Error, SECP256K1}; use {Error, SECP256K1};
@ -26,6 +27,12 @@ pub struct Secret {
inner: H256, inner: H256,
} }
impl ToHex for Secret {
fn to_hex(&self) -> String {
self.inner.to_hex()
}
}
impl fmt::Debug for Secret { impl fmt::Debug for Secret {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31]) write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31])

View File

@ -16,6 +16,7 @@ serde_derive = "1.0"
ethcore = { path = "../ethcore" } ethcore = { path = "../ethcore" }
ethcore-util = { path = "../util" } ethcore-util = { path = "../util" }
evm = { path = "../ethcore/evm" } evm = { path = "../ethcore/evm" }
vm = { path = "../ethcore/vm" }
panic_hook = { path = "../panic_hook" } panic_hook = { path = "../panic_hook" }
[features] [features]

View File

@ -21,7 +21,7 @@ use std::collections::HashMap;
use util::{U256, H256, ToPretty}; use util::{U256, H256, ToPretty};
use display; use display;
use vm; use info as vm;
/// JSON formatting informant. /// JSON formatting informant.
#[derive(Default)] #[derive(Default)]

View File

@ -20,7 +20,7 @@ use ethcore::trace;
use util::ToPretty; use util::ToPretty;
use display; use display;
use vm; use info as vm;
/// Simple formatting informant. /// Simple formatting informant.
#[derive(Default)] #[derive(Default)]

View File

@ -25,6 +25,7 @@ extern crate serde;
extern crate serde_derive; extern crate serde_derive;
extern crate docopt; extern crate docopt;
extern crate ethcore_util as util; extern crate ethcore_util as util;
extern crate vm;
extern crate evm; extern crate evm;
extern crate panic_hook; extern crate panic_hook;
@ -36,10 +37,10 @@ use util::{U256, Bytes, Address};
use ethcore::spec; use ethcore::spec;
use vm::ActionParams; use vm::ActionParams;
mod vm; mod info;
mod display; mod display;
use vm::Informant; use info::Informant;
const USAGE: &'static str = r#" const USAGE: &'static str = r#"
EVM implementation for Parity. EVM implementation for Parity.
@ -90,7 +91,7 @@ fn run<T: Informant>(args: Args, mut informant: T) {
params.data = data; params.data = data;
informant.set_gas(gas); informant.set_gas(gas);
let result = vm::run(&mut informant, spec, params); let result = info::run(&mut informant, spec, params);
informant.finish(result); informant.finish(result);
} }

View File

@ -188,8 +188,9 @@ fn random_temp_path() -> PathBuf {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rustc_hex::FromHex;
use std::sync::{Arc, mpsc}; use std::sync::{Arc, mpsc};
use util::{Mutex, FromHex}; use util::Mutex;
use futures::future; use futures::future;
use fetch::{self, Fetch}; use fetch::{self, Fetch};
use parity_reactor::Remote; use parity_reactor::Remote;

View File

@ -260,7 +260,7 @@ mod tests {
let client = nanoipc::fast_client::<HypervisorServiceClient<_>>(url).unwrap(); let client = nanoipc::fast_client::<HypervisorServiceClient<_>>(url).unwrap();
client.handshake().unwrap(); client.handshake().unwrap();
client.module_ready(test_module_id); client.module_ready(test_module_id, url.to_owned());
}); });
let hypervisor = Hypervisor::with_url(url).local_module(test_module_id); let hypervisor = Hypervisor::with_url(url).local_module(test_module_id);

View File

@ -233,7 +233,7 @@ mod tests {
let _ = write_chunk(&mut transport, &mut progress, b"foobar"); let _ = write_chunk(&mut transport, &mut progress, b"foobar");
assert_eq!(b"foobar".into_vec(), transport); assert_eq!(b"foobar".to_vec(), transport);
assert_eq!(6, progress); assert_eq!(6, progress);
} }
@ -244,7 +244,7 @@ mod tests {
let _ = write_chunk(&mut transport, &mut progress, b"foobar"); let _ = write_chunk(&mut transport, &mut progress, b"foobar");
assert_eq!(b"bar".into_vec(), transport); assert_eq!(b"bar".to_vec(), transport);
assert_eq!(6, progress); assert_eq!(6, progress);
} }

View File

@ -51,5 +51,5 @@ impl WebApp for App {
#[test] #[test]
fn test_js() { fn test_js() {
parity_dapps_glue::js::build(env!("CARGO_MANIFEST_DIR")); parity_dapps_glue::js::build(env!("CARGO_MANIFEST_DIR"), "build");
} }

View File

@ -49,6 +49,7 @@ pub struct Tendermint {
mod tests { mod tests {
use serde_json; use serde_json;
use bigint::prelude::H160; use bigint::prelude::H160;
use hash::Address;
use spec::tendermint::Tendermint; use spec::tendermint::Tendermint;
use spec::validator_set::ValidatorSet; use spec::validator_set::ValidatorSet;

View File

@ -16,9 +16,9 @@
//! Test implementation of miner service. //! Test implementation of miner service.
use std::collections::{BTreeMap, HashMap};
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use util::{Address, H256, Bytes, U256}; use util::{Address, H256, Bytes, U256, RwLock, Mutex};
use util::standard::*;
use ethcore::error::{Error, CallError}; use ethcore::error::{Error, CallError};
use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics}; use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics};
use ethcore::block::{ClosedBlock, IsBlock}; use ethcore::block::{ClosedBlock, IsBlock};

View File

@ -20,8 +20,7 @@ if ! type $KCOV > /dev/null; then
exit 1 exit 1
fi fi
. ./scripts/targets.sh RUSTFLAGS="-C link-dead-code" cargo test --all --exclude parity-ipfs-api --exclude evmjit --no-run || exit $?
RUSTFLAGS="-C link-dead-code" cargo test $TARGETS --no-run || exit $?
KCOV_TARGET="target/cov" KCOV_TARGET="target/cov"

View File

@ -1,7 +1,5 @@
#!/bin/sh #!/bin/sh
# generate documentation only for partiy and ethcore libraries # generate documentation only for partiy and ethcore libraries
. ./scripts/targets.sh cargo doc --no-deps --verbose --all --exclude parity-ipfs-api --exclude evmjit &&
cargo doc --no-deps --verbose $TARGETS &&
echo '<meta http-equiv=refresh content=0;url=ethcore/index.html>' > target/doc/index.html echo '<meta http-equiv=refresh content=0;url=ethcore/index.html>' > target/doc/index.html

View File

@ -1,6 +1,5 @@
#!/bin/sh #!/bin/sh
FILE=./.git/hooks/pre-push FILE=./.git/hooks/pre-push
. ./scripts/targets.sh
echo "#!/bin/sh\n" > $FILE echo "#!/bin/sh\n" > $FILE
# Exit on any error # Exit on any error
@ -8,7 +7,6 @@ echo "set -e" >> $FILE
# Run release build # Run release build
echo "cargo build --features dev" >> $FILE echo "cargo build --features dev" >> $FILE
# Build tests # Build tests
echo "cargo test --no-run --features dev \\" >> $FILE echo "cargo test --no-run --features dev --all --exclude parity-ipfs-api --exclude evmjit" >> $FILE
echo $TARGETS >> $FILE
echo "" >> $FILE echo "" >> $FILE
chmod +x $FILE chmod +x $FILE

View File

@ -1,24 +0,0 @@
#!/bin/bash
export TARGETS="
-p rlp\
-p ethash \
-p ethcore \
-p ethcore-bigint\
-p parity-dapps \
-p parity-rpc \
-p parity-rpc-client \
-p rpc-cli \
-p ethcore-util \
-p ethcore-network \
-p ethcore-io \
-p ethkey \
-p ethstore \
-p ethsync \
-p ethcore-ipc \
-p ethcore-ipc-tests \
-p ethcore-ipc-nano \
-p ethcore-light \
-p wasm \
-p evm \
-p parity"

View File

@ -342,7 +342,7 @@ mod tests {
let mut core = Core::new().expect("Tokio Core should be created with no errors"); let mut core = Core::new().expect("Tokio Core should be created with no errors");
let mut buffer = vec![0u8; 2048]; let mut buffer = vec![0u8; 2048];
let mut data_vec = data.as_bytes().into_vec(); let mut data_vec = data.as_bytes().to_vec();
data_vec.extend(b"\n"); data_vec.extend(b"\n");
let stream = TcpStream::connect(addr, &core.handle()) let stream = TcpStream::connect(addr, &core.handle())
@ -353,7 +353,7 @@ mod tests {
io::read(stream, &mut buffer) io::read(stream, &mut buffer)
}) })
.and_then(|(_, read_buf, len)| { .and_then(|(_, read_buf, len)| {
future::ok(read_buf[0..len].into_vec()) future::ok(read_buf[0..len].to_vec())
}); });
let result = core.run(stream).expect("Core should run with no errors"); let result = core.run(stream).expect("Core should run with no errors");
@ -454,7 +454,7 @@ mod tests {
let mut auth_request = let mut auth_request =
r#"{"jsonrpc": "2.0", "method": "mining.authorize", "params": ["miner1", ""], "id": 1}"# r#"{"jsonrpc": "2.0", "method": "mining.authorize", "params": ["miner1", ""], "id": 1}"#
.as_bytes() .as_bytes()
.into_vec(); .to_vec();
auth_request.extend(b"\n"); auth_request.extend(b"\n");
let mut core = Core::new().expect("Tokio Core should be created with no errors"); let mut core = Core::new().expect("Tokio Core should be created with no errors");
@ -487,7 +487,7 @@ mod tests {
}) })
.and_then(|(_, read_buf, len)| { .and_then(|(_, read_buf, len)| {
trace!(target: "stratum", "Received work from server"); trace!(target: "stratum", "Received work from server");
future::ok(read_buf[0..len].into_vec()) future::ok(read_buf[0..len].to_vec())
}); });
let response = String::from_utf8( let response = String::from_utf8(
core.run(stream).expect("Core should run with no errors") core.run(stream).expect("Core should run with no errors")

View File

@ -18,6 +18,8 @@
/// Blockchain downloader /// Blockchain downloader
/// ///
use std::collections::{HashSet, VecDeque};
use std::cmp;
use util::*; use util::*;
use rlp::*; use rlp::*;
use ethcore::views::{BlockView}; use ethcore::views::{BlockView};
@ -386,7 +388,7 @@ impl BlockDownloader {
debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash); debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash);
self.reset(); self.reset();
} else { } else {
let n = start - min(self.retract_step, start); let n = start - cmp::min(self.retract_step, start);
self.retract_step *= 2; self.retract_step *= 2;
match io.chain().block_hash(BlockId::Number(n)) { match io.chain().block_hash(BlockId::Number(n)) {
Some(h) => { Some(h) => {

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{HashSet, HashMap};
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use smallvec::SmallVec; use smallvec::SmallVec;
use util::*; use util::*;

View File

@ -89,6 +89,8 @@
/// All other messages are ignored. /// All other messages are ignored.
/// ///
use std::collections::{HashSet, HashMap};
use std::cmp;
use util::*; use util::*;
use rlp::*; use rlp::*;
use network::*; use network::*;
@ -421,7 +423,7 @@ impl ChainSync {
start_block_number: self.starting_block, start_block_number: self.starting_block,
last_imported_block_number: Some(last_imported_number), last_imported_block_number: Some(last_imported_number),
last_imported_old_block_number: self.old_blocks.as_ref().map(|d| d.last_imported_block_number()), last_imported_old_block_number: self.old_blocks.as_ref().map(|d| d.last_imported_block_number()),
highest_block_number: self.highest_block.map(|n| max(n, last_imported_number)), highest_block_number: self.highest_block.map(|n| cmp::max(n, last_imported_number)),
blocks_received: if last_imported_number > self.starting_block { last_imported_number - self.starting_block } else { 0 }, blocks_received: if last_imported_number > self.starting_block { last_imported_number - self.starting_block } else { 0 },
blocks_total: match self.highest_block { Some(x) if x > self.starting_block => x - self.starting_block, _ => 0 }, blocks_total: match self.highest_block { Some(x) if x > self.starting_block => x - self.starting_block, _ => 0 },
num_peers: self.peers.values().filter(|p| p.is_allowed()).count(), num_peers: self.peers.values().filter(|p| p.is_allowed()).count(),
@ -961,7 +963,7 @@ impl ChainSync {
} }
if self.state != SyncState::Idle { if self.state != SyncState::Idle {
trace!(target: "sync", "Ignoring new hashes since we're already downloading."); trace!(target: "sync", "Ignoring new hashes since we're already downloading.");
let max = r.iter().take(MAX_NEW_HASHES).map(|item| item.val_at::<BlockNumber>(1).unwrap_or(0)).fold(0u64, max); let max = r.iter().take(MAX_NEW_HASHES).map(|item| item.val_at::<BlockNumber>(1).unwrap_or(0)).fold(0u64, cmp::max);
if max > self.highest_block.unwrap_or(0) { if max > self.highest_block.unwrap_or(0) {
self.highest_block = Some(max); self.highest_block = Some(max);
} }
@ -1473,7 +1475,7 @@ impl ChainSync {
let mut item_count = r.item_count()?; let mut item_count = r.item_count()?;
trace!(target: "sync", "{:02} -> Transactions ({} entries)", peer_id, item_count); trace!(target: "sync", "{:02} -> Transactions ({} entries)", peer_id, item_count);
item_count = min(item_count, MAX_TX_TO_IMPORT); item_count = cmp::min(item_count, MAX_TX_TO_IMPORT);
let mut transactions = Vec::with_capacity(item_count); let mut transactions = Vec::with_capacity(item_count);
for i in 0 .. item_count { for i in 0 .. item_count {
let rlp = r.at(i)?; let rlp = r.at(i)?;
@ -1549,11 +1551,11 @@ impl ChainSync {
}; };
let mut number = if reverse { let mut number = if reverse {
min(last, number) cmp::min(last, number)
} else { } else {
max(0, number) cmp::max(0, number)
}; };
let max_count = min(MAX_HEADERS_TO_SEND, max_headers); let max_count = cmp::min(MAX_HEADERS_TO_SEND, max_headers);
let mut count = 0; let mut count = 0;
let mut data = Bytes::new(); let mut data = Bytes::new();
let inc = (skip + 1) as BlockNumber; let inc = (skip + 1) as BlockNumber;
@ -1594,7 +1596,7 @@ impl ChainSync {
debug!(target: "sync", "Empty GetBlockBodies request, ignoring."); debug!(target: "sync", "Empty GetBlockBodies request, ignoring.");
return Ok(None); return Ok(None);
} }
count = min(count, MAX_BODIES_TO_SEND); count = cmp::min(count, MAX_BODIES_TO_SEND);
let mut added = 0usize; let mut added = 0usize;
let mut data = Bytes::new(); let mut data = Bytes::new();
for i in 0..count { for i in 0..count {
@ -1617,7 +1619,7 @@ impl ChainSync {
debug!(target: "sync", "Empty GetNodeData request, ignoring."); debug!(target: "sync", "Empty GetNodeData request, ignoring.");
return Ok(None); return Ok(None);
} }
count = min(count, MAX_NODE_DATA_TO_SEND); count = cmp::min(count, MAX_NODE_DATA_TO_SEND);
let mut added = 0usize; let mut added = 0usize;
let mut data = Vec::new(); let mut data = Vec::new();
for i in 0..count { for i in 0..count {
@ -1641,7 +1643,7 @@ impl ChainSync {
debug!(target: "sync", "Empty GetReceipts request, ignoring."); debug!(target: "sync", "Empty GetReceipts request, ignoring.");
return Ok(None); return Ok(None);
} }
count = min(count, MAX_RECEIPTS_HEADERS_TO_SEND); count = cmp::min(count, MAX_RECEIPTS_HEADERS_TO_SEND);
let mut added_headers = 0usize; let mut added_headers = 0usize;
let mut added_receipts = 0usize; let mut added_receipts = 0usize;
let mut data = Bytes::new(); let mut data = Bytes::new();
@ -1915,8 +1917,8 @@ impl ChainSync {
// take sqrt(x) peers // take sqrt(x) peers
let mut peers = peers.to_vec(); let mut peers = peers.to_vec();
let mut count = (peers.len() as f64).powf(0.5).round() as usize; let mut count = (peers.len() as f64).powf(0.5).round() as usize;
count = min(count, MAX_PEERS_PROPAGATION); count = cmp::min(count, MAX_PEERS_PROPAGATION);
count = max(count, MIN_PEERS_PROPAGATION); count = cmp::max(count, MIN_PEERS_PROPAGATION);
random::new().shuffle(&mut peers); random::new().shuffle(&mut peers);
peers.truncate(count); peers.truncate(count);
peers peers
@ -2006,7 +2008,7 @@ impl ChainSync {
fn select_peers_for_transactions<F>(&self, filter: F) -> Vec<PeerId> fn select_peers_for_transactions<F>(&self, filter: F) -> Vec<PeerId>
where F: Fn(&PeerId) -> bool { where F: Fn(&PeerId) -> bool {
// sqrt(x)/x scaled to max u32 // sqrt(x)/x scaled to max u32
let fraction = (self.peers.len() as f64).powf(-0.5).mul(u32::max_value() as f64).round() as u32; let fraction = ((self.peers.len() as f64).powf(-0.5) * (u32::max_value() as f64).round()) as u32;
let small = self.peers.len() < MIN_PEERS_PROPAGATION; let small = self.peers.len() < MIN_PEERS_PROPAGATION;
let mut random = random::new(); let mut random = random::new();
@ -2112,7 +2114,7 @@ impl ChainSync {
peers.insert(peer_id); peers.insert(peer_id);
self.send_packet(io, peer_id, TRANSACTIONS_PACKET, rlp); self.send_packet(io, peer_id, TRANSACTIONS_PACKET, rlp);
trace!(target: "sync", "{:02} <- Transactions ({} entries)", peer_id, sent); trace!(target: "sync", "{:02} <- Transactions ({} entries)", peer_id, sent);
max_sent = max(max_sent, sent); max_sent = cmp::max(max_sent, sent);
} }
debug!(target: "sync", "Sent up to {} transactions to {} peers.", max_sent, lucky_peers_len); debug!(target: "sync", "Sent up to {} transactions to {} peers.", max_sent, lucky_peers_len);
} }

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*; use std::sync::Arc;
use ethcore::client::{TestBlockChainClient, BlockChainClient, BlockId, EachBlockWith}; use ethcore::client::{TestBlockChainClient, BlockChainClient, BlockId, EachBlockWith};
use chain::{SyncState}; use chain::{SyncState};
use super::helpers::*; use super::helpers::*;

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use util::*; use util::*;
use io::{IoHandler, IoContext, IoChannel}; use io::{IoHandler, IoContext, IoChannel};
use ethcore::client::{BlockChainClient, Client}; use ethcore::client::{BlockChainClient, Client};

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{VecDeque, HashSet, HashMap};
use std::sync::Arc;
use util::*; use util::*;
use network::*; use network::*;
use tests::snapshot::*; use tests::snapshot::*;

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::collections::HashMap;
use std::sync::Arc;
use util::*; use util::*;
use ethcore::snapshot::{SnapshotService, ManifestData, RestorationStatus}; use ethcore::snapshot::{SnapshotService, ManifestData, RestorationStatus};
use ethcore::header::BlockNumber; use ethcore::header::BlockNumber;

View File

@ -22,5 +22,4 @@ case $1 in
;; ;;
esac esac
. ./scripts/targets.sh cargo test -j 8 $OPTIONS --features "$FEATURES" --all --exclude parity-ipfs-api --exclude evmjit $1
cargo test -j 8 $OPTIONS --features "$FEATURES" $TARGETS $1 \

View File

@ -28,8 +28,6 @@ vergen = "0.1"
target_info = "0.1" target_info = "0.1"
ethcore-bigint = { path = "bigint", features = ["heapsizeof"] } ethcore-bigint = { path = "bigint", features = ["heapsizeof"] }
parking_lot = "0.4" parking_lot = "0.4"
using_queue = { path = "using_queue" }
table = { path = "table" }
ansi_term = "0.9" ansi_term = "0.9"
tiny-keccak= "1.0" tiny-keccak= "1.0"
ethcore-bloom-journal = { path = "bloom" } ethcore-bloom-journal = { path = "bloom" }

10
util/bloomable/Cargo.toml Normal file
View File

@ -0,0 +1,10 @@
[package]
name = "bloomable"
version = "0.1.0"
authors = ["debris <marek.kotewicz@gmail.com>"]
[dependencies]
ethcore-bigint = { path = "../bigint" }
[dev-dependencies]
tiny-keccak = "1.2.1"

View File

@ -16,9 +16,11 @@
//! Bloom operations. //! Bloom operations.
extern crate ethcore_bigint;
use std::mem; use std::mem;
use std::ops::DerefMut; use std::ops::DerefMut;
use {H64, H160, H256, H512, H520, H2048}; use ethcore_bigint::hash::{H64, H160, H256, H512, H520, H2048};
/// Returns log2. /// Returns log2.
pub fn log2(x: usize) -> u32 { pub fn log2(x: usize) -> u32 {
@ -115,31 +117,3 @@ impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64); impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65); impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256); impl_bloomable_for_hash!(H2048, 256);
#[cfg(test)]
mod tests {
use {H160, H256, H2048};
use sha3::Hashable;
use super::Bloomable;
#[test]
fn shift_bloomed() {
let bloom: H2048 = "00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let topic: H256 = "02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc".into();
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()));
}
}

View File

@ -0,0 +1,31 @@
extern crate tiny_keccak;
extern crate ethcore_bigint;
extern crate bloomable;
use ethcore_bigint::hash::{H160, H256, H2048};
use bloomable::Bloomable;
use tiny_keccak::keccak256;
fn sha3(input: &[u8]) -> H256 {
keccak256(input).into()
}
#[test]
fn shift_bloomed() {
let bloom: H2048 = "00000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020000000000000000000000000000000000000000000008000000001000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let topic: H256 = "02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc".into();
let mut my_bloom = H2048::default();
assert!(!my_bloom.contains_bloomed(&sha3(&address)));
assert!(!my_bloom.contains_bloomed(&sha3(&topic)));
my_bloom.shift_bloomed(&sha3(&address));
assert!(my_bloom.contains_bloomed(&sha3(&address)));
assert!(!my_bloom.contains_bloomed(&sha3(&topic)));
my_bloom.shift_bloomed(&sha3(&topic));
assert_eq!(my_bloom, bloom);
assert!(my_bloom.contains_bloomed(&sha3(&address)));
assert!(my_bloom.contains_bloomed(&sha3(&topic)));
}

View File

@ -16,9 +16,10 @@
use super::*; use super::*;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::Arc;
use std::thread; use std::thread;
use std::time::*; use std::time::*;
use util::common::*; use util::{Bytes, Mutex};
use io::TimerToken; use io::TimerToken;
use ethkey::{Random, Generator}; use ethkey::{Random, Generator};

View File

@ -16,13 +16,7 @@
//! Utils common types and macros global reexport. //! Utils common types and macros global reexport.
pub use standard::*; use std::io;
pub use error::*;
pub use bytes::*;
pub use vector::*;
pub use sha3::*;
pub use bigint::prelude::*;
pub use bigint::hash;
#[macro_export] #[macro_export]
macro_rules! vec_into { macro_rules! vec_into {
@ -88,8 +82,8 @@ macro_rules! map_into {
#[macro_export] #[macro_export]
macro_rules! flush { macro_rules! flush {
($arg:expr) => ($crate::flush($arg.into())); ($arg:expr) => ($crate::common::flush($arg.into()));
($($arg:tt)*) => ($crate::flush(format!("{}", format_args!($($arg)*)))); ($($arg:tt)*) => ($crate::common::flush(format!("{}", format_args!($($arg)*))));
} }
#[macro_export] #[macro_export]
@ -100,8 +94,8 @@ macro_rules! flushln {
#[doc(hidden)] #[doc(hidden)]
pub fn flush(s: String) { pub fn flush(s: String) {
let _ = ::std::io::stdout().write(s.as_bytes()); let _ = io::Write::write(&mut io::stdout(), s.as_bytes());
let _ = ::std::io::stdout().flush(); let _ = io::Write::flush(&mut io::stdout());
} }
#[test] #[test]

View File

@ -19,7 +19,7 @@
use rustc_hex::FromHexError; use rustc_hex::FromHexError;
use rlp::DecoderError; use rlp::DecoderError;
use std::fmt; use std::fmt;
use hash::H256; use bigint::hash::H256;
#[derive(Debug)] #[derive(Debug)]
/// Error in database subsystem. /// Error in database subsystem.

View File

@ -16,13 +16,15 @@
//! Disk-backed `HashDB` implementation. //! Disk-backed `HashDB` implementation.
use common::*; use std::collections::HashMap;
use std::sync::Arc;
use rlp::*; use rlp::*;
use hashdb::*; use hashdb::*;
use memorydb::*; use memorydb::*;
use super::{DB_PREFIX_LEN, LATEST_ERA_KEY}; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY};
use super::traits::JournalDB; use super::traits::JournalDB;
use kvdb::{KeyValueDB, DBTransaction}; use kvdb::{KeyValueDB, DBTransaction};
use {Bytes, H256, BaseDataError, UtilError};
/// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay /// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay
/// and latent-removal semantics. /// and latent-removal semantics.
@ -196,11 +198,12 @@ mod tests {
#![cfg_attr(feature="dev", allow(blacklisted_name))] #![cfg_attr(feature="dev", allow(blacklisted_name))]
#![cfg_attr(feature="dev", allow(similar_names))] #![cfg_attr(feature="dev", allow(similar_names))]
use common::*; use std::path::Path;
use hashdb::{HashDB, DBValue}; use hashdb::{HashDB, DBValue};
use super::*; use super::*;
use journaldb::traits::JournalDB; use journaldb::traits::JournalDB;
use kvdb::Database; use kvdb::Database;
use {Hashable, H32};
#[test] #[test]
fn insert_same_in_fork() { fn insert_same_in_fork() {

View File

@ -16,13 +16,19 @@
//! Disk-backed `HashDB` implementation. //! Disk-backed `HashDB` implementation.
use common::*; use std::fmt;
use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::RwLock;
use heapsize::HeapSizeOf;
use itertools::Itertools;
use rlp::*; use rlp::*;
use hashdb::*; use hashdb::*;
use memorydb::*; use memorydb::*;
use super::{DB_PREFIX_LEN, LATEST_ERA_KEY}; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY};
use super::traits::JournalDB; use super::traits::JournalDB;
use kvdb::{KeyValueDB, DBTransaction}; use kvdb::{KeyValueDB, DBTransaction};
use {H256, BaseDataError, UtilError, Bytes};
#[derive(Clone, PartialEq, Eq)] #[derive(Clone, PartialEq, Eq)]
struct RefInfo { struct RefInfo {
@ -549,12 +555,13 @@ mod tests {
#![cfg_attr(feature="dev", allow(blacklisted_name))] #![cfg_attr(feature="dev", allow(blacklisted_name))]
#![cfg_attr(feature="dev", allow(similar_names))] #![cfg_attr(feature="dev", allow(similar_names))]
use common::*; use std::path::Path;
use hashdb::{HashDB, DBValue}; use hashdb::{HashDB, DBValue};
use super::*; use super::*;
use super::super::traits::JournalDB; use super::super::traits::JournalDB;
use ethcore_logger::init_log; use ethcore_logger::init_log;
use kvdb::{DatabaseConfig}; use kvdb::{DatabaseConfig};
use {Hashable, H32};
#[test] #[test]
fn insert_same_in_fork() { fn insert_same_in_fork() {

View File

@ -16,7 +16,8 @@
//! `JournalDB` interface and implementation. //! `JournalDB` interface and implementation.
use common::*; use std::{fmt, str};
use std::sync::Arc;
/// Export the journaldb module. /// Export the journaldb module.
pub mod traits; pub mod traits;
@ -59,7 +60,7 @@ impl Default for Algorithm {
fn default() -> Algorithm { Algorithm::OverlayRecent } fn default() -> Algorithm { Algorithm::OverlayRecent }
} }
impl FromStr for Algorithm { impl str::FromStr for Algorithm {
type Err = String; type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {

View File

@ -16,13 +16,17 @@
//! `JournalDB` over in-memory overlay //! `JournalDB` over in-memory overlay
use common::*; use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::RwLock;
use heapsize::HeapSizeOf;
use rlp::*; use rlp::*;
use hashdb::*; use hashdb::*;
use memorydb::*; use memorydb::*;
use super::{DB_PREFIX_LEN, LATEST_ERA_KEY}; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY};
use kvdb::{KeyValueDB, DBTransaction}; use kvdb::{KeyValueDB, DBTransaction};
use super::JournalDB; use super::JournalDB;
use {H256, BaseDataError, UtilError, Bytes, H256FastMap};
/// Implementation of the `JournalDB` trait for a disk-backed database with a memory overlay /// Implementation of the `JournalDB` trait for a disk-backed database with a memory overlay
/// and, possibly, latent-removal semantics. /// and, possibly, latent-removal semantics.
@ -450,12 +454,13 @@ mod tests {
#![cfg_attr(feature="dev", allow(blacklisted_name))] #![cfg_attr(feature="dev", allow(blacklisted_name))]
#![cfg_attr(feature="dev", allow(similar_names))] #![cfg_attr(feature="dev", allow(similar_names))]
use common::*; use std::path::Path;
use super::*; use super::*;
use hashdb::{HashDB, DBValue}; use hashdb::{HashDB, DBValue};
use ethcore_logger::init_log; use ethcore_logger::init_log;
use journaldb::JournalDB; use journaldb::JournalDB;
use kvdb::Database; use kvdb::Database;
use {H32, Hashable};
fn new_db(path: &Path) -> OverlayRecentDB { fn new_db(path: &Path) -> OverlayRecentDB {
let backing = Arc::new(Database::open_default(path.to_str().unwrap()).unwrap()); let backing = Arc::new(Database::open_default(path.to_str().unwrap()).unwrap());

View File

@ -16,7 +16,9 @@
//! Disk-backed, ref-counted `JournalDB` implementation. //! Disk-backed, ref-counted `JournalDB` implementation.
use common::*; use std::collections::HashMap;
use std::sync::Arc;
use heapsize::HeapSizeOf;
use rlp::*; use rlp::*;
use hashdb::*; use hashdb::*;
use overlaydb::OverlayDB; use overlaydb::OverlayDB;
@ -24,6 +26,7 @@ use memorydb::MemoryDB;
use super::{DB_PREFIX_LEN, LATEST_ERA_KEY}; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY};
use super::traits::JournalDB; use super::traits::JournalDB;
use kvdb::{KeyValueDB, DBTransaction}; use kvdb::{KeyValueDB, DBTransaction};
use {UtilError, H256, Bytes};
/// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay /// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay
/// and latent-removal semantics. /// and latent-removal semantics.
@ -210,10 +213,10 @@ mod tests {
#![cfg_attr(feature="dev", allow(blacklisted_name))] #![cfg_attr(feature="dev", allow(blacklisted_name))]
#![cfg_attr(feature="dev", allow(similar_names))] #![cfg_attr(feature="dev", allow(similar_names))]
use common::*;
use hashdb::{HashDB, DBValue}; use hashdb::{HashDB, DBValue};
use super::*; use super::*;
use super::super::traits::JournalDB; use super::super::traits::JournalDB;
use {Hashable};
#[test] #[test]
fn long_history() { fn long_history() {

View File

@ -16,9 +16,10 @@
//! Disk-backed `HashDB` implementation. //! Disk-backed `HashDB` implementation.
use common::*; use std::sync::Arc;
use hashdb::*; use hashdb::*;
use kvdb::{self, DBTransaction}; use kvdb::{self, DBTransaction};
use {Bytes, H256, UtilError};
/// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually /// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually
/// exclusive actions. /// exclusive actions.

View File

@ -16,16 +16,21 @@
//! Key-Value store abstraction with `RocksDB` backend. //! Key-Value store abstraction with `RocksDB` backend.
use std::{mem, fs};
use std::collections::{HashMap, BTreeMap};
use std::io::ErrorKind; use std::io::ErrorKind;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::path::PathBuf; use std::path::{PathBuf, Path};
use parking_lot::{Mutex, MutexGuard, RwLock};
use common::*;
use elastic_array::*; use elastic_array::*;
use hashdb::DBValue; use hashdb::DBValue;
use rlp::{UntrustedRlp, RlpType, Compressible}; use rlp::{UntrustedRlp, RlpType, Compressible};
use rocksdb::{DB, Writable, WriteBatch, WriteOptions, IteratorMode, DBIterator, use rocksdb::{DB, Writable, WriteBatch, WriteOptions, IteratorMode, DBIterator,
Options, DBCompactionStyle, BlockBasedOptions, Direction, Cache, Column, ReadOptions}; Options, DBCompactionStyle, BlockBasedOptions, Direction, Cache, Column, ReadOptions};
use {UtilError, Bytes};
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use regex::Regex; use regex::Regex;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
@ -299,6 +304,7 @@ impl Default for CompactionProfile {
/// Given output of df command return Linux rotational flag file path. /// Given output of df command return Linux rotational flag file path.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub fn rotational_from_df_output(df_out: Vec<u8>) -> Option<PathBuf> { pub fn rotational_from_df_output(df_out: Vec<u8>) -> Option<PathBuf> {
use std::str;
str::from_utf8(df_out.as_slice()) str::from_utf8(df_out.as_slice())
.ok() .ok()
// Get the drive name. // Get the drive name.
@ -319,6 +325,7 @@ impl CompactionProfile {
/// Attempt to determine the best profile automatically, only Linux for now. /// Attempt to determine the best profile automatically, only Linux for now.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub fn auto(db_path: &Path) -> CompactionProfile { pub fn auto(db_path: &Path) -> CompactionProfile {
use std::io::Read;
let hdd_check_file = db_path let hdd_check_file = db_path
.to_str() .to_str()
.and_then(|path_str| Command::new("df").arg(path_str).output().ok()) .and_then(|path_str| Command::new("df").arg(path_str).output().ok())

View File

@ -112,11 +112,6 @@ extern crate ethcore_logger;
#[macro_use] #[macro_use]
extern crate log as rlog; extern crate log as rlog;
pub extern crate using_queue;
pub extern crate table;
pub mod bloom;
pub mod standard;
#[macro_use] #[macro_use]
pub mod common; pub mod common;
pub mod error; pub mod error;
@ -139,7 +134,6 @@ pub mod snappy;
pub mod cache; pub mod cache;
mod timer; mod timer;
pub use common::*;
pub use misc::*; pub use misc::*;
pub use hashdb::*; pub use hashdb::*;
pub use memorydb::MemoryDB; pub use memorydb::MemoryDB;
@ -147,11 +141,20 @@ pub use overlaydb::*;
pub use journaldb::JournalDB; pub use journaldb::JournalDB;
pub use triehash::*; pub use triehash::*;
pub use trie::{Trie, TrieMut, TrieDB, TrieDBMut, TrieFactory, TrieError, SecTrieDB, SecTrieDBMut}; pub use trie::{Trie, TrieMut, TrieDB, TrieDBMut, TrieFactory, TrieError, SecTrieDB, SecTrieDBMut};
pub use nibbleslice::*;
pub use semantic_version::*; pub use semantic_version::*;
pub use kvdb::*; pub use kvdb::*;
pub use timer::*; pub use timer::*;
pub use error::*;
pub use bytes::*;
pub use vector::*;
pub use sha3::*;
pub use bigint::prelude::*;
pub use bigint::hash;
pub use ansi_term::{Colour, Style}; pub use ansi_term::{Colour, Style};
pub use heapsize::HeapSizeOf;
pub use itertools::Itertools;
pub use parking_lot::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
/// 160-bit integer representing account address /// 160-bit integer representing account address
pub type Address = H160; pub type Address = H160;

View File

@ -18,12 +18,12 @@
//! A random temp directory is created. A database is created within it, and migrations //! A random temp directory is created. A database is created within it, and migrations
//! are performed in temp sub-directories. //! are performed in temp sub-directories.
use common::*; use std::collections::BTreeMap;
use std::sync::Arc;
use std::path::{Path, PathBuf};
use migration::{Batch, Config, Error, SimpleMigration, Migration, Manager}; use migration::{Batch, Config, Error, SimpleMigration, Migration, Manager};
use kvdb::Database; use kvdb::Database;
use devtools::RandomTempPath; use devtools::RandomTempPath;
use std::path::PathBuf;
fn db_path(path: &Path) -> PathBuf { fn db_path(path: &Path) -> PathBuf {
let mut p = path.to_owned(); let mut p = path.to_owned();

View File

@ -16,9 +16,9 @@
//! Diff misc. //! Diff misc.
use common::*;
use rlp::RlpStream; use rlp::RlpStream;
use target_info::Target; use target_info::Target;
use Bytes;
include!(concat!(env!("OUT_DIR"), "/version.rs")); include!(concat!(env!("OUT_DIR"), "/version.rs"));
include!(concat!(env!("OUT_DIR"), "/rustc_version.rs")); include!(concat!(env!("OUT_DIR"), "/rustc_version.rs"));
@ -60,9 +60,9 @@ pub fn version() -> String {
pub fn version_data() -> Bytes { pub fn version_data() -> Bytes {
let mut s = RlpStream::new_list(4); let mut s = RlpStream::new_list(4);
let v = let v =
(u32::from_str(env!("CARGO_PKG_VERSION_MAJOR")).expect("Environment variables are known to be valid; qed") << 16) + (env!("CARGO_PKG_VERSION_MAJOR").parse::<u32>().expect("Environment variables are known to be valid; qed") << 16) +
(u32::from_str(env!("CARGO_PKG_VERSION_MINOR")).expect("Environment variables are known to be valid; qed") << 8) + (env!("CARGO_PKG_VERSION_MINOR").parse::<u32>().expect("Environment variables are known to be valid; qed") << 8) +
u32::from_str(env!("CARGO_PKG_VERSION_PATCH")).expect("Environment variables are known to be valid; qed"); env!("CARGO_PKG_VERSION_PATCH").parse::<u32>().expect("Environment variables are known to be valid; qed");
s.append(&v); s.append(&v);
s.append(&"Parity"); s.append(&"Parity");
s.append(&rustc_version()); s.append(&rustc_version());

View File

@ -17,7 +17,7 @@
//! An owning, nibble-oriented byte vector. //! An owning, nibble-oriented byte vector.
use ::NibbleSlice; use nibbleslice::NibbleSlice;
use elastic_array::ElasticArray36; use elastic_array::ElasticArray36;
/// Owning, nibble-oriented byte vector. Counterpart to `NibbleSlice`. /// Owning, nibble-oriented byte vector. Counterpart to `NibbleSlice`.

View File

@ -1,45 +0,0 @@
// Copyright 2015-2017 Parity Technologies (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 <http://www.gnu.org/licenses/>.
//! Std lib global reexports.
pub use std::io;
pub use std::fs;
pub use std::str;
pub use std::fmt;
pub use std::cmp;
pub use std::ptr;
pub use std::mem;
pub use std::ops;
pub use std::slice;
pub use std::result;
pub use std::option;
pub use std::path::Path;
pub use std::str::{FromStr};
pub use std::io::{Read,Write};
pub use std::hash::{Hash, Hasher};
pub use std::error::Error as StdError;
pub use std::ops::*;
pub use std::cmp::*;
pub use std::sync::Arc;
pub use std::collections::*;
pub use heapsize::HeapSizeOf;
pub use itertools::Itertools;
pub use parking_lot::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};

View File

@ -14,13 +14,15 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use common::*; use std::fmt;
use itertools::Itertools;
use hashdb::*; use hashdb::*;
use nibbleslice::*; use nibbleslice::*;
use rlp::*; use rlp::*;
use super::node::{Node, OwnedNode}; use super::node::{Node, OwnedNode};
use super::lookup::Lookup; use super::lookup::Lookup;
use super::{Trie, TrieItem, TrieError, TrieIterator, Query}; use super::{Trie, TrieItem, TrieError, TrieIterator, Query};
use {ToPretty, Bytes, H256};
/// A `Trie` implementation using a generic `HashDB` backing database. /// A `Trie` implementation using a generic `HashDB` backing database.
/// ///