From 0467bfc9edc682f2ee628b65e4dbf823cf259736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Fri, 8 Jul 2016 13:35:25 +0200 Subject: [PATCH 01/36] Using parity-ui repository for builds --- .travis.yml | 4 ++++ Cargo.lock | 39 ++++++++++++++++++--------------- dapps/Cargo.toml | 10 ++++----- dapps/src/apps/mod.rs | 24 +++----------------- signer/Cargo.toml | 2 +- signer/src/lib.rs | 2 +- signer/src/ws_server/session.rs | 4 ++-- 7 files changed, 36 insertions(+), 49 deletions(-) diff --git a/.travis.yml b/.travis.yml index d051971bcec..d9ed3c98013 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,6 +31,7 @@ matrix: env: FEATURES="--features travis-nightly" RUN_TESTS="true" env: global: + - TRAVIS_NODE_VERSION="5" # GH_TOKEN - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= - TARGETS="-p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethjson -p ethcore-dapps -p ethcore-signer -p bigint" @@ -54,6 +55,9 @@ addons: - libelf-dev - libdw-dev +install: + - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION + script: - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose ${FEATURES} ${TARGETS}; fi - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run ${FEATURES} ${TARGETS}; fi diff --git a/Cargo.lock b/Cargo.lock index eae4823f606..d1c1363c3a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,10 +274,10 @@ dependencies = [ "jsonrpc-http-server 5.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-dapps-rs.git)", - "parity-dapps-builtins 0.5.2 (git+https://github.com/ethcore/parity-dapps-builtins-rs.git)", - "parity-dapps-status 0.5.1 (git+https://github.com/ethcore/parity-dapps-status-rs.git)", - "parity-dapps-wallet 0.6.1 (git+https://github.com/ethcore/parity-dapps-wallet-rs.git)", + "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-home 0.5.2 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-status 0.5.1 (git+https://github.com/ethcore/parity-ui.git)", + "parity-dapps-wallet 0.6.1 (git+https://github.com/ethcore/parity-ui.git)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", "serde_codegen 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", @@ -359,7 +359,7 @@ dependencies = [ "ethcore-util 1.3.0", "jsonrpc-core 2.0.7 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-minimal-sysui 0.2.0 (git+https://github.com/ethcore/parity-dapps-minimal-sysui-rs.git)", + "parity-dapps-signer 0.2.0 (git+https://github.com/ethcore/parity-ui.git)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "ws 0.5.0 (git+https://github.com/ethcore/ws-rs.git?branch=stable)", @@ -848,7 +848,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-dapps" version = "0.3.0" -source = "git+https://github.com/ethcore/parity-dapps-rs.git#8ce18c014d8b69fa31fb203b68ff240091d77a23" +source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -860,34 +860,37 @@ dependencies = [ ] [[package]] -name = "parity-dapps-builtins" +name = "parity-dapps-home" version = "0.5.2" -source = "git+https://github.com/ethcore/parity-dapps-builtins-rs.git#01af2091d5d70dfe0aecbfd96308f0ae79fc61e6" +source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" dependencies = [ - "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-dapps-rs.git)", + "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", +] + +[[package]] +name = "parity-dapps-signer" +version = "0.2.0" +source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +dependencies = [ + "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] [[package]] name = "parity-dapps-status" version = "0.5.1" -source = "git+https://github.com/ethcore/parity-dapps-status-rs.git#110ef2e66142ec8dc15fc40b8ddda5ed3bcfc1fb" +source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" dependencies = [ - "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-dapps-rs.git)", + "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] [[package]] name = "parity-dapps-wallet" version = "0.6.1" -source = "git+https://github.com/ethcore/parity-dapps-wallet-rs.git#867994fe25038f000f1cc09cd024a83700a03930" +source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" dependencies = [ - "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-dapps-rs.git)", + "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] -[[package]] -name = "parity-minimal-sysui" -version = "0.2.0" -source = "git+https://github.com/ethcore/parity-dapps-minimal-sysui-rs.git#996c9f3f0ebedc727aecb4ece191154e956ae292" - [[package]] name = "phf" version = "0.7.14" diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index c42ed8eff9c..051e4addf3f 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -21,13 +21,11 @@ serde_json = "0.7.0" serde_macros = { version = "0.7.0", optional = true } ethcore-rpc = { path = "../rpc" } ethcore-util = { path = "../util" } -parity-dapps = { git = "https://github.com/ethcore/parity-dapps-rs.git", version = "0.3" } +parity-dapps = { git = "https://github.com/ethcore/parity-ui.git", version = "0.3" } # List of apps -parity-dapps-status = { git = "https://github.com/ethcore/parity-dapps-status-rs.git", version = "0.5.1" } -parity-dapps-builtins = { git = "https://github.com/ethcore/parity-dapps-builtins-rs.git", version = "0.5.2" } -parity-dapps-wallet = { git = "https://github.com/ethcore/parity-dapps-wallet-rs.git", version = "0.6.0", optional = true } -parity-dapps-dao = { git = "https://github.com/ethcore/parity-dapps-dao-rs.git", version = "0.4.0", optional = true } -parity-dapps-makerotc = { git = "https://github.com/ethcore/parity-dapps-makerotc-rs.git", version = "0.3.0", optional = true } +parity-dapps-status = { git = "https://github.com/ethcore/parity-ui.git", version = "0.5.1" } +parity-dapps-home = { git = "https://github.com/ethcore/parity-ui.git", version = "0.5.2" } +parity-dapps-wallet = { git = "https://github.com/ethcore/parity-ui.git", version = "0.6.0", optional = true } mime_guess = { version = "1.6.1" } clippy = { version = "0.0.78", optional = true} diff --git a/dapps/src/apps/mod.rs b/dapps/src/apps/mod.rs index 9f6a5c7458d..50bdd207325 100644 --- a/dapps/src/apps/mod.rs +++ b/dapps/src/apps/mod.rs @@ -22,7 +22,7 @@ use parity_dapps::WebApp; mod fs; extern crate parity_dapps_status; -extern crate parity_dapps_builtins; +extern crate parity_dapps_home; pub const DAPPS_DOMAIN : &'static str = ".parity"; pub const RPC_PATH : &'static str = "rpc"; @@ -34,7 +34,7 @@ pub fn main_page() -> &'static str { } pub fn utils() -> Box { - Box::new(PageEndpoint::with_prefix(parity_dapps_builtins::App::default(), UTILS_PATH.to_owned())) + Box::new(PageEndpoint::with_prefix(parity_dapps_home::App::default(), UTILS_PATH.to_owned())) } pub fn all_endpoints(dapps_path: String) -> Endpoints { @@ -44,7 +44,7 @@ pub fn all_endpoints(dapps_path: String) -> Endpoints { // because we use Cross-Origin LocalStorage. // TODO [ToDr] Account naming should be moved to parity. pages.insert("home".into(), Box::new( - PageEndpoint::new_safe_to_embed(parity_dapps_builtins::App::default()) + PageEndpoint::new_safe_to_embed(parity_dapps_home::App::default()) )); pages.insert("proxy".into(), ProxyPac::boxed()); insert::(&mut pages, "parity"); @@ -52,8 +52,6 @@ pub fn all_endpoints(dapps_path: String) -> Endpoints { // Optional dapps wallet_page(&mut pages); - daodapp_page(&mut pages); - makerotc_page(&mut pages); pages } @@ -66,22 +64,6 @@ fn wallet_page(pages: &mut Endpoints) { #[cfg(not(feature = "parity-dapps-wallet"))] fn wallet_page(_pages: &mut Endpoints) {} -#[cfg(feature = "parity-dapps-dao")] -fn daodapp_page(pages: &mut Endpoints) { - extern crate parity_dapps_dao; - insert::(pages, "dao"); -} -#[cfg(not(feature = "parity-dapps-dao"))] -fn daodapp_page(_pages: &mut Endpoints) {} - -#[cfg(feature = "parity-dapps-makerotc")] -fn makerotc_page(pages: &mut Endpoints) { - extern crate parity_dapps_makerotc; - insert::(pages, "makerotc"); -} -#[cfg(not(feature = "parity-dapps-makerotc"))] -fn makerotc_page(_pages: &mut Endpoints) {} - fn insert(pages: &mut Endpoints, id: &str) { pages.insert(id.to_owned(), Box::new(PageEndpoint::new(T::default()))); } diff --git a/signer/Cargo.toml b/signer/Cargo.toml index 5e59d04a7a3..8f9746ae717 100644 --- a/signer/Cargo.toml +++ b/signer/Cargo.toml @@ -18,7 +18,7 @@ env_logger = "0.3" ws = { git = "https://github.com/ethcore/ws-rs.git", branch = "stable" } ethcore-util = { path = "../util" } ethcore-rpc = { path = "../rpc" } -parity-minimal-sysui = { git = "https://github.com/ethcore/parity-dapps-minimal-sysui-rs.git", version = "0.2.0" } +parity-dapps-signer = { git = "https://github.com/ethcore/parity-ui.git", version = "0.2.0" } clippy = { version = "0.0.78", optional = true} diff --git a/signer/src/lib.rs b/signer/src/lib.rs index 3aaed8bcf43..bf7de3e5390 100644 --- a/signer/src/lib.rs +++ b/signer/src/lib.rs @@ -51,7 +51,7 @@ extern crate ethcore_util as util; extern crate ethcore_rpc as rpc; extern crate jsonrpc_core; extern crate ws; -extern crate parity_minimal_sysui as sysui; +extern crate parity_dapps_signer as signer; mod authcode_store; mod ws_server; diff --git a/signer/src/ws_server/session.rs b/signer/src/ws_server/session.rs index 4b2eb808c59..38931ddd5a6 100644 --- a/signer/src/ws_server/session.rs +++ b/signer/src/ws_server/session.rs @@ -17,7 +17,7 @@ //! Session handlers factory. use ws; -use sysui; +use signer; use authcode_store::AuthCodes; use std::path::{PathBuf, Path}; use std::sync::Arc; @@ -111,7 +111,7 @@ impl ws::Handler for Session { } // Otherwise try to serve a page. - Ok(sysui::handle(req.resource()) + Ok(signer::handle(req.resource()) .map_or_else( // return 404 not found || add_headers(ws::Response::not_found("Not found".into()), "text/plain"), From 598ad4d5da6ee0999d1c58f33d7ed96aa51ebe88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Fri, 8 Jul 2016 15:25:24 +0200 Subject: [PATCH 02/36] Updating node version for appveyor. --- .travis.yml | 2 +- appveyor.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d9ed3c98013..b9a530390cf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,7 @@ matrix: env: FEATURES="--features travis-nightly" RUN_TESTS="true" env: global: - - TRAVIS_NODE_VERSION="5" + - TRAVIS_NODE_VERSION="6" # GH_TOKEN - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= - TARGETS="-p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethjson -p ethcore-dapps -p ethcore-signer -p bigint" diff --git a/appveyor.yml b/appveyor.yml index 212b26ea91e..eeee19c4580 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,5 @@ environment: + nodejs_version: "6.3.0" matrix: - TARGET: x86_64-pc-windows-msvc cert: From 803682d9b8590d6dfd467081eb16a861ffbb1cc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 10:43:02 +0200 Subject: [PATCH 03/36] Installing node on appveyor --- appveyor.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index eeee19c4580..b183af550b1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,4 @@ environment: - nodejs_version: "6.3.0" matrix: - TARGET: x86_64-pc-windows-msvc cert: @@ -18,6 +17,7 @@ branches: install: - git submodule update --init --recursive + - ps: Install-Product node 6 - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-1.9.0-x86_64-pc-windows-msvc.exe" - ps: Start-FileDownload "https://github.com/ethcore/win-build/raw/master/SimpleFC.dll" -FileName nsis\SimpleFC.dll - ps: Start-FileDownload "https://github.com/ethcore/win-build/raw/master/vc_redist.x64.exe" -FileName nsis\vc_redist.x64.exe @@ -25,6 +25,8 @@ install: - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin;C:\Program Files (x86)\NSIS;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin - rustc -V - cargo -V + - node -v + - npm -v build: off From edaf24a2ce230a2adf85ae1ab39a0bad80001b0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 12:15:22 +0200 Subject: [PATCH 04/36] EVM bin benches --- evmbin/Cargo.toml | 8 ++++++ evmbin/benches/mod.rs | 61 +++++++++++++++++++++++++++++++++++++++++++ evmbin/src/main.rs | 29 +++++++++++++++++--- 3 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 evmbin/benches/mod.rs diff --git a/evmbin/Cargo.toml b/evmbin/Cargo.toml index 3e531f5d389..8ec68768759 100644 --- a/evmbin/Cargo.toml +++ b/evmbin/Cargo.toml @@ -4,6 +4,14 @@ description = "Parity's EVM implementation" version = "0.1.0" authors = ["Ethcore "] +[lib] +name = "evm" +path = "./src/main.rs" + +[[bin]] +name = "evm" +path = "./src/main.rs" + [dependencies] rustc-serialize = "0.3" docopt = { version = "0.6" } diff --git a/evmbin/benches/mod.rs b/evmbin/benches/mod.rs new file mode 100644 index 00000000000..3013a170a3b --- /dev/null +++ b/evmbin/benches/mod.rs @@ -0,0 +1,61 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! benchmarking for EVM +//! should be started with: +//! ```bash +//! multirust run nightly cargo bench +//! ``` + +#![feature(test)] + +extern crate test; +extern crate ethcore; +extern crate evm; +extern crate ethcore_util; +extern crate rustc_serialize; + +use self::test::{Bencher, black_box}; + +use evm::run_vm; +use ethcore::action_params::ActionParams; +use ethcore_util::{U256, Uint}; +use rustc_serialize::hex::FromHex; + +#[bench] +fn simple_loop_usize(b: &mut Bencher) { + simple_loop(U256::from(::std::usize::MAX), b) +} + +#[bench] +fn simple_loop_u256(b: &mut Bencher) { + simple_loop(!U256::zero(), b) +} + +fn simple_loop(gas: U256, b: &mut Bencher) { + let code = black_box( + "606060405260005b620f42408112156019575b6001016007565b600081905550600680602b6000396000f3606060405200".from_hex().unwrap() + ); + + b.iter(|| { + let mut params = ActionParams::default(); + params.gas = gas; + params.code = Some(code.clone()); + + run_vm(params) + }); +} + diff --git a/evmbin/src/main.rs b/evmbin/src/main.rs index 3fa06d00411..240a02ccf6d 100644 --- a/evmbin/src/main.rs +++ b/evmbin/src/main.rs @@ -25,7 +25,7 @@ extern crate ethcore_util as util; mod ext; -use std::time::Instant; +use std::time::{Instant, Duration}; use std::str::FromStr; use docopt::Docopt; use util::{U256, FromHex, Uint, Bytes}; @@ -58,6 +58,15 @@ fn main() { params.code = Some(args.code()); params.data = args.data(); + let result = run_vm(params); + println!("Gas used: {:?}", result.gas_used); + println!("Output: {:?}", result.output); + println!("Time: {}.{:.9}s", result.time.as_secs(), result.time.subsec_nanos()); +} + +/// Execute VM with given `ActionParams` +pub fn run_vm(params: ActionParams) -> ExecutionResults { + let initial_gas = params.gas; let factory = Factory::new(VMType::Interpreter); let mut vm = factory.create(params.gas); let mut ext = ext::FakeExt::default(); @@ -66,9 +75,21 @@ fn main() { let gas_left = vm.exec(params, &mut ext).finalize(ext).expect("OK"); let duration = start.elapsed(); - println!("Gas used: {:?}", args.gas() - gas_left); - println!("Output: {:?}", ""); - println!("Time: {}.{:.9}s", duration.as_secs(), duration.subsec_nanos()); + ExecutionResults { + gas_used: initial_gas - gas_left, + output: Vec::new(), + time: duration, + } +} + +/// VM execution results +pub struct ExecutionResults { + /// Used gas + pub gas_used: U256, + /// Output as bytes + pub output: Vec, + /// Time Taken + pub time: Duration, } #[derive(Debug, RustcDecodable)] From f1edd3d6834b6fa8c7cd9921b9e567e281db64aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 12:51:31 +0200 Subject: [PATCH 05/36] Optimizing mem gas cost --- ethcore/src/evm/evm.rs | 70 ++++++++++++++++++++++++ ethcore/src/evm/interpreter/gasometer.rs | 18 +++--- evmbin/src/main.rs | 1 + 3 files changed, 79 insertions(+), 10 deletions(-) diff --git a/ethcore/src/evm/evm.rs b/ethcore/src/evm/evm.rs index 3ec943f18c9..a300650f3e5 100644 --- a/ethcore/src/evm/evm.rs +++ b/ethcore/src/evm/evm.rs @@ -107,6 +107,11 @@ pub trait CostType: ops::Mul + ops::Div + ops::Add (Self, bool); /// Multiple with overflow fn overflow_mul(self, other: Self) -> (Self, bool); + /// Divide with overflow + fn overflow_div(self, other: Self) -> (Self, bool); + /// Single-step full multiplication and division: `self*other/div` + /// Should not overflow on intermediate steps + fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool); } impl CostType for U256 { @@ -129,6 +134,21 @@ impl CostType for U256 { fn overflow_mul(self, other: Self) -> (Self, bool) { Uint::overflowing_mul(self, other) } + + fn overflow_div(self, other: Self) -> (Self, bool) { + Uint::overflowing_div(self, other) + } + + fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool) { + let x = self.full_mul(other); + let (U512(parts), o) = Uint::overflowing_div(x, U512::from(div)); + let overflow = (parts[4] | parts[5] | parts[6] | parts[7]) > 0; + + ( + U256([parts[0], parts[1], parts[2], parts[3]]), + o | overflow + ) + } } impl CostType for usize { @@ -154,6 +174,18 @@ impl CostType for usize { fn overflow_mul(self, other: Self) -> (Self, bool) { self.overflowing_mul(other) } + + fn overflow_div(self, other: Self) -> (Self, bool) { + self.overflowing_div(other) + } + + fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool) { + let (c, o) = U128::from(self).overflowing_mul(U128::from(other)); + let (U128(parts), o1) = c.overflowing_div(U128::from(div)); + let result = parts[0] as usize; + let overflow = o | o1 | (parts[1] > 0) | (parts[0] > result as u64); + (result, overflow) + } } /// Evm interface @@ -164,3 +196,41 @@ pub trait Evm { /// to compute the final gas left. fn exec(&mut self, params: ActionParams, ext: &mut Ext) -> Result; } + + +#[test] +fn should_calculate_overflow_mul_div_without_overflow() { + // given + let num = 10_000_000; + + // when + let (res1, o1) = U256::from(num).overflow_mul_div(U256::from(num), U256::from(num)); + let (res2, o2) = num.overflow_mul_div(num, num); + + // then + assert_eq!(res1, U256::from(num)); + assert!(!o1); + assert_eq!(res2, num); + assert!(!o2); +} + +#[test] +fn should_calculate_overflow_mul_div_with_overflow() { + // given + let max = ::std::u64::MAX; + let num1 = U256([max, max, max, max]); + let num2 = ::std::usize::MAX; + + // when + let (res1, o1) = num1.overflow_mul_div(num1, num1 - U256::from(2)); + let (res2, o2) = num2.overflow_mul_div(num2, num2 - 2); + + // then + // (x+2)^2/x = (x^2 + 4x + 4)/x = x + 4 + 4/x ~ (MAX-2) + 4 + 0 = 1 + assert_eq!(res2, 1); + assert!(o2); + + assert_eq!(res1, U256::from(1)); + assert!(o1); +} + diff --git a/ethcore/src/evm/interpreter/gasometer.rs b/ethcore/src/evm/interpreter/gasometer.rs index 069d70e19dc..0fc349a27d3 100644 --- a/ethcore/src/evm/interpreter/gasometer.rs +++ b/ethcore/src/evm/interpreter/gasometer.rs @@ -68,6 +68,9 @@ impl Gasometer { let default_gas = Gas::from(schedule.tier_step_gas[tier]); let cost = match instruction { + instructions::JUMPDEST => { + InstructionCost::Gas(Gas::from(1)) + }, instructions::SSTORE => { let address = H256::from(stack.peek(0)); let newval = stack.peek(1); @@ -106,9 +109,6 @@ impl Gasometer { instructions::EXTCODECOPY => { InstructionCost::GasMemCopy(default_gas, try!(self.mem_needed(stack.peek(1), stack.peek(3))), try!(Gas::from_u256(*stack.peek(3)))) }, - instructions::JUMPDEST => { - InstructionCost::Gas(Gas::from(1)) - }, instructions::LOG0...instructions::LOG4 => { let no_of_topics = instructions::get_log_topics(instruction); let log_gas = schedule.log_gas + schedule.log_topic_gas * no_of_topics; @@ -199,14 +199,12 @@ impl Gasometer { let s = mem_size >> 5; // s * memory_gas + s * s / quad_coeff_div let a = overflowing!(s.overflow_mul(Gas::from(schedule.memory_gas))); - // We need to go to U512 to calculate s*s/quad_coeff_div - let b = U512::from(s.as_u256()) * U512::from(s.as_u256()) / U512::from(schedule.quad_coeff_div); - if b > U512::from(!U256::zero()) { - Err(evm::Error::OutOfGas) - } else { - Ok(overflowing!(a.overflow_add(try!(Gas::from_u256(U256::from(b)))))) - } + + // Calculate s*s/quad_coeff_div + let b = overflowing!(s.overflow_mul_div(s, Gas::from(schedule.quad_coeff_div))); + Ok(overflowing!(a.overflow_add(b))) }; + let current_mem_size = Gas::from(current_mem_size); let req_mem_size_rounded = (overflowing!(mem_size.overflow_add(Gas::from(31 as usize))) >> 5) << 5; diff --git a/evmbin/src/main.rs b/evmbin/src/main.rs index 240a02ccf6d..94684129ca0 100644 --- a/evmbin/src/main.rs +++ b/evmbin/src/main.rs @@ -17,6 +17,7 @@ //! Parity EVM interpreter binary. #![warn(missing_docs)] +#![allow(dead_code)] extern crate ethcore; extern crate rustc_serialize; extern crate docopt; From cca4efb861002e44b466ad015c56989f547d75b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 14:52:56 +0200 Subject: [PATCH 06/36] Removing overflow_div since it's not used --- ethcore/src/evm/evm.rs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/ethcore/src/evm/evm.rs b/ethcore/src/evm/evm.rs index a300650f3e5..77b57bf69d3 100644 --- a/ethcore/src/evm/evm.rs +++ b/ethcore/src/evm/evm.rs @@ -107,8 +107,6 @@ pub trait CostType: ops::Mul + ops::Div + ops::Add (Self, bool); /// Multiple with overflow fn overflow_mul(self, other: Self) -> (Self, bool); - /// Divide with overflow - fn overflow_div(self, other: Self) -> (Self, bool); /// Single-step full multiplication and division: `self*other/div` /// Should not overflow on intermediate steps fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool); @@ -135,10 +133,6 @@ impl CostType for U256 { Uint::overflowing_mul(self, other) } - fn overflow_div(self, other: Self) -> (Self, bool) { - Uint::overflowing_div(self, other) - } - fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool) { let x = self.full_mul(other); let (U512(parts), o) = Uint::overflowing_div(x, U512::from(div)); @@ -175,10 +169,6 @@ impl CostType for usize { self.overflowing_mul(other) } - fn overflow_div(self, other: Self) -> (Self, bool) { - self.overflowing_div(other) - } - fn overflow_mul_div(self, other: Self, div: Self) -> (Self, bool) { let (c, o) = U128::from(self).overflowing_mul(U128::from(other)); let (U128(parts), o1) = c.overflowing_div(U128::from(div)); From 986c28efb7e2c61342cf912dbf1c17e1587b78da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 15:45:47 +0200 Subject: [PATCH 07/36] Updating UI --- Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94014110aec..4d2bd078167 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -862,7 +862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-dapps" version = "0.3.0" -source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -876,7 +876,7 @@ dependencies = [ [[package]] name = "parity-dapps-home" version = "0.5.2" -source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -884,7 +884,7 @@ dependencies = [ [[package]] name = "parity-dapps-signer" version = "0.2.0" -source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -892,7 +892,7 @@ dependencies = [ [[package]] name = "parity-dapps-status" version = "0.5.1" -source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -900,7 +900,7 @@ dependencies = [ [[package]] name = "parity-dapps-wallet" version = "0.6.1" -source = "git+https://github.com/ethcore/parity-ui.git#b0c1fa6cbe5e72d7e6542b547e886b37f7cf86de" +source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] From fbdde8f0e67a1a2dc6a9ed9c9bf31fbba4b0b13d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 16:17:30 +0200 Subject: [PATCH 08/36] More benchmarks --- evmbin/bench.sh | 24 ++++++++++++++++++++++++ evmbin/benches/mod.rs | 26 +++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100755 evmbin/bench.sh diff --git a/evmbin/bench.sh b/evmbin/bench.sh new file mode 100755 index 00000000000..a7d5557cbd7 --- /dev/null +++ b/evmbin/bench.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +set -x +set -e + +cargo build --release + +# LOOP TEST +CODE1=606060405260005b620f42408112156019575b6001016007565b600081905550600680602b6000396000f3606060405200 +ethvm --code $CODE1 +echo "^^^^ ethvm" +./target/release/evm stats --code $CODE1 --gas 4402000 +echo "^^^^ usize" +./target/release/evm stats --code $CODE1 +echo "^^^^ U256" + +# RNG TEST +CODE2=6060604052600360056007600b60005b620f4240811215607f5767ffe7649d5eca84179490940267f47ed85c4b9a6379019367f8e5dd9a5c994bba9390930267f91d87e4b8b74e55019267ff97f6f3b29cda529290920267f393ada8dd75c938019167fe8d437c45bb3735830267f47d9a7b5428ffec019150600101600f565b838518831882186000555050505050600680609a6000396000f3606060405200 +ethvm --code $CODE2 +echo "^^^^ ethvm" +./target/release/evm stats --code $CODE2 --gas 143020115 +echo "^^^^ usize" +./target/release/evm stats --code $CODE2 +echo "^^^^ U256" diff --git a/evmbin/benches/mod.rs b/evmbin/benches/mod.rs index 3013a170a3b..3013dca5447 100644 --- a/evmbin/benches/mod.rs +++ b/evmbin/benches/mod.rs @@ -47,7 +47,31 @@ fn simple_loop_u256(b: &mut Bencher) { fn simple_loop(gas: U256, b: &mut Bencher) { let code = black_box( - "606060405260005b620f42408112156019575b6001016007565b600081905550600680602b6000396000f3606060405200".from_hex().unwrap() + "606060405260005b620042408112156019575b6001016007565b600081905550600680602b6000396000f3606060405200".from_hex().unwrap() + ); + + b.iter(|| { + let mut params = ActionParams::default(); + params.gas = gas; + params.code = Some(code.clone()); + + run_vm(params) + }); +} + +#[bench] +fn rng_usize(b: &mut Bencher) { + rng(U256::from(::std::usize::MAX), b) +} + +#[bench] +fn rng_u256(b: &mut Bencher) { + rng(!U256::zero(), b) +} + +fn rng(gas: U256, b: &mut Bencher) { + let code = black_box( + "6060604052600360056007600b60005b62004240811215607f5767ffe7649d5eca84179490940267f47ed85c4b9a6379019367f8e5dd9a5c994bba9390930267f91d87e4b8b74e55019267ff97f6f3b29cda529290920267f393ada8dd75c938019167fe8d437c45bb3735830267f47d9a7b5428ffec019150600101600f565b838518831882186000555050505050600680609a6000396000f3606060405200".from_hex().unwrap() ); b.iter(|| { From 2d5d632d7418871086ab97712654b85415d11908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 16:18:27 +0200 Subject: [PATCH 09/36] Optimizing instruction info --- ethcore/src/evm/instructions.rs | 283 +++++++++++++++++--------------- 1 file changed, 147 insertions(+), 136 deletions(-) diff --git a/ethcore/src/evm/instructions.rs b/ethcore/src/evm/instructions.rs index 9a1ea97cc0b..9e7527fa30f 100644 --- a/ethcore/src/evm/instructions.rs +++ b/ethcore/src/evm/instructions.rs @@ -101,6 +101,12 @@ pub enum GasPriceTier { Invalid } +impl Default for GasPriceTier { + fn default() -> Self { + GasPriceTier::Invalid + } +} + /// Returns the index in schedule for specific `GasPriceTier` pub fn get_tier_idx (tier: GasPriceTier) -> usize { match tier { @@ -116,6 +122,7 @@ pub fn get_tier_idx (tier: GasPriceTier) -> usize { } } +#[derive(Copy, Clone, Default)] pub struct InstructionInfo { pub name: &'static str, pub additional: usize, @@ -126,7 +133,7 @@ pub struct InstructionInfo { } impl InstructionInfo { - pub fn new(name: &'static str, additional: usize, args: usize, ret: usize, side_effects: bool, tier: GasPriceTier) -> InstructionInfo { + pub fn new(name: &'static str, additional: usize, args: usize, ret: usize, side_effects: bool, tier: GasPriceTier) -> Self { InstructionInfo { name: name, additional: additional, @@ -138,142 +145,146 @@ impl InstructionInfo { } } -#[cfg_attr(rustfmt, rustfmt_skip)] +lazy_static! { + static ref INSTRUCTIONS: [InstructionInfo; 0x100] = { + let mut arr = [InstructionInfo::default(); 0x100]; + arr[STOP as usize] = InstructionInfo::new("STOP", 0, 0, 0, true, GasPriceTier::Zero); + arr[ADD as usize] = InstructionInfo::new("ADD", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[SUB as usize] = InstructionInfo::new("SUB", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[MUL as usize] = InstructionInfo::new("MUL", 0, 2, 1, false, GasPriceTier::Low); + arr[DIV as usize] = InstructionInfo::new("DIV", 0, 2, 1, false, GasPriceTier::Low); + arr[SDIV as usize] = InstructionInfo::new("SDIV", 0, 2, 1, false, GasPriceTier::Low); + arr[MOD as usize] = InstructionInfo::new("MOD", 0, 2, 1, false, GasPriceTier::Low); + arr[SMOD as usize] = InstructionInfo::new("SMOD", 0, 2, 1, false, GasPriceTier::Low); + arr[EXP as usize] = InstructionInfo::new("EXP", 0, 2, 1, false, GasPriceTier::Special); + arr[NOT as usize] = InstructionInfo::new("NOT", 0, 1, 1, false, GasPriceTier::VeryLow); + arr[LT as usize] = InstructionInfo::new("LT", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[GT as usize] = InstructionInfo::new("GT", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[SLT as usize] = InstructionInfo::new("SLT", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[SGT as usize] = InstructionInfo::new("SGT", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[EQ as usize] = InstructionInfo::new("EQ", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[ISZERO as usize] = InstructionInfo::new("ISZERO", 0, 1, 1, false, GasPriceTier::VeryLow); + arr[AND as usize] = InstructionInfo::new("AND", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[OR as usize] = InstructionInfo::new("OR", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[XOR as usize] = InstructionInfo::new("XOR", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[BYTE as usize] = InstructionInfo::new("BYTE", 0, 2, 1, false, GasPriceTier::VeryLow); + arr[ADDMOD as usize] = InstructionInfo::new("ADDMOD", 0, 3, 1, false, GasPriceTier::Mid); + arr[MULMOD as usize] = InstructionInfo::new("MULMOD", 0, 3, 1, false, GasPriceTier::Mid); + arr[SIGNEXTEND as usize] = InstructionInfo::new("SIGNEXTEND", 0, 2, 1, false, GasPriceTier::Low); + arr[SHA3 as usize] = InstructionInfo::new("SHA3", 0, 2, 1, false, GasPriceTier::Special); + arr[ADDRESS as usize] = InstructionInfo::new("ADDRESS", 0, 0, 1, false, GasPriceTier::Base); + arr[BALANCE as usize] = InstructionInfo::new("BALANCE", 0, 1, 1, false, GasPriceTier::Ext); + arr[ORIGIN as usize] = InstructionInfo::new("ORIGIN", 0, 0, 1, false, GasPriceTier::Base); + arr[CALLER as usize] = InstructionInfo::new("CALLER", 0, 0, 1, false, GasPriceTier::Base); + arr[CALLVALUE as usize] = InstructionInfo::new("CALLVALUE", 0, 0, 1, false, GasPriceTier::Base); + arr[CALLDATALOAD as usize] = InstructionInfo::new("CALLDATALOAD", 0, 1, 1, false, GasPriceTier::VeryLow); + arr[CALLDATASIZE as usize] = InstructionInfo::new("CALLDATASIZE", 0, 0, 1, false, GasPriceTier::Base); + arr[CALLDATACOPY as usize] = InstructionInfo::new("CALLDATACOPY", 0, 3, 0, true, GasPriceTier::VeryLow); + arr[CODESIZE as usize] = InstructionInfo::new("CODESIZE", 0, 0, 1, false, GasPriceTier::Base); + arr[CODECOPY as usize] = InstructionInfo::new("CODECOPY", 0, 3, 0, true, GasPriceTier::VeryLow); + arr[GASPRICE as usize] = InstructionInfo::new("GASPRICE", 0, 0, 1, false, GasPriceTier::Base); + arr[EXTCODESIZE as usize] = InstructionInfo::new("EXTCODESIZE", 0, 1, 1, false, GasPriceTier::Ext); + arr[EXTCODECOPY as usize] = InstructionInfo::new("EXTCODECOPY", 0, 4, 0, true, GasPriceTier::Ext); + arr[BLOCKHASH as usize] = InstructionInfo::new("BLOCKHASH", 0, 1, 1, false, GasPriceTier::Ext); + arr[COINBASE as usize] = InstructionInfo::new("COINBASE", 0, 0, 1, false, GasPriceTier::Base); + arr[TIMESTAMP as usize] = InstructionInfo::new("TIMESTAMP", 0, 0, 1, false, GasPriceTier::Base); + arr[NUMBER as usize] = InstructionInfo::new("NUMBER", 0, 0, 1, false, GasPriceTier::Base); + arr[DIFFICULTY as usize] = InstructionInfo::new("DIFFICULTY", 0, 0, 1, false, GasPriceTier::Base); + arr[GASLIMIT as usize] = InstructionInfo::new("GASLIMIT", 0, 0, 1, false, GasPriceTier::Base); + arr[POP as usize] = InstructionInfo::new("POP", 0, 1, 0, false, GasPriceTier::Base); + arr[MLOAD as usize] = InstructionInfo::new("MLOAD", 0, 1, 1, false, GasPriceTier::VeryLow); + arr[MSTORE as usize] = InstructionInfo::new("MSTORE", 0, 2, 0, true, GasPriceTier::VeryLow); + arr[MSTORE8 as usize] = InstructionInfo::new("MSTORE8", 0, 2, 0, true, GasPriceTier::VeryLow); + arr[SLOAD as usize] = InstructionInfo::new("SLOAD", 0, 1, 1, false, GasPriceTier::Special); + arr[SSTORE as usize] = InstructionInfo::new("SSTORE", 0, 2, 0, true, GasPriceTier::Special); + arr[JUMP as usize] = InstructionInfo::new("JUMP", 0, 1, 0, true, GasPriceTier::Mid); + arr[JUMPI as usize] = InstructionInfo::new("JUMPI", 0, 2, 0, true, GasPriceTier::High); + arr[PC as usize] = InstructionInfo::new("PC", 0, 0, 1, false, GasPriceTier::Base); + arr[MSIZE as usize] = InstructionInfo::new("MSIZE", 0, 0, 1, false, GasPriceTier::Base); + arr[GAS as usize] = InstructionInfo::new("GAS", 0, 0, 1, false, GasPriceTier::Base); + arr[JUMPDEST as usize] = InstructionInfo::new("JUMPDEST", 0, 0, 0, true, GasPriceTier::Special); + arr[PUSH1 as usize] = InstructionInfo::new("PUSH1", 1, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH2 as usize] = InstructionInfo::new("PUSH2", 2, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH3 as usize] = InstructionInfo::new("PUSH3", 3, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH4 as usize] = InstructionInfo::new("PUSH4", 4, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH5 as usize] = InstructionInfo::new("PUSH5", 5, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH6 as usize] = InstructionInfo::new("PUSH6", 6, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH7 as usize] = InstructionInfo::new("PUSH7", 7, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH8 as usize] = InstructionInfo::new("PUSH8", 8, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH9 as usize] = InstructionInfo::new("PUSH9", 9, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH10 as usize] = InstructionInfo::new("PUSH10", 10, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH11 as usize] = InstructionInfo::new("PUSH11", 11, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH12 as usize] = InstructionInfo::new("PUSH12", 12, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH13 as usize] = InstructionInfo::new("PUSH13", 13, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH14 as usize] = InstructionInfo::new("PUSH14", 14, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH15 as usize] = InstructionInfo::new("PUSH15", 15, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH16 as usize] = InstructionInfo::new("PUSH16", 16, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH17 as usize] = InstructionInfo::new("PUSH17", 17, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH18 as usize] = InstructionInfo::new("PUSH18", 18, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH19 as usize] = InstructionInfo::new("PUSH19", 19, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH20 as usize] = InstructionInfo::new("PUSH20", 20, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH21 as usize] = InstructionInfo::new("PUSH21", 21, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH22 as usize] = InstructionInfo::new("PUSH22", 22, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH23 as usize] = InstructionInfo::new("PUSH23", 23, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH24 as usize] = InstructionInfo::new("PUSH24", 24, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH25 as usize] = InstructionInfo::new("PUSH25", 25, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH26 as usize] = InstructionInfo::new("PUSH26", 26, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH27 as usize] = InstructionInfo::new("PUSH27", 27, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH28 as usize] = InstructionInfo::new("PUSH28", 28, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH29 as usize] = InstructionInfo::new("PUSH29", 29, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH30 as usize] = InstructionInfo::new("PUSH30", 30, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH31 as usize] = InstructionInfo::new("PUSH31", 31, 0, 1, false, GasPriceTier::VeryLow); + arr[PUSH32 as usize] = InstructionInfo::new("PUSH32", 32, 0, 1, false, GasPriceTier::VeryLow); + arr[DUP1 as usize] = InstructionInfo::new("DUP1", 0, 1, 2, false, GasPriceTier::VeryLow); + arr[DUP2 as usize] = InstructionInfo::new("DUP2", 0, 2, 3, false, GasPriceTier::VeryLow); + arr[DUP3 as usize] = InstructionInfo::new("DUP3", 0, 3, 4, false, GasPriceTier::VeryLow); + arr[DUP4 as usize] = InstructionInfo::new("DUP4", 0, 4, 5, false, GasPriceTier::VeryLow); + arr[DUP5 as usize] = InstructionInfo::new("DUP5", 0, 5, 6, false, GasPriceTier::VeryLow); + arr[DUP6 as usize] = InstructionInfo::new("DUP6", 0, 6, 7, false, GasPriceTier::VeryLow); + arr[DUP7 as usize] = InstructionInfo::new("DUP7", 0, 7, 8, false, GasPriceTier::VeryLow); + arr[DUP8 as usize] = InstructionInfo::new("DUP8", 0, 8, 9, false, GasPriceTier::VeryLow); + arr[DUP9 as usize] = InstructionInfo::new("DUP9", 0, 9, 10, false, GasPriceTier::VeryLow); + arr[DUP10 as usize] = InstructionInfo::new("DUP10", 0, 10, 11, false, GasPriceTier::VeryLow); + arr[DUP11 as usize] = InstructionInfo::new("DUP11", 0, 11, 12, false, GasPriceTier::VeryLow); + arr[DUP12 as usize] = InstructionInfo::new("DUP12", 0, 12, 13, false, GasPriceTier::VeryLow); + arr[DUP13 as usize] = InstructionInfo::new("DUP13", 0, 13, 14, false, GasPriceTier::VeryLow); + arr[DUP14 as usize] = InstructionInfo::new("DUP14", 0, 14, 15, false, GasPriceTier::VeryLow); + arr[DUP15 as usize] = InstructionInfo::new("DUP15", 0, 15, 16, false, GasPriceTier::VeryLow); + arr[DUP16 as usize] = InstructionInfo::new("DUP16", 0, 16, 17, false, GasPriceTier::VeryLow); + arr[SWAP1 as usize] = InstructionInfo::new("SWAP1", 0, 2, 2, false, GasPriceTier::VeryLow); + arr[SWAP2 as usize] = InstructionInfo::new("SWAP2", 0, 3, 3, false, GasPriceTier::VeryLow); + arr[SWAP3 as usize] = InstructionInfo::new("SWAP3", 0, 4, 4, false, GasPriceTier::VeryLow); + arr[SWAP4 as usize] = InstructionInfo::new("SWAP4", 0, 5, 5, false, GasPriceTier::VeryLow); + arr[SWAP5 as usize] = InstructionInfo::new("SWAP5", 0, 6, 6, false, GasPriceTier::VeryLow); + arr[SWAP6 as usize] = InstructionInfo::new("SWAP6", 0, 7, 7, false, GasPriceTier::VeryLow); + arr[SWAP7 as usize] = InstructionInfo::new("SWAP7", 0, 8, 8, false, GasPriceTier::VeryLow); + arr[SWAP8 as usize] = InstructionInfo::new("SWAP8", 0, 9, 9, false, GasPriceTier::VeryLow); + arr[SWAP9 as usize] = InstructionInfo::new("SWAP9", 0, 10, 10, false, GasPriceTier::VeryLow); + arr[SWAP10 as usize] = InstructionInfo::new("SWAP10", 0, 11, 11, false, GasPriceTier::VeryLow); + arr[SWAP11 as usize] = InstructionInfo::new("SWAP11", 0, 12, 12, false, GasPriceTier::VeryLow); + arr[SWAP12 as usize] = InstructionInfo::new("SWAP12", 0, 13, 13, false, GasPriceTier::VeryLow); + arr[SWAP13 as usize] = InstructionInfo::new("SWAP13", 0, 14, 14, false, GasPriceTier::VeryLow); + arr[SWAP14 as usize] = InstructionInfo::new("SWAP14", 0, 15, 15, false, GasPriceTier::VeryLow); + arr[SWAP15 as usize] = InstructionInfo::new("SWAP15", 0, 16, 16, false, GasPriceTier::VeryLow); + arr[SWAP16 as usize] = InstructionInfo::new("SWAP16", 0, 17, 17, false, GasPriceTier::VeryLow); + arr[LOG0 as usize] = InstructionInfo::new("LOG0", 0, 2, 0, true, GasPriceTier::Special); + arr[LOG1 as usize] = InstructionInfo::new("LOG1", 0, 3, 0, true, GasPriceTier::Special); + arr[LOG2 as usize] = InstructionInfo::new("LOG2", 0, 4, 0, true, GasPriceTier::Special); + arr[LOG3 as usize] = InstructionInfo::new("LOG3", 0, 5, 0, true, GasPriceTier::Special); + arr[LOG4 as usize] = InstructionInfo::new("LOG4", 0, 6, 0, true, GasPriceTier::Special); + arr[CREATE as usize] = InstructionInfo::new("CREATE", 0, 3, 1, true, GasPriceTier::Special); + arr[CALL as usize] = InstructionInfo::new("CALL", 0, 7, 1, true, GasPriceTier::Special); + arr[CALLCODE as usize] = InstructionInfo::new("CALLCODE", 0, 7, 1, true, GasPriceTier::Special); + arr[RETURN as usize] = InstructionInfo::new("RETURN", 0, 2, 0, true, GasPriceTier::Zero); + arr[DELEGATECALL as usize] = InstructionInfo::new("DELEGATECALL", 0, 6, 1, true, GasPriceTier::Special); + arr[SUICIDE as usize] = InstructionInfo::new("SUICIDE", 0, 1, 0, true, GasPriceTier::Zero); + arr + }; +} + /// Return details about specific instruction -pub fn get_info(instruction: Instruction) -> InstructionInfo { - match instruction { - STOP => InstructionInfo::new("STOP", 0, 0, 0, true, GasPriceTier::Zero), - ADD => InstructionInfo::new("ADD", 0, 2, 1, false, GasPriceTier::VeryLow), - SUB => InstructionInfo::new("SUB", 0, 2, 1, false, GasPriceTier::VeryLow), - MUL => InstructionInfo::new("MUL", 0, 2, 1, false, GasPriceTier::Low), - DIV => InstructionInfo::new("DIV", 0, 2, 1, false, GasPriceTier::Low), - SDIV => InstructionInfo::new("SDIV", 0, 2, 1, false, GasPriceTier::Low), - MOD => InstructionInfo::new("MOD", 0, 2, 1, false, GasPriceTier::Low), - SMOD => InstructionInfo::new("SMOD", 0, 2, 1, false, GasPriceTier::Low), - EXP => InstructionInfo::new("EXP", 0, 2, 1, false, GasPriceTier::Special), - NOT => InstructionInfo::new("NOT", 0, 1, 1, false, GasPriceTier::VeryLow), - LT => InstructionInfo::new("LT", 0, 2, 1, false, GasPriceTier::VeryLow), - GT => InstructionInfo::new("GT", 0, 2, 1, false, GasPriceTier::VeryLow), - SLT => InstructionInfo::new("SLT", 0, 2, 1, false, GasPriceTier::VeryLow), - SGT => InstructionInfo::new("SGT", 0, 2, 1, false, GasPriceTier::VeryLow), - EQ => InstructionInfo::new("EQ", 0, 2, 1, false, GasPriceTier::VeryLow), - ISZERO => InstructionInfo::new("ISZERO", 0, 1, 1, false, GasPriceTier::VeryLow), - AND => InstructionInfo::new("AND", 0, 2, 1, false, GasPriceTier::VeryLow), - OR => InstructionInfo::new("OR", 0, 2, 1, false, GasPriceTier::VeryLow), - XOR => InstructionInfo::new("XOR", 0, 2, 1, false, GasPriceTier::VeryLow), - BYTE => InstructionInfo::new("BYTE", 0, 2, 1, false, GasPriceTier::VeryLow), - ADDMOD => InstructionInfo::new("ADDMOD", 0, 3, 1, false, GasPriceTier::Mid), - MULMOD => InstructionInfo::new("MULMOD", 0, 3, 1, false, GasPriceTier::Mid), - SIGNEXTEND => InstructionInfo::new("SIGNEXTEND", 0, 2, 1, false, GasPriceTier::Low), - SHA3 => InstructionInfo::new("SHA3", 0, 2, 1, false, GasPriceTier::Special), - ADDRESS => InstructionInfo::new("ADDRESS", 0, 0, 1, false, GasPriceTier::Base), - BALANCE => InstructionInfo::new("BALANCE", 0, 1, 1, false, GasPriceTier::Ext), - ORIGIN => InstructionInfo::new("ORIGIN", 0, 0, 1, false, GasPriceTier::Base), - CALLER => InstructionInfo::new("CALLER", 0, 0, 1, false, GasPriceTier::Base), - CALLVALUE => InstructionInfo::new("CALLVALUE", 0, 0, 1, false, GasPriceTier::Base), - CALLDATALOAD => InstructionInfo::new("CALLDATALOAD", 0, 1, 1, false, GasPriceTier::VeryLow), - CALLDATASIZE => InstructionInfo::new("CALLDATASIZE", 0, 0, 1, false, GasPriceTier::Base), - CALLDATACOPY => InstructionInfo::new("CALLDATACOPY", 0, 3, 0, true, GasPriceTier::VeryLow), - CODESIZE => InstructionInfo::new("CODESIZE", 0, 0, 1, false, GasPriceTier::Base), - CODECOPY => InstructionInfo::new("CODECOPY", 0, 3, 0, true, GasPriceTier::VeryLow), - GASPRICE => InstructionInfo::new("GASPRICE", 0, 0, 1, false, GasPriceTier::Base), - EXTCODESIZE => InstructionInfo::new("EXTCODESIZE", 0, 1, 1, false, GasPriceTier::Ext), - EXTCODECOPY => InstructionInfo::new("EXTCODECOPY", 0, 4, 0, true, GasPriceTier::Ext), - BLOCKHASH => InstructionInfo::new("BLOCKHASH", 0, 1, 1, false, GasPriceTier::Ext), - COINBASE => InstructionInfo::new("COINBASE", 0, 0, 1, false, GasPriceTier::Base), - TIMESTAMP => InstructionInfo::new("TIMESTAMP", 0, 0, 1, false, GasPriceTier::Base), - NUMBER => InstructionInfo::new("NUMBER", 0, 0, 1, false, GasPriceTier::Base), - DIFFICULTY => InstructionInfo::new("DIFFICULTY", 0, 0, 1, false, GasPriceTier::Base), - GASLIMIT => InstructionInfo::new("GASLIMIT", 0, 0, 1, false, GasPriceTier::Base), - POP => InstructionInfo::new("POP", 0, 1, 0, false, GasPriceTier::Base), - MLOAD => InstructionInfo::new("MLOAD", 0, 1, 1, false, GasPriceTier::VeryLow), - MSTORE => InstructionInfo::new("MSTORE", 0, 2, 0, true, GasPriceTier::VeryLow), - MSTORE8 => InstructionInfo::new("MSTORE8", 0, 2, 0, true, GasPriceTier::VeryLow), - SLOAD => InstructionInfo::new("SLOAD", 0, 1, 1, false, GasPriceTier::Special), - SSTORE => InstructionInfo::new("SSTORE", 0, 2, 0, true, GasPriceTier::Special), - JUMP => InstructionInfo::new("JUMP", 0, 1, 0, true, GasPriceTier::Mid), - JUMPI => InstructionInfo::new("JUMPI", 0, 2, 0, true, GasPriceTier::High), - PC => InstructionInfo::new("PC", 0, 0, 1, false, GasPriceTier::Base), - MSIZE => InstructionInfo::new("MSIZE", 0, 0, 1, false, GasPriceTier::Base), - GAS => InstructionInfo::new("GAS", 0, 0, 1, false, GasPriceTier::Base), - JUMPDEST => InstructionInfo::new("JUMPDEST", 0, 0, 0, true, GasPriceTier::Special), - PUSH1 => InstructionInfo::new("PUSH1", 1, 0, 1, false, GasPriceTier::VeryLow), - PUSH2 => InstructionInfo::new("PUSH2", 2, 0, 1, false, GasPriceTier::VeryLow), - PUSH3 => InstructionInfo::new("PUSH3", 3, 0, 1, false, GasPriceTier::VeryLow), - PUSH4 => InstructionInfo::new("PUSH4", 4, 0, 1, false, GasPriceTier::VeryLow), - PUSH5 => InstructionInfo::new("PUSH5", 5, 0, 1, false, GasPriceTier::VeryLow), - PUSH6 => InstructionInfo::new("PUSH6", 6, 0, 1, false, GasPriceTier::VeryLow), - PUSH7 => InstructionInfo::new("PUSH7", 7, 0, 1, false, GasPriceTier::VeryLow), - PUSH8 => InstructionInfo::new("PUSH8", 8, 0, 1, false, GasPriceTier::VeryLow), - PUSH9 => InstructionInfo::new("PUSH9", 9, 0, 1, false, GasPriceTier::VeryLow), - PUSH10 => InstructionInfo::new("PUSH10", 10, 0, 1, false, GasPriceTier::VeryLow), - PUSH11 => InstructionInfo::new("PUSH11", 11, 0, 1, false, GasPriceTier::VeryLow), - PUSH12 => InstructionInfo::new("PUSH12", 12, 0, 1, false, GasPriceTier::VeryLow), - PUSH13 => InstructionInfo::new("PUSH13", 13, 0, 1, false, GasPriceTier::VeryLow), - PUSH14 => InstructionInfo::new("PUSH14", 14, 0, 1, false, GasPriceTier::VeryLow), - PUSH15 => InstructionInfo::new("PUSH15", 15, 0, 1, false, GasPriceTier::VeryLow), - PUSH16 => InstructionInfo::new("PUSH16", 16, 0, 1, false, GasPriceTier::VeryLow), - PUSH17 => InstructionInfo::new("PUSH17", 17, 0, 1, false, GasPriceTier::VeryLow), - PUSH18 => InstructionInfo::new("PUSH18", 18, 0, 1, false, GasPriceTier::VeryLow), - PUSH19 => InstructionInfo::new("PUSH19", 19, 0, 1, false, GasPriceTier::VeryLow), - PUSH20 => InstructionInfo::new("PUSH20", 20, 0, 1, false, GasPriceTier::VeryLow), - PUSH21 => InstructionInfo::new("PUSH21", 21, 0, 1, false, GasPriceTier::VeryLow), - PUSH22 => InstructionInfo::new("PUSH22", 22, 0, 1, false, GasPriceTier::VeryLow), - PUSH23 => InstructionInfo::new("PUSH23", 23, 0, 1, false, GasPriceTier::VeryLow), - PUSH24 => InstructionInfo::new("PUSH24", 24, 0, 1, false, GasPriceTier::VeryLow), - PUSH25 => InstructionInfo::new("PUSH25", 25, 0, 1, false, GasPriceTier::VeryLow), - PUSH26 => InstructionInfo::new("PUSH26", 26, 0, 1, false, GasPriceTier::VeryLow), - PUSH27 => InstructionInfo::new("PUSH27", 27, 0, 1, false, GasPriceTier::VeryLow), - PUSH28 => InstructionInfo::new("PUSH28", 28, 0, 1, false, GasPriceTier::VeryLow), - PUSH29 => InstructionInfo::new("PUSH29", 29, 0, 1, false, GasPriceTier::VeryLow), - PUSH30 => InstructionInfo::new("PUSH30", 30, 0, 1, false, GasPriceTier::VeryLow), - PUSH31 => InstructionInfo::new("PUSH31", 31, 0, 1, false, GasPriceTier::VeryLow), - PUSH32 => InstructionInfo::new("PUSH32", 32, 0, 1, false, GasPriceTier::VeryLow), - DUP1 => InstructionInfo::new("DUP1", 0, 1, 2, false, GasPriceTier::VeryLow), - DUP2 => InstructionInfo::new("DUP2", 0, 2, 3, false, GasPriceTier::VeryLow), - DUP3 => InstructionInfo::new("DUP3", 0, 3, 4, false, GasPriceTier::VeryLow), - DUP4 => InstructionInfo::new("DUP4", 0, 4, 5, false, GasPriceTier::VeryLow), - DUP5 => InstructionInfo::new("DUP5", 0, 5, 6, false, GasPriceTier::VeryLow), - DUP6 => InstructionInfo::new("DUP6", 0, 6, 7, false, GasPriceTier::VeryLow), - DUP7 => InstructionInfo::new("DUP7", 0, 7, 8, false, GasPriceTier::VeryLow), - DUP8 => InstructionInfo::new("DUP8", 0, 8, 9, false, GasPriceTier::VeryLow), - DUP9 => InstructionInfo::new("DUP9", 0, 9, 10, false, GasPriceTier::VeryLow), - DUP10 => InstructionInfo::new("DUP10", 0, 10, 11, false, GasPriceTier::VeryLow), - DUP11 => InstructionInfo::new("DUP11", 0, 11, 12, false, GasPriceTier::VeryLow), - DUP12 => InstructionInfo::new("DUP12", 0, 12, 13, false, GasPriceTier::VeryLow), - DUP13 => InstructionInfo::new("DUP13", 0, 13, 14, false, GasPriceTier::VeryLow), - DUP14 => InstructionInfo::new("DUP14", 0, 14, 15, false, GasPriceTier::VeryLow), - DUP15 => InstructionInfo::new("DUP15", 0, 15, 16, false, GasPriceTier::VeryLow), - DUP16 => InstructionInfo::new("DUP16", 0, 16, 17, false, GasPriceTier::VeryLow), - SWAP1 => InstructionInfo::new("SWAP1", 0, 2, 2, false, GasPriceTier::VeryLow), - SWAP2 => InstructionInfo::new("SWAP2", 0, 3, 3, false, GasPriceTier::VeryLow), - SWAP3 => InstructionInfo::new("SWAP3", 0, 4, 4, false, GasPriceTier::VeryLow), - SWAP4 => InstructionInfo::new("SWAP4", 0, 5, 5, false, GasPriceTier::VeryLow), - SWAP5 => InstructionInfo::new("SWAP5", 0, 6, 6, false, GasPriceTier::VeryLow), - SWAP6 => InstructionInfo::new("SWAP6", 0, 7, 7, false, GasPriceTier::VeryLow), - SWAP7 => InstructionInfo::new("SWAP7", 0, 8, 8, false, GasPriceTier::VeryLow), - SWAP8 => InstructionInfo::new("SWAP8", 0, 9, 9, false, GasPriceTier::VeryLow), - SWAP9 => InstructionInfo::new("SWAP9", 0, 10, 10, false, GasPriceTier::VeryLow), - SWAP10 => InstructionInfo::new("SWAP10", 0, 11, 11, false, GasPriceTier::VeryLow), - SWAP11 => InstructionInfo::new("SWAP11", 0, 12, 12, false, GasPriceTier::VeryLow), - SWAP12 => InstructionInfo::new("SWAP12", 0, 13, 13, false, GasPriceTier::VeryLow), - SWAP13 => InstructionInfo::new("SWAP13", 0, 14, 14, false, GasPriceTier::VeryLow), - SWAP14 => InstructionInfo::new("SWAP14", 0, 15, 15, false, GasPriceTier::VeryLow), - SWAP15 => InstructionInfo::new("SWAP15", 0, 16, 16, false, GasPriceTier::VeryLow), - SWAP16 => InstructionInfo::new("SWAP16", 0, 17, 17, false, GasPriceTier::VeryLow), - LOG0 => InstructionInfo::new("LOG0", 0, 2, 0, true, GasPriceTier::Special), - LOG1 => InstructionInfo::new("LOG1", 0, 3, 0, true, GasPriceTier::Special), - LOG2 => InstructionInfo::new("LOG2", 0, 4, 0, true, GasPriceTier::Special), - LOG3 => InstructionInfo::new("LOG3", 0, 5, 0, true, GasPriceTier::Special), - LOG4 => InstructionInfo::new("LOG4", 0, 6, 0, true, GasPriceTier::Special), - CREATE => InstructionInfo::new("CREATE", 0, 3, 1, true, GasPriceTier::Special), - CALL => InstructionInfo::new("CALL", 0, 7, 1, true, GasPriceTier::Special), - CALLCODE => InstructionInfo::new("CALLCODE", 0, 7, 1, true, GasPriceTier::Special), - RETURN => InstructionInfo::new("RETURN", 0, 2, 0, true, GasPriceTier::Zero), - DELEGATECALL => InstructionInfo::new("DELEGATECALL", 0, 6, 1, true, GasPriceTier::Special), - SUICIDE => InstructionInfo::new("SUICIDE", 0, 1, 0, true, GasPriceTier::Zero), - _ => InstructionInfo::new("INVALID_INSTRUCTION", 0, 0, 0, false, GasPriceTier::Invalid) - } +pub fn get_info(instruction: Instruction) -> &'static InstructionInfo { + &INSTRUCTIONS[instruction as usize] } /// Virtual machine bytecode instruction. From 9eeafecd76e2f9ee74172a7b9e4c86435cbc5d8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 18:17:54 +0200 Subject: [PATCH 10/36] Build & Scripts optimization --- .travis.yml | 101 ++++++++++++++----------------------------------- add_license.sh | 6 --- cov.sh | 43 --------------------- doc.sh | 14 ------- fmt.sh | 16 -------- hook.sh | 12 ------ test.sh | 27 +++++++------ 7 files changed, 44 insertions(+), 175 deletions(-) delete mode 100755 add_license.sh delete mode 100755 cov.sh delete mode 100755 doc.sh delete mode 100755 fmt.sh delete mode 100755 hook.sh diff --git a/.travis.yml b/.travis.yml index d051971bcec..91a5dd5b91f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,3 @@ -sudo: required dist: trusty language: rust branches: @@ -8,45 +7,33 @@ branches: - /^stable-.*$/ - /^beta$/ - /^stable$/ + git: depth: 3 + matrix: - fast_finish: true - allow_failures: - - rust: nightly include: - rust: stable env: FEATURES="--features travis-beta" RUN_TESTS="true" - # - rust: beta - # env: FEATURES="--features travis-beta" RUN_TESTS="true" - - rust: stable - env: FEATURES="--features travis-beta" RUN_BUILD="true" - rust: beta - env: FEATURES="--features travis-beta" RUN_BUILD="true" - - rust: stable env: FEATURES="--features travis-beta" RUN_COVERAGE="true" - # - rust: nightly - # env: FEATURES="--features travis-nightly" RUN_BENCHES="true" - - rust: nightly - env: FEATURES="--features travis-nightly" RUN_TESTS="true" + env: global: - # GH_TOKEN - - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= - - TARGETS="-p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethjson -p ethcore-dapps -p ethcore-signer -p bigint" - - ARCHIVE_SUFFIX="-${TRAVIS_OS_NAME}-${TRAVIS_TAG}" - - KCOV_FEATURES="" - - KCOV_CMD="./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests target/kcov" + - RUST_BACKTRACE="1" - RUN_TESTS="false" - RUN_COVERAGE="false" - - RUN_BUILD="false" - - RUN_BENCHES="false" - - RUST_BACKTRACE="1" + # GH_TOKEN for documentation + - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= + - KCOV_CMD="./kcov-master/tmp/usr/local/bin/kcov" + cache: apt: true directories: - $TRAVIS_BUILD_DIR/target + - $TRAVIS_BUILD_DIR/kcov-master - $HOME/.cargo + addons: apt: packages: @@ -55,54 +42,24 @@ addons: - libdw-dev script: - - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose ${FEATURES}; fi - - if [ "$RUN_BUILD" = "true" ]; then tar cvzf parity${ARCHIVE_SUFFIX}.tar.gz -C target/release parity; fi - -after_success: | - [ "$RUN_COVERAGE" = "true" ] && - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && - tar xzf master.tar.gz && mkdir kcov-master/build && cd kcov-master/build && cmake .. && make && make install DESTDIR=../tmp && cd ../.. && - cargo test --no-run ${KCOV_FEATURES} ${TARGETS} && - $KCOV_CMD target/debug/deps/ethkey-* && - $KCOV_CMD target/debug/deps/ethstore-* && - $KCOV_CMD target/debug/deps/ethcore_util-* && - $KCOV_CMD target/debug/deps/ethash-* && - $KCOV_CMD target/debug/deps/ethcore-* && - $KCOV_CMD target/debug/deps/ethsync-* && - $KCOV_CMD target/debug/deps/ethcore_rpc-* && - $KCOV_CMD target/debug/deps/ethcore_dapps-* && - $KCOV_CMD target/debug/deps/ethcore_signer-* && - $KCOV_CMD target/debug/deps/ethjson-* && - $KCOV_CMD target/debug/parity-* && - [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] && - [ $TRAVIS_RUST_VERSION = stable ] && - cargo doc --no-deps --verbose ${KCOV_FEATURES} ${TARGETS} && - echo '' > target/doc/index.html && - pip install --user ghp-import && - /home/travis/.local/bin/ghp-import -n target/doc && - git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages - -deploy: - provider: releases - api_key: - secure: "t+oGT/4lsy7IScw5s86Dpntl5Nyck4qG6nhHwMScc6FYzwLldgwgJaafL8Ej+HG+b7nFLriN+Snoa4YQ5o74X5ZlSWubVREOYQlL/fq7vcPB0DwAZ0Jufq1QW2R1M+3SwwF1eAwTv2W3G7A2K7dxjCVvENcy/gdxnZ36NeUPsqaCC9UcI2Yc7+4jyQwvx6ZfBvQeu+HbKENA0eUNs2ZQOID/1IPy0LJBvSyxAQYsysXdjTzGdNu4+Iba20E8uWYe4fAbgz+gwGarXg1L6D6gKyMlWkViqWjvXWBuDJJqMQZ3rw41AwZOoh3mKd2Lc0l6l4oZcEqPuob0yKTNjz1tuJy9xKTC2F2bDzsvUgk1IRfMK5ukXXXS09ZCZWuA9/GtnsqJ1xGTiwX+DhQzpVBHaBiseSNlYE1YN/3jNyGY+iSts1qut+1BwE7swmcTLsAPoAy8Ue+f7ErNoCg1lm71vq7VO2DLn7x2NqHyHUEuJ+7olDHSdE84G7d9otDRu/+TfMOw7GXwTaha6yJRInuNsnj4CFMLNVvYACzCC2idB7f7nUZoSFi9jf18S9fCMPVmazMrFj4g95HWrVHkjpV5zRTeUdTWw6DJl6pC9HFqORHdCvLv4Rc4dm5r3CmOcAQ0ZuiccV2oKzw4/Wic96daae8M5f5KSQ/WTr+h0wXZKp0=" - skip_cleanup: true - file: parity${ARCHIVE_SUFFIX}.tar.gz - on: - tags: true + - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi -notifications: - webhooks: - urls: - - https://hooks.slack.com/services/${SLACK_WEBHOOK} - on_success: always - on_failure: always - on_start: never +install: + - [ "$RUN_COVERAGE" = "true" ] && + wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && + tar xzf master.tar.gz && + mkdir kcov-master/build && + cd kcov-master/build && + cmake .. && + make && make install DESTDIR=../tmp && + cd ../.. -notifications: - slack: - rooms: - - ethcore:4EGxt9WP6AS7uX4JKXSfR9vi#chatops +after_success: + - [ "$RUN_COVERAGE" = "true" ] && ./scripts/cov.sh "$KCOV_CMD" + - [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] && + [ $TRAVIS_RUST_VERSION = stable ] && + ./scripts/doc.sh && + pip install --user ghp-import && + /home/travis/.local/bin/ghp-import -n target/doc && + git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages diff --git a/add_license.sh b/add_license.sh deleted file mode 100755 index 1d916f42796..00000000000 --- a/add_license.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -for f in $(find . -name '*.rs'); do - cat license_header $f > $f.new - mv $f.new $f -done diff --git a/cov.sh b/cov.sh deleted file mode 100755 index 8de2264c05c..00000000000 --- a/cov.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/sh -# Installing KCOV under ubuntu -# https://users.rust-lang.org/t/tutorial-how-to-collect-test-coverages-for-rust-project/650# -### Install deps -# $ sudo apt-get install libcurl4-openssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev -# -### Compile kcov -# $ wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && tar xf master.tar.gz -# $ cd kcov-master && mkdir build && cd build -# $ cmake .. && make && sudo make install - -### Running coverage -if ! type kcov > /dev/null; then - echo "Install kcov first (details inside this file). Aborting." - exit 1 -fi - -cargo test \ - -p ethkey \ - -p ethstore \ - -p ethash \ - -p ethcore-util \ - -p ethcore \ - -p ethsync \ - -p ethcore-rpc \ - -p parity \ - -p ethcore-signer \ - -p ethcore-dapps \ - --no-run || exit $? -rm -rf target/coverage -mkdir -p target/coverage - -EXCLUDE="~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethkey-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethstore-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethash-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_util-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethsync-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_rpc-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_signer-* -kcov --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_dapps-* -xdg-open target/coverage/index.html diff --git a/doc.sh b/doc.sh deleted file mode 100755 index 41251f7a884..00000000000 --- a/doc.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# generate documentation only for partiy and ethcore libraries - -cargo doc --no-deps --verbose \ - -p ethkey \ - -p ethstore \ - -p ethash \ - -p ethcore-util \ - -p ethcore \ - -p ethsync \ - -p ethcore-rpc \ - -p ethcore-signer \ - -p ethcore-dapps \ - -p parity \ diff --git a/fmt.sh b/fmt.sh deleted file mode 100755 index 624b404ffcf..00000000000 --- a/fmt.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -RUSTFMT="rustfmt --write-mode overwrite" - -$RUSTFMT ./ethash/src/lib.rs -$RUSTFMT ./ethcore/src/lib.rs -$RUSTFMT ./evmjit/src/lib.rs -$RUSTFMT ./json/src/lib.rs -$RUSTFMT ./miner/src/lib.rs -$RUSTFMT ./parity/main.rs -$RUSTFMT ./rpc/src/lib.rs -$RUSTFMT ./signer/src/lib.rs -$RUSTFMT ./dapps/src/lib.rs -$RUSTFMT ./sync/src/lib.rs -$RUSTFMT ./util/src/lib.rs - diff --git a/hook.sh b/hook.sh deleted file mode 100755 index 9ce825f800b..00000000000 --- a/hook.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -FILE=./.git/hooks/pre-push -echo "#!/bin/sh\n" > $FILE -# Exit on any error -echo "set -e" >> $FILE -# Run release build -echo "cargo build --features dev" >> $FILE -# Build tests -echo "cargo test --no-run --features dev \\" >> $FILE -echo " -p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethcore-dapps -p ethcore-signer" >> $FILE -echo "" >> $FILE -chmod +x $FILE diff --git a/test.sh b/test.sh index a62c835e8a0..0de4d758c04 100755 --- a/test.sh +++ b/test.sh @@ -1,15 +1,18 @@ #!/bin/sh # Running Parity Full Test Sute -cargo test --features ethcore/json-tests $1 \ - -p ethkey \ - -p ethstore \ - -p ethash \ - -p ethcore-util \ - -p ethcore \ - -p ethsync \ - -p ethcore-rpc \ - -p ethcore-signer \ - -p ethcore-dapps \ - -p parity \ - -p bigint +FEATURES="--features ethcore/json-tests" + +case $1 in + --no-json) + FEATURES="" + shift # past argument=value + ;; + *) + # unknown option + ;; +esac + +. ./scripts/targets.sh +cargo test $FEATURES $TARGETS $1 \ + From 248428657d6731534abcb24a8eed8910c0955b72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 18:23:24 +0200 Subject: [PATCH 11/36] Fixing travis.yml --- .editorconfig | 5 +++++ .travis.yml | 34 +++++++++++++++++----------------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/.editorconfig b/.editorconfig index 0ac22f0737d..28b11218608 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,3 +9,8 @@ trim_trailing_whitespace=true max_line_length=120 insert_final_newline=true +[.travis.yml] +indent_style=space +indent_size=2 +tab_width=8 +end_of_line=lf diff --git a/.travis.yml b/.travis.yml index 91a5dd5b91f..f3cbb4f4516 100644 --- a/.travis.yml +++ b/.travis.yml @@ -44,22 +44,22 @@ addons: script: - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi -install: - - [ "$RUN_COVERAGE" = "true" ] && - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && - tar xzf master.tar.gz && - mkdir kcov-master/build && - cd kcov-master/build && - cmake .. && - make && make install DESTDIR=../tmp && - cd ../.. +install: | + [ "$RUN_COVERAGE" = "true" ] && + wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && + tar xzf master.tar.gz && + mkdir kcov-master/build && + cd kcov-master/build && + cmake .. && + make && make install DESTDIR=../tmp && + cd ../.. after_success: - - [ "$RUN_COVERAGE" = "true" ] && ./scripts/cov.sh "$KCOV_CMD" - - [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] && - [ $TRAVIS_RUST_VERSION = stable ] && - ./scripts/doc.sh && - pip install --user ghp-import && - /home/travis/.local/bin/ghp-import -n target/doc && - git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages + - true && [ "$RUN_COVERAGE" = "true" ] && ./scripts/cov.sh "$KCOV_CMD" + - true && [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] && + [ $TRAVIS_RUST_VERSION = stable ] && + ./scripts/doc.sh && + pip install --user ghp-import && + /home/travis/.local/bin/ghp-import -n target/doc && + git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages From d65a1d2b2a47576d557b3c3783befabf40829167 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 18:30:58 +0200 Subject: [PATCH 12/36] Fixing coverage script. --- .travis.yml | 8 ++++---- scripts/add_license.sh | 6 ++++++ scripts/cov.sh | 39 +++++++++++++++++++++++++++++++++++++++ scripts/doc.sh | 7 +++++++ scripts/fmt.sh | 16 ++++++++++++++++ scripts/hook.sh | 14 ++++++++++++++ scripts/targets.sh | 14 ++++++++++++++ 7 files changed, 100 insertions(+), 4 deletions(-) create mode 100755 scripts/add_license.sh create mode 100755 scripts/cov.sh create mode 100755 scripts/doc.sh create mode 100755 scripts/fmt.sh create mode 100755 scripts/hook.sh create mode 100644 scripts/targets.sh diff --git a/.travis.yml b/.travis.yml index f3cbb4f4516..7a741b28745 100644 --- a/.travis.yml +++ b/.travis.yml @@ -45,14 +45,14 @@ script: - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi install: | - [ "$RUN_COVERAGE" = "true" ] && - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && + [ "$RUN_COVERAGE" = "false" ] || + (wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && tar xzf master.tar.gz && - mkdir kcov-master/build && + mkdir -p kcov-master/build && cd kcov-master/build && cmake .. && make && make install DESTDIR=../tmp && - cd ../.. + cd) after_success: - true && [ "$RUN_COVERAGE" = "true" ] && ./scripts/cov.sh "$KCOV_CMD" diff --git a/scripts/add_license.sh b/scripts/add_license.sh new file mode 100755 index 00000000000..1d916f42796 --- /dev/null +++ b/scripts/add_license.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +for f in $(find . -name '*.rs'); do + cat license_header $f > $f.new + mv $f.new $f +done diff --git a/scripts/cov.sh b/scripts/cov.sh new file mode 100755 index 00000000000..8b49607e563 --- /dev/null +++ b/scripts/cov.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Installing KCOV under ubuntu +# https://users.rust-lang.org/t/tutorial-how-to-collect-test-coverages-for-rust-project/650# +### Install deps +# $ sudo apt-get install libcurl4-openssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev +# +### Compile kcov +# $ wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && tar xf master.tar.gz +# $ cd kcov-master && mkdir build && cd build +# $ cmake .. && make && sudo make install + +### Running coverage + +KCOV_CMD=${1:-kcov} + +if ! type $KCOV_CMD > /dev/null; then + echo "Install kcov first (details inside this file). Aborting." + exit 1 +fi + +. ./scripts/targets.sh + +cargo test $TARGETS --no-run || exit $? +rm -rf target/coverage +mkdir -p target/coverage + +EXCLUDE="~/.multirust,rocksdb,secp256k1,/usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests target/kcov" +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethkey-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethstore-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethash-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_util-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethsync-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_rpc-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_signer-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_dapps-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethjson-* +$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/parity-* +xdg-open target/coverage/index.html diff --git a/scripts/doc.sh b/scripts/doc.sh new file mode 100755 index 00000000000..657f47567d1 --- /dev/null +++ b/scripts/doc.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# generate documentation only for partiy and ethcore libraries + +. ./scripts/targets.sh + +cargo doc --no-deps --verbose $TARGETS && + echo '' > target/doc/index.html diff --git a/scripts/fmt.sh b/scripts/fmt.sh new file mode 100755 index 00000000000..624b404ffcf --- /dev/null +++ b/scripts/fmt.sh @@ -0,0 +1,16 @@ +#!/bin/sh + +RUSTFMT="rustfmt --write-mode overwrite" + +$RUSTFMT ./ethash/src/lib.rs +$RUSTFMT ./ethcore/src/lib.rs +$RUSTFMT ./evmjit/src/lib.rs +$RUSTFMT ./json/src/lib.rs +$RUSTFMT ./miner/src/lib.rs +$RUSTFMT ./parity/main.rs +$RUSTFMT ./rpc/src/lib.rs +$RUSTFMT ./signer/src/lib.rs +$RUSTFMT ./dapps/src/lib.rs +$RUSTFMT ./sync/src/lib.rs +$RUSTFMT ./util/src/lib.rs + diff --git a/scripts/hook.sh b/scripts/hook.sh new file mode 100755 index 00000000000..9b5512ac0f4 --- /dev/null +++ b/scripts/hook.sh @@ -0,0 +1,14 @@ +#!/bin/sh +FILE=./.git/hooks/pre-push +. ./scripts/targets.sh + +echo "#!/bin/sh\n" > $FILE +# Exit on any error +echo "set -e" >> $FILE +# Run release build +echo "cargo build --features dev" >> $FILE +# Build tests +echo "cargo test --no-run --features dev \\" >> $FILE +echo $TARGETS >> $FILE +echo "" >> $FILE +chmod +x $FILE diff --git a/scripts/targets.sh b/scripts/targets.sh new file mode 100644 index 00000000000..4c2b7ca6808 --- /dev/null +++ b/scripts/targets.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +export TARGETS=" + -p ethkey \ + -p ethstore \ + -p ethash \ + -p ethcore-util \ + -p ethcore \ + -p ethsync \ + -p ethcore-rpc \ + -p ethcore-signer \ + -p ethcore-dapps \ + -p parity \ + -p bigint" From ab1c6cd65574b744145d0b37d00dec27ce288991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 18:47:58 +0200 Subject: [PATCH 13/36] New GCC --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.travis.yml b/.travis.yml index 7a741b28745..5dd844b108d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,8 @@ matrix: env: global: + - CXX="g++-4.8" + - CC="gcc-4.8" - RUST_BACKTRACE="1" - RUN_TESTS="false" - RUN_COVERAGE="false" @@ -36,10 +38,14 @@ cache: addons: apt: + sources: + - ubuntu-toolchain-r-test packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev + - gcc-4.8 + - g++-4.8 script: - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi From 3159e20814ecd21db57dbc8a821c11b6c5b6d097 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 18:56:28 +0200 Subject: [PATCH 14/36] Build fixes --- .travis.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5dd844b108d..d9aa5965cac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -47,9 +47,6 @@ addons: - gcc-4.8 - g++-4.8 -script: - - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi - install: | [ "$RUN_COVERAGE" = "false" ] || (wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && @@ -60,12 +57,15 @@ install: | make && make install DESTDIR=../tmp && cd) -after_success: - - true && [ "$RUN_COVERAGE" = "true" ] && ./scripts/cov.sh "$KCOV_CMD" - - true && [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] && - [ $TRAVIS_RUST_VERSION = stable ] && - ./scripts/doc.sh && - pip install --user ghp-import && - /home/travis/.local/bin/ghp-import -n target/doc && - git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages +script: + - if [ "$RUN_TESTS" = "true" ]; then ./test.sh; fi + - if [ "$RUN_COVERAGE" = "true" ]; then ./scripts/cov.sh "$KCOV_CMD"; fi + +after_success: | + [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] && + [ $TRAVIS_RUST_VERSION = stable ] && + ./scripts/doc.sh && + pip install --user ghp-import && + /home/travis/.local/bin/ghp-import -n target/doc && + git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages From d9aeafa40eafbc473f6d18931a612d67e7135c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 19:11:42 +0200 Subject: [PATCH 15/36] Removing --verify [ci skip] --- scripts/cov.sh | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/scripts/cov.sh b/scripts/cov.sh index 8b49607e563..927afe5f030 100755 --- a/scripts/cov.sh +++ b/scripts/cov.sh @@ -10,30 +10,34 @@ # $ cmake .. && make && sudo make install ### Running coverage - -KCOV_CMD=${1:-kcov} - -if ! type $KCOV_CMD > /dev/null; then +if ! type kcov > /dev/null; then echo "Install kcov first (details inside this file). Aborting." exit 1 fi -. ./scripts/targets.sh - -cargo test $TARGETS --no-run || exit $? +cargo test \ + -p ethkey \ + -p ethstore \ + -p ethash \ + -p ethcore-util \ + -p ethcore \ + -p ethsync \ + -p ethcore-rpc \ + -p parity \ + -p ethcore-signer \ + -p ethcore-dapps \ + --no-run || exit $? rm -rf target/coverage mkdir -p target/coverage -EXCLUDE="~/.multirust,rocksdb,secp256k1,/usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests target/kcov" -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethkey-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethstore-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethash-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_util-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethsync-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_rpc-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_signer-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethcore_dapps-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/deps/ethjson-* -$KCOV_CMD --exclude-pattern $EXCLUDE --include-pattern src --verify target/coverage target/debug/parity-* +EXCLUDE="~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethkey-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethstore-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethash-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_util-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethsync-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_rpc-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_signer-* +kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_dapps-* xdg-open target/coverage/index.html From cb2ace82db96ee86140004f33d56ea977594a022 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 19:20:48 +0200 Subject: [PATCH 16/36] Uploading to coveralls --- scripts/cov.sh | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/scripts/cov.sh b/scripts/cov.sh index 927afe5f030..01caa35c355 100755 --- a/scripts/cov.sh +++ b/scripts/cov.sh @@ -10,34 +10,29 @@ # $ cmake .. && make && sudo make install ### Running coverage -if ! type kcov > /dev/null; then + +KCOV=${1:-kcov} + +if ! type $KCOV > /dev/null; then echo "Install kcov first (details inside this file). Aborting." exit 1 fi -cargo test \ - -p ethkey \ - -p ethstore \ - -p ethash \ - -p ethcore-util \ - -p ethcore \ - -p ethsync \ - -p ethcore-rpc \ - -p parity \ - -p ethcore-signer \ - -p ethcore-dapps \ - --no-run || exit $? -rm -rf target/coverage -mkdir -p target/coverage +. ./scripts/targets.sh + +cargo test $TARGETS --no-run || exit $? +rm -rf target/kcov +mkdir -p target/kcov EXCLUDE="~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethkey-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethstore-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethash-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_util-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethsync-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_rpc-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_signer-* -kcov --exclude-pattern $EXCLUDE --include-pattern src target/coverage target/debug/deps/ethcore_dapps-* -xdg-open target/coverage/index.html +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethkey-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethstore-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethash-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_util-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethsync-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_rpc-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_signer-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_dapps-* +$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethjson-* +$KCOV --coveralls-id=${TRAVIS_JOB_ID} --exclude-pattern $EXCLUDE target/kcov target/debug/parity-* From 7e13ce6185d5b2cbae56dc2d037d64bf98eb24c7 Mon Sep 17 00:00:00 2001 From: Robert Habermeier Date: Mon, 11 Jul 2016 19:39:06 +0200 Subject: [PATCH 17/36] v7 migration progress --- ethcore/src/migrations/state/v7.rs | 16 +++++++++++++++- parity/migration.rs | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/ethcore/src/migrations/state/v7.rs b/ethcore/src/migrations/state/v7.rs index 45a5669b270..57f7d97a8c8 100644 --- a/ethcore/src/migrations/state/v7.rs +++ b/ethcore/src/migrations/state/v7.rs @@ -62,7 +62,8 @@ fn attempt_migrate(mut key_h: H256, val: &[u8]) -> Option { } /// Version for ArchiveDB. -pub struct ArchiveV7; +#[derive(Default)] +pub struct ArchiveV7(usize); impl SimpleMigration for ArchiveV7 { fn version(&self) -> u32 { @@ -70,6 +71,12 @@ impl SimpleMigration for ArchiveV7 { } fn simple_migrate(&mut self, key: Vec, value: Vec) -> Option<(Vec, Vec)> { + self.0 += 1; + if self.0 == 100_000 { + self.0 = 0; + println!("."); + } + if key.len() != 32 { // metadata key, ignore. return Some((key, value)); @@ -228,7 +235,14 @@ impl Migration for OverlayRecentV7 { _ => return Err(Error::MigrationImpossible), // missing or wrong version } + let mut count = 0; for (key, value) in source.iter() { + count += 1; + if count == 100_000 { + count = 0; + println!("."); + } + let mut key = key.into_vec(); if key.len() == 32 { let key_h = H256::from_slice(&key[..]); diff --git a/parity/migration.rs b/parity/migration.rs index 853cb6e3532..ff0a6b0ee13 100644 --- a/parity/migration.rs +++ b/parity/migration.rs @@ -157,7 +157,7 @@ fn extras_database_migrations() -> Result { fn state_database_migrations(pruning: Algorithm) -> Result { let mut manager = MigrationManager::new(default_migration_settings()); let res = match pruning { - Algorithm::Archive => manager.add_migration(migrations::state::ArchiveV7), + Algorithm::Archive => manager.add_migration(migrations::state::ArchiveV7::default()), Algorithm::OverlayRecent => manager.add_migration(migrations::state::OverlayRecentV7::default()), _ => die!("Unsupported pruning method for migration. Delete DB and resync"), }; From 29a2238299020a21a311bb5790bb639fbf3d176f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Mon, 11 Jul 2016 19:53:26 +0200 Subject: [PATCH 18/36] Going back to standard builds --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index d9aa5965cac..9f3bd5e7afc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +sudo: required dist: trusty language: rust branches: From c7a11418bbb55e217f416cd35e9e4de7c3777781 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 10:28:42 +0200 Subject: [PATCH 19/36] Getting rid of get_info --- ethcore/src/evm/instructions.rs | 7 +------ ethcore/src/evm/interpreter/mod.rs | 3 ++- ethcore/src/evm/mod.rs | 1 - ethcore/src/lib.rs | 1 - 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/ethcore/src/evm/instructions.rs b/ethcore/src/evm/instructions.rs index 9e7527fa30f..62cfe77d614 100644 --- a/ethcore/src/evm/instructions.rs +++ b/ethcore/src/evm/instructions.rs @@ -146,7 +146,7 @@ impl InstructionInfo { } lazy_static! { - static ref INSTRUCTIONS: [InstructionInfo; 0x100] = { + pub static ref INSTRUCTIONS: [InstructionInfo; 0x100] = { let mut arr = [InstructionInfo::default(); 0x100]; arr[STOP as usize] = InstructionInfo::new("STOP", 0, 0, 0, true, GasPriceTier::Zero); arr[ADD as usize] = InstructionInfo::new("ADD", 0, 2, 1, false, GasPriceTier::VeryLow); @@ -282,11 +282,6 @@ lazy_static! { }; } -/// Return details about specific instruction -pub fn get_info(instruction: Instruction) -> &'static InstructionInfo { - &INSTRUCTIONS[instruction as usize] -} - /// Virtual machine bytecode instruction. /// halts execution pub const STOP: Instruction = 0x00; diff --git a/ethcore/src/evm/interpreter/mod.rs b/ethcore/src/evm/interpreter/mod.rs index f79d18b36e4..a43592c6daf 100644 --- a/ethcore/src/evm/interpreter/mod.rs +++ b/ethcore/src/evm/interpreter/mod.rs @@ -104,12 +104,13 @@ impl evm::Evm for Interpreter { position: 0, code: &code }; + let infos = &*instructions::INSTRUCTIONS; while reader.position < code.len() { let instruction = code[reader.position]; reader.position += 1; - let info = instructions::get_info(instruction); + let info = infos[instruction as usize]; try!(self.verify_instruction(ext, instruction, &info, &stack)); // Calculate gas cost diff --git a/ethcore/src/evm/mod.rs b/ethcore/src/evm/mod.rs index de208c6a485..d0f379f2498 100644 --- a/ethcore/src/evm/mod.rs +++ b/ethcore/src/evm/mod.rs @@ -35,4 +35,3 @@ pub use self::evm::{Evm, Error, Finalize, GasLeft, Result, CostType}; pub use self::ext::{Ext, ContractCreateResult, MessageCallResult}; pub use self::factory::{Factory, VMType}; pub use self::schedule::Schedule; -pub use self::instructions::get_info; diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 4f644db0393..9f4f0249174 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -146,5 +146,4 @@ mod tests; mod json_tests; pub use types::*; -pub use evm::get_info; pub use executive::contract_address; From fd6d66fc86914dc2d5a07a9ff2c2a0ee818e4fe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 10:30:59 +0200 Subject: [PATCH 20/36] Fixing coverage reports --- scripts/cov.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/cov.sh b/scripts/cov.sh index 01caa35c355..f94a2fda9f6 100755 --- a/scripts/cov.sh +++ b/scripts/cov.sh @@ -24,7 +24,7 @@ cargo test $TARGETS --no-run || exit $? rm -rf target/kcov mkdir -p target/kcov -EXCLUDE="~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" +EXCLUDE="~/.cargo,~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethkey-* $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethstore-* $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore-* @@ -34,5 +34,6 @@ $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/ $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_rpc-* $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_signer-* $KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_dapps-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethjson-* $KCOV --coveralls-id=${TRAVIS_JOB_ID} --exclude-pattern $EXCLUDE target/kcov target/debug/parity-* + +exit 0 From 174e142ad9d97ab3136e5efb3cdb606f1ac52468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 12:06:17 +0200 Subject: [PATCH 21/36] Updating UI --- Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 65886475ba2..b223cd57fce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -862,7 +862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-dapps" version = "0.3.0" -source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" +source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -876,7 +876,7 @@ dependencies = [ [[package]] name = "parity-dapps-home" version = "0.5.2" -source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" +source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -884,7 +884,7 @@ dependencies = [ [[package]] name = "parity-dapps-signer" version = "0.2.0" -source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" +source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -892,7 +892,7 @@ dependencies = [ [[package]] name = "parity-dapps-status" version = "0.5.1" -source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" +source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -900,7 +900,7 @@ dependencies = [ [[package]] name = "parity-dapps-wallet" version = "0.6.1" -source = "git+https://github.com/ethcore/parity-ui.git#171ccf74a4962c2e7f2d95c9c8e63ec3c93f6a77" +source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] From 86df371a727def10fc3ef170026a73a89f383d66 Mon Sep 17 00:00:00 2001 From: Robert Habermeier Date: Tue, 12 Jul 2016 12:20:43 +0200 Subject: [PATCH 22/36] dots on same line --- ethcore/src/migrations/state/v7.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ethcore/src/migrations/state/v7.rs b/ethcore/src/migrations/state/v7.rs index 57f7d97a8c8..a69eecb2d60 100644 --- a/ethcore/src/migrations/state/v7.rs +++ b/ethcore/src/migrations/state/v7.rs @@ -74,7 +74,7 @@ impl SimpleMigration for ArchiveV7 { self.0 += 1; if self.0 == 100_000 { self.0 = 0; - println!("."); + flush!("."); } if key.len() != 32 { @@ -240,7 +240,7 @@ impl Migration for OverlayRecentV7 { count += 1; if count == 100_000 { count = 0; - println!("."); + flush!("."); } let mut key = key.into_vec(); From c3925a494d640ade2b4573e25984116b2f7529ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 13:25:55 +0200 Subject: [PATCH 23/36] Fixing coverage reports generation --- scripts/cov.sh | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/scripts/cov.sh b/scripts/cov.sh index f94a2fda9f6..690b67dedc7 100755 --- a/scripts/cov.sh +++ b/scripts/cov.sh @@ -11,6 +11,8 @@ ### Running coverage +set -x + KCOV=${1:-kcov} if ! type $KCOV > /dev/null; then @@ -19,21 +21,34 @@ if ! type $KCOV > /dev/null; then fi . ./scripts/targets.sh - cargo test $TARGETS --no-run || exit $? -rm -rf target/kcov -mkdir -p target/kcov - -EXCLUDE="~/.cargo,~/.multirust,rocksdb,secp256k1,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests" -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethkey-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethstore-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethash-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_util-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethsync-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_rpc-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_signer-* -$KCOV --exclude-pattern $EXCLUDE --include-pattern src target/kcov target/debug/deps/ethcore_dapps-* -$KCOV --coveralls-id=${TRAVIS_JOB_ID} --exclude-pattern $EXCLUDE target/kcov target/debug/parity-* + + + +KCOV_TARGET="target/kcov" +KCOV_FLAGS="--verify" +EXCLUDE="\ + /usr/lib,\ + /usr/include,\ + $HOME/.cargo,\ + $HOME/.multirust,\ + rocksdb,\ + secp256k1,\ + src/tests,\ + util/json-tests,\ + util/src/network/tests,\ + ethcore/src/evm/tests,\ + ethstore/tests\ +" + +rm -rf $KCOV_TARGET +mkdir -p $KCOV_TARGET + +for FILE in `find target/debug/deps ! -name "*.*"` +do + $KCOV --exclude-pattern $EXCLUDE $KCOV_FLAGS $KCOV_TARGET $FILE +done + +$KCOV --coveralls-id=${TRAVIS_JOB_ID} --exclude-pattern $EXCLUDE $KCOV_FLAGS $KCOV_TARGET target/debug/parity-* exit 0 From a784240734e4259fb2be7b78ea4e0243683cc41f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 16:22:05 +0200 Subject: [PATCH 24/36] Fixing formatting for coverage --- scripts/cov.sh | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/scripts/cov.sh b/scripts/cov.sh index 690b67dedc7..49ef97c090e 100755 --- a/scripts/cov.sh +++ b/scripts/cov.sh @@ -27,18 +27,17 @@ cargo test $TARGETS --no-run || exit $? KCOV_TARGET="target/kcov" KCOV_FLAGS="--verify" -EXCLUDE="\ - /usr/lib,\ - /usr/include,\ - $HOME/.cargo,\ - $HOME/.multirust,\ - rocksdb,\ - secp256k1,\ - src/tests,\ - util/json-tests,\ - util/src/network/tests,\ - ethcore/src/evm/tests,\ - ethstore/tests\ +EXCLUDE="/usr/lib,\ +/usr/include,\ +$HOME/.cargo,\ +$HOME/.multirust,\ +rocksdb,\ +secp256k1,\ +src/tests,\ +util/json-tests,\ +util/src/network/tests,\ +ethcore/src/evm/tests,\ +ethstore/tests\ " rm -rf $KCOV_TARGET From 11cae70cdd1a0ef8a44f7fa90708e39e9e8384aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 12 Jul 2016 20:15:36 +0200 Subject: [PATCH 25/36] No-ui compilation feature --- Cargo.toml | 1 + parity/configuration.rs | 2 +- parity/dapps.rs | 8 ++++---- parity/main.rs | 2 +- signer/Cargo.toml | 1 + signer/src/lib.rs | 1 + signer/src/ws_server/session.rs | 21 ++++++++++++++++++++- 7 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fe035c3486d..667335e39fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ default-features = false [features] default = ["dapps"] +no-ui = ["ethcore-signer/no-ui"] dapps = ["ethcore-dapps"] dev = ["clippy", "ethcore/dev", "ethcore-util/dev", "ethsync/dev", "ethcore-rpc/dev", "ethcore-dapps/dev", "ethcore-signer/dev"] diff --git a/parity/configuration.rs b/parity/configuration.rs index dc00cb2376e..6644e343741 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -561,7 +561,7 @@ impl Configuration { } pub fn dapps_enabled(&self) -> bool { - !self.args.flag_dapps_off && !self.args.flag_no_dapps + !self.args.flag_dapps_off && !self.args.flag_no_dapps && cfg!(not(feature = "no-ui")) } pub fn signer_enabled(&self) -> bool { diff --git a/parity/dapps.rs b/parity/dapps.rs index 917c59fc67e..67b6ce28032 100644 --- a/parity/dapps.rs +++ b/parity/dapps.rs @@ -21,9 +21,9 @@ use util::panics::PanicHandler; use die::*; use rpc_apis; -#[cfg(feature = "dapps")] +#[cfg(all(feature = "dapps", not(feature = "no-ui")))] pub use ethcore_dapps::Server as WebappServer; -#[cfg(not(feature = "dapps"))] +#[cfg(any(not(feature = "dapps"), feature = "no-ui"))] pub struct WebappServer; pub struct Configuration { @@ -62,7 +62,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Option Option { + signer::handle(req) + } +} +#[cfg(feature = "no-ui")] +mod signer { + pub struct File { + pub content: String, + pub mime: String, + } + + pub fn handle(_req: &str) -> Option { + None + } +} + fn origin_is_allowed(self_origin: &str, header: Option<&[u8]>) -> bool { match header { None => false, From 3abe3e1fbc2a7b60f2f07ff7e3fd61786d848d3f Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Wed, 13 Jul 2016 09:05:26 +0200 Subject: [PATCH 26/36] Fix logging (#1590) * Strip colour for everywhere except the terminal. * Log to file. Fixes #1560. * Fix indentation. [ci:skip] * Remove unnecessary clone()ing. * Update setup_log.rs * remove unnecessary mutex in logging (#1601) --- Cargo.lock | 2 ++ Cargo.toml | 2 ++ parity/cli.rs | 5 ++++- parity/main.rs | 9 ++++++--- parity/setup_log.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b223cd57fce..0a5b8f4ba5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -22,9 +22,11 @@ dependencies = [ "fdlimit 0.1.0", "hyper 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "json-ipc-server 0.2.4 (git+https://github.com/ethcore/json-ipc-server.git)", + "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "number_prefix 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", "rpassword 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index fe035c3486d..7776172c750 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,8 @@ ethcore-ipc = { path = "ipc/rpc" } ethcore-ipc-hypervisor = { path = "ipc/hypervisor" } json-ipc-server = { git = "https://github.com/ethcore/json-ipc-server.git" } ansi_term = "0.7" +lazy_static = "0.2" +regex = "0.1" [target.'cfg(windows)'.dependencies] winapi = "0.2" diff --git a/parity/cli.rs b/parity/cli.rs index 07bba06d191..4fb2d2e5191 100644 --- a/parity/cli.rs +++ b/parity/cli.rs @@ -264,6 +264,8 @@ Legacy Options: Miscellaneous Options: -l --logging LOGGING Specify the logging level. Must conform to the same format as RUST_LOG. + --log-file FILENAME Specify a filename into which logging should be + directed. --no-color Don't use terminal color codes in output. -v --version Show information about version. -h --help Show this screen. @@ -339,7 +341,7 @@ pub struct Args { pub flag_author: Option, pub flag_usd_per_tx: String, pub flag_usd_per_eth: String, - pub flag_price_update_period: String, + pub flag_price_update_period: String, pub flag_gas_floor_target: String, pub flag_gas_cap: String, pub flag_extra_data: Option, @@ -351,6 +353,7 @@ pub struct Args { pub flag_to: String, pub flag_format: Option, pub flag_jitvm: bool, + pub flag_log_file: Option, pub flag_no_color: bool, pub flag_no_network: bool, // legacy... diff --git a/parity/main.rs b/parity/main.rs index f1f018cc243..7314b9f99c7 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -50,6 +50,9 @@ extern crate ethcore_rpc; extern crate ethcore_signer; extern crate ansi_term; +#[macro_use] +extern crate lazy_static; +extern crate regex; #[cfg(feature = "dapps")] extern crate ethcore_dapps; @@ -184,7 +187,7 @@ fn execute_client(conf: Configuration, spec: Spec, client_config: ClientConfig) let panic_handler = PanicHandler::new_in_arc(); // Setup logging - let logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color()); + let logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color(), &conf.args.flag_log_file); // Raise fdlimit unsafe { ::fdlimit::raise_fd_limit(); } @@ -342,7 +345,7 @@ fn execute_export(conf: Configuration) { let panic_handler = PanicHandler::new_in_arc(); // Setup logging - let _logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color()); + let _logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color(), &conf.args.flag_log_file); // Raise fdlimit unsafe { ::fdlimit::raise_fd_limit(); } @@ -403,7 +406,7 @@ fn execute_import(conf: Configuration) { let panic_handler = PanicHandler::new_in_arc(); // Setup logging - let _logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color()); + let _logger = setup_log::setup_log(&conf.args.flag_logging, conf.have_color(), &conf.args.flag_log_file); // Raise fdlimit unsafe { ::fdlimit::raise_fd_limit(); } diff --git a/parity/setup_log.rs b/parity/setup_log.rs index d347a6bf031..fb45bd549b3 100644 --- a/parity/setup_log.rs +++ b/parity/setup_log.rs @@ -17,12 +17,16 @@ use std::env; use std::sync::Arc; +use std::fs::File; +use std::io::Write; use time; use env_logger::LogBuilder; +use regex::Regex; use util::RotatingLogger; +use util::log::{Applyable, Colour}; /// Sets up the logger -pub fn setup_log(init: &Option, enable_color: bool) -> Arc { +pub fn setup_log(init: &Option, enable_color: bool, log_to_file: &Option) -> Arc { use rlog::*; let mut levels = String::new(); @@ -45,14 +49,24 @@ pub fn setup_log(init: &Option, enable_color: bool) -> Arc, enable_color: bool) -> Arc String { + lazy_static! { + static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap(); + } + RE.replace_all(s, "") +} + +#[test] +fn should_remove_colour() { + let before = "test"; + let after = kill_color(&before.apply(Colour::Red.bold())); + assert_eq!(after, "test"); +} + +#[test] +fn should_remove_multiple_colour() { + let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again")); + let after = kill_color(&t); + assert_eq!(after, "test again"); +} From 420f2ad6c4ef83265edfcad8bba57a85b7c5fef0 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Wed, 13 Jul 2016 09:10:46 +0200 Subject: [PATCH 27/36] Update parity-dapps to be able tobuild on mac. --- Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0a5b8f4ba5d..d952b7b9853 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -864,7 +864,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-dapps" version = "0.3.0" -source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" +source = "git+https://github.com/ethcore/parity-ui.git#f16a7e8b7f1ea4fe4da12af22f36a745a07513d6" dependencies = [ "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -878,7 +878,7 @@ dependencies = [ [[package]] name = "parity-dapps-home" version = "0.5.2" -source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" +source = "git+https://github.com/ethcore/parity-ui.git#f16a7e8b7f1ea4fe4da12af22f36a745a07513d6" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -886,7 +886,7 @@ dependencies = [ [[package]] name = "parity-dapps-signer" version = "0.2.0" -source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" +source = "git+https://github.com/ethcore/parity-ui.git#f16a7e8b7f1ea4fe4da12af22f36a745a07513d6" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -894,7 +894,7 @@ dependencies = [ [[package]] name = "parity-dapps-status" version = "0.5.1" -source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" +source = "git+https://github.com/ethcore/parity-ui.git#f16a7e8b7f1ea4fe4da12af22f36a745a07513d6" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] @@ -902,7 +902,7 @@ dependencies = [ [[package]] name = "parity-dapps-wallet" version = "0.6.1" -source = "git+https://github.com/ethcore/parity-ui.git#4c5a972e81379cbf96fe6119a127d3540de14b1b" +source = "git+https://github.com/ethcore/parity-ui.git#f16a7e8b7f1ea4fe4da12af22f36a745a07513d6" dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] From 29076da4b753c1a67c0b1053620f0543c9b61b97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 13 Jul 2016 11:10:43 +0200 Subject: [PATCH 28/36] UI feature --- Cargo.toml | 5 ++--- parity/configuration.rs | 2 +- parity/dapps.rs | 8 ++++---- parity/main.rs | 2 +- signer/Cargo.toml | 5 +++-- signer/src/lib.rs | 2 +- signer/src/ws_server/session.rs | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 667335e39fc..281ea624392 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,13 +29,13 @@ ethsync = { path = "sync" } ethcore-devtools = { path = "devtools" } ethcore-rpc = { path = "rpc" } ethcore-signer = { path = "signer" } -ethcore-dapps = { path = "dapps", optional = true } semver = "0.2" ethcore-ipc-nano = { path = "ipc/nano" } ethcore-ipc = { path = "ipc/rpc" } ethcore-ipc-hypervisor = { path = "ipc/hypervisor" } json-ipc-server = { git = "https://github.com/ethcore/json-ipc-server.git" } ansi_term = "0.7" +ethcore-dapps = { path = "dapps", optional = true } [target.'cfg(windows)'.dependencies] winapi = "0.2" @@ -48,8 +48,7 @@ version = "0.8" default-features = false [features] -default = ["dapps"] -no-ui = ["ethcore-signer/no-ui"] +default = ["dapps", "ethcore-signer/ui"] dapps = ["ethcore-dapps"] dev = ["clippy", "ethcore/dev", "ethcore-util/dev", "ethsync/dev", "ethcore-rpc/dev", "ethcore-dapps/dev", "ethcore-signer/dev"] diff --git a/parity/configuration.rs b/parity/configuration.rs index 6644e343741..f41784bc115 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -561,7 +561,7 @@ impl Configuration { } pub fn dapps_enabled(&self) -> bool { - !self.args.flag_dapps_off && !self.args.flag_no_dapps && cfg!(not(feature = "no-ui")) + !self.args.flag_dapps_off && !self.args.flag_no_dapps && cfg!(feature = "dapps") } pub fn signer_enabled(&self) -> bool { diff --git a/parity/dapps.rs b/parity/dapps.rs index 67b6ce28032..917c59fc67e 100644 --- a/parity/dapps.rs +++ b/parity/dapps.rs @@ -21,9 +21,9 @@ use util::panics::PanicHandler; use die::*; use rpc_apis; -#[cfg(all(feature = "dapps", not(feature = "no-ui")))] +#[cfg(feature = "dapps")] pub use ethcore_dapps::Server as WebappServer; -#[cfg(any(not(feature = "dapps"), feature = "no-ui"))] +#[cfg(not(feature = "dapps"))] pub struct WebappServer; pub struct Configuration { @@ -62,7 +62,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Option Date: Wed, 13 Jul 2016 11:29:18 +0200 Subject: [PATCH 29/36] pow uses shifts and zero comp --- util/bigint/src/uint.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/util/bigint/src/uint.rs b/util/bigint/src/uint.rs index 8e08e590adc..b67c491fcc1 100644 --- a/util/bigint/src/uint.rs +++ b/util/bigint/src/uint.rs @@ -713,9 +713,8 @@ macro_rules! construct_uint { /// Fast exponentation by squaring /// https://en.wikipedia.org/wiki/Exponentiation_by_squaring fn overflowing_pow(self, expon: Self) -> (Self, bool) { - if expon == Self::zero() { - return (Self::one(), false) - } + if expon.is_zero() { return (Self::one(), false) } + let is_even = |x : &Self| x.low_u64() & 1 == 0; let u_one = Self::one(); @@ -728,11 +727,11 @@ macro_rules! construct_uint { while n > u_one { if is_even(&n) { x = overflowing!(x.overflowing_mul(x), overflow); - n = n / u_two; + n = n >> 1; } else { y = overflowing!(x.overflowing_mul(y), overflow); x = overflowing!(x.overflowing_mul(x), overflow); - n = (n - u_one) / u_two; + n = (n - u_one) >> 1; } } let res = overflowing!(x.overflowing_mul(y), overflow); From e75274df669dbf38a424f08d8092453e74aacc3a Mon Sep 17 00:00:00 2001 From: NikVolf Date: Wed, 13 Jul 2016 11:58:08 +0200 Subject: [PATCH 30/36] more pow opts --- util/bigint/src/uint.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/util/bigint/src/uint.rs b/util/bigint/src/uint.rs index b67c491fcc1..e3c27f80dd5 100644 --- a/util/bigint/src/uint.rs +++ b/util/bigint/src/uint.rs @@ -687,24 +687,25 @@ macro_rules! construct_uint { /// Fast exponentation by squaring /// https://en.wikipedia.org/wiki/Exponentiation_by_squaring fn pow(self, expon: Self) -> Self { - if expon == Self::zero() { + if expon.is_zero() { return Self::one() } let is_even = |x : &Self| x.low_u64() & 1 == 0; let u_one = Self::one(); - let u_two = Self::from(2); let mut y = u_one; let mut n = expon; let mut x = self; while n > u_one { if is_even(&n) { x = x * x; - n = n / u_two; + n = n >> 1; } else { y = x * y; x = x * x; - n = (n - u_one) / u_two; + // to reduce odd number by 1 we should just clear the last bit + n.0[$n_words-1] = n.0[$n_words-1] & ((!0u64)>>1); + n = n >> 1; } } x * y @@ -718,7 +719,6 @@ macro_rules! construct_uint { let is_even = |x : &Self| x.low_u64() & 1 == 0; let u_one = Self::one(); - let u_two = Self::from(2); let mut y = u_one; let mut n = expon; let mut x = self; @@ -1067,7 +1067,7 @@ macro_rules! construct_uint { impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if *self == $name::zero() { + if self.is_zero() { return write!(f, "0"); } @@ -1075,7 +1075,7 @@ macro_rules! construct_uint { let mut current = *self; let ten = $name::from(10); - while current != $name::zero() { + while !current.is_zero() { s = format!("{}{}", (current % ten).low_u32(), s); current = current / ten; } From 91ae781f0590e115249af0b6fb26d9b5d50b00b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 13 Jul 2016 11:58:55 +0200 Subject: [PATCH 31/36] Disabling building UI --- .travis.yml | 6 +++--- appveyor.yml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index b9a530390cf..82d34c91995 100644 --- a/.travis.yml +++ b/.travis.yml @@ -59,9 +59,9 @@ install: - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION script: - - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose ${FEATURES}; fi + - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose --no-default-features ${FEATURES} ${TARGETS}; fi + - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run --no-default-features ${FEATURES} ${TARGETS}; fi + - if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose --no-default-features ${FEATURES}; fi - if [ "$RUN_BUILD" = "true" ]; then tar cvzf parity${ARCHIVE_SUFFIX}.tar.gz -C target/release parity; fi after_success: | diff --git a/appveyor.yml b/appveyor.yml index b183af550b1..712445ca6b5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -31,10 +31,10 @@ install: build: off test_script: - - cargo test --verbose --release + - cargo test --verbose --release --no-default-features after_test: - - cargo build --verbose --release + - cargo build --verbose --release --no-default-features - ps: if($env:cert) { Start-FileDownload $env:cert -FileName $env:keyfile } - ps: if($env:cert) { signtool sign /f $env:keyfile /p $env:certpass target\release\parity.exe } - makensis.exe nsis\installer.nsi From 29a5c1785c8be8b8ac7c88007b2403cb01538514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 13 Jul 2016 11:58:55 +0200 Subject: [PATCH 32/36] Disabling building UI --- .travis.yml | 6 +++--- appveyor.yml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index b9a530390cf..82d34c91995 100644 --- a/.travis.yml +++ b/.travis.yml @@ -59,9 +59,9 @@ install: - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION script: - - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run ${FEATURES} ${TARGETS}; fi - - if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose ${FEATURES}; fi + - if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose --no-default-features ${FEATURES} ${TARGETS}; fi + - if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run --no-default-features ${FEATURES} ${TARGETS}; fi + - if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose --no-default-features ${FEATURES}; fi - if [ "$RUN_BUILD" = "true" ]; then tar cvzf parity${ARCHIVE_SUFFIX}.tar.gz -C target/release parity; fi after_success: | diff --git a/appveyor.yml b/appveyor.yml index b183af550b1..712445ca6b5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -31,10 +31,10 @@ install: build: off test_script: - - cargo test --verbose --release + - cargo test --verbose --release --no-default-features after_test: - - cargo build --verbose --release + - cargo build --verbose --release --no-default-features - ps: if($env:cert) { Start-FileDownload $env:cert -FileName $env:keyfile } - ps: if($env:cert) { signtool sign /f $env:keyfile /p $env:certpass target\release\parity.exe } - makensis.exe nsis\installer.nsi From 507a638762a4a6447cd9be72abdc3a7481bea18d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 13 Jul 2016 16:39:03 +0200 Subject: [PATCH 33/36] Disabling ethcore-dapps testing (for a while) --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 82d34c91995..6adc35074e6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,7 +34,7 @@ env: - TRAVIS_NODE_VERSION="6" # GH_TOKEN - secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw= - - TARGETS="-p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethjson -p ethcore-dapps -p ethcore-signer -p bigint" + - TARGETS="-p ethkey -p ethstore -p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethjson -p ethcore-signer -p bigint" - ARCHIVE_SUFFIX="-${TRAVIS_OS_NAME}-${TRAVIS_TAG}" - KCOV_FEATURES="" - KCOV_CMD="./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests,ethstore/tests target/kcov" @@ -76,7 +76,6 @@ after_success: | $KCOV_CMD target/debug/deps/ethcore-* && $KCOV_CMD target/debug/deps/ethsync-* && $KCOV_CMD target/debug/deps/ethcore_rpc-* && - $KCOV_CMD target/debug/deps/ethcore_dapps-* && $KCOV_CMD target/debug/deps/ethcore_signer-* && $KCOV_CMD target/debug/deps/ethjson-* && $KCOV_CMD target/debug/parity-* && From 36d3d0d7d71684abe1217f0b30704fb68a6d0d2d Mon Sep 17 00:00:00 2001 From: Robert Habermeier Date: Wed, 13 Jul 2016 19:59:59 +0200 Subject: [PATCH 34/36] replace synchronization primitives with those from parking_lot (#1593) * parking_lot in cargo.toml * replace all lock invocations with parking_lot ones * use parking_lot synchronization primitives --- Cargo.lock | 18 ++ dapps/src/lib.rs | 4 +- db/src/database.rs | 35 ++-- ethash/Cargo.toml | 1 + ethash/src/compute.rs | 5 +- ethash/src/lib.rs | 19 +- ethcore/src/account_provider.rs | 14 +- ethcore/src/block_queue.rs | 76 ++++---- ethcore/src/blockchain/blockchain.rs | 50 +++--- ethcore/src/client/client.rs | 35 ++-- ethcore/src/client/test_client.rs | 90 +++++----- ethcore/src/db.rs | 10 +- ethcore/src/lib.rs | 1 - ethcore/src/miner/external.rs | 10 +- ethcore/src/miner/miner.rs | 109 ++++++------ ethcore/src/miner/mod.rs | 2 +- ethcore/src/miner/price_info.rs | 13 +- ethcore/src/miner/work_notify.rs | 4 +- ethcore/src/spec/spec.rs | 10 +- ethcore/src/trace/db.rs | 9 +- parity/informant.rs | 18 +- parity/main.rs | 7 +- rpc/rpctest/src/main.rs | 3 +- rpc/src/v1/helpers/signing_queue.rs | 34 ++-- rpc/src/v1/impls/eth.rs | 6 +- rpc/src/v1/impls/eth_filter.rs | 17 +- rpc/src/v1/tests/helpers/miner_service.rs | 52 +++--- rpc/src/v1/tests/helpers/sync_provider.rs | 5 +- rpc/src/v1/tests/mocked/eth.rs | 26 +-- rpc/src/v1/tests/mocked/eth_signing.rs | 2 +- rpc/src/v1/tests/mocked/personal.rs | 3 +- rpc/src/v1/tests/mocked/personal_signer.rs | 5 +- sync/src/chain.rs | 2 +- sync/src/lib.rs | 18 +- sync/src/tests/chain.rs | 22 +-- sync/src/tests/helpers.rs | 10 +- util/Cargo.toml | 1 + util/src/io/service.rs | 15 +- util/src/io/worker.rs | 9 +- util/src/journaldb/earlymergedb.rs | 7 +- util/src/journaldb/overlayrecentdb.rs | 13 +- util/src/lib.rs | 1 + util/src/log.rs | 10 +- util/src/misc.rs | 27 +-- util/src/network/connection.rs | 6 +- util/src/network/host.rs | 193 +++++++++++---------- util/src/network/service.rs | 22 +-- util/src/network/tests.rs | 5 +- util/src/panics.rs | 39 ++--- util/src/standard.rs | 4 +- 50 files changed, 547 insertions(+), 550 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d952b7b9853..28a08fb6899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,6 +232,7 @@ name = "ethash" version = "1.3.0" dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "primal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "sha3 0.1.0", ] @@ -403,6 +404,7 @@ dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", "nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rocksdb 0.4.5 (git+https://github.com/ethcore/rust-rocksdb)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", @@ -907,6 +909,17 @@ dependencies = [ "parity-dapps 0.3.0 (git+https://github.com/ethcore/parity-ui.git)", ] +[[package]] +name = "parking_lot" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", + "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "phf" version = "0.7.14" @@ -1174,6 +1187,11 @@ name = "slab" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "smallvec" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "solicit" version = "0.4.4" diff --git a/dapps/src/lib.rs b/dapps/src/lib.rs index a94cf1bde65..133b4ebaadd 100644 --- a/dapps/src/lib.rs +++ b/dapps/src/lib.rs @@ -70,7 +70,7 @@ mod url; use std::sync::{Arc, Mutex}; use std::net::SocketAddr; use std::collections::HashMap; -use ethcore_util::misc::Lockable; + use jsonrpc_core::{IoHandler, IoDelegate}; use router::auth::{Authorization, NoAuth, HttpBasicAuth}; use ethcore_rpc::Extendable; @@ -153,7 +153,7 @@ impl Server { /// Set callback for panics. pub fn set_panic_handler(&self, handler: F) where F : Fn() -> () + Send + 'static { - *self.panic_handler.locked() = Some(Box::new(handler)); + *self.panic_handler.lock().unwrap() = Some(Box::new(handler)); } } diff --git a/db/src/database.rs b/db/src/database.rs index 2360e69ca91..777ec3bbc09 100644 --- a/db/src/database.rs +++ b/db/src/database.rs @@ -17,7 +17,6 @@ //! Ethcore rocksdb ipc service use traits::*; -use misc::RwLockable; use rocksdb::{DB, Writable, WriteBatch, IteratorMode, DBIterator, IndexType, Options, DBCompactionStyle, BlockBasedOptions, Direction}; use std::sync::{RwLock, Arc}; use std::convert::From; @@ -137,8 +136,8 @@ impl Database { } pub fn flush(&self) -> Result<(), Error> { - let mut cache_lock = self.write_cache.unwrapped_write(); - let db_lock = self.db.unwrapped_read(); + let mut cache_lock = self.write_cache.write(); + let db_lock = self.db.read(); if db_lock.is_none() { return Ok(()); } let db = db_lock.as_ref().unwrap(); @@ -147,8 +146,8 @@ impl Database { } pub fn flush_all(&self) -> Result<(), Error> { - let mut cache_lock = self.write_cache.unwrapped_write(); - let db_lock = self.db.unwrapped_read(); + let mut cache_lock = self.write_cache.write(); + let db_lock = self.db.read(); if db_lock.is_none() { return Ok(()); } let db = db_lock.as_ref().expect("we should have exited with Ok(()) on the previous step"); @@ -167,7 +166,7 @@ impl Drop for Database { #[derive(Ipc)] impl DatabaseService for Database { fn open(&self, config: DatabaseConfig, path: String) -> Result<(), Error> { - let mut db = self.db.unwrapped_write(); + let mut db = self.db.write(); if db.is_some() { return Err(Error::AlreadyOpen); } let mut opts = Options::new(); @@ -194,7 +193,7 @@ impl DatabaseService for Database { fn close(&self) -> Result<(), Error> { try!(self.flush_all()); - let mut db = self.db.unwrapped_write(); + let mut db = self.db.write(); if db.is_none() { return Err(Error::IsClosed); } *db = None; @@ -202,19 +201,19 @@ impl DatabaseService for Database { } fn put(&self, key: &[u8], value: &[u8]) -> Result<(), Error> { - let mut cache_lock = self.write_cache.unwrapped_write(); + let mut cache_lock = self.write_cache.write(); cache_lock.write(key.to_vec(), value.to_vec()); Ok(()) } fn delete(&self, key: &[u8]) -> Result<(), Error> { - let mut cache_lock = self.write_cache.unwrapped_write(); + let mut cache_lock = self.write_cache.write(); cache_lock.remove(key.to_vec()); Ok(()) } fn write(&self, transaction: DBTransaction) -> Result<(), Error> { - let mut cache_lock = self.write_cache.unwrapped_write(); + let mut cache_lock = self.write_cache.write(); let mut writes = transaction.writes.borrow_mut(); for kv in writes.drain(..) { @@ -231,13 +230,13 @@ impl DatabaseService for Database { fn get(&self, key: &[u8]) -> Result>, Error> { { let key_vec = key.to_vec(); - let cache_hit = self.write_cache.unwrapped_read().get(&key_vec); + let cache_hit = self.write_cache.read().get(&key_vec); if cache_hit.is_some() { return Ok(Some(cache_hit.expect("cache_hit.is_some() = true, still there is none somehow here"))) } } - let db_lock = self.db.unwrapped_read(); + let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); match try!(db.get(key)) { @@ -249,7 +248,7 @@ impl DatabaseService for Database { } fn get_by_prefix(&self, prefix: &[u8]) -> Result>, Error> { - let db_lock = self.db.unwrapped_read(); + let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let mut iter = db.iterator(IteratorMode::From(prefix, Direction::Forward)); @@ -261,17 +260,17 @@ impl DatabaseService for Database { } fn is_empty(&self) -> Result { - let db_lock = self.db.unwrapped_read(); + let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); Ok(db.iterator(IteratorMode::Start).next().is_none()) } fn iter(&self) -> Result { - let db_lock = self.db.unwrapped_read(); + let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); - let mut iterators = self.iterators.unwrapped_write(); + let mut iterators = self.iterators.write(); let next_iterator = iterators.keys().last().unwrap_or(&0) + 1; iterators.insert(next_iterator, db.iterator(IteratorMode::Start)); Ok(next_iterator) @@ -279,7 +278,7 @@ impl DatabaseService for Database { fn iter_next(&self, handle: IteratorHandle) -> Option { - let mut iterators = self.iterators.unwrapped_write(); + let mut iterators = self.iterators.write(); let mut iterator = match iterators.get_mut(&handle) { Some(some_iterator) => some_iterator, None => { return None; }, @@ -294,7 +293,7 @@ impl DatabaseService for Database { } fn dispose_iter(&self, handle: IteratorHandle) -> Result<(), Error> { - let mut iterators = self.iterators.unwrapped_write(); + let mut iterators = self.iterators.write(); iterators.remove(&handle); Ok(()) } diff --git a/ethash/Cargo.toml b/ethash/Cargo.toml index 94a714d5558..a0501e8d3fa 100644 --- a/ethash/Cargo.toml +++ b/ethash/Cargo.toml @@ -9,3 +9,4 @@ authors = ["arkpar io::Result<()> { - let seed_compute = self.seed_compute.lock().unwrap(); + let seed_compute = self.seed_compute.lock(); let path = Light::file_path(seed_compute.get_seedhash(self.block_number)); try!(fs::create_dir_all(path.parent().unwrap())); let mut file = try!(File::create(path)); diff --git a/ethash/src/lib.rs b/ethash/src/lib.rs index 3f67f27482c..8fb2c43f6db 100644 --- a/ethash/src/lib.rs +++ b/ethash/src/lib.rs @@ -18,6 +18,8 @@ //! See https://github.com/ethereum/wiki/wiki/Ethash extern crate primal; extern crate sha3; +extern crate parking_lot; + #[macro_use] extern crate log; mod compute; @@ -26,7 +28,8 @@ use std::mem; use compute::Light; pub use compute::{ETHASH_EPOCH_LENGTH, H256, ProofOfWork, SeedHashCompute, quick_get_difficulty}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use parking_lot::Mutex; struct LightCache { recent_epoch: Option, @@ -61,7 +64,7 @@ impl EthashManager { pub fn compute_light(&self, block_number: u64, header_hash: &H256, nonce: u64) -> ProofOfWork { let epoch = block_number / ETHASH_EPOCH_LENGTH; let light = { - let mut lights = self.cache.lock().unwrap(); + let mut lights = self.cache.lock(); let light = match lights.recent_epoch.clone() { Some(ref e) if *e == epoch => lights.recent.clone(), _ => match lights.prev_epoch.clone() { @@ -108,12 +111,12 @@ fn test_lru() { let hash = [0u8; 32]; ethash.compute_light(1, &hash, 1); ethash.compute_light(50000, &hash, 1); - assert_eq!(ethash.cache.lock().unwrap().recent_epoch.unwrap(), 1); - assert_eq!(ethash.cache.lock().unwrap().prev_epoch.unwrap(), 0); + assert_eq!(ethash.cache.lock().recent_epoch.unwrap(), 1); + assert_eq!(ethash.cache.lock().prev_epoch.unwrap(), 0); ethash.compute_light(1, &hash, 1); - assert_eq!(ethash.cache.lock().unwrap().recent_epoch.unwrap(), 0); - assert_eq!(ethash.cache.lock().unwrap().prev_epoch.unwrap(), 1); + assert_eq!(ethash.cache.lock().recent_epoch.unwrap(), 0); + assert_eq!(ethash.cache.lock().prev_epoch.unwrap(), 1); ethash.compute_light(70000, &hash, 1); - assert_eq!(ethash.cache.lock().unwrap().recent_epoch.unwrap(), 2); - assert_eq!(ethash.cache.lock().unwrap().prev_epoch.unwrap(), 0); + assert_eq!(ethash.cache.lock().recent_epoch.unwrap(), 2); + assert_eq!(ethash.cache.lock().prev_epoch.unwrap(), 0); } diff --git a/ethcore/src/account_provider.rs b/ethcore/src/account_provider.rs index 90d44bfba72..332426cab51 100644 --- a/ethcore/src/account_provider.rs +++ b/ethcore/src/account_provider.rs @@ -17,13 +17,13 @@ //! Account management. use std::fmt; -use std::sync::RwLock; use std::collections::HashMap; -use util::{Address as H160, H256, H520, RwLockable}; +use util::{Address as H160, H256, H520, RwLock}; use ethstore::{SecretStore, Error as SSError, SafeAccount, EthStore}; use ethstore::dir::{KeyDirectory}; use ethstore::ethkey::{Address as SSAddress, Message as SSMessage, Secret as SSSecret, Random, Generator}; + /// Type of unlock. #[derive(Clone)] enum Unlock { @@ -177,7 +177,7 @@ impl AccountProvider { // check if account is already unlocked pernamently, if it is, do nothing { - let unlocked = self.unlocked.unwrapped_read(); + let unlocked = self.unlocked.read(); if let Some(data) = unlocked.get(&account) { if let Unlock::Perm = data.unlock { return Ok(()) @@ -190,7 +190,7 @@ impl AccountProvider { password: password, }; - let mut unlocked = self.unlocked.unwrapped_write(); + let mut unlocked = self.unlocked.write(); unlocked.insert(account, data); Ok(()) } @@ -208,7 +208,7 @@ impl AccountProvider { /// Checks if given account is unlocked pub fn is_unlocked(&self, account: A) -> bool where Address: From { let account = Address::from(account).into(); - let unlocked = self.unlocked.unwrapped_read(); + let unlocked = self.unlocked.read(); unlocked.get(&account).is_some() } @@ -218,12 +218,12 @@ impl AccountProvider { let message = Message::from(message).into(); let data = { - let unlocked = self.unlocked.unwrapped_read(); + let unlocked = self.unlocked.read(); try!(unlocked.get(&account).ok_or(Error::NotUnlocked)).clone() }; if let Unlock::Temp = data.unlock { - let mut unlocked = self.unlocked.unwrapped_write(); + let mut unlocked = self.unlocked.write(); unlocked.remove(&account).expect("data exists: so key must exist: qed"); } diff --git a/ethcore/src/block_queue.rs b/ethcore/src/block_queue.rs index 19f5d0a4c33..623fab4a678 100644 --- a/ethcore/src/block_queue.rs +++ b/ethcore/src/block_queue.rs @@ -193,14 +193,14 @@ impl BlockQueue { fn verify(verification: Arc, engine: Arc>, wait: Arc, ready: Arc, deleting: Arc, empty: Arc) { while !deleting.load(AtomicOrdering::Acquire) { { - let mut unverified = verification.unverified.locked(); + let mut unverified = verification.unverified.lock(); - if unverified.is_empty() && verification.verifying.locked().is_empty() { + if unverified.is_empty() && verification.verifying.lock().is_empty() { empty.notify_all(); } while unverified.is_empty() && !deleting.load(AtomicOrdering::Acquire) { - unverified = wait.wait(unverified).unwrap(); + wait.wait(&mut unverified); } if deleting.load(AtomicOrdering::Acquire) { @@ -209,11 +209,11 @@ impl BlockQueue { } let block = { - let mut unverified = verification.unverified.locked(); + let mut unverified = verification.unverified.lock(); if unverified.is_empty() { continue; } - let mut verifying = verification.verifying.locked(); + let mut verifying = verification.verifying.lock(); let block = unverified.pop_front().unwrap(); verifying.push_back(VerifyingBlock{ hash: block.header.hash(), block: None }); block @@ -222,7 +222,7 @@ impl BlockQueue { let block_hash = block.header.hash(); match verify_block_unordered(block.header, block.bytes, engine.deref().deref()) { Ok(verified) => { - let mut verifying = verification.verifying.locked(); + let mut verifying = verification.verifying.lock(); for e in verifying.iter_mut() { if e.hash == block_hash { e.block = Some(verified); @@ -231,16 +231,16 @@ impl BlockQueue { } if !verifying.is_empty() && verifying.front().unwrap().hash == block_hash { // we're next! - let mut verified = verification.verified.locked(); - let mut bad = verification.bad.locked(); + let mut verified = verification.verified.lock(); + let mut bad = verification.bad.lock(); BlockQueue::drain_verifying(&mut verifying, &mut verified, &mut bad); ready.set(); } }, Err(err) => { - let mut verifying = verification.verifying.locked(); - let mut verified = verification.verified.locked(); - let mut bad = verification.bad.locked(); + let mut verifying = verification.verifying.lock(); + let mut verified = verification.verified.lock(); + let mut bad = verification.bad.lock(); warn!(target: "client", "Stage 2 block verification failed for {}\nError: {:?}", block_hash, err); bad.insert(block_hash.clone()); verifying.retain(|e| e.hash != block_hash); @@ -265,29 +265,29 @@ impl BlockQueue { /// Clear the queue and stop verification activity. pub fn clear(&self) { - let mut unverified = self.verification.unverified.locked(); - let mut verifying = self.verification.verifying.locked(); - let mut verified = self.verification.verified.locked(); + let mut unverified = self.verification.unverified.lock(); + let mut verifying = self.verification.verifying.lock(); + let mut verified = self.verification.verified.lock(); unverified.clear(); verifying.clear(); verified.clear(); - self.processing.unwrapped_write().clear(); + self.processing.write().clear(); } /// Wait for unverified queue to be empty pub fn flush(&self) { - let mut unverified = self.verification.unverified.locked(); - while !unverified.is_empty() || !self.verification.verifying.locked().is_empty() { - unverified = self.empty.wait(unverified).unwrap(); + let mut unverified = self.verification.unverified.lock(); + while !unverified.is_empty() || !self.verification.verifying.lock().is_empty() { + self.empty.wait(&mut unverified); } } /// Check if the block is currently in the queue pub fn block_status(&self, hash: &H256) -> BlockStatus { - if self.processing.unwrapped_read().contains(&hash) { + if self.processing.read().contains(&hash) { return BlockStatus::Queued; } - if self.verification.bad.locked().contains(&hash) { + if self.verification.bad.lock().contains(&hash) { return BlockStatus::Bad; } BlockStatus::Unknown @@ -298,11 +298,11 @@ impl BlockQueue { let header = BlockView::new(&bytes).header(); let h = header.hash(); { - if self.processing.unwrapped_read().contains(&h) { + if self.processing.read().contains(&h) { return Err(ImportError::AlreadyQueued.into()); } - let mut bad = self.verification.bad.locked(); + let mut bad = self.verification.bad.lock(); if bad.contains(&h) { return Err(ImportError::KnownBad.into()); } @@ -315,14 +315,14 @@ impl BlockQueue { match verify_block_basic(&header, &bytes, self.engine.deref().deref()) { Ok(()) => { - self.processing.unwrapped_write().insert(h.clone()); - self.verification.unverified.locked().push_back(UnverifiedBlock { header: header, bytes: bytes }); + self.processing.write().insert(h.clone()); + self.verification.unverified.lock().push_back(UnverifiedBlock { header: header, bytes: bytes }); self.more_to_verify.notify_all(); Ok(h) }, Err(err) => { warn!(target: "client", "Stage 1 block verification failed for {}\nError: {:?}", BlockView::new(&bytes).header_view().sha3(), err); - self.verification.bad.locked().insert(h.clone()); + self.verification.bad.lock().insert(h.clone()); Err(err) } } @@ -333,10 +333,10 @@ impl BlockQueue { if block_hashes.is_empty() { return; } - let mut verified_lock = self.verification.verified.locked(); + let mut verified_lock = self.verification.verified.lock(); let mut verified = verified_lock.deref_mut(); - let mut bad = self.verification.bad.locked(); - let mut processing = self.processing.unwrapped_write(); + let mut bad = self.verification.bad.lock(); + let mut processing = self.processing.write(); bad.reserve(block_hashes.len()); for hash in block_hashes { bad.insert(hash.clone()); @@ -360,7 +360,7 @@ impl BlockQueue { if block_hashes.is_empty() { return; } - let mut processing = self.processing.unwrapped_write(); + let mut processing = self.processing.write(); for hash in block_hashes { processing.remove(&hash); } @@ -368,7 +368,7 @@ impl BlockQueue { /// Removes up to `max` verified blocks from the queue pub fn drain(&self, max: usize) -> Vec { - let mut verified = self.verification.verified.locked(); + let mut verified = self.verification.verified.lock(); let count = min(max, verified.len()); let mut result = Vec::with_capacity(count); for _ in 0..count { @@ -385,15 +385,15 @@ impl BlockQueue { /// Get queue status. pub fn queue_info(&self) -> BlockQueueInfo { let (unverified_len, unverified_bytes) = { - let v = self.verification.unverified.locked(); + let v = self.verification.unverified.lock(); (v.len(), v.heap_size_of_children()) }; let (verifying_len, verifying_bytes) = { - let v = self.verification.verifying.locked(); + let v = self.verification.verifying.lock(); (v.len(), v.heap_size_of_children()) }; let (verified_len, verified_bytes) = { - let v = self.verification.verified.locked(); + let v = self.verification.verified.lock(); (v.len(), v.heap_size_of_children()) }; BlockQueueInfo { @@ -407,18 +407,18 @@ impl BlockQueue { + verifying_bytes + verified_bytes // TODO: https://github.com/servo/heapsize/pull/50 - //+ self.processing.unwrapped_read().heap_size_of_children(), + //+ self.processing.read().heap_size_of_children(), } } /// Optimise memory footprint of the heap fields. pub fn collect_garbage(&self) { { - self.verification.unverified.locked().shrink_to_fit(); - self.verification.verifying.locked().shrink_to_fit(); - self.verification.verified.locked().shrink_to_fit(); + self.verification.unverified.lock().shrink_to_fit(); + self.verification.verifying.lock().shrink_to_fit(); + self.verification.verified.lock().shrink_to_fit(); } - self.processing.unwrapped_write().shrink_to_fit(); + self.processing.write().shrink_to_fit(); } } diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index 3ff030ca003..982288d927a 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -170,7 +170,7 @@ impl BlockProvider for BlockChain { /// Get raw block data fn block(&self, hash: &H256) -> Option { { - let read = self.blocks.unwrapped_read(); + let read = self.blocks.read(); if let Some(v) = read.get(hash) { return Some(v.clone()); } @@ -184,7 +184,7 @@ impl BlockProvider for BlockChain { match opt { Some(b) => { let bytes: Bytes = b.to_vec(); - let mut write = self.blocks.unwrapped_write(); + let mut write = self.blocks.write(); write.insert(hash.clone(), bytes.clone()); Some(bytes) }, @@ -338,7 +338,7 @@ impl BlockChain { }; { - let mut best_block = bc.best_block.unwrapped_write(); + let mut best_block = bc.best_block.write(); best_block.number = bc.block_number(&best_block_hash).unwrap(); best_block.total_difficulty = bc.block_details(&best_block_hash).unwrap().total_difficulty; best_block.hash = best_block_hash; @@ -483,25 +483,25 @@ impl BlockChain { self.note_used(CacheID::BlockDetails(hash)); } - let mut write_details = self.block_details.unwrapped_write(); + let mut write_details = self.block_details.write(); batch.extend_with_cache(write_details.deref_mut(), update.block_details, CacheUpdatePolicy::Overwrite); } { - let mut write_receipts = self.block_receipts.unwrapped_write(); + let mut write_receipts = self.block_receipts.write(); batch.extend_with_cache(write_receipts.deref_mut(), update.block_receipts, CacheUpdatePolicy::Remove); } { - let mut write_blocks_blooms = self.blocks_blooms.unwrapped_write(); + let mut write_blocks_blooms = self.blocks_blooms.write(); batch.extend_with_cache(write_blocks_blooms.deref_mut(), update.blocks_blooms, CacheUpdatePolicy::Remove); } // These cached values must be updated last and togeterh { - let mut best_block = self.best_block.unwrapped_write(); - let mut write_hashes = self.block_hashes.unwrapped_write(); - let mut write_txs = self.transaction_addresses.unwrapped_write(); + let mut best_block = self.best_block.write(); + let mut write_hashes = self.block_hashes.write(); + let mut write_txs = self.transaction_addresses.write(); // update best block match update.info.location { @@ -728,33 +728,33 @@ impl BlockChain { /// Get best block hash. pub fn best_block_hash(&self) -> H256 { - self.best_block.unwrapped_read().hash.clone() + self.best_block.read().hash.clone() } /// Get best block number. pub fn best_block_number(&self) -> BlockNumber { - self.best_block.unwrapped_read().number + self.best_block.read().number } /// Get best block total difficulty. pub fn best_block_total_difficulty(&self) -> U256 { - self.best_block.unwrapped_read().total_difficulty + self.best_block.read().total_difficulty } /// Get current cache size. pub fn cache_size(&self) -> CacheSize { CacheSize { - blocks: self.blocks.unwrapped_read().heap_size_of_children(), - block_details: self.block_details.unwrapped_read().heap_size_of_children(), - transaction_addresses: self.transaction_addresses.unwrapped_read().heap_size_of_children(), - blocks_blooms: self.blocks_blooms.unwrapped_read().heap_size_of_children(), - block_receipts: self.block_receipts.unwrapped_read().heap_size_of_children(), + blocks: self.blocks.read().heap_size_of_children(), + block_details: self.block_details.read().heap_size_of_children(), + transaction_addresses: self.transaction_addresses.read().heap_size_of_children(), + blocks_blooms: self.blocks_blooms.read().heap_size_of_children(), + block_receipts: self.block_receipts.read().heap_size_of_children(), } } /// Let the cache system know that a cacheable item has been used. fn note_used(&self, id: CacheID) { - let mut cache_man = self.cache_man.unwrapped_write(); + let mut cache_man = self.cache_man.write(); if !cache_man.cache_usage[0].contains(&id) { cache_man.cache_usage[0].insert(id.clone()); if cache_man.in_use.contains(&id) { @@ -773,13 +773,13 @@ impl BlockChain { for _ in 0..COLLECTION_QUEUE_SIZE { { - let mut blocks = self.blocks.unwrapped_write(); - let mut block_details = self.block_details.unwrapped_write(); - let mut block_hashes = self.block_hashes.unwrapped_write(); - let mut transaction_addresses = self.transaction_addresses.unwrapped_write(); - let mut blocks_blooms = self.blocks_blooms.unwrapped_write(); - let mut block_receipts = self.block_receipts.unwrapped_write(); - let mut cache_man = self.cache_man.unwrapped_write(); + let mut blocks = self.blocks.write(); + let mut block_details = self.block_details.write(); + let mut block_hashes = self.block_hashes.write(); + let mut transaction_addresses = self.transaction_addresses.write(); + let mut blocks_blooms = self.blocks_blooms.write(); + let mut block_receipts = self.block_receipts.write(); + let mut cache_man = self.cache_man.write(); for id in cache_man.cache_usage.pop_back().unwrap().into_iter() { cache_man.in_use.remove(&id); diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index f95df66fb68..c92d8263670 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -18,7 +18,7 @@ use std::collections::{HashSet, HashMap}; use std::ops::Deref; use std::mem; use std::collections::VecDeque; -use std::sync::*; +use std::sync::{Arc, Weak}; use std::path::{Path, PathBuf}; use std::fmt; use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering}; @@ -30,12 +30,13 @@ use util::panics::*; use util::io::*; use util::rlp; use util::sha3::*; -use util::{Bytes, Lockable, RwLockable}; +use util::Bytes; use util::rlp::{RlpStream, Rlp, UntrustedRlp}; use util::journaldb; use util::journaldb::JournalDB; use util::kvdb::*; use util::{Applyable, Stream, View, PerfTimer, Itertools, Colour}; +use util::{Mutex, RwLock}; // other use views::BlockView; @@ -236,12 +237,12 @@ impl Client { /// Sets the actor to be notified on certain events pub fn set_notify(&self, target: &Arc) { - let mut write_lock = self.notify.unwrapped_write(); + let mut write_lock = self.notify.write(); *write_lock = Some(Arc::downgrade(target)); } fn notify(&self) -> Option> { - let read_lock = self.notify.unwrapped_read(); + let read_lock = self.notify.read(); read_lock.as_ref().and_then(|weak| weak.upgrade()) } @@ -293,7 +294,7 @@ impl Client { // Enact Verified Block let parent = chain_has_parent.unwrap(); let last_hashes = self.build_last_hashes(header.parent_hash.clone()); - let db = self.state_db.locked().boxed_clone(); + let db = self.state_db.lock().boxed_clone(); let enact_result = enact_verified(&block, engine, self.tracedb.tracing_enabled(), db, &parent, last_hashes, &self.vm_factory, self.trie_factory.clone()); if let Err(e) = enact_result { @@ -369,7 +370,7 @@ impl Client { let route = self.commit_block(closed_block, &header.hash(), &block.bytes); import_results.push(route); - self.report.unwrapped_write().accrue_block(&block); + self.report.write().accrue_block(&block); trace!(target: "client", "Imported #{} ({})", header.number(), header.hash()); } @@ -471,7 +472,7 @@ impl Client { }; self.block_header(id).and_then(|header| { - let db = self.state_db.locked().boxed_clone(); + let db = self.state_db.lock().boxed_clone(); // early exit for pruned blocks if db.is_pruned() && self.chain.best_block_number() >= block_number + HISTORY { @@ -487,7 +488,7 @@ impl Client { /// Get a copy of the best block's state. pub fn state(&self) -> State { State::from_existing( - self.state_db.locked().boxed_clone(), + self.state_db.lock().boxed_clone(), HeaderView::new(&self.best_block_header()).state_root(), self.engine.account_start_nonce(), self.trie_factory.clone()) @@ -501,8 +502,8 @@ impl Client { /// Get the report. pub fn report(&self) -> ClientReport { - let mut report = self.report.unwrapped_read().clone(); - report.state_db_mem = self.state_db.locked().mem_used(); + let mut report = self.report.read().clone(); + report.state_db_mem = self.state_db.lock().mem_used(); report } @@ -514,7 +515,7 @@ impl Client { match self.mode { Mode::Dark(timeout) => { - let mut ss = self.sleep_state.locked(); + let mut ss = self.sleep_state.lock(); if let Some(t) = ss.last_activity { if Instant::now() > t + timeout { self.sleep(); @@ -523,7 +524,7 @@ impl Client { } } Mode::Passive(timeout, wakeup_after) => { - let mut ss = self.sleep_state.locked(); + let mut ss = self.sleep_state.lock(); let now = Instant::now(); if let Some(t) = ss.last_activity { if now > t + timeout { @@ -600,14 +601,14 @@ impl Client { } else { trace!(target: "mode", "sleep: Cannot sleep - syncing ongoing."); // TODO: Consider uncommenting. - //*self.last_activity.locked() = Some(Instant::now()); + //*self.last_activity.lock() = Some(Instant::now()); } } } /// Notify us that the network has been started. pub fn network_started(&self, url: &str) { - let mut previous_enode = self.previous_enode.locked(); + let mut previous_enode = self.previous_enode.lock(); if let Some(ref u) = *previous_enode { if u == url { return; @@ -661,7 +662,7 @@ impl BlockChainClient for Client { fn keep_alive(&self) { if self.mode != Mode::Active { self.wake_up(); - (*self.sleep_state.locked()).last_activity = Some(Instant::now()); + (*self.sleep_state.lock()).last_activity = Some(Instant::now()); } } @@ -785,7 +786,7 @@ impl BlockChainClient for Client { } fn state_data(&self, hash: &H256) -> Option { - self.state_db.locked().state(hash) + self.state_db.lock().state(hash) } fn block_receipts(&self, hash: &H256) -> Option { @@ -946,7 +947,7 @@ impl MiningBlockChainClient for Client { &self.vm_factory, self.trie_factory.clone(), false, // TODO: this will need to be parameterised once we want to do immediate mining insertion. - self.state_db.locked().boxed_clone(), + self.state_db.lock().boxed_clone(), &self.chain.block_header(&h).expect("h is best block hash: so it's header must exist: qed"), self.build_last_hashes(h.clone()), author, diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index f7387e6ab13..b60d537a1b4 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -115,38 +115,38 @@ impl TestBlockChainClient { vm_factory: EvmFactory::new(VMType::Interpreter), }; client.add_blocks(1, EachBlockWith::Nothing); // add genesis block - client.genesis_hash = client.last_hash.unwrapped_read().clone(); + client.genesis_hash = client.last_hash.read().clone(); client } /// Set the transaction receipt result pub fn set_transaction_receipt(&self, id: TransactionID, receipt: LocalizedReceipt) { - self.receipts.unwrapped_write().insert(id, receipt); + self.receipts.write().insert(id, receipt); } /// Set the execution result. pub fn set_execution_result(&self, result: Executed) { - *self.execution_result.unwrapped_write() = Some(result); + *self.execution_result.write() = Some(result); } /// Set the balance of account `address` to `balance`. pub fn set_balance(&self, address: Address, balance: U256) { - self.balances.unwrapped_write().insert(address, balance); + self.balances.write().insert(address, balance); } /// Set nonce of account `address` to `nonce`. pub fn set_nonce(&self, address: Address, nonce: U256) { - self.nonces.unwrapped_write().insert(address, nonce); + self.nonces.write().insert(address, nonce); } /// Set `code` at `address`. pub fn set_code(&self, address: Address, code: Bytes) { - self.code.unwrapped_write().insert(address, code); + self.code.write().insert(address, code); } /// Set storage `position` to `value` for account `address`. pub fn set_storage(&self, address: Address, position: H256, value: H256) { - self.storage.unwrapped_write().insert((address, position), value); + self.storage.write().insert((address, position), value); } /// Set block queue size for testing @@ -156,11 +156,11 @@ impl TestBlockChainClient { /// Add blocks to test client. pub fn add_blocks(&self, count: usize, with: EachBlockWith) { - let len = self.numbers.unwrapped_read().len(); + let len = self.numbers.read().len(); for n in len..(len + count) { let mut header = BlockHeader::new(); header.difficulty = From::from(n); - header.parent_hash = self.last_hash.unwrapped_read().clone(); + header.parent_hash = self.last_hash.read().clone(); header.number = n as BlockNumber; header.gas_limit = U256::from(1_000_000); let uncles = match with { @@ -168,7 +168,7 @@ impl TestBlockChainClient { let mut uncles = RlpStream::new_list(1); let mut uncle_header = BlockHeader::new(); uncle_header.difficulty = From::from(n); - uncle_header.parent_hash = self.last_hash.unwrapped_read().clone(); + uncle_header.parent_hash = self.last_hash.read().clone(); uncle_header.number = n as BlockNumber; uncles.append(&uncle_header); header.uncles_hash = uncles.as_raw().sha3(); @@ -181,7 +181,7 @@ impl TestBlockChainClient { let mut txs = RlpStream::new_list(1); let keypair = KeyPair::create().unwrap(); // Update nonces value - self.nonces.unwrapped_write().insert(keypair.address(), U256::one()); + self.nonces.write().insert(keypair.address(), U256::one()); let tx = Transaction { action: Action::Create, value: U256::from(100), @@ -214,7 +214,7 @@ impl TestBlockChainClient { rlp.append(&header); rlp.append_raw(&rlp::NULL_RLP, 1); rlp.append_raw(&rlp::NULL_RLP, 1); - self.blocks.unwrapped_write().insert(hash, rlp.out()); + self.blocks.write().insert(hash, rlp.out()); } /// Make a bad block by setting invalid parent hash. @@ -226,12 +226,12 @@ impl TestBlockChainClient { rlp.append(&header); rlp.append_raw(&rlp::NULL_RLP, 1); rlp.append_raw(&rlp::NULL_RLP, 1); - self.blocks.unwrapped_write().insert(hash, rlp.out()); + self.blocks.write().insert(hash, rlp.out()); } /// TODO: pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { - let blocks_read = self.numbers.unwrapped_read(); + let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index].clone() } @@ -239,9 +239,9 @@ impl TestBlockChainClient { fn block_hash(&self, id: BlockID) -> Option { match id { BlockID::Hash(hash) => Some(hash), - BlockID::Number(n) => self.numbers.unwrapped_read().get(&(n as usize)).cloned(), - BlockID::Earliest => self.numbers.unwrapped_read().get(&0).cloned(), - BlockID::Latest => self.numbers.unwrapped_read().get(&(self.numbers.unwrapped_read().len() - 1)).cloned() + BlockID::Number(n) => self.numbers.read().get(&(n as usize)).cloned(), + BlockID::Earliest => self.numbers.read().get(&0).cloned(), + BlockID::Latest => self.numbers.read().get(&(self.numbers.read().len() - 1)).cloned() } } } @@ -288,7 +288,7 @@ impl MiningBlockChainClient for TestBlockChainClient { impl BlockChainClient for TestBlockChainClient { fn call(&self, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result { - Ok(self.execution_result.unwrapped_read().clone().unwrap()) + Ok(self.execution_result.read().clone().unwrap()) } fn block_total_difficulty(&self, _id: BlockID) -> Option { @@ -301,7 +301,7 @@ impl BlockChainClient for TestBlockChainClient { fn nonce(&self, address: &Address, id: BlockID) -> Option { match id { - BlockID::Latest => Some(self.nonces.unwrapped_read().get(address).cloned().unwrap_or_else(U256::zero)), + BlockID::Latest => Some(self.nonces.read().get(address).cloned().unwrap_or_else(U256::zero)), _ => None, } } @@ -311,12 +311,12 @@ impl BlockChainClient for TestBlockChainClient { } fn code(&self, address: &Address) -> Option { - self.code.unwrapped_read().get(address).cloned() + self.code.read().get(address).cloned() } fn balance(&self, address: &Address, id: BlockID) -> Option { if let BlockID::Latest = id { - Some(self.balances.unwrapped_read().get(address).cloned().unwrap_or_else(U256::zero)) + Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) } else { None } @@ -328,7 +328,7 @@ impl BlockChainClient for TestBlockChainClient { fn storage_at(&self, address: &Address, position: &H256, id: BlockID) -> Option { if let BlockID::Latest = id { - Some(self.storage.unwrapped_read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) + Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) } else { None } @@ -343,7 +343,7 @@ impl BlockChainClient for TestBlockChainClient { } fn transaction_receipt(&self, id: TransactionID) -> Option { - self.receipts.unwrapped_read().get(&id).cloned() + self.receipts.read().get(&id).cloned() } fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockID, _to_block: BlockID) -> Option> { @@ -359,11 +359,11 @@ impl BlockChainClient for TestBlockChainClient { } fn block_header(&self, id: BlockID) -> Option { - self.block_hash(id).and_then(|hash| self.blocks.unwrapped_read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) + self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) } fn block_body(&self, id: BlockID) -> Option { - self.block_hash(id).and_then(|hash| self.blocks.unwrapped_read().get(&hash).map(|r| { + self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| { let mut stream = RlpStream::new_list(2); stream.append_raw(Rlp::new(&r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(&r).at(2).as_raw(), 1); @@ -372,13 +372,13 @@ impl BlockChainClient for TestBlockChainClient { } fn block(&self, id: BlockID) -> Option { - self.block_hash(id).and_then(|hash| self.blocks.unwrapped_read().get(&hash).cloned()) + self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).cloned()) } fn block_status(&self, id: BlockID) -> BlockStatus { match id { - BlockID::Number(number) if (number as usize) < self.blocks.unwrapped_read().len() => BlockStatus::InChain, - BlockID::Hash(ref hash) if self.blocks.unwrapped_read().get(hash).is_some() => BlockStatus::InChain, + BlockID::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, + BlockID::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, _ => BlockStatus::Unknown } } @@ -389,7 +389,7 @@ impl BlockChainClient for TestBlockChainClient { ancestor: H256::new(), index: 0, blocks: { - let numbers_read = self.numbers.unwrapped_read(); + let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); @@ -446,11 +446,11 @@ impl BlockChainClient for TestBlockChainClient { let header = Rlp::new(&b).val_at::(0); let h = header.hash(); let number: usize = header.number as usize; - if number > self.blocks.unwrapped_read().len() { - panic!("Unexpected block number. Expected {}, got {}", self.blocks.unwrapped_read().len(), number); + if number > self.blocks.read().len() { + panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().len(), number); } if number > 0 { - match self.blocks.unwrapped_read().get(&header.parent_hash) { + match self.blocks.read().get(&header.parent_hash) { Some(parent) => { let parent = Rlp::new(parent).val_at::(0); if parent.number != (header.number - 1) { @@ -462,27 +462,27 @@ impl BlockChainClient for TestBlockChainClient { } } } - let len = self.numbers.unwrapped_read().len(); + let len = self.numbers.read().len(); if number == len { { - let mut difficulty = self.difficulty.unwrapped_write(); + let mut difficulty = self.difficulty.write(); *difficulty.deref_mut() = *difficulty.deref() + header.difficulty; } - mem::replace(self.last_hash.unwrapped_write().deref_mut(), h.clone()); - self.blocks.unwrapped_write().insert(h.clone(), b); - self.numbers.unwrapped_write().insert(number, h.clone()); + mem::replace(self.last_hash.write().deref_mut(), h.clone()); + self.blocks.write().insert(h.clone(), b); + self.numbers.write().insert(number, h.clone()); let mut parent_hash = header.parent_hash; if number > 0 { let mut n = number - 1; - while n > 0 && self.numbers.unwrapped_read()[&n] != parent_hash { - *self.numbers.unwrapped_write().get_mut(&n).unwrap() = parent_hash.clone(); + while n > 0 && self.numbers.read()[&n] != parent_hash { + *self.numbers.write().get_mut(&n).unwrap() = parent_hash.clone(); n -= 1; - parent_hash = Rlp::new(&self.blocks.unwrapped_read()[&parent_hash]).val_at::(0).parent_hash; + parent_hash = Rlp::new(&self.blocks.read()[&parent_hash]).val_at::(0).parent_hash; } } } else { - self.blocks.unwrapped_write().insert(h.clone(), b.to_vec()); + self.blocks.write().insert(h.clone(), b.to_vec()); } Ok(h) } @@ -503,11 +503,11 @@ impl BlockChainClient for TestBlockChainClient { fn chain_info(&self) -> BlockChainInfo { BlockChainInfo { - total_difficulty: *self.difficulty.unwrapped_read(), - pending_total_difficulty: *self.difficulty.unwrapped_read(), + total_difficulty: *self.difficulty.read(), + pending_total_difficulty: *self.difficulty.read(), genesis_hash: self.genesis_hash.clone(), - best_block_hash: self.last_hash.unwrapped_read().clone(), - best_block_number: self.blocks.unwrapped_read().len() as BlockNumber - 1, + best_block_hash: self.last_hash.read().clone(), + best_block_number: self.blocks.read().len() as BlockNumber - 1, } } diff --git a/ethcore/src/db.rs b/ethcore/src/db.rs index 576aaef5b13..57b4cfdc6b1 100644 --- a/ethcore/src/db.rs +++ b/ethcore/src/db.rs @@ -18,11 +18,11 @@ use std::ops::Deref; use std::hash::Hash; -use std::sync::RwLock; use std::collections::HashMap; -use util::{DBTransaction, Database, RwLockable}; +use util::{DBTransaction, Database, RwLock}; use util::rlp::{encode, Encodable, decode, Decodable}; + #[derive(Clone, Copy)] pub enum CacheUpdatePolicy { Overwrite, @@ -115,14 +115,14 @@ pub trait Readable { T: Clone + Decodable, C: Cache { { - let read = cache.unwrapped_read(); + let read = cache.read(); if let Some(v) = read.get(key) { return Some(v.clone()); } } self.read(key).map(|value: T|{ - let mut write = cache.unwrapped_write(); + let mut write = cache.write(); write.insert(key.clone(), value.clone()); value }) @@ -137,7 +137,7 @@ pub trait Readable { R: Deref, C: Cache { { - let read = cache.unwrapped_read(); + let read = cache.read(); if read.get(key).is_some() { return true; } diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 86e9bb288d5..b8de63adb5a 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -97,7 +97,6 @@ extern crate ethash; pub extern crate ethstore; extern crate semver; extern crate ethcore_ipc_nano as nanoipc; - extern crate ethcore_devtools as devtools; #[cfg(feature = "jit" )] extern crate evmjit; diff --git a/ethcore/src/miner/external.rs b/ethcore/src/miner/external.rs index 650df228e92..ef68759300d 100644 --- a/ethcore/src/miner/external.rs +++ b/ethcore/src/miner/external.rs @@ -15,8 +15,8 @@ // along with Parity. If not, see . use std::collections::HashMap; -use std::sync::{Arc, RwLock}; -use util::{RwLockable, U256, H256}; +use std::sync::Arc; +use util::{RwLock, U256, H256}; /// External miner interface. pub trait ExternalMinerService: Send + Sync { @@ -54,15 +54,15 @@ impl ExternalMiner { impl ExternalMinerService for ExternalMiner { fn submit_hashrate(&self, hashrate: U256, id: H256) { - self.hashrates.unwrapped_write().insert(id, hashrate); + self.hashrates.write().insert(id, hashrate); } fn hashrate(&self) -> U256 { - self.hashrates.unwrapped_read().iter().fold(U256::from(0), |sum, (_, v)| sum + *v) + self.hashrates.read().iter().fold(U256::from(0), |sum, (_, v)| sum + *v) } fn is_mining(&self) -> bool { - !self.hashrates.unwrapped_read().is_empty() + !self.hashrates.read().is_empty() } } diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index 800f8f49207..4c174195950 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . use rayon::prelude::*; -use std::sync::atomic::AtomicBool; +use std::sync::atomic::{self, AtomicBool}; use std::time::{Instant, Duration}; use util::*; @@ -26,7 +26,7 @@ use client::{MiningBlockChainClient, Executive, Executed, EnvInfo, TransactOptio use block::{ClosedBlock, IsBlock}; use error::*; use transaction::SignedTransaction; -use receipt::{Receipt}; +use receipt::Receipt; use spec::Spec; use engine::Engine; use miner::{MinerService, MinerStatus, TransactionQueue, AccountDetails, TransactionOrigin}; @@ -34,7 +34,6 @@ use miner::work_notify::WorkPoster; use client::TransactionImportResult; use miner::price_info::PriceInfo; - /// Different possible definitions for pending transaction set. #[derive(Debug)] pub enum PendingSet { @@ -236,16 +235,16 @@ impl Miner { { trace!(target: "miner", "recalibrating..."); let txq = self.transaction_queue.clone(); - self.gas_pricer.lock().unwrap().recalibrate(move |price| { + self.gas_pricer.lock().recalibrate(move |price| { trace!(target: "miner", "Got gas price! {}", price); - txq.lock().unwrap().set_minimal_gas_price(price); + txq.lock().set_minimal_gas_price(price); }); trace!(target: "miner", "done recalibration."); } let (transactions, mut open_block, original_work_hash) = { - let transactions = {self.transaction_queue.locked().top_transactions()}; - let mut sealing_work = self.sealing_work.locked(); + let transactions = {self.transaction_queue.lock().top_transactions()}; + let mut sealing_work = self.sealing_work.lock(); let last_work_hash = sealing_work.peek_last_ref().map(|pb| pb.block().fields().header.hash()); let best_hash = chain.best_block_header().sha3(); /* @@ -315,7 +314,7 @@ impl Miner { }; { - let mut queue = self.transaction_queue.locked(); + let mut queue = self.transaction_queue.lock(); for hash in invalid_transactions.into_iter() { queue.remove_invalid(&hash, &fetch_account); } @@ -346,7 +345,7 @@ impl Miner { } let (work, is_new) = { - let mut sealing_work = self.sealing_work.locked(); + let mut sealing_work = self.sealing_work.lock(); let last_work_hash = sealing_work.peek_last_ref().map(|pb| pb.block().fields().header.hash()); trace!(target: "miner", "Checking whether we need to reseal: orig={:?} last={:?}, this={:?}", original_work_hash, last_work_hash, block.block().fields().header.hash()); let (work, is_new) = if last_work_hash.map_or(true, |h| h != block.block().fields().header.hash()) { @@ -374,14 +373,14 @@ impl Miner { fn update_gas_limit(&self, chain: &MiningBlockChainClient) { let gas_limit = HeaderView::new(&chain.best_block_header()).gas_limit(); - let mut queue = self.transaction_queue.locked(); + let mut queue = self.transaction_queue.lock(); queue.set_gas_limit(gas_limit); } /// Returns true if we had to prepare new pending block fn enable_and_prepare_sealing(&self, chain: &MiningBlockChainClient) -> bool { trace!(target: "miner", "enable_and_prepare_sealing: entering"); - let have_work = self.sealing_work.locked().peek_last_ref().is_some(); + let have_work = self.sealing_work.lock().peek_last_ref().is_some(); trace!(target: "miner", "enable_and_prepare_sealing: have_work={}", have_work); if !have_work { // -------------------------------------------------------------------------- @@ -391,7 +390,7 @@ impl Miner { self.sealing_enabled.store(true, atomic::Ordering::Relaxed); self.prepare_sealing(chain); } - let mut sealing_block_last_request = self.sealing_block_last_request.locked(); + let mut sealing_block_last_request = self.sealing_block_last_request.lock(); let best_number = chain.chain_info().best_block_number; if *sealing_block_last_request != best_number { trace!(target: "miner", "enable_and_prepare_sealing: Miner received request (was {}, now {}) - waking up.", *sealing_block_last_request, best_number); @@ -416,7 +415,7 @@ impl Miner { } /// Are we allowed to do a non-mandatory reseal? - fn tx_reseal_allowed(&self) -> bool { Instant::now() > *self.next_allowed_reseal.locked() } + fn tx_reseal_allowed(&self) -> bool { Instant::now() > *self.next_allowed_reseal.lock() } } const SEALING_TIMEOUT_IN_BLOCKS : u64 = 5; @@ -424,7 +423,7 @@ const SEALING_TIMEOUT_IN_BLOCKS : u64 = 5; impl MinerService for Miner { fn clear_and_reset(&self, chain: &MiningBlockChainClient) { - self.transaction_queue.locked().clear(); + self.transaction_queue.lock().clear(); // -------------------------------------------------------------------------- // | NOTE Code below requires transaction_queue and sealing_work locks. | // | Make sure to release the locks before calling that method. | @@ -433,8 +432,8 @@ impl MinerService for Miner { } fn status(&self) -> MinerStatus { - let status = self.transaction_queue.locked().status(); - let sealing_work = self.sealing_work.locked(); + let status = self.transaction_queue.lock().status(); + let sealing_work = self.sealing_work.lock(); MinerStatus { transactions_in_pending_queue: status.pending, transactions_in_future_queue: status.future, @@ -443,7 +442,7 @@ impl MinerService for Miner { } fn call(&self, chain: &MiningBlockChainClient, t: &SignedTransaction, analytics: CallAnalytics) -> Result { - let sealing_work = self.sealing_work.locked(); + let sealing_work = self.sealing_work.lock(); match sealing_work.peek_last_ref() { Some(work) => { let block = work.block(); @@ -490,7 +489,7 @@ impl MinerService for Miner { } fn balance(&self, chain: &MiningBlockChainClient, address: &Address) -> U256 { - let sealing_work = self.sealing_work.locked(); + let sealing_work = self.sealing_work.lock(); sealing_work.peek_last_ref().map_or_else( || chain.latest_balance(address), |b| b.block().fields().state.balance(address) @@ -498,7 +497,7 @@ impl MinerService for Miner { } fn storage_at(&self, chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 { - let sealing_work = self.sealing_work.locked(); + let sealing_work = self.sealing_work.lock(); sealing_work.peek_last_ref().map_or_else( || chain.latest_storage_at(address, position), |b| b.block().fields().state.storage_at(address, position) @@ -506,79 +505,79 @@ impl MinerService for Miner { } fn nonce(&self, chain: &MiningBlockChainClient, address: &Address) -> U256 { - let sealing_work = self.sealing_work.locked(); + let sealing_work = self.sealing_work.lock(); sealing_work.peek_last_ref().map_or_else(|| chain.latest_nonce(address), |b| b.block().fields().state.nonce(address)) } fn code(&self, chain: &MiningBlockChainClient, address: &Address) -> Option { - let sealing_work = self.sealing_work.locked(); + let sealing_work = self.sealing_work.lock(); sealing_work.peek_last_ref().map_or_else(|| chain.code(address), |b| b.block().fields().state.code(address)) } fn set_author(&self, author: Address) { - *self.author.unwrapped_write() = author; + *self.author.write() = author; } fn set_extra_data(&self, extra_data: Bytes) { - *self.extra_data.unwrapped_write() = extra_data; + *self.extra_data.write() = extra_data; } /// Set the gas limit we wish to target when sealing a new block. fn set_gas_floor_target(&self, target: U256) { - self.gas_range_target.unwrapped_write().0 = target; + self.gas_range_target.write().0 = target; } fn set_gas_ceil_target(&self, target: U256) { - self.gas_range_target.unwrapped_write().1 = target; + self.gas_range_target.write().1 = target; } fn set_minimal_gas_price(&self, min_gas_price: U256) { - self.transaction_queue.locked().set_minimal_gas_price(min_gas_price); + self.transaction_queue.lock().set_minimal_gas_price(min_gas_price); } fn minimal_gas_price(&self) -> U256 { - *self.transaction_queue.locked().minimal_gas_price() + *self.transaction_queue.lock().minimal_gas_price() } fn sensible_gas_price(&self) -> U256 { // 10% above our minimum. - *self.transaction_queue.locked().minimal_gas_price() * 110.into() / 100.into() + *self.transaction_queue.lock().minimal_gas_price() * 110.into() / 100.into() } fn sensible_gas_limit(&self) -> U256 { - self.gas_range_target.unwrapped_read().0 / 5.into() + self.gas_range_target.read().0 / 5.into() } fn transactions_limit(&self) -> usize { - self.transaction_queue.locked().limit() + self.transaction_queue.lock().limit() } fn set_transactions_limit(&self, limit: usize) { - self.transaction_queue.locked().set_limit(limit) + self.transaction_queue.lock().set_limit(limit) } fn set_tx_gas_limit(&self, limit: U256) { - self.transaction_queue.locked().set_tx_gas_limit(limit) + self.transaction_queue.lock().set_tx_gas_limit(limit) } /// Get the author that we will seal blocks as. fn author(&self) -> Address { - *self.author.unwrapped_read() + *self.author.read() } /// Get the extra_data that we will seal blocks with. fn extra_data(&self) -> Bytes { - self.extra_data.unwrapped_read().clone() + self.extra_data.read().clone() } /// Get the gas limit we wish to target when sealing a new block. fn gas_floor_target(&self) -> U256 { - self.gas_range_target.unwrapped_read().0 + self.gas_range_target.read().0 } /// Get the gas limit we wish to target when sealing a new block. fn gas_ceil_target(&self) -> U256 { - self.gas_range_target.unwrapped_read().1 + self.gas_range_target.read().1 } fn import_external_transactions( @@ -588,7 +587,7 @@ impl MinerService for Miner { ) -> Vec> { let results = { - let mut transaction_queue = self.transaction_queue.locked(); + let mut transaction_queue = self.transaction_queue.lock(); self.add_transactions_to_queue( chain, transactions, TransactionOrigin::External, &mut transaction_queue ) @@ -615,7 +614,7 @@ impl MinerService for Miner { let imported = { // Be sure to release the lock before we call enable_and_prepare_sealing - let mut transaction_queue = self.transaction_queue.locked(); + let mut transaction_queue = self.transaction_queue.lock(); let import = self.add_transactions_to_queue(chain, vec![transaction], TransactionOrigin::Local, &mut transaction_queue).pop().unwrap(); match import { @@ -651,13 +650,13 @@ impl MinerService for Miner { } fn all_transactions(&self) -> Vec { - let queue = self.transaction_queue.locked(); + let queue = self.transaction_queue.lock(); queue.top_transactions() } fn pending_transactions(&self) -> Vec { - let queue = self.transaction_queue.locked(); - let sw = self.sealing_work.locked(); + let queue = self.transaction_queue.lock(); + let sw = self.sealing_work.lock(); // TODO: should only use the sealing_work when it's current (it could be an old block) let sealing_set = match self.sealing_enabled.load(atomic::Ordering::Relaxed) { true => sw.peek_last_ref(), @@ -670,8 +669,8 @@ impl MinerService for Miner { } fn pending_transactions_hashes(&self) -> Vec { - let queue = self.transaction_queue.locked(); - let sw = self.sealing_work.locked(); + let queue = self.transaction_queue.lock(); + let sw = self.sealing_work.lock(); let sealing_set = match self.sealing_enabled.load(atomic::Ordering::Relaxed) { true => sw.peek_last_ref(), false => None, @@ -683,8 +682,8 @@ impl MinerService for Miner { } fn transaction(&self, hash: &H256) -> Option { - let queue = self.transaction_queue.locked(); - let sw = self.sealing_work.locked(); + let queue = self.transaction_queue.lock(); + let sw = self.sealing_work.lock(); let sealing_set = match self.sealing_enabled.load(atomic::Ordering::Relaxed) { true => sw.peek_last_ref(), false => None, @@ -696,7 +695,7 @@ impl MinerService for Miner { } fn pending_receipts(&self) -> BTreeMap { - match (self.sealing_enabled.load(atomic::Ordering::Relaxed), self.sealing_work.locked().peek_last_ref()) { + match (self.sealing_enabled.load(atomic::Ordering::Relaxed), self.sealing_work.lock().peek_last_ref()) { (true, Some(pending)) => { let hashes = pending.transactions() .iter() @@ -711,14 +710,14 @@ impl MinerService for Miner { } fn last_nonce(&self, address: &Address) -> Option { - self.transaction_queue.locked().last_nonce(address) + self.transaction_queue.lock().last_nonce(address) } fn update_sealing(&self, chain: &MiningBlockChainClient) { if self.sealing_enabled.load(atomic::Ordering::Relaxed) { let current_no = chain.chain_info().best_block_number; - let has_local_transactions = self.transaction_queue.locked().has_local_pending_transactions(); - let last_request = *self.sealing_block_last_request.locked(); + let has_local_transactions = self.transaction_queue.lock().has_local_pending_transactions(); + let last_request = *self.sealing_block_last_request.lock(); let should_disable_sealing = !self.forced_sealing() && !has_local_transactions && current_no > last_request @@ -727,9 +726,9 @@ impl MinerService for Miner { if should_disable_sealing { trace!(target: "miner", "Miner sleeping (current {}, last {})", current_no, last_request); self.sealing_enabled.store(false, atomic::Ordering::Relaxed); - self.sealing_work.locked().reset(); + self.sealing_work.lock().reset(); } else { - *self.next_allowed_reseal.locked() = Instant::now() + self.options.reseal_min_period; + *self.next_allowed_reseal.lock() = Instant::now() + self.options.reseal_min_period; // -------------------------------------------------------------------------- // | NOTE Code below requires transaction_queue and sealing_work locks. | // | Make sure to release the locks before calling that method. | @@ -743,14 +742,14 @@ impl MinerService for Miner { trace!(target: "miner", "map_sealing_work: entering"); self.enable_and_prepare_sealing(chain); trace!(target: "miner", "map_sealing_work: sealing prepared"); - let mut sealing_work = self.sealing_work.locked(); + let mut sealing_work = self.sealing_work.lock(); let ret = sealing_work.use_last_ref(); trace!(target: "miner", "map_sealing_work: leaving use_last_ref={:?}", ret.as_ref().map(|b| b.block().fields().header.hash())); ret.map(f) } fn submit_seal(&self, chain: &MiningBlockChainClient, pow_hash: H256, seal: Vec) -> Result<(), Error> { - let result = if let Some(b) = self.sealing_work.locked().get_used_if(if self.options.enable_resubmission { GetAction::Clone } else { GetAction::Take }, |b| &b.hash() == &pow_hash) { + let result = if let Some(b) = self.sealing_work.lock().get_used_if(if self.options.enable_resubmission { GetAction::Clone } else { GetAction::Take }, |b| &b.hash() == &pow_hash) { b.lock().try_seal(self.engine(), seal).or_else(|_| { warn!(target: "miner", "Mined solution rejected: Invalid."); Err(Error::PowInvalid) @@ -797,7 +796,7 @@ impl MinerService for Miner { .par_iter() .map(|h| fetch_transactions(chain, h)); out_of_chain.for_each(|txs| { - let mut transaction_queue = self.transaction_queue.locked(); + let mut transaction_queue = self.transaction_queue.lock(); let _ = self.add_transactions_to_queue( chain, txs, TransactionOrigin::External, &mut transaction_queue ); @@ -811,7 +810,7 @@ impl MinerService for Miner { .map(|h: &H256| fetch_transactions(chain, h)); in_chain.for_each(|mut txs| { - let mut transaction_queue = self.transaction_queue.locked(); + let mut transaction_queue = self.transaction_queue.lock(); let to_remove = txs.drain(..) .map(|tx| { diff --git a/ethcore/src/miner/mod.rs b/ethcore/src/miner/mod.rs index a72ae0a8f83..4b8f01c0e0d 100644 --- a/ethcore/src/miner/mod.rs +++ b/ethcore/src/miner/mod.rs @@ -38,7 +38,7 @@ //! assert_eq!(miner.status().transactions_in_pending_queue, 0); //! //! // Check block for sealing -//! //assert!(miner.sealing_block(client.deref()).locked().is_some()); +//! //assert!(miner.sealing_block(client.deref()).lock().is_some()); //! } //! ``` diff --git a/ethcore/src/miner/price_info.rs b/ethcore/src/miner/price_info.rs index ac2f81cd0e9..ee4220c0cd4 100644 --- a/ethcore/src/miner/price_info.rs +++ b/ethcore/src/miner/price_info.rs @@ -80,14 +80,17 @@ impl PriceInfo { //#[ignore] #[test] fn should_get_price_info() { - use std::sync::{Condvar, Mutex, Arc}; + use std::sync::Arc; use std::time::Duration; use util::log::init_log; + use util::{Condvar, Mutex}; + init_log(); let done = Arc::new((Mutex::new(PriceInfo { ethusd: 0f32 }), Condvar::new())); let rdone = done.clone(); - PriceInfo::get(move |price| { let mut p = rdone.0.lock().unwrap(); *p = price; rdone.1.notify_one(); }).unwrap(); - let p = done.1.wait_timeout(done.0.lock().unwrap(), Duration::from_millis(10000)).unwrap(); - assert!(!p.1.timed_out()); - assert!(p.0.ethusd != 0f32); + PriceInfo::get(move |price| { let mut p = rdone.0.lock(); *p = price; rdone.1.notify_one(); }).unwrap(); + let mut p = done.0.lock(); + let t = done.1.wait_for(&mut p, Duration::from_millis(10000)); + assert!(!t.timed_out()); + assert!(p.ethusd != 0f32); } \ No newline at end of file diff --git a/ethcore/src/miner/work_notify.rs b/ethcore/src/miner/work_notify.rs index a1b6f0a8b2c..b9952e14bc5 100644 --- a/ethcore/src/miner/work_notify.rs +++ b/ethcore/src/miner/work_notify.rs @@ -61,13 +61,13 @@ impl WorkPoster { pub fn notify(&self, pow_hash: H256, difficulty: U256, number: u64) { // TODO: move this to engine let target = Ethash::difficulty_to_boundary(&difficulty); - let seed_hash = &self.seed_compute.locked().get_seedhash(number); + let seed_hash = &self.seed_compute.lock().get_seedhash(number); let seed_hash = H256::from_slice(&seed_hash[..]); let body = format!( r#"{{ "result": ["0x{}","0x{}","0x{}","0x{:x}"] }}"#, pow_hash.hex(), seed_hash.hex(), target.hex(), number ); - let mut client = self.client.locked(); + let mut client = self.client.lock(); for u in &self.urls { if let Err(e) = client.request(u.clone(), PostHandler { body: body.clone() }) { warn!("Error sending HTTP notification to {} : {}, retrying", u, e); diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 1f7bd6fd84d..e71d7d4321c 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -136,10 +136,10 @@ impl Spec { /// Return the state root for the genesis state, memoising accordingly. pub fn state_root(&self) -> H256 { - if self.state_root_memo.unwrapped_read().is_none() { - *self.state_root_memo.unwrapped_write() = Some(self.genesis_state.root()); + if self.state_root_memo.read().is_none() { + *self.state_root_memo.write() = Some(self.genesis_state.root()); } - self.state_root_memo.unwrapped_read().as_ref().unwrap().clone() + self.state_root_memo.read().as_ref().unwrap().clone() } /// Get the known knodes of the network in enode format. @@ -209,12 +209,12 @@ impl Spec { /// Alter the value of the genesis state. pub fn set_genesis_state(&mut self, s: PodState) { self.genesis_state = s; - *self.state_root_memo.unwrapped_write() = None; + *self.state_root_memo.write() = None; } /// Returns `false` if the memoized state root is invalid. `true` otherwise. pub fn is_state_root_valid(&self) -> bool { - self.state_root_memo.unwrapped_read().clone().map_or(true, |sr| sr == self.genesis_state.root()) + self.state_root_memo.read().clone().map_or(true, |sr| sr == self.genesis_state.root()) } /// Ensure that the given state DB has the trie nodes in for the genesis state. diff --git a/ethcore/src/trace/db.rs b/ethcore/src/trace/db.rs index a49d28924d0..cac96bcbee2 100644 --- a/ethcore/src/trace/db.rs +++ b/ethcore/src/trace/db.rs @@ -18,17 +18,18 @@ use std::ptr; use std::ops::{Deref, DerefMut}; use std::collections::HashMap; -use std::sync::{RwLock, Arc}; +use std::sync::Arc; use std::path::Path; use bloomchain::{Number, Config as BloomConfig}; use bloomchain::group::{BloomGroupDatabase, BloomGroupChain, GroupPosition, BloomGroup}; -use util::{H256, H264, Database, DatabaseConfig, DBTransaction, RwLockable}; +use util::{H256, H264, Database, DatabaseConfig, DBTransaction, RwLock}; use header::BlockNumber; use trace::{BlockTraces, LocalizedTrace, Config, Switch, Filter, Database as TraceDatabase, ImportRequest, DatabaseExtras, Error}; use db::{Key, Writable, Readable, CacheUpdatePolicy}; use blooms; use super::flat::{FlatTrace, FlatBlockTraces, FlatTransactionTraces}; + const TRACE_DB_VER: &'static [u8] = b"1.0"; #[derive(Debug, Copy, Clone)] @@ -231,7 +232,7 @@ impl TraceDatabase for TraceDB where T: DatabaseExtras { // at first, let's insert new block traces { - let mut traces = self.traces.unwrapped_write(); + let mut traces = self.traces.write(); // it's important to use overwrite here, // cause this value might be queried by hash later batch.write_with_cache(traces.deref_mut(), request.block_hash, request.traces, CacheUpdatePolicy::Overwrite); @@ -259,7 +260,7 @@ impl TraceDatabase for TraceDB where T: DatabaseExtras { .map(|p| (From::from(p.0), From::from(p.1))) .collect::>(); - let mut blooms = self.blooms.unwrapped_write(); + let mut blooms = self.blooms.write(); batch.extend_with_cache(blooms.deref_mut(), blooms_to_insert, CacheUpdatePolicy::Remove); } diff --git a/parity/informant.rs b/parity/informant.rs index 006cfc57513..1a78db79b9b 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -19,10 +19,9 @@ use self::ansi_term::Colour::{White, Yellow, Green, Cyan, Blue, Purple}; use self::ansi_term::Style; use std::time::{Instant, Duration}; -use std::sync::RwLock; use std::ops::{Deref, DerefMut}; use ethsync::SyncStatus; -use util::{Uint, RwLockable, NetworkConfiguration}; +use util::{Uint, RwLock, NetworkConfiguration}; use ethcore::client::*; use number_prefix::{binary_prefix, Standalone, Prefixed}; @@ -75,20 +74,21 @@ impl Informant { } } + #[cfg_attr(feature="dev", allow(match_bool))] pub fn tick(&self, client: &Client, maybe_status: Option<(SyncStatus, NetworkConfiguration)>) { - let elapsed = self.last_tick.unwrapped_read().elapsed(); + let elapsed = self.last_tick.read().elapsed(); if elapsed < Duration::from_secs(5) { return; } - *self.last_tick.unwrapped_write() = Instant::now(); + *self.last_tick.write() = Instant::now(); let chain_info = client.chain_info(); let queue_info = client.queue_info(); let cache_info = client.blockchain_cache_info(); - let mut write_report = self.report.unwrapped_write(); + let mut write_report = self.report.write(); let report = client.report(); let paint = |c: Style, t: String| match self.with_color { @@ -97,8 +97,8 @@ impl Informant { }; if let (_, _, &Some(ref last_report)) = ( - self.chain_info.unwrapped_read().deref(), - self.cache_info.unwrapped_read().deref(), + self.chain_info.read().deref(), + self.cache_info.read().deref(), write_report.deref() ) { println!("{} {} {} blk/s {} tx/s {} Mgas/s {}{}+{} Qed {} db {} chain {} queue{}", @@ -133,8 +133,8 @@ impl Informant { ); } - *self.chain_info.unwrapped_write().deref_mut() = Some(chain_info); - *self.cache_info.unwrapped_write().deref_mut() = Some(cache_info); + *self.chain_info.write().deref_mut() = Some(chain_info); + *self.cache_info.write().deref_mut() = Some(cache_info); *write_report.deref_mut() = Some(report); } } diff --git a/parity/main.rs b/parity/main.rs index 7314b9f99c7..c1bd6f1ce40 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -74,7 +74,7 @@ mod url; use std::io::{Write, Read, BufReader, BufRead}; use std::ops::Deref; -use std::sync::{Arc, Mutex, Condvar}; +use std::sync::Arc; use std::path::Path; use std::fs::File; use std::str::{FromStr, from_utf8}; @@ -82,7 +82,7 @@ use std::thread::sleep; use std::time::Duration; use rustc_serialize::hex::FromHex; use ctrlc::CtrlC; -use util::{Lockable, H256, ToPretty, PayloadInfo, Bytes, Colour, Applyable, version, journaldb}; +use util::{H256, ToPretty, PayloadInfo, Bytes, Colour, Applyable, version, journaldb}; use util::panics::{MayPanic, ForwardPanic, PanicHandler}; use ethcore::client::{BlockID, BlockChainClient, ClientConfig, get_db_path, BlockImportError, ChainNotify, Mode}; @@ -93,6 +93,7 @@ use ethsync::EthSync; use ethcore::miner::{Miner, MinerService, ExternalMiner}; use migration::migrate; use informant::Informant; +use util::{Mutex, Condvar}; use die::*; use cli::print_version; @@ -593,7 +594,7 @@ fn wait_for_exit( // Wait for signal let mutex = Mutex::new(()); - let _ = exit.wait(mutex.locked()).unwrap(); + let _ = exit.wait(&mut mutex.lock()); info!("Finishing work, please wait..."); } diff --git a/rpc/rpctest/src/main.rs b/rpc/rpctest/src/main.rs index ed812cd79b7..7078793c2c6 100644 --- a/rpc/rpctest/src/main.rs +++ b/rpc/rpctest/src/main.rs @@ -41,7 +41,6 @@ use rpc::v1::tests::helpers::{TestSyncProvider, Config as SyncConfig, TestMinerS use rpc::v1::{Eth, EthClient, EthFilter, EthFilterClient}; use util::panics::MayPanic; use util::hash::Address; -use util::Lockable; const USAGE: &'static str = r#" Parity rpctest client. @@ -138,7 +137,7 @@ impl Configuration { panic_handler.on_panic(move |_reason| { e.notify_all(); }); let mutex = Mutex::new(()); - let _ = exit.wait(mutex.locked()).unwrap(); + let _ = exit.wait(mutex.lock()).unwrap(); } } diff --git a/rpc/src/v1/helpers/signing_queue.rs b/rpc/src/v1/helpers/signing_queue.rs index d41114f963a..8477ed4dbc5 100644 --- a/rpc/src/v1/helpers/signing_queue.rs +++ b/rpc/src/v1/helpers/signing_queue.rs @@ -16,10 +16,10 @@ use std::thread; use std::time::{Instant, Duration}; -use std::sync::{mpsc, Mutex, RwLock, Arc}; +use std::sync::{mpsc, Arc}; use std::collections::HashMap; use jsonrpc_core; -use util::{U256, Lockable, RwLockable}; +use util::{Mutex, RwLock, U256}; use v1::helpers::{TransactionRequest, TransactionConfirmation}; /// Result that can be returned from JSON RPC. @@ -110,7 +110,7 @@ pub struct ConfirmationPromise { impl ConfirmationToken { /// Submit solution to all listeners fn resolve(&self, result: Option) { - let mut res = self.result.locked(); + let mut res = self.result.lock(); *res = result.map_or(ConfirmationResult::Rejected, |h| ConfirmationResult::Confirmed(h)); // Notify listener self.handle.unpark(); @@ -142,7 +142,7 @@ impl ConfirmationPromise { // Park thread (may wake up spuriously) thread::park_timeout(deadline - now); // Take confirmation result - let res = self.result.locked(); + let res = self.result.lock(); // Check the result match *res { ConfirmationResult::Rejected => return None, @@ -183,7 +183,7 @@ impl ConfirmationsQueue { /// This method can be used only once (only single consumer of events can exist). pub fn start_listening(&self, listener: F) -> Result<(), QueueError> where F: Fn(QueueEvent) -> () { - let recv = self.receiver.locked().take(); + let recv = self.receiver.lock().take(); if let None = recv { return Err(QueueError::AlreadyUsed); } @@ -208,13 +208,13 @@ impl ConfirmationsQueue { /// Notifies receiver about the event happening in this queue. fn notify(&self, message: QueueEvent) { // We don't really care about the result - let _ = self.sender.locked().send(message); + let _ = self.sender.lock().send(message); } /// Removes transaction from this queue and notifies `ConfirmationPromise` holders about the result. /// Notifies also a receiver about that event. fn remove(&self, id: U256, result: Option) -> Option { - let token = self.queue.unwrapped_write().remove(&id); + let token = self.queue.write().remove(&id); if let Some(token) = token { // notify receiver about the event @@ -241,13 +241,13 @@ impl SigningQueue for ConfirmationsQueue { fn add_request(&self, transaction: TransactionRequest) -> ConfirmationPromise { // Increment id let id = { - let mut last_id = self.id.locked(); + let mut last_id = self.id.lock(); *last_id = *last_id + U256::from(1); *last_id }; // Add request to queue let res = { - let mut queue = self.queue.unwrapped_write(); + let mut queue = self.queue.write(); queue.insert(id, ConfirmationToken { result: Arc::new(Mutex::new(ConfirmationResult::Waiting)), handle: thread::current(), @@ -266,7 +266,7 @@ impl SigningQueue for ConfirmationsQueue { } fn peek(&self, id: &U256) -> Option { - self.queue.unwrapped_read().get(id).map(|token| token.request.clone()) + self.queue.read().get(id).map(|token| token.request.clone()) } fn request_rejected(&self, id: U256) -> Option { @@ -280,17 +280,17 @@ impl SigningQueue for ConfirmationsQueue { } fn requests(&self) -> Vec { - let queue = self.queue.unwrapped_read(); + let queue = self.queue.read(); queue.values().map(|token| token.request.clone()).collect() } fn len(&self) -> usize { - let queue = self.queue.unwrapped_read(); + let queue = self.queue.read(); queue.len() } fn is_empty(&self) -> bool { - let queue = self.queue.unwrapped_read(); + let queue = self.queue.read(); queue.is_empty() } } @@ -300,8 +300,8 @@ impl SigningQueue for ConfirmationsQueue { mod test { use std::time::Duration; use std::thread; - use std::sync::{Arc, Mutex}; - use util::{Address, U256, H256, Lockable}; + use std::sync::Arc; + use util::{Address, U256, H256, Mutex}; use v1::helpers::{SigningQueue, ConfirmationsQueue, QueueEvent, TransactionRequest}; use v1::types::H256 as NH256; use jsonrpc_core::to_value; @@ -354,7 +354,7 @@ mod test { let r = received.clone(); let handle = thread::spawn(move || { q.start_listening(move |notification| { - let mut v = r.locked(); + let mut v = r.lock(); *v = Some(notification); }).expect("Should be closed nicely.") }); @@ -363,7 +363,7 @@ mod test { // then handle.join().expect("Thread should finish nicely"); - let r = received.locked().take(); + let r = received.lock().take(); assert_eq!(r, Some(QueueEvent::NewRequest(U256::from(1)))); } diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 7cfe251fd74..9133393e93c 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -20,7 +20,7 @@ extern crate ethash; use std::thread; use std::time::{Instant, Duration}; -use std::sync::{Arc, Weak, Mutex}; +use std::sync::{Arc, Weak}; use std::ops::Deref; use ethsync::{SyncProvider, SyncState}; use ethcore::miner::{MinerService, ExternalMinerService}; @@ -28,7 +28,7 @@ use jsonrpc_core::*; use util::numbers::*; use util::sha3::*; use util::rlp::{encode, decode, UntrustedRlp, View}; -use util::Lockable; +use util::Mutex; use ethcore::account_provider::AccountProvider; use ethcore::client::{MiningBlockChainClient, BlockID, TransactionID, UncleID}; use ethcore::header::Header as BlockHeader; @@ -562,7 +562,7 @@ impl Eth for EthClient where miner.map_sealing_work(client.deref(), |b| { let pow_hash = b.hash(); let target = Ethash::difficulty_to_boundary(b.block().header().difficulty()); - let seed_hash = self.seed_compute.locked().get_seedhash(b.block().header().number()); + let seed_hash = self.seed_compute.lock().get_seedhash(b.block().header().number()); let block_number = RpcU256::from(b.block().header().number()); to_value(&(RpcH256::from(pow_hash), RpcH256::from(seed_hash), RpcH256::from(target), block_number)) }).unwrap_or(Err(Error::internal_error())) // no work found. diff --git a/rpc/src/v1/impls/eth_filter.rs b/rpc/src/v1/impls/eth_filter.rs index c12783c1b2a..6eb0c60bbd0 100644 --- a/rpc/src/v1/impls/eth_filter.rs +++ b/rpc/src/v1/impls/eth_filter.rs @@ -17,19 +17,18 @@ //! Eth Filter RPC implementation use std::ops::Deref; -use std::sync::{Arc, Weak, Mutex}; +use std::sync::{Arc, Weak}; use std::collections::HashSet; use jsonrpc_core::*; -use util::Lockable; use ethcore::miner::MinerService; use ethcore::filter::Filter as EthcoreFilter; use ethcore::client::{BlockChainClient, BlockID}; +use util::Mutex; use v1::traits::EthFilter; use v1::types::{BlockNumber, Index, Filter, Log, H256 as RpcH256, U256 as RpcU256}; use v1::helpers::{PollFilter, PollManager}; use v1::impls::eth::pending_logs; - /// Eth filter rpc implementation. pub struct EthFilterClient where C: BlockChainClient, @@ -68,7 +67,7 @@ impl EthFilter for EthFilterClient where try!(self.active()); from_params::<(Filter,)>(params) .and_then(|(filter,)| { - let mut polls = self.polls.locked(); + let mut polls = self.polls.lock(); let block_number = take_weak!(self.client).chain_info().best_block_number; let id = polls.create_poll(PollFilter::Logs(block_number, Default::default(), filter)); to_value(&RpcU256::from(id)) @@ -79,7 +78,7 @@ impl EthFilter for EthFilterClient where try!(self.active()); match params { Params::None => { - let mut polls = self.polls.locked(); + let mut polls = self.polls.lock(); let id = polls.create_poll(PollFilter::Block(take_weak!(self.client).chain_info().best_block_number)); to_value(&RpcU256::from(id)) }, @@ -91,7 +90,7 @@ impl EthFilter for EthFilterClient where try!(self.active()); match params { Params::None => { - let mut polls = self.polls.locked(); + let mut polls = self.polls.lock(); let pending_transactions = take_weak!(self.miner).pending_transactions_hashes(); let id = polls.create_poll(PollFilter::PendingTransaction(pending_transactions)); @@ -106,7 +105,7 @@ impl EthFilter for EthFilterClient where let client = take_weak!(self.client); from_params::<(Index,)>(params) .and_then(|(index,)| { - let mut polls = self.polls.locked(); + let mut polls = self.polls.lock(); match polls.poll_mut(&index.value()) { None => Ok(Value::Array(vec![] as Vec)), Some(filter) => match *filter { @@ -196,7 +195,7 @@ impl EthFilter for EthFilterClient where try!(self.active()); from_params::<(Index,)>(params) .and_then(|(index,)| { - let mut polls = self.polls.locked(); + let mut polls = self.polls.lock(); match polls.poll(&index.value()) { Some(&PollFilter::Logs(ref _block_number, ref _previous_log, ref filter)) => { let include_pending = filter.to_block == Some(BlockNumber::Pending); @@ -222,7 +221,7 @@ impl EthFilter for EthFilterClient where try!(self.active()); from_params::<(Index,)>(params) .and_then(|(index,)| { - self.polls.locked().remove_poll(&index.value()); + self.polls.lock().remove_poll(&index.value()); to_value(&true) }) } diff --git a/rpc/src/v1/tests/helpers/miner_service.rs b/rpc/src/v1/tests/helpers/miner_service.rs index b0a4f111566..8b67b8e09f8 100644 --- a/rpc/src/v1/tests/helpers/miner_service.rs +++ b/rpc/src/v1/tests/helpers/miner_service.rs @@ -16,7 +16,7 @@ //! Test implementation of miner service. -use util::{Address, H256, Bytes, U256, FixedHash, Uint, Lockable, RwLockable}; +use util::{Address, H256, Bytes, U256, FixedHash, Uint}; use util::standard::*; use ethcore::error::{Error, ExecutionError}; use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics}; @@ -76,68 +76,68 @@ impl MinerService for TestMinerService { } fn set_author(&self, author: Address) { - *self.author.unwrapped_write() = author; + *self.author.write() = author; } fn set_extra_data(&self, extra_data: Bytes) { - *self.extra_data.unwrapped_write() = extra_data; + *self.extra_data.write() = extra_data; } /// Set the lower gas limit we wish to target when sealing a new block. fn set_gas_floor_target(&self, target: U256) { - self.gas_range_target.unwrapped_write().0 = target; + self.gas_range_target.write().0 = target; } /// Set the upper gas limit we wish to target when sealing a new block. fn set_gas_ceil_target(&self, target: U256) { - self.gas_range_target.unwrapped_write().1 = target; + self.gas_range_target.write().1 = target; } fn set_minimal_gas_price(&self, min_gas_price: U256) { - *self.min_gas_price.unwrapped_write() = min_gas_price; + *self.min_gas_price.write() = min_gas_price; } fn set_transactions_limit(&self, limit: usize) { - *self.limit.unwrapped_write() = limit; + *self.limit.write() = limit; } fn set_tx_gas_limit(&self, limit: U256) { - *self.tx_gas_limit.unwrapped_write() = limit; + *self.tx_gas_limit.write() = limit; } fn transactions_limit(&self) -> usize { - *self.limit.unwrapped_read() + *self.limit.read() } fn author(&self) -> Address { - *self.author.unwrapped_read() + *self.author.read() } fn minimal_gas_price(&self) -> U256 { - *self.min_gas_price.unwrapped_read() + *self.min_gas_price.read() } fn extra_data(&self) -> Bytes { - self.extra_data.unwrapped_read().clone() + self.extra_data.read().clone() } fn gas_floor_target(&self) -> U256 { - self.gas_range_target.unwrapped_read().0 + self.gas_range_target.read().0 } fn gas_ceil_target(&self) -> U256 { - self.gas_range_target.unwrapped_read().1 + self.gas_range_target.read().1 } /// Imports transactions to transaction queue. fn import_external_transactions(&self, _chain: &MiningBlockChainClient, transactions: Vec) -> Vec> { // lets assume that all txs are valid - self.imported_transactions.locked().extend_from_slice(&transactions); + self.imported_transactions.lock().extend_from_slice(&transactions); for sender in transactions.iter().filter_map(|t| t.sender().ok()) { let nonce = self.last_nonce(&sender).expect("last_nonce must be populated in tests"); - self.last_nonces.unwrapped_write().insert(sender, nonce + U256::from(1)); + self.last_nonces.write().insert(sender, nonce + U256::from(1)); } transactions .iter() @@ -152,11 +152,11 @@ impl MinerService for TestMinerService { // keep the pending nonces up to date if let Ok(ref sender) = transaction.sender() { let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender)); - self.last_nonces.unwrapped_write().insert(sender.clone(), nonce + U256::from(1)); + self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1)); } // lets assume that all txs are valid - self.imported_transactions.locked().push(transaction); + self.imported_transactions.lock().push(transaction); Ok(TransactionImportResult::Current) } @@ -186,23 +186,23 @@ impl MinerService for TestMinerService { } fn transaction(&self, hash: &H256) -> Option { - self.pending_transactions.locked().get(hash).cloned() + self.pending_transactions.lock().get(hash).cloned() } fn all_transactions(&self) -> Vec { - self.pending_transactions.locked().values().cloned().collect() + self.pending_transactions.lock().values().cloned().collect() } fn pending_transactions(&self) -> Vec { - self.pending_transactions.locked().values().cloned().collect() + self.pending_transactions.lock().values().cloned().collect() } fn pending_receipts(&self) -> BTreeMap { - self.pending_receipts.locked().clone() + self.pending_receipts.lock().clone() } fn last_nonce(&self, address: &Address) -> Option { - self.last_nonces.unwrapped_read().get(address).cloned() + self.last_nonces.read().get(address).cloned() } /// Submit `seal` as a valid solution for the header of `pow_hash`. @@ -212,7 +212,7 @@ impl MinerService for TestMinerService { } fn balance(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 { - self.latest_closed_block.locked().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone()) + self.latest_closed_block.lock().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone()) } fn call(&self, _chain: &MiningBlockChainClient, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result { @@ -220,7 +220,7 @@ impl MinerService for TestMinerService { } fn storage_at(&self, _chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 { - self.latest_closed_block.locked().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone()) + self.latest_closed_block.lock().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone()) } fn nonce(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 { @@ -230,7 +230,7 @@ impl MinerService for TestMinerService { } fn code(&self, _chain: &MiningBlockChainClient, address: &Address) -> Option { - self.latest_closed_block.locked().as_ref().map_or(None, |b| b.block().fields().state.code(address).clone()) + self.latest_closed_block.lock().as_ref().map_or(None, |b| b.block().fields().state.code(address).clone()) } } diff --git a/rpc/src/v1/tests/helpers/sync_provider.rs b/rpc/src/v1/tests/helpers/sync_provider.rs index 9dfb3ba273c..94f7b489364 100644 --- a/rpc/src/v1/tests/helpers/sync_provider.rs +++ b/rpc/src/v1/tests/helpers/sync_provider.rs @@ -16,9 +16,8 @@ //! Test implementation of SyncProvider. -use util::{U256, RwLockable}; +use util::{RwLock, U256}; use ethsync::{SyncProvider, SyncStatus, SyncState}; -use std::sync::RwLock; /// TestSyncProvider config. pub struct Config { @@ -57,7 +56,7 @@ impl TestSyncProvider { impl SyncProvider for TestSyncProvider { fn status(&self) -> SyncStatus { - self.status.unwrapped_read().clone() + self.status.read().clone() } } diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index 112624baf96..688a43b2413 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -16,11 +16,11 @@ use std::str::FromStr; use std::collections::HashMap; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use jsonrpc_core::IoHandler; -use util::RwLockable; use util::hash::{Address, H256, FixedHash}; use util::numbers::{Uint, U256}; +use util::RwLock; use ethcore::account_provider::AccountProvider; use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionID}; use ethcore::log_entry::{LocalizedLogEntry, LogEntry}; @@ -104,13 +104,13 @@ fn rpc_eth_syncing() { assert_eq!(tester.io.handle_request(request), Some(false_res.to_owned())); { - let mut status = tester.sync.status.unwrapped_write(); + let mut status = tester.sync.status.write(); status.state = SyncState::Blocks; status.highest_block_number = Some(2500); // "sync" to 1000 blocks. // causes TestBlockChainClient to return 1000 for its best block number. - let mut blocks = tester.client.blocks.unwrapped_write(); + let mut blocks = tester.client.blocks.write(); for i in 0..1000 { blocks.insert(H256::from(i), Vec::new()); } @@ -121,7 +121,7 @@ fn rpc_eth_syncing() { { // finish "syncing" - let mut blocks = tester.client.blocks.unwrapped_write(); + let mut blocks = tester.client.blocks.write(); for i in 0..1500 { blocks.insert(H256::from(i + 1000), Vec::new()); } @@ -133,9 +133,9 @@ fn rpc_eth_syncing() { #[test] fn rpc_eth_hashrate() { let tester = EthTester::default(); - tester.hashrates.unwrapped_write().insert(H256::from(0), U256::from(0xfffa)); - tester.hashrates.unwrapped_write().insert(H256::from(0), U256::from(0xfffb)); - tester.hashrates.unwrapped_write().insert(H256::from(1), U256::from(0x1)); + tester.hashrates.write().insert(H256::from(0), U256::from(0xfffa)); + tester.hashrates.write().insert(H256::from(0), U256::from(0xfffb)); + tester.hashrates.write().insert(H256::from(1), U256::from(0x1)); let request = r#"{"jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":"0xfffc","id":1}"#; @@ -158,7 +158,7 @@ fn rpc_eth_submit_hashrate() { let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; assert_eq!(tester.io.handle_request(request), Some(response.to_owned())); - assert_eq!(tester.hashrates.unwrapped_read().get(&H256::from("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c")).cloned(), + assert_eq!(tester.hashrates.read().get(&H256::from("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c")).cloned(), Some(U256::from(0x500_000))); } @@ -215,7 +215,7 @@ fn rpc_eth_mining() { let response = r#"{"jsonrpc":"2.0","result":false,"id":1}"#; assert_eq!(tester.io.handle_request(request), Some(response.to_owned())); - tester.hashrates.unwrapped_write().insert(H256::from(1), U256::from(0x1)); + tester.hashrates.write().insert(H256::from(1), U256::from(0x1)); let request = r#"{"jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; @@ -364,7 +364,7 @@ fn rpc_eth_pending_transaction_by_hash() { let tester = EthTester::default(); { let tx: SignedTransaction = decode(&FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); - tester.miner.pending_transactions.locked().insert(H256::zero(), tx); + tester.miner.pending_transactions.lock().insert(H256::zero(), tx); } let response = r#"{"jsonrpc":"2.0","result":{"blockHash":null,"blockNumber":null,"creates":null,"from":"0x0f65fe9276bc9a24ae7083ae28e2660ef72df99e","gas":"0x5208","gasPrice":"0x01","hash":"0x41df922fd0d4766fcc02e161f8295ec28522f329ae487f14d811e4b64c8d6e31","input":"0x","nonce":"0x00","to":"0x095e7baea6a6c7c4c2dfeb977efac326af552d87","transactionIndex":null,"value":"0x0a"},"id":1}"#; @@ -591,7 +591,7 @@ fn rpc_eth_send_transaction() { assert_eq!(tester.io.handle_request(&request), Some(response)); - tester.miner.last_nonces.unwrapped_write().insert(address.clone(), U256::zero()); + tester.miner.last_nonces.write().insert(address.clone(), U256::zero()); let t = Transaction { nonce: U256::one(), @@ -749,7 +749,7 @@ fn returns_error_if_can_mine_and_no_closed_block() { use ethsync::{SyncState}; let eth_tester = EthTester::default(); - eth_tester.sync.status.unwrapped_write().state = SyncState::Idle; + eth_tester.sync.status.write().state = SyncState::Idle; let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error","data":null},"id":1}"#; diff --git a/rpc/src/v1/tests/mocked/eth_signing.rs b/rpc/src/v1/tests/mocked/eth_signing.rs index 5f3e75d353b..794d5fc9356 100644 --- a/rpc/src/v1/tests/mocked/eth_signing.rs +++ b/rpc/src/v1/tests/mocked/eth_signing.rs @@ -88,7 +88,7 @@ fn should_add_transaction_to_queue() { } #[test] -fn should_dispatch_transaction_if_account_is_unlocked() { +fn should_dispatch_transaction_if_account_is_unlock() { // given let tester = eth_signing(); let acc = tester.accounts.new_account("test").unwrap(); diff --git a/rpc/src/v1/tests/mocked/personal.rs b/rpc/src/v1/tests/mocked/personal.rs index 6cd3ae58363..3b299728c15 100644 --- a/rpc/src/v1/tests/mocked/personal.rs +++ b/rpc/src/v1/tests/mocked/personal.rs @@ -18,7 +18,6 @@ use std::sync::Arc; use std::str::FromStr; use jsonrpc_core::IoHandler; use util::numbers::*; -use util::RwLockable; use ethcore::account_provider::AccountProvider; use v1::{PersonalClient, Personal}; use v1::tests::helpers::TestMinerService; @@ -175,7 +174,7 @@ fn sign_and_send_transaction() { assert_eq!(tester.io.handle_request(request.as_ref()), Some(response)); - tester.miner.last_nonces.unwrapped_write().insert(address.clone(), U256::zero()); + tester.miner.last_nonces.write().insert(address.clone(), U256::zero()); let t = Transaction { nonce: U256::one(), diff --git a/rpc/src/v1/tests/mocked/personal_signer.rs b/rpc/src/v1/tests/mocked/personal_signer.rs index 374c5dfa02f..ced9a228afd 100644 --- a/rpc/src/v1/tests/mocked/personal_signer.rs +++ b/rpc/src/v1/tests/mocked/personal_signer.rs @@ -18,7 +18,6 @@ use std::sync::Arc; use std::str::FromStr; use jsonrpc_core::IoHandler; use util::numbers::*; -use util::Lockable; use ethcore::account_provider::AccountProvider; use ethcore::client::TestBlockChainClient; use ethcore::transaction::{Transaction, Action}; @@ -113,7 +112,7 @@ fn should_reject_transaction_from_queue_without_dispatching() { // then assert_eq!(tester.io.handle_request(&request), Some(response.to_owned())); assert_eq!(tester.queue.requests().len(), 0); - assert_eq!(tester.miner.imported_transactions.locked().len(), 0); + assert_eq!(tester.miner.imported_transactions.lock().len(), 0); } #[test] @@ -182,6 +181,6 @@ fn should_confirm_transaction_and_dispatch() { // then assert_eq!(tester.io.handle_request(&request), Some(response.to_owned())); assert_eq!(tester.queue.requests().len(), 0); - assert_eq!(tester.miner.imported_transactions.locked().len(), 1); + assert_eq!(tester.miner.imported_transactions.lock().len(), 1); } diff --git a/sync/src/chain.rs b/sync/src/chain.rs index c96ba8b3473..17f9e94cca6 100644 --- a/sync/src/chain.rs +++ b/sync/src/chain.rs @@ -1142,7 +1142,7 @@ impl ChainSync { |e| format!("Error sending nodes: {:?}", e)), _ => { - sync.unwrapped_write().on_packet(io, peer, packet_id, data); + sync.write().on_packet(io, peer, packet_id, data); Ok(()) } }; diff --git a/sync/src/lib.rs b/sync/src/lib.rs index 3b252bfb7dd..4464fa8bc37 100644 --- a/sync/src/lib.rs +++ b/sync/src/lib.rs @@ -73,9 +73,9 @@ extern crate rand; extern crate heapsize; use std::ops::*; -use std::sync::*; +use std::sync::Arc; use util::network::{NetworkProtocolHandler, NetworkService, NetworkContext, PeerId, NetworkConfiguration}; -use util::{TimerToken, U256, H256, RwLockable, UtilError}; +use util::{TimerToken, U256, H256, RwLock, UtilError}; use ethcore::client::{Client, ChainNotify}; use io::NetSyncIo; use chain::ChainSync; @@ -140,7 +140,7 @@ impl EthSync { impl SyncProvider for EthSync { /// Get sync status fn status(&self) -> SyncStatus { - self.handler.sync.unwrapped_read().status() + self.handler.sync.read().status() } } @@ -161,16 +161,16 @@ impl NetworkProtocolHandler for SyncProtocolHandler { } fn connected(&self, io: &NetworkContext, peer: &PeerId) { - self.sync.unwrapped_write().on_peer_connected(&mut NetSyncIo::new(io, self.chain.deref()), *peer); + self.sync.write().on_peer_connected(&mut NetSyncIo::new(io, self.chain.deref()), *peer); } fn disconnected(&self, io: &NetworkContext, peer: &PeerId) { - self.sync.unwrapped_write().on_peer_aborting(&mut NetSyncIo::new(io, self.chain.deref()), *peer); + self.sync.write().on_peer_aborting(&mut NetSyncIo::new(io, self.chain.deref()), *peer); } fn timeout(&self, io: &NetworkContext, _timer: TimerToken) { - self.sync.unwrapped_write().maintain_peers(&mut NetSyncIo::new(io, self.chain.deref())); - self.sync.unwrapped_write().maintain_sync(&mut NetSyncIo::new(io, self.chain.deref())); + self.sync.write().maintain_peers(&mut NetSyncIo::new(io, self.chain.deref())); + self.sync.write().maintain_sync(&mut NetSyncIo::new(io, self.chain.deref())); } } @@ -184,7 +184,7 @@ impl ChainNotify for EthSync { { self.network.with_context(ETH_PROTOCOL, |context| { let mut sync_io = NetSyncIo::new(context, self.handler.chain.deref()); - self.handler.sync.unwrapped_write().chain_new_blocks( + self.handler.sync.write().chain_new_blocks( &mut sync_io, &imported, &invalid, @@ -241,7 +241,7 @@ impl ManageNetwork for EthSync { fn stop_network(&self) { self.network.with_context(ETH_PROTOCOL, |context| { let mut sync_io = NetSyncIo::new(context, self.handler.chain.deref()); - self.handler.sync.unwrapped_write().abort(&mut sync_io); + self.handler.sync.write().abort(&mut sync_io); }); self.stop(); } diff --git a/sync/src/tests/chain.rs b/sync/src/tests/chain.rs index e5a8b3fb918..84e25429d3d 100644 --- a/sync/src/tests/chain.rs +++ b/sync/src/tests/chain.rs @@ -27,7 +27,7 @@ fn two_peers() { net.peer_mut(2).chain.add_blocks(1000, EachBlockWith::Uncle); net.sync(); assert!(net.peer(0).chain.block(BlockID::Number(1000)).is_some()); - assert_eq!(net.peer(0).chain.blocks.unwrapped_read().deref(), net.peer(1).chain.blocks.unwrapped_read().deref()); + assert_eq!(net.peer(0).chain.blocks.read().deref(), net.peer(1).chain.blocks.read().deref()); } #[test] @@ -37,7 +37,7 @@ fn long_chain() { net.peer_mut(1).chain.add_blocks(50000, EachBlockWith::Nothing); net.sync(); assert!(net.peer(0).chain.block(BlockID::Number(50000)).is_some()); - assert_eq!(net.peer(0).chain.blocks.unwrapped_read().deref(), net.peer(1).chain.blocks.unwrapped_read().deref()); + assert_eq!(net.peer(0).chain.blocks.read().deref(), net.peer(1).chain.blocks.read().deref()); } #[test] @@ -47,7 +47,7 @@ fn status_after_sync() { net.peer_mut(1).chain.add_blocks(1000, EachBlockWith::Uncle); net.peer_mut(2).chain.add_blocks(1000, EachBlockWith::Uncle); net.sync(); - let status = net.peer(0).sync.unwrapped_read().status(); + let status = net.peer(0).sync.read().status(); assert_eq!(status.state, SyncState::Idle); } @@ -71,7 +71,7 @@ fn empty_blocks() { } net.sync(); assert!(net.peer(0).chain.block(BlockID::Number(1000)).is_some()); - assert_eq!(net.peer(0).chain.blocks.unwrapped_read().deref(), net.peer(1).chain.blocks.unwrapped_read().deref()); + assert_eq!(net.peer(0).chain.blocks.read().deref(), net.peer(1).chain.blocks.read().deref()); } #[test] @@ -87,12 +87,12 @@ fn forked() { net.peer_mut(1).chain.add_blocks(100, EachBlockWith::Uncle); //fork between 1 and 2 net.peer_mut(2).chain.add_blocks(10, EachBlockWith::Nothing); // peer 1 has the best chain of 601 blocks - let peer1_chain = net.peer(1).chain.numbers.unwrapped_read().clone(); + let peer1_chain = net.peer(1).chain.numbers.read().clone(); net.sync(); - assert_eq!(net.peer(0).chain.difficulty.unwrapped_read().deref(), net.peer(1).chain.difficulty.unwrapped_read().deref()); - assert_eq!(net.peer(0).chain.numbers.unwrapped_read().deref(), &peer1_chain); - assert_eq!(net.peer(1).chain.numbers.unwrapped_read().deref(), &peer1_chain); - assert_eq!(net.peer(2).chain.numbers.unwrapped_read().deref(), &peer1_chain); + assert_eq!(net.peer(0).chain.difficulty.read().deref(), net.peer(1).chain.difficulty.read().deref()); + assert_eq!(net.peer(0).chain.numbers.read().deref(), &peer1_chain); + assert_eq!(net.peer(1).chain.numbers.read().deref(), &peer1_chain); + assert_eq!(net.peer(2).chain.numbers.read().deref(), &peer1_chain); } #[test] @@ -107,14 +107,14 @@ fn restart() { assert!(net.peer(0).chain.chain_info().best_block_number > 100); net.restart_peer(0); - let status = net.peer(0).sync.unwrapped_read().status(); + let status = net.peer(0).sync.read().status(); assert_eq!(status.state, SyncState::ChainHead); } #[test] fn status_empty() { let net = TestNet::new(2); - assert_eq!(net.peer(0).sync.unwrapped_read().status().state, SyncState::Idle); + assert_eq!(net.peer(0).sync.read().status().state, SyncState::Idle); } #[test] diff --git a/sync/src/tests/helpers.rs b/sync/src/tests/helpers.rs index f3a5c6c4c65..d5fda2e7040 100644 --- a/sync/src/tests/helpers.rs +++ b/sync/src/tests/helpers.rs @@ -118,7 +118,7 @@ impl TestNet { for client in 0..self.peers.len() { if peer != client { let mut p = self.peers.get_mut(peer).unwrap(); - p.sync.unwrapped_write().on_peer_connected(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(client as PeerId)), client as PeerId); + p.sync.write().on_peer_connected(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(client as PeerId)), client as PeerId); } } } @@ -133,18 +133,18 @@ impl TestNet { trace!("----------------"); } let mut p = self.peers.get_mut(peer).unwrap(); - p.sync.unwrapped_write().maintain_sync(&mut TestIo::new(&mut p.chain, &mut p.queue, None)); + p.sync.write().maintain_sync(&mut TestIo::new(&mut p.chain, &mut p.queue, None)); } } pub fn sync_step_peer(&mut self, peer_num: usize) { let mut peer = self.peer_mut(peer_num); - peer.sync.unwrapped_write().maintain_sync(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None)); + peer.sync.write().maintain_sync(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None)); } pub fn restart_peer(&mut self, i: usize) { let peer = self.peer_mut(i); - peer.sync.unwrapped_write().restart(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None)); + peer.sync.write().restart(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None)); } pub fn sync(&mut self) -> u32 { @@ -173,6 +173,6 @@ impl TestNet { pub fn trigger_chain_new_blocks(&mut self, peer_id: usize) { let mut peer = self.peer_mut(peer_id); - peer.sync.unwrapped_write().chain_new_blocks(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None), &[], &[], &[], &[], &[]); + peer.sync.write().chain_new_blocks(&mut TestIo::new(&mut peer.chain, &mut peer.queue, None), &[], &[], &[], &[], &[]); } } diff --git a/util/Cargo.toml b/util/Cargo.toml index 9a38cabbafd..db8a1501f3e 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -35,6 +35,7 @@ vergen = "0.1" target_info = "0.1" bigint = { path = "bigint" } chrono = "0.2" +parking_lot = "0.2.6" using_queue = { path = "using_queue" } table = { path = "table" } ansi_term = "0.7" diff --git a/util/src/io/service.rs b/util/src/io/service.rs index 7f80d50d740..bfd63b04ca4 100644 --- a/util/src/io/service.rs +++ b/util/src/io/service.rs @@ -14,18 +14,19 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use std::sync::*; +use std::sync::Arc; use std::thread::{self, JoinHandle}; use std::collections::HashMap; use mio::*; use crossbeam::sync::chase_lev; use slab::Slab; use error::*; -use misc::*; use io::{IoError, IoHandler}; use io::worker::{Worker, Work, WorkType}; use panics::*; +use parking_lot::{Condvar, RwLock, Mutex}; + /// Timer ID pub type TimerToken = usize; /// Timer ID @@ -228,7 +229,7 @@ impl Handler for IoManager where Message: Send + Clone + Sync let handler_index = token.as_usize() / TOKENS_PER_HANDLER; let token_id = token.as_usize() % TOKENS_PER_HANDLER; if let Some(handler) = self.handlers.get(handler_index) { - if let Some(timer) = self.timers.unwrapped_read().get(&token.as_usize()) { + if let Some(timer) = self.timers.read().get(&token.as_usize()) { event_loop.timeout_ms(token, timer.delay).expect("Error re-registering user timer"); self.worker_channel.push(Work { work_type: WorkType::Timeout, token: token_id, handler: handler.clone(), handler_id: handler_index }); self.work_ready.notify_all(); @@ -250,7 +251,7 @@ impl Handler for IoManager where Message: Send + Clone + Sync // TODO: flush event loop self.handlers.remove(handler_id); // unregister timers - let mut timers = self.timers.unwrapped_write(); + let mut timers = self.timers.write(); let to_remove: Vec<_> = timers.keys().cloned().filter(|timer_id| timer_id / TOKENS_PER_HANDLER == handler_id).collect(); for timer_id in to_remove { let timer = timers.remove(&timer_id).expect("to_remove only contains keys from timers; qed"); @@ -260,11 +261,11 @@ impl Handler for IoManager where Message: Send + Clone + Sync IoMessage::AddTimer { handler_id, token, delay } => { let timer_id = token + handler_id * TOKENS_PER_HANDLER; let timeout = event_loop.timeout_ms(Token(timer_id), delay).expect("Error registering user timer"); - self.timers.unwrapped_write().insert(timer_id, UserTimer { delay: delay, timeout: timeout }); + self.timers.write().insert(timer_id, UserTimer { delay: delay, timeout: timeout }); }, IoMessage::RemoveTimer { handler_id, token } => { let timer_id = token + handler_id * TOKENS_PER_HANDLER; - if let Some(timer) = self.timers.unwrapped_write().remove(&timer_id) { + if let Some(timer) = self.timers.write().remove(&timer_id) { event_loop.clear_timeout(timer.timeout); } }, @@ -278,7 +279,7 @@ impl Handler for IoManager where Message: Send + Clone + Sync handler.deregister_stream(token, event_loop); // unregister a timer associated with the token (if any) let timer_id = token + handler_id * TOKENS_PER_HANDLER; - if let Some(timer) = self.timers.unwrapped_write().remove(&timer_id) { + if let Some(timer) = self.timers.write().remove(&timer_id) { event_loop.clear_timeout(timer.timeout); } } diff --git a/util/src/io/worker.rs b/util/src/io/worker.rs index 333acb6af95..0ceadcd92b0 100644 --- a/util/src/io/worker.rs +++ b/util/src/io/worker.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use std::sync::*; +use std::sync::Arc; use std::mem; use std::thread::{JoinHandle, self}; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; @@ -22,7 +22,8 @@ use crossbeam::sync::chase_lev; use io::service::{HandlerId, IoChannel, IoContext}; use io::{IoHandler}; use panics::*; -use misc::Lockable; + +use parking_lot::{Condvar, Mutex}; pub enum WorkType { Readable, @@ -82,11 +83,11 @@ impl Worker { where Message: Send + Sync + Clone + 'static { loop { { - let lock = wait_mutex.locked(); + let mut lock = wait_mutex.lock(); if deleting.load(AtomicOrdering::Acquire) { return; } - let _ = wait.wait(lock).unwrap(); + let _ = wait.wait(&mut lock); } if deleting.load(AtomicOrdering::Acquire) { diff --git a/util/src/journaldb/earlymergedb.rs b/util/src/journaldb/earlymergedb.rs index abc6fb2e046..e976576bc8d 100644 --- a/util/src/journaldb/earlymergedb.rs +++ b/util/src/journaldb/earlymergedb.rs @@ -20,7 +20,6 @@ use common::*; use rlp::*; use hashdb::*; use memorydb::*; -use misc::RwLockable; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY, VERSION_KEY}; use super::traits::JournalDB; use kvdb::{Database, DBTransaction, DatabaseConfig}; @@ -226,7 +225,7 @@ impl EarlyMergeDB { #[cfg(test)] fn can_reconstruct_refs(&self) -> bool { let (latest_era, reconstructed) = Self::read_refs(&self.backing); - let refs = self.refs.as_ref().unwrap().unwrapped_write(); + let refs = self.refs.as_ref().unwrap().write(); if *refs != reconstructed || latest_era != self.latest_era { let clean_refs = refs.iter().filter_map(|(k, v)| if reconstructed.get(k) == Some(v) {None} else {Some((k.clone(), v.clone()))}).collect::>(); let clean_recon = reconstructed.into_iter().filter_map(|(k, v)| if refs.get(&k) == Some(&v) {None} else {Some((k.clone(), v.clone()))}).collect::>(); @@ -334,7 +333,7 @@ impl JournalDB for EarlyMergeDB { fn mem_used(&self) -> usize { self.overlay.mem_used() + match self.refs { - Some(ref c) => c.unwrapped_read().heap_size_of_children(), + Some(ref c) => c.read().heap_size_of_children(), None => 0 } } @@ -390,7 +389,7 @@ impl JournalDB for EarlyMergeDB { // // record new commit's details. - let mut refs = self.refs.as_ref().unwrap().unwrapped_write(); + let mut refs = self.refs.as_ref().unwrap().write(); let batch = DBTransaction::new(); let trace = false; { diff --git a/util/src/journaldb/overlayrecentdb.rs b/util/src/journaldb/overlayrecentdb.rs index 269b7e457dc..fcc537d5364 100644 --- a/util/src/journaldb/overlayrecentdb.rs +++ b/util/src/journaldb/overlayrecentdb.rs @@ -20,7 +20,6 @@ use common::*; use rlp::*; use hashdb::*; use memorydb::*; -use misc::RwLockable; use super::{DB_PREFIX_LEN, LATEST_ERA_KEY, VERSION_KEY}; use kvdb::{Database, DBTransaction, DatabaseConfig}; #[cfg(test)] @@ -137,7 +136,7 @@ impl OverlayRecentDB { #[cfg(test)] fn can_reconstruct_refs(&self) -> bool { let reconstructed = Self::read_overlay(&self.backing); - let journal_overlay = self.journal_overlay.unwrapped_read(); + let journal_overlay = self.journal_overlay.read(); *journal_overlay == reconstructed } @@ -207,7 +206,7 @@ impl JournalDB for OverlayRecentDB { fn mem_used(&self) -> usize { let mut mem = self.transaction_overlay.mem_used(); - let overlay = self.journal_overlay.unwrapped_read(); + let overlay = self.journal_overlay.read(); mem += overlay.backing_overlay.mem_used(); mem += overlay.journal.heap_size_of_children(); mem @@ -217,17 +216,17 @@ impl JournalDB for OverlayRecentDB { self.backing.get(&LATEST_ERA_KEY).expect("Low level database error").is_none() } - fn latest_era(&self) -> Option { self.journal_overlay.unwrapped_read().latest_era } + fn latest_era(&self) -> Option { self.journal_overlay.read().latest_era } fn state(&self, key: &H256) -> Option { - let v = self.journal_overlay.unwrapped_read().backing_overlay.get(&OverlayRecentDB::to_short_key(key)).map(|v| v.to_vec()); + let v = self.journal_overlay.read().backing_overlay.get(&OverlayRecentDB::to_short_key(key)).map(|v| v.to_vec()); v.or_else(|| self.backing.get_by_prefix(&key[0..DB_PREFIX_LEN]).map(|b| b.to_vec())) } fn commit(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result { // record new commit's details. trace!("commit: #{} ({}), end era: {:?}", now, id, end); - let mut journal_overlay = self.journal_overlay.unwrapped_write(); + let mut journal_overlay = self.journal_overlay.write(); let batch = DBTransaction::new(); { let mut r = RlpStream::new_list(3); @@ -334,7 +333,7 @@ impl HashDB for OverlayRecentDB { match k { Some(&(ref d, rc)) if rc > 0 => Some(d), _ => { - let v = self.journal_overlay.unwrapped_read().backing_overlay.get(&OverlayRecentDB::to_short_key(key)).map(|v| v.to_vec()); + let v = self.journal_overlay.read().backing_overlay.get(&OverlayRecentDB::to_short_key(key)).map(|v| v.to_vec()); match v { Some(x) => { Some(&self.transaction_overlay.denote(key, x).0) diff --git a/util/src/lib.rs b/util/src/lib.rs index ee6b5313851..bcd9df97161 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -116,6 +116,7 @@ extern crate libc; extern crate target_info; extern crate bigint; extern crate chrono; +extern crate parking_lot; pub extern crate using_queue; pub extern crate table; extern crate ansi_term; diff --git a/util/src/log.rs b/util/src/log.rs index 7857375910b..b4169f91c8a 100644 --- a/util/src/log.rs +++ b/util/src/log.rs @@ -18,14 +18,14 @@ use std::env; use std::borrow::Cow; -use rlog::{LogLevelFilter}; +use rlog::LogLevelFilter; use env_logger::LogBuilder; -use std::sync::{RwLock, RwLockReadGuard}; use std::sync::atomic::{Ordering, AtomicBool}; use arrayvec::ArrayVec; -use misc::RwLockable; pub use ansi_term::{Colour, Style}; +use parking_lot::{RwLock, RwLockReadGuard}; + lazy_static! { static ref USE_COLOR: AtomicBool = AtomicBool::new(false); } @@ -91,7 +91,7 @@ impl RotatingLogger { /// Append new log entry pub fn append(&self, log: String) { - self.logs.unwrapped_write().insert(0, log); + self.logs.write().insert(0, log); } /// Return levels @@ -101,7 +101,7 @@ impl RotatingLogger { /// Return logs pub fn logs(&self) -> RwLockReadGuard> { - self.logs.unwrapped_read() + self.logs.read() } } diff --git a/util/src/misc.rs b/util/src/misc.rs index fff03259ae1..62e8542db74 100644 --- a/util/src/misc.rs +++ b/util/src/misc.rs @@ -64,29 +64,4 @@ pub fn version_data() -> Bytes { s.append(&rustc_version()); s.append(&&Target::os()[0..2]); s.out() -} - -/// Object can be locked directly into a `MutexGuard`. -pub trait Lockable { - /// Lock object directly into a `MutexGuard`. - fn locked(&self) -> MutexGuard; -} - -impl Lockable for Mutex { - fn locked(&self) -> MutexGuard { self.lock().unwrap() } -} - -/// Object can be read or write locked directly into a guard. -pub trait RwLockable { - /// Read-lock object directly into a `ReadGuard`. - fn unwrapped_read(&self) -> RwLockReadGuard; - - /// Write-lock object directly into a `WriteGuard`. - fn unwrapped_write(&self) -> RwLockWriteGuard; -} - -impl RwLockable for RwLock { - fn unwrapped_read(&self) -> RwLockReadGuard { self.read().unwrap() } - fn unwrapped_write(&self) -> RwLockWriteGuard { self.write().unwrap() } -} - +} \ No newline at end of file diff --git a/util/src/network/connection.rs b/util/src/network/connection.rs index 9ee045c8751..9963d94b7c1 100644 --- a/util/src/network/connection.rs +++ b/util/src/network/connection.rs @@ -96,13 +96,13 @@ impl GenericConnection { } }, Ok(_) => return Ok(None), - Err(e) => { + Err(e) => { debug!(target:"network", "Read error {} ({})", self.token, e); return Err(e) } } } - } + } /// Add a packet to send queue. pub fn send(&mut self, io: &IoContext, data: Bytes) where Message: Send + Clone { @@ -490,7 +490,7 @@ pub fn test_encryption() { #[cfg(test)] mod tests { use super::*; - use std::sync::*; + use std::sync::Arc; use std::sync::atomic::AtomicBool; use super::super::stats::*; use std::io::{Read, Write, Error, Cursor, ErrorKind}; diff --git a/util/src/network/host.rs b/util/src/network/host.rs index 701437ab315..0612e4444de 100644 --- a/util/src/network/host.rs +++ b/util/src/network/host.rs @@ -17,7 +17,7 @@ use std::net::SocketAddr; use std::collections::{HashMap, HashSet}; use std::str::FromStr; -use std::sync::*; +use std::sync::Arc; use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering}; use std::ops::*; use std::cmp::min; @@ -42,6 +42,7 @@ use network::error::{NetworkError, DisconnectReason}; use network::discovery::{Discovery, TableUpdates, NodeEntry}; use network::ip_utils::{map_external_address, select_public_address}; use path::restrict_permissions_owner; +use parking_lot::{Mutex, RwLock}; type Slab = ::slab::Slab; @@ -201,7 +202,7 @@ impl<'s> NetworkContext<'s> { protocol: ProtocolId, session: Option, sessions: Arc>>, reserved_peers: &'s HashSet) -> NetworkContext<'s> { - let id = session.as_ref().map(|s| s.locked().token()); + let id = session.as_ref().map(|s| s.lock().token()); NetworkContext { io: io, protocol: protocol, @@ -215,7 +216,7 @@ impl<'s> NetworkContext<'s> { fn resolve_session(&self, peer: PeerId) -> Option { match self.session_id { Some(id) if id == peer => self.session.clone(), - _ => self.sessions.unwrapped_read().get(peer).cloned(), + _ => self.sessions.read().get(peer).cloned(), } } @@ -223,7 +224,7 @@ impl<'s> NetworkContext<'s> { pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec) -> Result<(), UtilError> { let session = self.resolve_session(peer); if let Some(session) = session { - try!(session.locked().send_packet(self.io, self.protocol, packet_id as u8, &data)); + try!(session.lock().send_packet(self.io, self.protocol, packet_id as u8, &data)); } else { trace!(target: "network", "Send: Peer no longer exist") } @@ -256,7 +257,7 @@ impl<'s> NetworkContext<'s> { /// Check if the session is still active. pub fn is_expired(&self) -> bool { - self.session.as_ref().map_or(false, |s| s.locked().expired()) + self.session.as_ref().map_or(false, |s| s.lock().expired()) } /// Register a new IO timer. 'IoHandler::timeout' will be called with the token. @@ -273,7 +274,7 @@ impl<'s> NetworkContext<'s> { pub fn peer_info(&self, peer: PeerId) -> String { let session = self.resolve_session(peer); if let Some(session) = session { - return session.locked().info.client_version.clone() + return session.lock().info.client_version.clone() } "unknown".to_owned() } @@ -416,8 +417,8 @@ impl Host { Ok(n) => { let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() }; - self.nodes.unwrapped_write().add_node(n); - if let Some(ref mut discovery) = *self.discovery.locked() { + self.nodes.write().add_node(n); + if let Some(ref mut discovery) = *self.discovery.lock() { discovery.add_node(entry); } } @@ -428,9 +429,9 @@ impl Host { let n = try!(Node::from_str(id)); let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() }; - self.reserved_nodes.unwrapped_write().insert(n.id.clone()); + self.reserved_nodes.write().insert(n.id.clone()); - if let Some(ref mut discovery) = *self.discovery.locked() { + if let Some(ref mut discovery) = *self.discovery.lock() { discovery.add_node(entry); } @@ -438,17 +439,17 @@ impl Host { } pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode, io: &IoContext) { - let mut info = self.info.unwrapped_write(); + let mut info = self.info.write(); if info.config.non_reserved_mode != mode { info.config.non_reserved_mode = mode.clone(); drop(info); if let NonReservedPeerMode::Deny = mode { // disconnect all non-reserved peers here. - let reserved: HashSet = self.reserved_nodes.unwrapped_read().clone(); + let reserved: HashSet = self.reserved_nodes.read().clone(); let mut to_kill = Vec::new(); - for e in self.sessions.unwrapped_write().iter_mut() { - let mut s = e.locked(); + for e in self.sessions.write().iter_mut() { + let mut s = e.lock(); { let id = s.id(); if id.is_some() && reserved.contains(id.unwrap()) { @@ -469,7 +470,7 @@ impl Host { pub fn remove_reserved_node(&self, id: &str) -> Result<(), UtilError> { let n = try!(Node::from_str(id)); - self.reserved_nodes.unwrapped_write().remove(&n.id); + self.reserved_nodes.write().remove(&n.id); Ok(()) } @@ -479,11 +480,11 @@ impl Host { } pub fn external_url(&self) -> Option { - self.info.unwrapped_read().public_endpoint.as_ref().map(|e| format!("{}", Node::new(self.info.unwrapped_read().id().clone(), e.clone()))) + self.info.read().public_endpoint.as_ref().map(|e| format!("{}", Node::new(self.info.read().id().clone(), e.clone()))) } pub fn local_url(&self) -> String { - let r = format!("{}", Node::new(self.info.unwrapped_read().id().clone(), self.info.unwrapped_read().local_endpoint.clone())); + let r = format!("{}", Node::new(self.info.read().id().clone(), self.info.read().local_endpoint.clone())); println!("{}", r); r } @@ -491,8 +492,8 @@ impl Host { pub fn stop(&self, io: &IoContext) -> Result<(), UtilError> { self.stopping.store(true, AtomicOrdering::Release); let mut to_kill = Vec::new(); - for e in self.sessions.unwrapped_write().iter_mut() { - let mut s = e.locked(); + for e in self.sessions.write().iter_mut() { + let mut s = e.lock(); s.disconnect(io, DisconnectReason::ClientQuit); to_kill.push(s.token()); } @@ -505,16 +506,16 @@ impl Host { } fn init_public_interface(&self, io: &IoContext) -> Result<(), UtilError> { - if self.info.unwrapped_read().public_endpoint.is_some() { + if self.info.read().public_endpoint.is_some() { return Ok(()); } - let local_endpoint = self.info.unwrapped_read().local_endpoint.clone(); - let public_address = self.info.unwrapped_read().config.public_address.clone(); + let local_endpoint = self.info.read().local_endpoint.clone(); + let public_address = self.info.read().config.public_address.clone(); let public_endpoint = match public_address { None => { let public_address = select_public_address(local_endpoint.address.port()); let public_endpoint = NodeEndpoint { address: public_address, udp_port: local_endpoint.udp_port }; - if self.info.unwrapped_read().config.nat_enabled { + if self.info.read().config.nat_enabled { match map_external_address(&local_endpoint) { Some(endpoint) => { info!("NAT mapped to external address {}", endpoint.address); @@ -529,7 +530,7 @@ impl Host { Some(addr) => NodeEndpoint { address: addr, udp_port: local_endpoint.udp_port } }; - self.info.unwrapped_write().public_endpoint = Some(public_endpoint.clone()); + self.info.write().public_endpoint = Some(public_endpoint.clone()); if let Some(url) = self.external_url() { io.message(NetworkIoMessage::NetworkStarted(url)).unwrap_or_else(|e| warn!("Error sending IO notification: {:?}", e)); @@ -537,7 +538,7 @@ impl Host { // Initialize discovery. let discovery = { - let info = self.info.unwrapped_read(); + let info = self.info.read(); if info.config.discovery_enabled && info.config.non_reserved_mode == NonReservedPeerMode::Accept { let mut udp_addr = local_endpoint.address.clone(); udp_addr.set_port(local_endpoint.udp_port); @@ -546,11 +547,11 @@ impl Host { }; if let Some(mut discovery) = discovery { - discovery.init_node_list(self.nodes.unwrapped_read().unordered_entries()); - for n in self.nodes.unwrapped_read().unordered_entries() { + discovery.init_node_list(self.nodes.read().unordered_entries()); + for n in self.nodes.read().unordered_entries() { discovery.add_node(n.clone()); } - *self.discovery.locked() = Some(discovery); + *self.discovery.lock() = Some(discovery); io.register_stream(DISCOVERY).expect("Error registering UDP listener"); io.register_timer(DISCOVERY_REFRESH, 7200).expect("Error registering discovery timer"); io.register_timer(DISCOVERY_ROUND, 300).expect("Error registering discovery timer"); @@ -566,7 +567,7 @@ impl Host { } fn have_session(&self, id: &NodeId) -> bool { - self.sessions.unwrapped_read().iter().any(|e| e.locked().info.id == Some(id.clone())) + self.sessions.read().iter().any(|e| e.lock().info.id == Some(id.clone())) } fn session_count(&self) -> usize { @@ -574,17 +575,17 @@ impl Host { } fn connecting_to(&self, id: &NodeId) -> bool { - self.sessions.unwrapped_read().iter().any(|e| e.locked().id() == Some(id)) + self.sessions.read().iter().any(|e| e.lock().id() == Some(id)) } fn handshake_count(&self) -> usize { - self.sessions.unwrapped_read().count() - self.session_count() + self.sessions.read().count() - self.session_count() } fn keep_alive(&self, io: &IoContext) { let mut to_kill = Vec::new(); - for e in self.sessions.unwrapped_write().iter_mut() { - let mut s = e.locked(); + for e in self.sessions.write().iter_mut() { + let mut s = e.lock(); if !s.keep_alive(io) { s.disconnect(io, DisconnectReason::PingTimeout); to_kill.push(s.token()); @@ -598,7 +599,7 @@ impl Host { fn connect_peers(&self, io: &IoContext) { let (ideal_peers, mut pin) = { - let info = self.info.unwrapped_read(); + let info = self.info.read(); if info.capabilities.is_empty() { return; } @@ -608,7 +609,7 @@ impl Host { }; let session_count = self.session_count(); - let reserved_nodes = self.reserved_nodes.unwrapped_read(); + let reserved_nodes = self.reserved_nodes.read(); if session_count >= ideal_peers as usize + reserved_nodes.len() { // check if all pinned nodes are connected. if reserved_nodes.iter().all(|n| self.have_session(n) && self.connecting_to(n)) { @@ -629,7 +630,7 @@ impl Host { // iterate over all nodes, reserved ones coming first. // if we are pinned to only reserved nodes, ignore all others. let nodes = reserved_nodes.iter().cloned().chain(if !pin { - self.nodes.unwrapped_read().nodes() + self.nodes.read().nodes() } else { Vec::new() }); @@ -657,7 +658,7 @@ impl Host { let socket = { let address = { - let mut nodes = self.nodes.unwrapped_write(); + let mut nodes = self.nodes.write(); if let Some(node) = nodes.get_mut(id) { node.last_attempted = Some(::time::now()); node.endpoint.address @@ -682,11 +683,11 @@ impl Host { #[cfg_attr(feature="dev", allow(block_in_if_condition_stmt))] fn create_connection(&self, socket: TcpStream, id: Option<&NodeId>, io: &IoContext) -> Result<(), UtilError> { - let nonce = self.info.unwrapped_write().next_nonce(); - let mut sessions = self.sessions.unwrapped_write(); + let nonce = self.info.write().next_nonce(); + let mut sessions = self.sessions.write(); let token = sessions.insert_with_opt(|token| { - match Session::new(io, socket, token, id, &nonce, self.stats.clone(), &self.info.unwrapped_read()) { + match Session::new(io, socket, token, id, &nonce, self.stats.clone(), &self.info.read()) { Ok(s) => Some(Arc::new(Mutex::new(s))), Err(e) => { debug!(target: "network", "Session create error: {:?}", e); @@ -707,7 +708,7 @@ impl Host { fn accept(&self, io: &IoContext) { trace!(target: "network", "Accepting incoming connection"); loop { - let socket = match self.tcp_listener.locked().accept() { + let socket = match self.tcp_listener.lock().accept() { Ok(None) => break, Ok(Some((sock, _addr))) => sock, Err(e) => { @@ -722,11 +723,11 @@ impl Host { } fn session_writable(&self, token: StreamToken, io: &IoContext) { - let session = { self.sessions.unwrapped_read().get(token).cloned() }; + let session = { self.sessions.read().get(token).cloned() }; if let Some(session) = session { - let mut s = session.locked(); - if let Err(e) = s.writable(io, &self.info.unwrapped_read()) { + let mut s = session.lock(); + if let Err(e) = s.writable(io, &self.info.read()) { trace!(target: "network", "Session write error: {}: {:?}", token, e); } if s.done() { @@ -745,16 +746,16 @@ impl Host { let mut ready_data: Vec = Vec::new(); let mut packet_data: Vec<(ProtocolId, PacketId, Vec)> = Vec::new(); let mut kill = false; - let session = { self.sessions.unwrapped_read().get(token).cloned() }; + let session = { self.sessions.read().get(token).cloned() }; if let Some(session) = session.clone() { - let mut s = session.locked(); + let mut s = session.lock(); loop { - match s.readable(io, &self.info.unwrapped_read()) { + match s.readable(io, &self.info.read()) { Err(e) => { trace!(target: "network", "Session read error: {}:{:?} ({:?}) {:?}", token, s.id(), s.remote_addr(), e); if let UtilError::Network(NetworkError::Disconnect(DisconnectReason::IncompatibleProtocol)) = e { if let Some(id) = s.id() { - self.nodes.unwrapped_write().mark_as_useless(id); + self.nodes.write().mark_as_useless(id); } } kill = true; @@ -764,9 +765,9 @@ impl Host { self.num_sessions.fetch_add(1, AtomicOrdering::SeqCst); if !s.info.originated { let session_count = self.session_count(); - let reserved_nodes = self.reserved_nodes.unwrapped_read(); + let reserved_nodes = self.reserved_nodes.read(); let (ideal_peers, reserved_only) = { - let info = self.info.unwrapped_read(); + let info = self.info.read(); (info.config.ideal_peers, info.config.non_reserved_mode == NonReservedPeerMode::Deny) }; @@ -781,14 +782,14 @@ impl Host { // Add it no node table if let Ok(address) = s.remote_addr() { let entry = NodeEntry { id: s.id().unwrap().clone(), endpoint: NodeEndpoint { address: address, udp_port: address.port() } }; - self.nodes.unwrapped_write().add_node(Node::new(entry.id.clone(), entry.endpoint.clone())); - let mut discovery = self.discovery.locked(); + self.nodes.write().add_node(Node::new(entry.id.clone(), entry.endpoint.clone())); + let mut discovery = self.discovery.lock(); if let Some(ref mut discovery) = *discovery.deref_mut() { discovery.add_node(entry); } } } - for (p, _) in self.handlers.unwrapped_read().iter() { + for (p, _) in self.handlers.read().iter() { if s.have_capability(p) { ready_data.push(p); } @@ -799,7 +800,7 @@ impl Host { protocol, packet_id, }) => { - match self.handlers.unwrapped_read().get(protocol) { + match self.handlers.read().get(protocol) { None => { warn!(target: "network", "No handler found for protocol: {:?}", protocol) }, Some(_) => packet_data.push((protocol, packet_id, data)), } @@ -812,16 +813,16 @@ impl Host { if kill { self.kill_connection(token, io, true); } - let handlers = self.handlers.unwrapped_read(); + let handlers = self.handlers.read(); for p in ready_data { let h = handlers.get(p).unwrap().clone(); self.stats.inc_sessions(); - let reserved = self.reserved_nodes.unwrapped_read(); + let reserved = self.reserved_nodes.read(); h.connected(&NetworkContext::new(io, p, session.clone(), self.sessions.clone(), &reserved), &token); } for (p, packet_id, data) in packet_data { let h = handlers.get(p).unwrap().clone(); - let reserved = self.reserved_nodes.unwrapped_read(); + let reserved = self.reserved_nodes.read(); h.read(&NetworkContext::new(io, p, session.clone(), self.sessions.clone(), &reserved), &token, packet_id, &data[1..]); } } @@ -837,14 +838,14 @@ impl Host { let mut deregister = false; let mut expired_session = None; if let FIRST_SESSION ... LAST_SESSION = token { - let sessions = self.sessions.unwrapped_write(); + let sessions = self.sessions.write(); if let Some(session) = sessions.get(token).cloned() { expired_session = Some(session.clone()); - let mut s = session.locked(); + let mut s = session.lock(); if !s.expired() { if s.is_ready() { self.num_sessions.fetch_sub(1, AtomicOrdering::SeqCst); - for (p, _) in self.handlers.unwrapped_read().iter() { + for (p, _) in self.handlers.read().iter() { if s.have_capability(p) { to_disconnect.push(p); } @@ -858,12 +859,12 @@ impl Host { } if let Some(id) = failure_id { if remote { - self.nodes.unwrapped_write().note_failure(&id); + self.nodes.write().note_failure(&id); } } for p in to_disconnect { - let h = self.handlers.unwrapped_read().get(p).unwrap().clone(); - let reserved = self.reserved_nodes.unwrapped_read(); + let h = self.handlers.read().get(p).unwrap().clone(); + let reserved = self.reserved_nodes.read(); h.disconnected(&NetworkContext::new(io, p, expired_session.clone(), self.sessions.clone(), &reserved), &token); } if deregister { @@ -874,9 +875,9 @@ impl Host { fn update_nodes(&self, io: &IoContext, node_changes: TableUpdates) { let mut to_remove: Vec = Vec::new(); { - let sessions = self.sessions.unwrapped_write(); + let sessions = self.sessions.write(); for c in sessions.iter() { - let s = c.locked(); + let s = c.lock(); if let Some(id) = s.id() { if node_changes.removed.contains(id) { to_remove.push(s.token()); @@ -888,11 +889,11 @@ impl Host { trace!(target: "network", "Removed from node table: {}", i); self.kill_connection(i, io, false); } - self.nodes.unwrapped_write().update(node_changes); + self.nodes.write().update(node_changes); } pub fn with_context(&self, protocol: ProtocolId, io: &IoContext, action: F) where F: Fn(&NetworkContext) { - let reserved = { self.reserved_nodes.unwrapped_read() }; + let reserved = { self.reserved_nodes.read() }; let context = NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved); action(&context); @@ -922,7 +923,7 @@ impl IoHandler for Host { match stream { FIRST_SESSION ... LAST_SESSION => self.session_readable(stream, io), DISCOVERY => { - let node_changes = { self.discovery.locked().as_mut().unwrap().readable(io) }; + let node_changes = { self.discovery.lock().as_mut().unwrap().readable(io) }; if let Some(node_changes) = node_changes { self.update_nodes(io, node_changes); } @@ -939,7 +940,7 @@ impl IoHandler for Host { match stream { FIRST_SESSION ... LAST_SESSION => self.session_writable(stream, io), DISCOVERY => { - self.discovery.locked().as_mut().unwrap().writable(io); + self.discovery.lock().as_mut().unwrap().writable(io); } _ => panic!("Received unknown writable token"), } @@ -953,11 +954,11 @@ impl IoHandler for Host { IDLE => self.maintain_network(io), FIRST_SESSION ... LAST_SESSION => self.connection_timeout(token, io), DISCOVERY_REFRESH => { - self.discovery.locked().as_mut().unwrap().refresh(); + self.discovery.lock().as_mut().unwrap().refresh(); io.update_registration(DISCOVERY).unwrap_or_else(|e| debug!("Error updating discovery registration: {:?}", e)); }, DISCOVERY_ROUND => { - let node_changes = { self.discovery.locked().as_mut().unwrap().round() }; + let node_changes = { self.discovery.lock().as_mut().unwrap().round() }; if let Some(node_changes) = node_changes { self.update_nodes(io, node_changes); } @@ -965,13 +966,13 @@ impl IoHandler for Host { }, NODE_TABLE => { trace!(target: "network", "Refreshing node table"); - self.nodes.unwrapped_write().clear_useless(); + self.nodes.write().clear_useless(); }, - _ => match self.timers.unwrapped_read().get(&token).cloned() { - Some(timer) => match self.handlers.unwrapped_read().get(timer.protocol).cloned() { + _ => match self.timers.read().get(&token).cloned() { + Some(timer) => match self.handlers.read().get(timer.protocol).cloned() { None => { warn!(target: "network", "No handler found for protocol: {:?}", timer.protocol) }, Some(h) => { - let reserved = self.reserved_nodes.unwrapped_read(); + let reserved = self.reserved_nodes.read(); h.timeout(&NetworkContext::new(io, timer.protocol, None, self.sessions.clone(), &reserved), timer.token); } }, @@ -991,10 +992,10 @@ impl IoHandler for Host { ref versions } => { let h = handler.clone(); - let reserved = self.reserved_nodes.unwrapped_read(); + let reserved = self.reserved_nodes.read(); h.initialize(&NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved)); - self.handlers.unwrapped_write().insert(protocol, h); - let mut info = self.info.unwrapped_write(); + self.handlers.write().insert(protocol, h); + let mut info = self.info.write(); for v in versions { info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 }); } @@ -1005,29 +1006,29 @@ impl IoHandler for Host { ref token, } => { let handler_token = { - let mut timer_counter = self.timer_counter.unwrapped_write(); + let mut timer_counter = self.timer_counter.write(); let counter = &mut *timer_counter; let handler_token = *counter; *counter += 1; handler_token }; - self.timers.unwrapped_write().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token }); + self.timers.write().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token }); io.register_timer(handler_token, *delay).unwrap_or_else(|e| debug!("Error registering timer {}: {:?}", token, e)); }, NetworkIoMessage::Disconnect(ref peer) => { - let session = { self.sessions.unwrapped_read().get(*peer).cloned() }; + let session = { self.sessions.read().get(*peer).cloned() }; if let Some(session) = session { - session.locked().disconnect(io, DisconnectReason::DisconnectRequested); + session.lock().disconnect(io, DisconnectReason::DisconnectRequested); } trace!(target: "network", "Disconnect requested {}", peer); self.kill_connection(*peer, io, false); }, NetworkIoMessage::DisablePeer(ref peer) => { - let session = { self.sessions.unwrapped_read().get(*peer).cloned() }; + let session = { self.sessions.read().get(*peer).cloned() }; if let Some(session) = session { - session.locked().disconnect(io, DisconnectReason::DisconnectRequested); - if let Some(id) = session.locked().id() { - self.nodes.unwrapped_write().mark_as_useless(id) + session.lock().disconnect(io, DisconnectReason::DisconnectRequested); + if let Some(id) = session.lock().id() { + self.nodes.write().mark_as_useless(id) } } trace!(target: "network", "Disabling peer {}", peer); @@ -1042,13 +1043,13 @@ impl IoHandler for Host { fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop>) { match stream { FIRST_SESSION ... LAST_SESSION => { - let session = { self.sessions.unwrapped_read().get(stream).cloned() }; + let session = { self.sessions.read().get(stream).cloned() }; if let Some(session) = session { - session.locked().register_socket(reg, event_loop).expect("Error registering socket"); + session.lock().register_socket(reg, event_loop).expect("Error registering socket"); } } - DISCOVERY => self.discovery.locked().as_ref().unwrap().register_socket(event_loop).expect("Error registering discovery socket"), - TCP_ACCEPT => event_loop.register(&*self.tcp_listener.locked(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error registering stream"), + DISCOVERY => self.discovery.lock().as_ref().unwrap().register_socket(event_loop).expect("Error registering discovery socket"), + TCP_ACCEPT => event_loop.register(&*self.tcp_listener.lock(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error registering stream"), _ => warn!("Unexpected stream registration") } } @@ -1056,9 +1057,9 @@ impl IoHandler for Host { fn deregister_stream(&self, stream: StreamToken, event_loop: &mut EventLoop>) { match stream { FIRST_SESSION ... LAST_SESSION => { - let mut connections = self.sessions.unwrapped_write(); + let mut connections = self.sessions.write(); if let Some(connection) = connections.get(stream).cloned() { - connection.locked().deregister_socket(event_loop).expect("Error deregistering socket"); + connection.lock().deregister_socket(event_loop).expect("Error deregistering socket"); connections.remove(stream); } } @@ -1070,13 +1071,13 @@ impl IoHandler for Host { fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop>) { match stream { FIRST_SESSION ... LAST_SESSION => { - let connection = { self.sessions.unwrapped_read().get(stream).cloned() }; + let connection = { self.sessions.read().get(stream).cloned() }; if let Some(connection) = connection { - connection.locked().update_socket(reg, event_loop).expect("Error updating socket"); + connection.lock().update_socket(reg, event_loop).expect("Error updating socket"); } } - DISCOVERY => self.discovery.locked().as_ref().unwrap().update_registration(event_loop).expect("Error reregistering discovery socket"), - TCP_ACCEPT => event_loop.reregister(&*self.tcp_listener.locked(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error reregistering stream"), + DISCOVERY => self.discovery.lock().as_ref().unwrap().update_registration(event_loop).expect("Error reregistering discovery socket"), + TCP_ACCEPT => event_loop.reregister(&*self.tcp_listener.lock(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error reregistering stream"), _ => warn!("Unexpected stream update") } } diff --git a/util/src/network/service.rs b/util/src/network/service.rs index ece8324c7dd..d95db5842c4 100644 --- a/util/src/network/service.rs +++ b/util/src/network/service.rs @@ -14,16 +14,18 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use std::sync::*; use error::*; use panics::*; -use misc::RwLockable; use network::{NetworkProtocolHandler, NetworkConfiguration}; use network::error::NetworkError; use network::host::{Host, NetworkContext, NetworkIoMessage, ProtocolId}; use network::stats::NetworkStats; use io::*; +use std::sync::Arc; + +use parking_lot::RwLock; + /// IO Service with networking /// `Message` defines a notification data type. pub struct NetworkService { @@ -86,19 +88,19 @@ impl NetworkService { /// Returns external url if available. pub fn external_url(&self) -> Option { - let host = self.host.unwrapped_read(); + let host = self.host.read(); host.as_ref().and_then(|h| h.external_url()) } /// Returns external url if available. pub fn local_url(&self) -> Option { - let host = self.host.unwrapped_read(); + let host = self.host.read(); host.as_ref().map(|h| h.local_url()) } /// Start network IO pub fn start(&self) -> Result<(), UtilError> { - let mut host = self.host.unwrapped_write(); + let mut host = self.host.write(); if host.is_none() { let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone()))); try!(self.io_service.register_handler(h.clone())); @@ -109,7 +111,7 @@ impl NetworkService { /// Stop network IO pub fn stop(&self) -> Result<(), UtilError> { - let mut host = self.host.unwrapped_write(); + let mut host = self.host.write(); if let Some(ref host) = *host { let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host try!(host.stop(&io)); @@ -120,7 +122,7 @@ impl NetworkService { /// Try to add a reserved peer. pub fn add_reserved_peer(&self, peer: &str) -> Result<(), UtilError> { - let host = self.host.unwrapped_read(); + let host = self.host.read(); if let Some(ref host) = *host { host.add_reserved_node(peer) } else { @@ -130,7 +132,7 @@ impl NetworkService { /// Try to remove a reserved peer. pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), UtilError> { - let host = self.host.unwrapped_read(); + let host = self.host.read(); if let Some(ref host) = *host { host.remove_reserved_node(peer) } else { @@ -140,7 +142,7 @@ impl NetworkService { /// Set the non-reserved peer mode. pub fn set_non_reserved_mode(&self, mode: ::network::NonReservedPeerMode) { - let host = self.host.unwrapped_read(); + let host = self.host.read(); if let Some(ref host) = *host { let io_ctxt = IoContext::new(self.io_service.channel(), 0); host.set_non_reserved_mode(mode, &io_ctxt); @@ -150,7 +152,7 @@ impl NetworkService { /// Executes action in the network context pub fn with_context(&self, protocol: ProtocolId, action: F) where F: Fn(&NetworkContext) { let io = IoContext::new(self.io_service.channel(), 0); - let host = self.host.unwrapped_read(); + let host = self.host.read(); if let Some(ref host) = host.as_ref() { host.with_context(protocol, &io, action); }; diff --git a/util/src/network/tests.rs b/util/src/network/tests.rs index b428a0a8e9e..450b5dd0038 100644 --- a/util/src/network/tests.rs +++ b/util/src/network/tests.rs @@ -18,7 +18,6 @@ use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::thread; use std::time::*; use common::*; -use misc::*; use network::*; use io::TimerToken; use crypto::KeyPair; @@ -47,7 +46,7 @@ impl TestProtocol { } pub fn got_packet(&self) -> bool { - self.packet.locked().deref()[..] == b"hello"[..] + self.packet.lock().deref()[..] == b"hello"[..] } pub fn got_timeout(&self) -> bool { @@ -66,7 +65,7 @@ impl NetworkProtocolHandler for TestProtocol { fn read(&self, _io: &NetworkContext, _peer: &PeerId, packet_id: u8, data: &[u8]) { assert_eq!(packet_id, 33); - self.packet.locked().extend(data); + self.packet.lock().extend(data); } fn connected(&self, io: &NetworkContext, peer: &PeerId) { diff --git a/util/src/panics.rs b/util/src/panics.rs index 7b6c92639e6..8db875bdfdd 100644 --- a/util/src/panics.rs +++ b/util/src/panics.rs @@ -18,9 +18,10 @@ use std::thread; use std::ops::DerefMut; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::default::Default; -use misc::Lockable; + +use parking_lot::Mutex; /// Thread-safe closure for handling possible panics pub trait OnPanicListener: Send + Sync + 'static { @@ -89,7 +90,7 @@ impl PanicHandler { /// Notifies all listeners in case there is a panic. /// You should use `catch_panic` instead of calling this method explicitly. pub fn notify_all(&self, r: String) { - let mut listeners = self.listeners.locked(); + let mut listeners = self.listeners.lock(); for listener in listeners.deref_mut() { listener.call(&r); } @@ -98,7 +99,7 @@ impl PanicHandler { impl MayPanic for PanicHandler { fn on_panic(&self, closure: F) where F: OnPanicListener { - self.listeners.locked().push(Box::new(closure)); + self.listeners.lock().push(Box::new(closure)); } } @@ -119,50 +120,46 @@ impl OnPanicListener for F #[test] #[ignore] // panic forwarding doesnt work on the same thread in beta fn should_notify_listeners_about_panic () { - use std::sync::RwLock; - use misc::RwLockable; + use parking_lot::RwLock; // given let invocations = Arc::new(RwLock::new(vec![])); let i = invocations.clone(); let p = PanicHandler::new(); - p.on_panic(move |t| i.unwrapped_write().push(t)); + p.on_panic(move |t| i.write().push(t)); // when p.catch_panic(|| panic!("Panic!")).unwrap_err(); // then - assert!(invocations.unwrapped_read()[0] == "Panic!"); + assert!(invocations.read()[0] == "Panic!"); } #[test] #[ignore] // panic forwarding doesnt work on the same thread in beta fn should_notify_listeners_about_panic_when_string_is_dynamic () { - use std::sync::RwLock; - use misc::RwLockable; + use parking_lot::RwLock; // given let invocations = Arc::new(RwLock::new(vec![])); let i = invocations.clone(); let p = PanicHandler::new(); - p.on_panic(move |t| i.unwrapped_write().push(t)); + p.on_panic(move |t| i.write().push(t)); // when p.catch_panic(|| panic!("Panic: {}", 1)).unwrap_err(); // then - assert!(invocations.unwrapped_read()[0] == "Panic: 1"); + assert!(invocations.read()[0] == "Panic: 1"); } #[test] fn should_notify_listeners_about_panic_in_other_thread () { use std::thread; - use std::sync::RwLock; - use misc::RwLockable; - + use parking_lot::RwLock; // given let invocations = Arc::new(RwLock::new(vec![])); let i = invocations.clone(); let p = PanicHandler::new(); - p.on_panic(move |t| i.unwrapped_write().push(t)); + p.on_panic(move |t| i.write().push(t)); // when let t = thread::spawn(move || @@ -171,20 +168,18 @@ fn should_notify_listeners_about_panic_in_other_thread () { t.join().unwrap_err(); // then - assert!(invocations.unwrapped_read()[0] == "Panic!"); + assert!(invocations.read()[0] == "Panic!"); } #[test] #[ignore] // panic forwarding doesnt work on the same thread in beta fn should_forward_panics () { -use std::sync::RwLock; - use misc::RwLockable; - + use parking_lot::RwLock; // given let invocations = Arc::new(RwLock::new(vec![])); let i = invocations.clone(); let p = PanicHandler::new_in_arc(); - p.on_panic(move |t| i.unwrapped_write().push(t)); + p.on_panic(move |t| i.write().push(t)); let p2 = PanicHandler::new(); p.forward_from(&p2); @@ -193,5 +188,5 @@ use std::sync::RwLock; p2.catch_panic(|| panic!("Panic!")).unwrap_err(); // then - assert!(invocations.unwrapped_read()[0] == "Panic!"); + assert!(invocations.read()[0] == "Panic!"); } diff --git a/util/src/standard.rs b/util/src/standard.rs index c588e9d5330..ac41ef50d28 100644 --- a/util/src/standard.rs +++ b/util/src/standard.rs @@ -36,7 +36,7 @@ pub use std::error::Error as StdError; pub use std::ops::*; pub use std::cmp::*; -pub use std::sync::*; +pub use std::sync::Arc; pub use std::cell::*; pub use std::collections::*; @@ -46,3 +46,5 @@ pub use rustc_serialize::hex::{FromHex, FromHexError}; pub use heapsize::HeapSizeOf; pub use itertools::Itertools; + +pub use parking_lot::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; \ No newline at end of file From 1b86f8368df25437599aba95e332efe2ea35dd9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 13 Jul 2016 20:19:48 +0200 Subject: [PATCH 35/36] Updating jsonrpc-http-server (#1611) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 28a08fb6899..5201afad5aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -613,7 +613,7 @@ dependencies = [ [[package]] name = "jsonrpc-http-server" version = "5.1.0" -source = "git+https://github.com/ethcore/jsonrpc-http-server.git#e59c2fbaca499620874023755cb91f05b858ffe7" +source = "git+https://github.com/ethcore/jsonrpc-http-server.git#f16b956c61e60b3a530ad4bac82112a8974cf505" dependencies = [ "hyper 0.9.4 (git+https://github.com/ethcore/hyper)", "jsonrpc-core 2.0.7 (registry+https://github.com/rust-lang/crates.io-index)", From a7511b6b021be65ac4555005c719d218f6ba1187 Mon Sep 17 00:00:00 2001 From: Robert Habermeier Date: Wed, 13 Jul 2016 20:45:15 +0200 Subject: [PATCH 36/36] fix benchmark compilation (#1612) --- util/benches/trie.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/util/benches/trie.rs b/util/benches/trie.rs index 8c573e17012..7f0677943f4 100644 --- a/util/benches/trie.rs +++ b/util/benches/trie.rs @@ -25,7 +25,6 @@ use test::Bencher; use ethcore_util::hash::*; use ethcore_util::bytes::*; use ethcore_util::trie::*; -use ethcore_util::hashdb::*; use ethcore_util::memorydb::*; use ethcore_util::triehash::*; use ethcore_util::sha3::*; @@ -34,10 +33,10 @@ use ethcore_util::sha3::*; fn random_word(alphabet: &[u8], min_count: usize, diff_count: usize, seed: &mut H256) -> Vec { assert!(min_count + diff_count <= 32); *seed = seed.sha3(); - let r = min_count + (seed.bytes()[31] as usize % (diff_count + 1)); + let r = min_count + (seed[31] as usize % (diff_count + 1)); let mut ret: Vec = Vec::with_capacity(r); for i in 0..r { - ret.push(alphabet[seed.bytes()[i] as usize % alphabet.len()]); + ret.push(alphabet[seed[i] as usize % alphabet.len()]); } ret } @@ -45,15 +44,15 @@ fn random_word(alphabet: &[u8], min_count: usize, diff_count: usize, seed: &mut fn random_bytes(min_count: usize, diff_count: usize, seed: &mut H256) -> Vec { assert!(min_count + diff_count <= 32); *seed = seed.sha3(); - let r = min_count + (seed.bytes()[31] as usize % (diff_count + 1)); - seed.bytes()[0..r].to_vec() + let r = min_count + (seed[31] as usize % (diff_count + 1)); + seed[0..r].to_vec() } fn random_value(seed: &mut H256) -> Bytes { *seed = seed.sha3(); - match seed.bytes()[0] % 2 { - 1 => vec![seed.bytes()[31];1], - _ => seed.bytes().to_vec(), + match seed[0] % 2 { + 1 => vec![seed[31];1], + _ => seed.to_vec(), } }